diff --git a/.asf.yaml b/.asf.yaml deleted file mode 100644 index 0bada4974..000000000 --- a/.asf.yaml +++ /dev/null @@ -1,55 +0,0 @@ -github: - description: A software library of stochastic streaming algorithms, a.k.a. sketches. - homepage: https://datasketches.apache.org - ghp_branch: gh-pages - ghp_path: /docs - - protected_branches: - main: - required_status_checks: - # strict means "Require branches to be up to date before merging." - strict: true - - required_pull_request_reviews: - dismiss_stale_reviews: false - required_approving_review_count: 1 - - # squash or rebase must be allowed in the repo for this setting to be set to true. - required_linear_history: false - - required_signatures: false - - # requires all conversations to be resolved before merging is possible - required_conversation_resolution: false - - dependabot_alerts: true - dependabot_updates: false - - # Attempt to make the auto-generated github emails more easily readable in email clients. - custom_subjects: - new_pr: "[PR] {title} ({repository})" - close_pr: "Re: [PR] {title} ({repository})" - comment_pr: "Re: [PR] {title} ({repository})" - diffcomment: "Re: [PR] {title} ({repository})" - merge_pr: "Re: [PR] {title} ({repository})" - new_issue: "[I] {title} ({repository})" - comment_issue: "Re: [I] {title} ({repository})" - close_issue: "Re: [I] {title} ({repository})" - catchall: "[GH] {title} ({repository})" - new_discussion: "[D] {title} ({repository})" - edit_discussion: "Re: [D] {title} ({repository})" - close_discussion: "Re: [D] {title} ({repository})" - close_discussion_with_comment: "Re: [D] {title} ({repository})" - reopen_discussion: "Re: [D] {title} ({repository})" - new_comment_discussion: "Re: [D] {title} ({repository})" - edit_comment_discussion: "Re: [D] {title} ({repository})" - delete_comment_discussion: "Re: [D] {title} ({repository})" - -notifications: - commits: commits@datasketches.apache.org - issues: dev@datasketches.apache.org - discussions: dev@datasketches.apache.org - pullrequests_status: dev@datasketches.apache.org - pullrequests_comment: dev@datasketches.apache.org - # Send dependabot PRs to commits@ instead - pullrequests_bot_dependabot: commits@datasketches.apache.org diff --git a/.checkstyle b/.checkstyle new file mode 100644 index 000000000..9a861d12f --- /dev/null +++ b/.checkstyle @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/.classpath b/.classpath new file mode 100644 index 000000000..0bfdcd85c --- /dev/null +++ b/.classpath @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index 4ebca26dd..000000000 --- a/.editorconfig +++ /dev/null @@ -1,28 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -root = true - -[*] -end_of_line = lf -indent_style = space -insert_final_newline = true -trim_trailing_whitespace = true - -[*.java] -indent_size = tab -tab_width = 2 diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 48891d7b3..000000000 --- a/.gitattributes +++ /dev/null @@ -1,36 +0,0 @@ -# The default behavior, which overrides 'core.autocrlf', is to use Git's -# built-in heuristics to determine whether a particular file is text or binary. -# Text files are automatically normalized to the user's platforms. -* text=auto - -# Explicitly declare text files that should always be normalized and converted -# to native line endings. -.asf.yaml text -.gitattributes text -.gitignore text -git.properties text -.travis.yml text -LICENSE text -NOTICE text -*.html text -*.java text -*.md text -*.properties text -*.sh text -*.xml text -*.yml text -*.yaml text - -# Declare files that will always have CRLF line endings on checkout. - -# Explicitly denote all files that are truly binary and should not be modified. -*.jpg binary -*.png binary -*.svg binary - -# Declare files that should be ignored when creating an archive of the git repository -.asf.yaml export-ignore -.gitattributes export-ignore -.gitignore export-ignore -.travis.yml export-ignore -.github/ export-ignore diff --git a/.github/workflows/auto-jdk-matrix.yml b/.github/workflows/auto-jdk-matrix.yml deleted file mode 100644 index 2fb44a079..000000000 --- a/.github/workflows/auto-jdk-matrix.yml +++ /dev/null @@ -1,75 +0,0 @@ -name: Auto JDK Matrix Test & Install - -on: - push: - branches: [ 'main', '[0-9]+.[0-9]+.[Xx]' ] - pull_request: - paths-ignore: [ '**/*.html', '**/*.md', '**/*.txt', '**/LICENSE', '**/NOTICE' ] - # The branches below must be a subset of the branches above - branches: [ 'main', '[0-9]+.[0-9]+.[Xx]' ] - workflow_dispatch: - -env: - MAVEN_OPTS: -Xmx4g -Xms1g - -jobs: - build: - name: Build, Test, Install - runs-on: ubuntu-latest - - strategy: - fail-fast: false - matrix: - jdk: [ 25 ] - - env: - JDK_VERSION: ${{ matrix.jdk }} - - steps: - - name: "Checkout ${{ github.ref }} ( ${{ github.sha }} )" - uses: actions/checkout@v5 - with: - persist-credentials: false - - - name: Print Current workflow - run: > - cat .github/workflows/auto-jdk-matrix.yml - - - name: Cache local Maven repository - uses: actions/cache@v4 - with: - path: ~/.m2/repository - key: build-${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: build-${{ runner.os }}-maven- - - - name: Install Matrix JDK - uses: actions/setup-java@v5 - with: - java-version: ${{ matrix.jdk }} - distribution: 'temurin' - java-package: jdk - architecture: x64 - - - name: Echo Java Version - run: > - java -version - - - name: Test - run: > - mvn clean test -B - -Dmaven.javadoc.skip=true - -Dgpg.skip=true - - - name: Install - run: > - mvn clean install -B - -DskipTests=true - -Dgpg.skip=true - -# Architecture options: x86, x64, armv7, aarch64, ppc64le -# setup-java@v5 has a "with cache" option -# Lifecycle: validate, compile, test, package, verify, install, deploy -# -B batch mode, never stops for user input -# -V show Version without stopping -# -X debug mode -# -q quiet, only show errors diff --git a/.github/workflows/auto-os-matrix.yml b/.github/workflows/auto-os-matrix.yml deleted file mode 100644 index 0cc35c951..000000000 --- a/.github/workflows/auto-os-matrix.yml +++ /dev/null @@ -1,85 +0,0 @@ -name: Auto OS Matrix Test & Install - -on: - push: - paths-ignore: [ '**/*.html', '**/*.md', '**/*.txt', '**/LICENSE', '**/NOTICE' ] - branches: [ 'main', '[0-9]+.[0-9]+.[Xx]' ] - pull_request: - paths-ignore: [ '**/*.html', '**/*.md', '**/*.txt', '**/LICENSE', '**/NOTICE' ] - # The branches below must be a subset of the branches above - branches: [ 'main', '[0-9]+.[0-9]+.[Xx]' ] - workflow_dispatch: - -env: - MAVEN_OPTS: -Xmx4g -Xms1g - -jobs: - build: - name: Build, Test, Install - - strategy: - fail-fast: false - - matrix: - jdk: [ 25 ] - os: [ windows-latest, ubuntu-latest, macos-latest ] - include: - - os: windows-latest - skip_javadoc: "`-Dmaven`.javadoc`.skip=true" - skip_gpg: "`-Dgpg`.skip=true" - - os: ubuntu-latest - skip_javadoc: -Dmaven.javadoc.skip=true - skip_gpg: -Dgpg.skip=true - - os: macos-latest - skip_javadoc: -Dmaven.javadoc.skip=true - skip_gpg: -Dgpg.skip=true - - runs-on: ${{matrix.os}} - - env: - JDK_VERSION: ${{ matrix.jdk }} - - steps: - - name: "Checkout ${{ github.ref }} ( ${{ github.sha }} )" - uses: actions/checkout@v5 - with: - persist-credentials: false - - - name: Cache local Maven repository - uses: actions/cache@v4 - with: - path: ~/.m2/repository - key: build-${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: build-${{ runner.os }}-maven- - - - name: Install Matrix JDK - uses: actions/setup-java@v5 - with: - java-version: ${{ matrix.jdk }} - distribution: 'temurin' - java-package: jdk - architecture: x64 - - - name: Echo Java Version - run: > - java -version - - - name: Test - run: > - mvn clean test - ${{matrix.os.skip_javadoc}} - ${{matrix.os.skip_gpg}} - - - name: Install - run: > - mvn clean install -B - ${{matrix.os.skip_javadoc}} - -D skipTests=true - ${{matrix.os.skip_gpg}} - -# Architecture options: x86, x64, armv7, aarch64, ppc64le -# setup-java@v4 has a "with cache" option -# Lifecycle: validate, compile, test, package, verify, install, deploy -# -B batch mode -# -V show Version without stopping -# -q quiet, only show errors diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml deleted file mode 100644 index 0a6de05d9..000000000 --- a/.github/workflows/codeql-analysis.yml +++ /dev/null @@ -1,83 +0,0 @@ -name: "CodeQL" - -on: - push: - paths-ignore: [ '**/*.html', '**/*.md', '**/*.txt', '**/*.xml', '**/*.yaml', '**/*.yml', '**/LICENSE', '**/NOTICE' ] - branches: [ 'main', '[0-9]+.[0-9]+.[Xx]' ] - pull_request: - paths-ignore: [ '**/*.html', '**/*.md', '**/*.txt', '**/*.xml', '**/*.yaml', '**/*.yml', '**/LICENSE', '**/NOTICE' ] - # The branches below must be a subset of the branches above - branches: [ 'main', '[0-9]+.[0-9]+.[Xx]' ] - workflow_dispatch: - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - permissions: - actions: read - contents: read - security-events: write - - strategy: - fail-fast: false - matrix: - language: [ 'java' ] - # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] - # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support - - steps: - - name: Checkout repository - uses: actions/checkout@v5 - - - name: Setup Java - uses: actions/setup-java@v5 - with: - distribution: 'temurin' - cache: 'maven' - java-version: '25' - - - name: Initialize CodeQL - uses: github/codeql-action/init@v3 - with: - languages: ${{ matrix.language }} - queries: +security-and-quality - - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - # Details on CodeQL's query packs refer to link below. - - - name: Custom building using maven - run: > - mvn clean package -f "pom.xml" -B -V -e - -Dfindbugs.skip=true - -Dcheckstyle.skip=true - -Dpmd.skip=true - -Denforcer.skip - -Dmaven.javadoc.skip - -DskipTests=true - -Dmaven.test.skip.exec - -Dlicense.skip=true - -Dweb.console.skip=true - -Dgpg.skip=true - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 - with: - category: "/language:${{matrix.language}}" - - -# CodeQL's Query Packs: -# https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs - -# Command-line programs to run using the OS shell. -# See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun - -# Architecture options: x86, x64, armv7, aarch64, ppc64le -# Lifecycles: validate, compile, test, package, verify, install, deploy -# -B batch mode, never stops for user input -# -V show Version without stopping -# -X debug mode -# -q quiet, only show errors -# -e produce execution error messages diff --git a/.github/workflows/cpp-serde-compat.yml b/.github/workflows/cpp-serde-compat.yml deleted file mode 100644 index 496e11c31..000000000 --- a/.github/workflows/cpp-serde-compat.yml +++ /dev/null @@ -1,49 +0,0 @@ -name: CPP SerDe Compatibility Test - -on: - push: - paths-ignore: [ '**/*.html', '**/*.md', '**/*.txt', '**/LICENSE', '**/NOTICE' ] - branches: [ 'main', '[0-9]+.[0-9]+.[Xx]' ] - pull_request: - paths-ignore: [ '**/*.html', '**/*.md', '**/*.txt', '**/LICENSE', '**/NOTICE' ] - # The branches below must be a subset of the branches above - branches: [ 'main', '[0-9]+.[0-9]+.[Xx]' ] - workflow_dispatch: - -jobs: - build: - name: SerDe Test - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v5 - - - name: Checkout C++ - uses: actions/checkout@v5 - with: - repository: apache/datasketches-cpp - path: cpp - - - name: Setup Java - uses: actions/setup-java@v5 - with: - java-version: '25' - distribution: 'temurin' - - - name: Configure C++ build - run: cd cpp/build && cmake .. -DGENERATE=true - - - name: Build C++ unit tests - run: cd cpp && cmake --build build --config Release - - - name: Run C++ tests - run: cd cpp && cmake --build build --config Release --target test - - - name: Make dir - run: mkdir -p serialization_test_data/cpp_generated_files - - - name: Copy files - run: cp cpp/build/*/test/*_cpp.sk serialization_test_data/cpp_generated_files - - - name: Run Java tests - run: mvn test -P check-cpp-files diff --git a/.github/workflows/javadoc.yml b/.github/workflows/javadoc.yml deleted file mode 100644 index 426c744c2..000000000 --- a/.github/workflows/javadoc.yml +++ /dev/null @@ -1,101 +0,0 @@ -name: Deploy Versioned Javadoc (Manual Trigger) - -# Select the target TAG where to run the workflow from. -# This TAG name becomes the subdirectory under branch gh-pages/docs/${TAG} -# where the javadocs will be copied to. -# The gh-pages/docs branch/folder must exist. - -on: - workflow_dispatch: - inputs: - tag_ref: - description: 'Existing Git Tag to deploy (e.g., 1.0.0):' - required: true - default: '99.0.0' # unlikely to conflict if accidentally used. Can be left blank - -jobs: - build-and-deploy-javadoc: - runs-on: ubuntu-latest - permissions: - contents: write - - steps: - - name: "Checkout ${{ github.ref }} ( ${{ github.sha }} )" - uses: actions/checkout@v5 - with: - ref: ${{ github.event.inputs.tag_ref }} # from manual trigger input - fetch-depth: 0 - - - name: Set up JDK - uses: actions/setup-java@v4 - with: - java-version: '25' - distribution: 'temurin' - java-package: jdk - architecture: x64 - cache: 'maven' - overwrite-settings: true # ensures the runner's .m2/settings.xml is current - - - name: Build and Generate Javadoc # POM is configured to output to target/site/apidocs - run: mvn clean javadoc:javadoc - - - name: Deploy Javadoc via Worktree - env: - TAG_NAME: ${{ github.event.inputs.tag_ref }} - run: | - if [ -z "$TAG_NAME" ]; then echo "ERROR: No tag specified"; exit 1; fi - - # 1. Initialize error tracking - EXIT_CODE=0 - - # 2. Configure Git Identity - git config user.email "noreply@github.com" - git config user.name "github-actions[bot]" - - # 3. Ensure gh-pages exists and is fetched - echo "ECHO: git fetch origin gh-pages" - git fetch origin gh-pages - - # 4. Create worktree for the gh-pages branch in a separate folder - echo "ECHO: git worktree add -B gh-pages ./gh-pages-dir origin/gh-pages" - git worktree add -B gh-pages ./gh-pages-dir origin/gh-pages - - # 5. Deployment Logic in a subshell to capture exit code - ( - set -e - TARGET_PATH="gh-pages-dir/docs/$TAG_NAME" - mkdir -p "$TARGET_PATH" - - echo "ECHO: cp -a target/site/apidocs/. $TARGET_PATH/" - cp -a target/site/apidocs/. "$TARGET_PATH/" - cd gh-pages-dir - - echo "ECHO: git pull origin gh-pages --rebase" - git pull origin gh-pages --rebase - - echo "git add docs/$TAG_NAME" - git add "docs/$TAG_NAME" - - if git diff --staged --quiet; then - echo "No changes detected for Javadoc $TAG_NAME." - else - echo "ECHO: Changes detected for Javadoc $TAG_NAME." - echo "ECHO: git commit ..." - git commit -m "Manual Javadoc deployment for tag $TAG_NAME" - echo "ECHO: git push origin gh-pages" - git push origin gh-pages - fi - ) || EXIT_CODE=$? - - # 6. Cleanup (Always runs) - echo "ECHO: Cleaning up worktree..." - git worktree remove --force ./gh-pages-dir || true - - # 7. Final exit based on subshell success - exit $EXIT_CODE - - - name: Confirm Deployment - if: success() - run: | - echo "ECHO: Javadoc for ${{ github.event.inputs.tag_ref }} is now live on gh-pages." - diff --git a/.github/workflows/reusable-jdk-os-matrix.yml b/.github/workflows/reusable-jdk-os-matrix.yml new file mode 100644 index 000000000..05be7b905 --- /dev/null +++ b/.github/workflows/reusable-jdk-os-matrix.yml @@ -0,0 +1,89 @@ +name: Reusable JDK OS Matrix Logic + +on: + workflow_call: + inputs: + jdk_version: + required: true + type: string + os_type: + required: true + type: string + java_arch: + required: true + type: string + +env: + MAVEN_OPTS: -Xmx4g -Xms1g + MAVEN_ARGS: "-B -Dmaven.javadoc.skip=true -Dgpg.skip=true" + +jobs: + build: + name: Build (${{ inputs.os_type }}, JDK ${{ inputs.jdk_version }}, ${{ inputs.java_arch }}) + runs-on: ${{ inputs.os_type }} + steps: + - name: Checkout Source code + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Checkout Workflow Logic (workflows branch) + uses: actions/checkout@v4 + with: + ref: workflows + path: .github/workflow-logic + + - name: Install Matrix JDK + uses: actions/setup-java@v4 + with: + java-version: ${{ inputs.jdk_version }} + distribution: 'temurin' + java-package: jdk + architecture: ${{ inputs.java_arch }} + cache: 'maven' + overwrite-settings: true + + - name: Verify Toolchain Configuration + shell: bash + run: | + if [ -f ~/.m2/toolchains.xml ]; then + cat ~/.m2/toolchains.xml + else + echo "toolchains.xml not found in ~/.m2/" + fi + + - name: Echo Java & Maven Version + run: mvn -version + + - name: Print Current Workflows + continue-on-error: true + run: | + echo "Checking for workflow files..." + echo "--- Reusable Workflow: ---" + cat .github/workflow-logic/.github/workflows/reusable-jdk-os-matrix.yml || echo "::warning::Could not find Reusable Workflow file." + echo "--- Caller Workflow: ---" + cat .github/workflows/auto-jdk-os-matrix.yml || echo "::warning::Could not find Caller Workflow file." + + - name: Test + run: mvn clean test + + - name: Install + run: mvn clean install "-DskipTests=true" "-Dmaven.clean.failOnError=false" + + - name: Add Result to Summary + if: always() + shell: bash + run: | + # Define the header + HEADER="| OS | Arch | JDK | Status |" + SEP="|----|------|-----|--------|" + + # Check if the header already exists in the summary file + if ! grep -q "$HEADER" "$GITHUB_STEP_SUMMARY"; then + echo "$HEADER" >> $GITHUB_STEP_SUMMARY + echo "$SEP" >> $GITHUB_STEP_SUMMARY + fi + + # Append the specific job row + echo "| ${{ inputs.os_type }} | ${{ inputs.java_arch }} | ${{ inputs.jdk_version }} | ${{ job.status == 'success' && '✅' || '❌' }} |" >> $GITHUB_STEP_SUMMARY + diff --git a/.gitignore b/.gitignore index a3d5f0565..1f6f330f7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -# Eclipse project files +# Eclipse project files .classpath .project .settings/ @@ -23,6 +23,10 @@ # Compiler output, class files *.class bin/ +/bin/ + +# Java files +**/*.java # Log file *.log @@ -33,7 +37,7 @@ bin/ # Mobile Tools for Java (J2ME) .mtj.tmp/ -# Package Files # +# Package Files *.jar *.war *.ear @@ -50,7 +54,6 @@ local/ reports/ .pmd tmp/ -*.txt # Build artifacts target/ @@ -72,4 +75,4 @@ _*/ # Sketch binary test files *.sk -/tools/genCPPcrossLangFiles.sh \ No newline at end of file + diff --git a/.mvn/maven.config b/.mvn/maven.config deleted file mode 100644 index 87735fa0a..000000000 --- a/.mvn/maven.config +++ /dev/null @@ -1,5 +0,0 @@ -# suppresses the warning: -# Direct modification of testCompileSourceRoots through add() is deprecated and will not work in Maven 4.0.0. Please use the add/remove methods instead. -# If you're using a plugin that causes this warning, please upgrade to the latest version and report an issue if the warning persists. -# To disable these warnings, set -Dmaven.project.sourceRoots.warningsDisabled=true on the command line or in the .mvn/maven.config file. --Dmaven.project.sourceRoots.warningsDisabled=true diff --git a/.project b/.project new file mode 100644 index 000000000..ee763ad95 --- /dev/null +++ b/.project @@ -0,0 +1,50 @@ + + + datasketches-java21 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.jdt.core.javanature + + + + java + 2 + /Users/lrhodes/dev/git/Apache/datasketches-java25/src/main/java + + + + + 1739858969469 + + 22 + + org.eclipse.ui.ide.multiFilter + 1.0-name-matches-true-false-.DS_Store + + + + 1744320220701 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/.settings/edu.umd.cs.findbugs.core.prefs b/.settings/edu.umd.cs.findbugs.core.prefs new file mode 100644 index 000000000..1ce6937fa --- /dev/null +++ b/.settings/edu.umd.cs.findbugs.core.prefs @@ -0,0 +1,166 @@ +#SpotBugs User Preferences +#Tue Jul 01 13:02:19 PDT 2025 +detectorAppendingToAnObjectOutputStream=AppendingToAnObjectOutputStream|true +detectorAtomicityProblem=AtomicityProblem|true +detectorBadAppletConstructor=BadAppletConstructor|false +detectorBadResultSetAccess=BadResultSetAccess|true +detectorBadSyntaxForRegularExpression=BadSyntaxForRegularExpression|true +detectorBadUseOfReturnValue=BadUseOfReturnValue|true +detectorBadlyOverriddenAdapter=BadlyOverriddenAdapter|true +detectorBooleanReturnNull=BooleanReturnNull|true +detectorCallToUnsupportedMethod=CallToUnsupportedMethod|false +detectorCheckExpectedWarnings=CheckExpectedWarnings|false +detectorCheckImmutableAnnotation=CheckImmutableAnnotation|true +detectorCheckRelaxingNullnessAnnotation=CheckRelaxingNullnessAnnotation|true +detectorCheckTypeQualifiers=CheckTypeQualifiers|true +detectorCloneIdiom=CloneIdiom|true +detectorComparatorIdiom=ComparatorIdiom|true +detectorConfusedInheritance=ConfusedInheritance|true +detectorConfusionBetweenInheritedAndOuterMethod=ConfusionBetweenInheritedAndOuterMethod|true +detectorConstructorThrow=ConstructorThrow|true +detectorCovariantArrayAssignment=CovariantArrayAssignment|false +detectorCrossSiteScripting=CrossSiteScripting|true +detectorDateFormatStringChecker=DateFormatStringChecker|true +detectorDefaultEncodingDetector=DefaultEncodingDetector|true +detectorDoInsideDoPrivileged=DoInsideDoPrivileged|true +detectorDontAssertInstanceofInTests=DontAssertInstanceofInTests|true +detectorDontCatchIllegalMonitorStateException=DontCatchIllegalMonitorStateException|true +detectorDontCatchNullPointerException=DontCatchNullPointerException|true +detectorDontIgnoreResultOfPutIfAbsent=DontIgnoreResultOfPutIfAbsent|true +detectorDontReusePublicIdentifiers=DontReusePublicIdentifiers|false +detectorDontUseEnum=DontUseEnum|true +detectorDontUseFloatsAsLoopCounters=DontUseFloatsAsLoopCounters|true +detectorDroppedException=DroppedException|true +detectorDumbMethodInvocations=DumbMethodInvocations|true +detectorDumbMethods=DumbMethods|true +detectorDuplicateBranches=DuplicateBranches|true +detectorEmptyZipFileEntry=EmptyZipFileEntry|false +detectorEqualsOperandShouldHaveClassCompatibleWithThis=EqualsOperandShouldHaveClassCompatibleWithThis|true +detectorExplicitSerialization=ExplicitSerialization|true +detectorFinalizerNullsFields=FinalizerNullsFields|true +detectorFindArgumentAssertions=FindArgumentAssertions|true +detectorFindAssertionsWithSideEffects=FindAssertionsWithSideEffects|true +detectorFindBadCast2=FindBadCast2|true +detectorFindBadEndOfStreamCheck=FindBadEndOfStreamCheck|true +detectorFindBadForLoop=FindBadForLoop|true +detectorFindCircularDependencies=FindCircularDependencies|false +detectorFindComparatorProblems=FindComparatorProblems|true +detectorFindDeadLocalStores=FindDeadLocalStores|true +detectorFindDoubleCheck=FindDoubleCheck|true +detectorFindEmptySynchronizedBlock=FindEmptySynchronizedBlock|true +detectorFindFieldSelfAssignment=FindFieldSelfAssignment|true +detectorFindFinalizeInvocations=FindFinalizeInvocations|true +detectorFindFloatEquality=FindFloatEquality|true +detectorFindHEmismatch=FindHEmismatch|true +detectorFindHiddenMethod=FindHiddenMethod|true +detectorFindInconsistentSync2=FindInconsistentSync2|true +detectorFindInstanceLockOnSharedStaticData=FindInstanceLockOnSharedStaticData|true +detectorFindJSR166LockMonitorenter=FindJSR166LockMonitorenter|true +detectorFindLocalSelfAssignment2=FindLocalSelfAssignment2|true +detectorFindMaskedFields=FindMaskedFields|true +detectorFindMismatchedWaitOrNotify=FindMismatchedWaitOrNotify|true +detectorFindNakedNotify=FindNakedNotify|true +detectorFindNonShortCircuit=FindNonShortCircuit|true +detectorFindNullDeref=FindNullDeref|true +detectorFindNullDerefsInvolvingNonShortCircuitEvaluation=FindNullDerefsInvolvingNonShortCircuitEvaluation|true +detectorFindOpenStream=FindOpenStream|true +detectorFindOverridableMethodCall=FindOverridableMethodCall|true +detectorFindPotentialSecurityCheckBasedOnUntrustedSource=FindPotentialSecurityCheckBasedOnUntrustedSource|true +detectorFindPublicAttributes=FindPublicAttributes|true +detectorFindPuzzlers=FindPuzzlers|true +detectorFindRefComparison=FindRefComparison|true +detectorFindReturnRef=FindReturnRef|true +detectorFindRoughConstants=FindRoughConstants|true +detectorFindRunInvocations=FindRunInvocations|true +detectorFindSelfComparison=FindSelfComparison|true +detectorFindSelfComparison2=FindSelfComparison2|true +detectorFindSleepWithLockHeld=FindSleepWithLockHeld|true +detectorFindSpinLoop=FindSpinLoop|true +detectorFindSqlInjection=FindSqlInjection|true +detectorFindTwoLockWait=FindTwoLockWait|true +detectorFindUncalledPrivateMethods=FindUncalledPrivateMethods|true +detectorFindUnconditionalWait=FindUnconditionalWait|true +detectorFindUninitializedGet=FindUninitializedGet|true +detectorFindUnrelatedTypesInGenericContainer=FindUnrelatedTypesInGenericContainer|true +detectorFindUnreleasedLock=FindUnreleasedLock|true +detectorFindUnsatisfiedObligation=FindUnsatisfiedObligation|true +detectorFindUnsyncGet=FindUnsyncGet|true +detectorFindUseOfNonSerializableValue=FindUseOfNonSerializableValue|true +detectorFindUselessControlFlow=FindUselessControlFlow|true +detectorFindUselessObjects=FindUselessObjects|true +detectorFindVulnerableSecurityCheckMethods=FindVulnerableSecurityCheckMethods|true +detectorFormatStringChecker=FormatStringChecker|true +detectorHugeSharedStringConstants=HugeSharedStringConstants|true +detectorIDivResultCastToDouble=IDivResultCastToDouble|true +detectorIncompatMask=IncompatMask|true +detectorInconsistentAnnotations=InconsistentAnnotations|true +detectorInefficientIndexOf=InefficientIndexOf|false +detectorInefficientInitializationInsideLoop=InefficientInitializationInsideLoop|false +detectorInefficientMemberAccess=InefficientMemberAccess|false +detectorInefficientToArray=InefficientToArray|false +detectorInfiniteLoop=InfiniteLoop|true +detectorInfiniteRecursiveLoop=InfiniteRecursiveLoop|true +detectorInheritanceUnsafeGetResource=InheritanceUnsafeGetResource|true +detectorInitializationChain=InitializationChain|true +detectorInitializeNonnullFieldsInConstructor=InitializeNonnullFieldsInConstructor|true +detectorInstantiateStaticClass=InstantiateStaticClass|true +detectorIntCast2LongAsInstant=IntCast2LongAsInstant|true +detectorInvalidJUnitTest=InvalidJUnitTest|true +detectorIteratorIdioms=IteratorIdioms|true +detectorLazyInit=LazyInit|true +detectorLoadOfKnownNullValue=LoadOfKnownNullValue|true +detectorLostLoggerDueToWeakReference=LostLoggerDueToWeakReference|true +detectorMethodReturnCheck=MethodReturnCheck|true +detectorMultipleInstantiationsOfSingletons=MultipleInstantiationsOfSingletons|true +detectorMultithreadedInstanceAccess=MultithreadedInstanceAccess|true +detectorMutableEnum=MutableEnum|true +detectorMutableLock=MutableLock|true +detectorMutableStaticFields=MutableStaticFields|true +detectorNaming=Naming|true +detectorNoteUnconditionalParamDerefs=NoteUnconditionalParamDerefs|true +detectorNumberConstructor=NumberConstructor|true +detectorOptionalReturnNull=OptionalReturnNull|true +detectorOverridingEqualsNotSymmetrical=OverridingEqualsNotSymmetrical|true +detectorOverridingMethodsMustInvokeSuperDetector=OverridingMethodsMustInvokeSuperDetector|true +detectorPermissionsSuper=PermissionsSuper|true +detectorPreferZeroLengthArrays=PreferZeroLengthArrays|true +detectorPublicSemaphores=PublicSemaphores|false +detectorQuestionableBooleanAssignment=QuestionableBooleanAssignment|true +detectorReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass=ReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass|true +detectorReadReturnShouldBeChecked=ReadReturnShouldBeChecked|true +detectorRedundantConditions=RedundantConditions|true +detectorRedundantInterfaces=RedundantInterfaces|true +detectorReflectionIncreaseAccessibility=ReflectionIncreaseAccessibility|true +detectorRepeatedConditionals=RepeatedConditionals|true +detectorResourceInMultipleThreadsDetector=ResourceInMultipleThreadsDetector|true +detectorRuntimeExceptionCapture=RuntimeExceptionCapture|true +detectorSerializableIdiom=SerializableIdiom|true +detectorSharedVariableAtomicityDetector=SharedVariableAtomicityDetector|true +detectorStartInConstructor=StartInConstructor|true +detectorStaticCalendarDetector=StaticCalendarDetector|true +detectorStringConcatenation=StringConcatenation|true +detectorSuperfluousInstanceOf=SuperfluousInstanceOf|true +detectorSuspiciousThreadInterrupted=SuspiciousThreadInterrupted|true +detectorSwitchFallthrough=SwitchFallthrough|true +detectorSynchronizationOnSharedBuiltinConstant=SynchronizationOnSharedBuiltinConstant|true +detectorSynchronizeAndNullCheckField=SynchronizeAndNullCheckField|true +detectorSynchronizeOnClassLiteralNotGetClass=SynchronizeOnClassLiteralNotGetClass|true +detectorSynchronizingOnContentsOfFieldToProtectField=SynchronizingOnContentsOfFieldToProtectField|true +detectorThrowingExceptions=ThrowingExceptions|false +detectorURLProblems=URLProblems|true +detectorUncallableMethodOfAnonymousClass=UncallableMethodOfAnonymousClass|true +detectorUnnecessaryEnvUsage=UnnecessaryEnvUsage|true +detectorUnnecessaryMath=UnnecessaryMath|true +detectorUnreadFields=UnreadFields|true +detectorUselessSubclassMethod=UselessSubclassMethod|false +detectorVarArgsProblems=VarArgsProblems|true +detectorVolatileUsage=VolatileUsage|true +detectorWaitInLoop=WaitInLoop|true +detectorWrongMapIterator=WrongMapIterator|true +detectorXMLFactoryBypass=XMLFactoryBypass|true +detector_threshold=2 +effort=default +excludefilter0=tools/FindBugsExcludeFilter.xml|true +filter_settings=Medium|BAD_PRACTICE,CORRECTNESS,MT_CORRECTNESS,PERFORMANCE,STYLE|false|15 +filter_settings_neg=MALICIOUS_CODE,SECURITY,EXPERIMENTAL,NOISE,I18N| +run_at_full_build=false diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..839d647ee --- /dev/null +++ b/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/main/resources=UTF-8 +encoding//src/test/java=UTF-8 +encoding/=UTF-8 diff --git a/.settings/org.eclipse.jdt.apt.core.prefs b/.settings/org.eclipse.jdt.apt.core.prefs new file mode 100644 index 000000000..d4313d4b2 --- /dev/null +++ b/.settings/org.eclipse.jdt.apt.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.apt.aptEnabled=false diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..368dbce54 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,136 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.builder.annotationPath.allLocations=disabled +org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled +org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore +org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull +org.eclipse.jdt.core.compiler.annotation.nonnull.secondary= +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary= +org.eclipse.jdt.core.compiler.annotation.notowning=org.eclipse.jdt.annotation.NotOwning +org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable +org.eclipse.jdt.core.compiler.annotation.nullable.secondary= +org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled +org.eclipse.jdt.core.compiler.annotation.owning=org.eclipse.jdt.annotation.Owning +org.eclipse.jdt.core.compiler.annotation.resourceanalysis=disabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=25 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=25 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.compiler.problem.APILeak=warning +org.eclipse.jdt.core.compiler.problem.annotatedTypeArgumentToUnannotated=info +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore +org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompatibleOwningContract=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore +org.eclipse.jdt.core.compiler.problem.insufficientResourceAnalysis=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=public +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=warning +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=all_standard_tags +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=warning +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsMethodTypeParameters=enabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning +org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning +org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error +org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore +org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore +org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore +org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.suppressWarningsNotFullyAnalysed=ignore +org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.terminalDeprecation=warning +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentType=warning +org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentTypeStrict=disabled +org.eclipse.jdt.core.compiler.problem.unlikelyEqualsArgumentType=info +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unstableAutoModuleName=warning +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLambdaParameter=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.processAnnotations=disabled +org.eclipse.jdt.core.compiler.release=enabled +org.eclipse.jdt.core.compiler.source=25 diff --git a/.settings/org.eclipse.jdt.ui.prefs b/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 000000000..7103be722 --- /dev/null +++ b/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.ui.text.custom_code_templates= diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 000000000..f897a7f1c --- /dev/null +++ b/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/.settings/org.testng.eclipse.maven.prefs b/.settings/org.testng.eclipse.maven.prefs new file mode 100644 index 000000000..67542cff6 --- /dev/null +++ b/.settings/org.testng.eclipse.maven.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.testng.eclipse.maven.additionalClasspath=true +org.testng.eclipse.maven.argline=true +org.testng.eclipse.maven.environ=true +org.testng.eclipse.maven.properties=true +org.testng.eclipse.maven.sysproperties=true +userprojectsettings=false diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..23ae9df4e --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.checkstyle.configuration": "${workspaceFolder}/tools/SketchesCheckstyle.xml" +} \ No newline at end of file diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 0372fc3a6..000000000 --- a/LICENSE +++ /dev/null @@ -1,229 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - - -APPENDIX A: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - ------------------------------------------------------------- - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ------------------------------------------------------------- - - - -APPENDIX B: Additional licenses relevant to this product: - - This product includes a number of source files with code that has been - adapted from 3rd party sources including sources that may be subject - to different copyright notices and license terms. Your use of - the source code for these subcomponents is subject to the terms and - conditions of the following licenses. - - ============================================================= - Public Domain (optional) - ============================================================= - This product contains code to implement and test Austin Appleby's - C++ public domain implementation of the MurmurHash3 algorithm: - * src/main/java/org/apache/datasketches/hash/MurmurHash3.java - * src/main/java/org/apache/datasketches/hash/MurmurHash3Adaptor.java - * src/test/java/org/apache/datasketches/hash/MurmurHash3AdaptorTest.java - * src/test/java/org/apache/datasketches/hash/MurmurHash3Test.java - * src/test/java/org/apache/datasketches/hash/MurmurHash3v2Test.java - and adapted from C++ source code located at: - * https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp - diff --git a/NOTICE b/NOTICE deleted file mode 100644 index 17bbe0d20..000000000 --- a/NOTICE +++ /dev/null @@ -1,12 +0,0 @@ -Apache DataSketches Java -Copyright 2025 The Apache Software Foundation - -Copyright 2015-2018 Yahoo Inc. -Copyright 2019-2020 Verizon Media -Copyright 2021-2025 Yahoo Inc. - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). - -Prior to moving to ASF, the software for this project was developed at -Yahoo Inc. (https://developer.yahoo.com). diff --git a/README.md b/README.md index 676deee97..a7da959f6 100644 --- a/README.md +++ b/README.md @@ -17,70 +17,4 @@ under the License. --> -[![Maven Central](https://img.shields.io/maven-central/v/org.apache.datasketches/datasketches-java)](https://central.sonatype.com/artifact/org.apache.datasketches/datasketches-java/9.0.0/versions) -[![Coverage Status](https://coveralls.io/repos/github/apache/datasketches-java/badge.svg)](https://coveralls.io/github/apache/datasketches-java) - ------------------ - -# Apache® DataSketches™ Core Java Library Component - -This is the core Java component of the DataSketches library. It contains all of the sketching algorithms and can be accessed directly from user applications. - -This component is also a dependency of other components of the library that create adaptors for target systems, such as the [Apache Pig adaptor](https://github.com/apache/datasketches-pig), the [Apache Hive adaptor](https://github.com/apache/datasketches-hive), and others. - -Note that we have parallel core library components for C++, Python, GO, and Rust implementations of many of the same sketch algorithms: - -- [datasketches-cpp](https://github.com/apache/datasketches-cpp) -- [datasketches-python](https://github.com/apache/datasketches-python) -- [datasketches-go](https://github.com/apache/datasketches-go) -- [datasketches-rust](https://github.com/apache/datasketches-rust) - -Please visit the main [DataSketches website](https://datasketches.apache.org) for more information. - -If you are interested in making contributions to this site, please see our [Community](https://datasketches.apache.org/docs/Community/) page for how to contact us. - - -## Build & Runtime Dependencies - -### Installation Directory Path -**NOTE:** This component accesses resource files for testing. As a result, the directory elements of the full absolute path of the target installation directory must qualify as Java identifiers. In other words, the directory elements must not have any space characters (or non-Java identifier characters) in any of the path elements. This is required by the Oracle Java Specification in order to ensure location-independent access to resources: [See Oracle Location-Independent Access to Resources](https://docs.oracle.com/javase/8/docs/technotes/guides/lang/resources.html) - -### OpenJDK Version 25 -At minimum, an OpenJDK-compatible build of Java 25, provided by one of the Open-Source JVM providers, such as *Azul Systems*, *Red Hat*, *SAP*, *Eclipse Temurin*, etc, is required. -All of the testing of this release has been performed with the *Eclipse Temurin* build. - -## Compilation and Test using Maven -This DataSketches component is structured as a Maven project and Maven is the recommended tool for compile and test. - -#### A Toolchain is required - -* You must have a JDK type toolchain defined in location *~/.m2/toolchains.xml* that specifies where to find a locally installed OpenJDK-compatible version 25. -* Your default \$JAVA\_HOME compiler must be OpenJDK compatible, specified in the toolchain, and may be a version greater than 25. Note that if your \$JAVA\_HOME is set to a Java version greater than 25, Maven will automatically use the Java 25 version specified in the toolchain instead. The pom.xml specifies any necessary JVM flags, if required, so no further action is needed. -* Note that the paths specified in the toolchain must be fully qualified direct paths to the OpenJDK version locations. Using environment variables will not work. - -#### To run normal unit tests: - - $ mvn clean test - -#### To install jars built from the downloaded source: - - $ mvn clean install -DskipTests=true - -This will create the following jars: - -* datasketches-java-X.Y.Z.jar The compiled main class files. -* datasketches-java-X.Y.Z-tests.jar The compiled test class files. -* datasketches-java-X.Y.Z-sources.jar The main source files. -* datasketches-java-X.Y.Z-test-sources.jar The test source files -* datasketches-java-X.Y.Z-javadoc.jar The compressed Javadocs. - -## Known Issues - -### SpotBugs - -* Make sure you configure SpotBugs with the `/tools/FindBugsExcludeFilter.xml` file. Otherwise, you may get a lot of false positive or low risk issues that we have examined and eliminated with this exclusion file. - -### Checkstyle - -* At the time of this writing, Checkstyle had not been upgraded to handle Java 25 features. - +# DataSketches Java Reusable Workflows Branch diff --git a/pom.xml b/pom.xml deleted file mode 100644 index db8026352..000000000 --- a/pom.xml +++ /dev/null @@ -1,729 +0,0 @@ - - - - - - 4.0.0 - - org.apache.datasketches - datasketches-java - 9.0.1-SNAPSHOT - jar - - ${project.artifactId} - Core sketch algorithms used alone and by other Java repositories in the Apache DataSketches Project. - https://datasketches.apache.org/ - 2015 - - - - Apache-2.0 - https://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - - DataSketches Developers - dev-subscribe@datasketches.apache.org - dev-unsubscribe@datasketches.apache.org - dev@datasketches.apache.org - https://mail-archives.apache.org/mod_mbox/datasketches-dev - - - DataSketches Users - user-subscribe@datasketches.apache.org - user-unsubscribe@datasketches.apache.org - user@datasketches.apache.org - https://mail-archives.apache.org/mod_mbox/datasketches-user - - - - - scm:git:ssh://git@github.com/apache/${project.artifactId}.git - scm:git:ssh://git@github.com/apache/${project.artifactId}.git - https://github.com/apache/${project.artifactId} - HEAD - - - - - apache.releases.https - Apache Release Distribution Repository - https://repository.apache.org/service/local/staging/deploy/maven2 - - - apache.snapshots.https - Apache Development Snapshot Repository - https://repository.apache.org/content/repositories/snapshots - - - - - GitHub - https://github.com/apache/${project.artifactId}/issues - - - - - The Apache DataSketches Team - dev@datasketches.apache.org - https://datasketches.apache.org - Apache Software Foundation - http://www.apache.org - - - - - - 7.12.0 - - generate_java_files - check_cpp_files - check_go_files - check_cpp_historical_files - - - 3.9.12 - 25 - ${java.version} - -Xmx4g - -Duser.language=en - -Duser.country=US - -Dfile.encoding=UTF-8 - ${jvm.mem} ${jvm.locale.language} ${jvm.locale.country} ${jvm.locale.encoding} - UTF-8 - 2026-01-09T19:00:20Z - ${charset.encoding} - ${charset.encoding} - ${charset.encoding} - ${charset.encoding} - ${project.build.directory}/site - yyyy-MM-dd'T'HH-mm-ss'Z' - - - 3.15.0 - 3.1.4 - 3.6.2 - 3.2.8 - 3.1.4 - 3.4.2 - 3.12.0 - 3.3.1 - 3.4.0 - 3.5.4 - 3.2.0 - - - 0.17 - - - - 5.0.0 - - - 9.0.2 - - - 0.8.14 - - - 1.0.0 - - - - - apache.snapshots - Apache Snapshot Repository - https://repository.apache.org/content/groups/snapshots - - false - - - true - - - - apache - Apache Releases Repository - https://repository.apache.org/content/groups/public - - true - - - false - - - - - - - - org.testng - testng - ${testng.version} - test - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - true - - - - - org.apache.maven.plugins - maven-deploy-plugin - ${maven-deploy-plugin.version} - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${maven-enforcer-plugin.version} - - - enforce-banned-dependencies - - enforce - - - - - - [${maven.version},4.0.0) - - - - - com.google.code.findbugs:annotations - - - - true - - - - - - - org.apache.maven.plugins - maven-install-plugin - ${maven-install-plugin.version} - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven-jar-plugin.version} - - - default-jar - package - - jar - - - - default-test-jar - package - - test-jar - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven-javadoc-plugin.version} - - ${project.reporting.outputDirectory} - true - public - none - - -J${jvm.mem} - -J${jvm.locale.language} - -J${jvm.locale.country} - -J${jvm.locale.encoding} - - - - - attach-javadocs - - jar - - - - - - - org.apache.maven.plugins - maven-release-plugin - ${maven-release-plugin.version} - - - - org.apache.maven.plugins - maven-source-plugin - ${maven-source-plugin.version} - - - attach-sources - package - - jar-no-fork - - - - attach-test-sources - package - - test-jar-no-fork - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-failsafe-plugins.version} - - @{argLine} @{jvm.args} - false - false - false - ${project.build.directory}/test-output - - src/test/resources/testng.xml - - ${testng.generate-java-files},${testng.check-cpp-files},${testng.check-go-files},${testng.check-cpp-historical-files} - false - - - - - org.apache.maven.plugins - maven-toolchains-plugin - ${maven-toolchains-plugin.version} - - - - toolchain - - - - - - - ${java.version} - - - - - - - org.apache.rat - apache-rat-plugin - ${apache-rat-plugin.version} - - - verify - - check - - - - - ${project.basedir}/rat - true - - - StandardCollection - **/*.yaml - **/*.yml - **/.* - **/test/resources/**/*.txt - **/git.properties - **/doc/** - **/*.sk - LICENSE - NOTICE - **/*.code-workspace - - - - - - - com.github.hazendaz.maven - coveralls-maven-plugin - ${coveralls-maven-plugin.version} - - ${coveralls-repo-token} - - - - - io.github.git-commit-id - git-commit-id-maven-plugin - ${git-commit-id-maven-plugin.version} - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco-maven-plugin.version} - - - default-prepare-agent - - prepare-agent - - - - default-report - test - - report - - - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - org.apache.maven.plugins - maven-deploy-plugin - - - - org.apache.maven.plugins - maven-enforcer-plugin - - - - org.apache.maven.plugins - maven-jar-plugin - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - - org.apache.maven.plugins - maven-release-plugin - - - - org.apache.maven.plugins - maven-source-plugin - - - - org.apache.maven.plugins - maven-surefire-plugin - - - - org.apache.maven.plugins - maven-toolchains-plugin - - - - org.apache.rat - apache-rat-plugin - - - - com.github.hazendaz.maven - coveralls-maven-plugin - - - - io.github.git-commit-id - git-commit-id-maven-plugin - - - - org.jacoco - jacoco-maven-plugin - - - - - - - - - - nexus-jars - - - - - io.github.git-commit-id - git-commit-id-maven-plugin - ${git-commit-id-maven-plugin.version} - - - get-the-git-infos - - revision - - initialize - - - - ${project.basedir}/.git - UTC - false - false - json - true - ${project.build.directory}/git.properties - - false - true - full - - git.branch - git.commit.id.full - git.commit.time - git.commit.user.email - git.tags - - - false - true - 7 - -dirty - true - true - - - - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven-jar-plugin.version} - - - default-jar - - jar - - - - default-test-jar - - test-jar - - - - - - - false - false - true - true - - - org.apache.datasketches - The Apache Software Foundation - ${project.groupId}:${project.artifactId} - - - ${git.branch} - - ${git.commit.id.full} - - ${git.commit.time} - - ${git.commit.user.email} - - ${git.tags} - - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - ${maven-gpg-plugin.version} - - - sign-artifacts - verify - - sign - - - - - - --verbose - - --personal-digest-preferences=SHA512 - - - - - - - - - io.github.git-commit-id - git-commit-id-maven-plugin - - - org.apache.maven.plugins - maven-jar-plugin - - - org.apache.maven.plugins - maven-gpg-plugin - - - - - - - generate-java-files - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${testng.generate-java-files} - ${testng.check-cpp-files},${testng.check-go-files},${testng.check-cpp-historical-files} - - - - - - - - - check-cpp-files - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${testng.check-cpp-files} - ${testng.generate-java-files},${testng.check-go-files},${testng.check-cpp-historical-files} - - - - - - - - - check-go-files - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${testng.check-go-files} - ${testng.generate-java-files},${testng.check-cpp-files},${testng.check-cpp-historical-files} - - - - - - - - - - check-cpp-historical-files - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${testng.check-cpp-historical-files} - ${testng.generate-java-files},${testng.check-go-files},${testng.check-cpp-files} - - - - - - - - - - diff --git a/serialization_test_data/cpp_generated_files/aod_1_n0_cpp.sk b/serialization_test_data/cpp_generated_files/aod_1_n0_cpp.sk new file mode 100644 index 000000000..422b45e9c --- /dev/null +++ b/serialization_test_data/cpp_generated_files/aod_1_n0_cpp.sk @@ -0,0 +1 @@ + ̓ \ No newline at end of file diff --git a/serialization_test_data/cpp_generated_files/aod_1_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/aod_1_n1000000_cpp.sk new file mode 100644 index 000000000..14addf057 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_1_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_1_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/aod_1_n100000_cpp.sk new file mode 100644 index 000000000..4885fe85e Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_1_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_1_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/aod_1_n10000_cpp.sk new file mode 100644 index 000000000..bd039c5df Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_1_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_1_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/aod_1_n1000_cpp.sk new file mode 100644 index 000000000..4acb492f3 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_1_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_1_n100_cpp.sk b/serialization_test_data/cpp_generated_files/aod_1_n100_cpp.sk new file mode 100644 index 000000000..a14948ade Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_1_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_1_n10_cpp.sk b/serialization_test_data/cpp_generated_files/aod_1_n10_cpp.sk new file mode 100644 index 000000000..ac09b4e3c Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_1_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_1_n1_cpp.sk b/serialization_test_data/cpp_generated_files/aod_1_n1_cpp.sk new file mode 100644 index 000000000..0f5d47606 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_1_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_1_non_empty_no_entries_cpp.sk b/serialization_test_data/cpp_generated_files/aod_1_non_empty_no_entries_cpp.sk new file mode 100644 index 000000000..47d55f065 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_1_non_empty_no_entries_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_3_n0_cpp.sk b/serialization_test_data/cpp_generated_files/aod_3_n0_cpp.sk new file mode 100644 index 000000000..48185c22e --- /dev/null +++ b/serialization_test_data/cpp_generated_files/aod_3_n0_cpp.sk @@ -0,0 +1 @@ + ̓ \ No newline at end of file diff --git a/serialization_test_data/cpp_generated_files/aod_3_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/aod_3_n1000000_cpp.sk new file mode 100644 index 000000000..3e7abe73a Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_3_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_3_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/aod_3_n100000_cpp.sk new file mode 100644 index 000000000..e7441c519 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_3_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_3_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/aod_3_n10000_cpp.sk new file mode 100644 index 000000000..b0aeeb9dc Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_3_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_3_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/aod_3_n1000_cpp.sk new file mode 100644 index 000000000..0f3cc9c63 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_3_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_3_n100_cpp.sk b/serialization_test_data/cpp_generated_files/aod_3_n100_cpp.sk new file mode 100644 index 000000000..fd60dede5 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_3_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_3_n10_cpp.sk b/serialization_test_data/cpp_generated_files/aod_3_n10_cpp.sk new file mode 100644 index 000000000..28642641d Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_3_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/aod_3_n1_cpp.sk b/serialization_test_data/cpp_generated_files/aod_3_n1_cpp.sk new file mode 100644 index 000000000..265f4d154 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/aod_3_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/bf_n0_h3_cpp.sk b/serialization_test_data/cpp_generated_files/bf_n0_h3_cpp.sk new file mode 100644 index 000000000..cf7dd250d Binary files /dev/null and b/serialization_test_data/cpp_generated_files/bf_n0_h3_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/bf_n0_h5_cpp.sk b/serialization_test_data/cpp_generated_files/bf_n0_h5_cpp.sk new file mode 100644 index 000000000..f0dad2e76 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/bf_n0_h5_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/bf_n10000_h3_cpp.sk b/serialization_test_data/cpp_generated_files/bf_n10000_h3_cpp.sk new file mode 100644 index 000000000..bdef7325b Binary files /dev/null and b/serialization_test_data/cpp_generated_files/bf_n10000_h3_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/bf_n10000_h5_cpp.sk b/serialization_test_data/cpp_generated_files/bf_n10000_h5_cpp.sk new file mode 100644 index 000000000..2e09bd470 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/bf_n10000_h5_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/bf_n2000000_h3_cpp.sk b/serialization_test_data/cpp_generated_files/bf_n2000000_h3_cpp.sk new file mode 100644 index 000000000..5ac0166e1 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/bf_n2000000_h3_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/bf_n2000000_h5_cpp.sk b/serialization_test_data/cpp_generated_files/bf_n2000000_h5_cpp.sk new file mode 100644 index 000000000..72cd9f24c Binary files /dev/null and b/serialization_test_data/cpp_generated_files/bf_n2000000_h5_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/bf_n30000000_h3_cpp.sk b/serialization_test_data/cpp_generated_files/bf_n30000000_h3_cpp.sk new file mode 100644 index 000000000..1242db509 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/bf_n30000000_h3_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/bf_n30000000_h5_cpp.sk b/serialization_test_data/cpp_generated_files/bf_n30000000_h5_cpp.sk new file mode 100644 index 000000000..53d41037a Binary files /dev/null and b/serialization_test_data/cpp_generated_files/bf_n30000000_h5_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/cpc_n0_cpp.sk b/serialization_test_data/cpp_generated_files/cpc_n0_cpp.sk new file mode 100644 index 000000000..a25dd58c8 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/cpc_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/cpc_n100_cpp.sk b/serialization_test_data/cpp_generated_files/cpc_n100_cpp.sk new file mode 100644 index 000000000..ba1424272 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/cpc_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/cpc_n20000_cpp.sk b/serialization_test_data/cpp_generated_files/cpc_n20000_cpp.sk new file mode 100644 index 000000000..49508e900 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/cpc_n20000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/cpc_n2000_cpp.sk b/serialization_test_data/cpp_generated_files/cpc_n2000_cpp.sk new file mode 100644 index 000000000..b9b238fe5 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/cpc_n2000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/cpc_n200_cpp.sk b/serialization_test_data/cpp_generated_files/cpc_n200_cpp.sk new file mode 100644 index 000000000..a237fd863 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/cpc_n200_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_long_n0_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_long_n0_cpp.sk new file mode 100644 index 000000000..12d493c6d Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_long_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_long_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_long_n1000000_cpp.sk new file mode 100644 index 000000000..82ab32964 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_long_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_long_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_long_n100000_cpp.sk new file mode 100644 index 000000000..789b07663 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_long_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_long_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_long_n10000_cpp.sk new file mode 100644 index 000000000..55f33348a Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_long_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_long_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_long_n1000_cpp.sk new file mode 100644 index 000000000..8c3ab962c Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_long_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_long_n100_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_long_n100_cpp.sk new file mode 100644 index 000000000..4cfa8d830 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_long_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_long_n10_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_long_n10_cpp.sk new file mode 100644 index 000000000..0aa24d331 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_long_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_long_n1_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_long_n1_cpp.sk new file mode 100644 index 000000000..079515139 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_long_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_string_ascii_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_string_ascii_cpp.sk new file mode 100644 index 000000000..46aeb9a9c Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_string_ascii_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_string_n0_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_string_n0_cpp.sk new file mode 100644 index 000000000..12d493c6d Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_string_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_string_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_string_n1000000_cpp.sk new file mode 100644 index 000000000..e52a2c427 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_string_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_string_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_string_n100000_cpp.sk new file mode 100644 index 000000000..96a8b8049 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_string_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_string_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_string_n10000_cpp.sk new file mode 100644 index 000000000..48ffd2d60 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_string_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_string_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_string_n1000_cpp.sk new file mode 100644 index 000000000..848b52939 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_string_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_string_n100_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_string_n100_cpp.sk new file mode 100644 index 000000000..9531d72a3 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_string_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_string_n10_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_string_n10_cpp.sk new file mode 100644 index 000000000..7dc0bed97 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_string_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_string_n1_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_string_n1_cpp.sk new file mode 100644 index 000000000..b61ea204e Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_string_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/frequent_string_utf8_cpp.sk b/serialization_test_data/cpp_generated_files/frequent_string_utf8_cpp.sk new file mode 100644 index 000000000..0f9da5209 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/frequent_string_utf8_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll4_n0_cpp.sk b/serialization_test_data/cpp_generated_files/hll4_n0_cpp.sk new file mode 100644 index 000000000..074868c23 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll4_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll4_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/hll4_n1000000_cpp.sk new file mode 100644 index 000000000..9a8c62616 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll4_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll4_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/hll4_n100000_cpp.sk new file mode 100644 index 000000000..2b4b4dc7f Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll4_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll4_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/hll4_n10000_cpp.sk new file mode 100644 index 000000000..e97b1815b Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll4_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll4_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/hll4_n1000_cpp.sk new file mode 100644 index 000000000..a6b5f9aa2 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll4_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll4_n100_cpp.sk b/serialization_test_data/cpp_generated_files/hll4_n100_cpp.sk new file mode 100644 index 000000000..0e12ff4ac Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll4_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll4_n10_cpp.sk b/serialization_test_data/cpp_generated_files/hll4_n10_cpp.sk new file mode 100644 index 000000000..e4ed655d7 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll4_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll4_n1_cpp.sk b/serialization_test_data/cpp_generated_files/hll4_n1_cpp.sk new file mode 100644 index 000000000..1f4f6eedb Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll4_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll6_n0_cpp.sk b/serialization_test_data/cpp_generated_files/hll6_n0_cpp.sk new file mode 100644 index 000000000..c31bd2693 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll6_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll6_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/hll6_n1000000_cpp.sk new file mode 100644 index 000000000..a51d1e0ac Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll6_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll6_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/hll6_n100000_cpp.sk new file mode 100644 index 000000000..aba532bef Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll6_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll6_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/hll6_n10000_cpp.sk new file mode 100644 index 000000000..cd49aad2d Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll6_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll6_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/hll6_n1000_cpp.sk new file mode 100644 index 000000000..e3d5f00e6 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll6_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll6_n100_cpp.sk b/serialization_test_data/cpp_generated_files/hll6_n100_cpp.sk new file mode 100644 index 000000000..71fc293ba Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll6_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll6_n10_cpp.sk b/serialization_test_data/cpp_generated_files/hll6_n10_cpp.sk new file mode 100644 index 000000000..2a22d9137 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll6_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll6_n1_cpp.sk b/serialization_test_data/cpp_generated_files/hll6_n1_cpp.sk new file mode 100644 index 000000000..3f2f5450b --- /dev/null +++ b/serialization_test_data/cpp_generated_files/hll6_n1_cpp.sk @@ -0,0 +1 @@ +  \ No newline at end of file diff --git a/serialization_test_data/cpp_generated_files/hll8_n0_cpp.sk b/serialization_test_data/cpp_generated_files/hll8_n0_cpp.sk new file mode 100644 index 000000000..5ecf871d9 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll8_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll8_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/hll8_n1000000_cpp.sk new file mode 100644 index 000000000..67ec831d0 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll8_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll8_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/hll8_n100000_cpp.sk new file mode 100644 index 000000000..0210961c6 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll8_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll8_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/hll8_n10000_cpp.sk new file mode 100644 index 000000000..a5c8a1544 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll8_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll8_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/hll8_n1000_cpp.sk new file mode 100644 index 000000000..dd703ecbf Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll8_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll8_n100_cpp.sk b/serialization_test_data/cpp_generated_files/hll8_n100_cpp.sk new file mode 100644 index 000000000..c2bfa4891 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll8_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll8_n10_cpp.sk b/serialization_test_data/cpp_generated_files/hll8_n10_cpp.sk new file mode 100644 index 000000000..86277b3a1 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/hll8_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/hll8_n1_cpp.sk b/serialization_test_data/cpp_generated_files/hll8_n1_cpp.sk new file mode 100644 index 000000000..fd3a97327 --- /dev/null +++ b/serialization_test_data/cpp_generated_files/hll8_n1_cpp.sk @@ -0,0 +1 @@ +  \ No newline at end of file diff --git a/serialization_test_data/cpp_generated_files/kll_double_n0_cpp.sk b/serialization_test_data/cpp_generated_files/kll_double_n0_cpp.sk new file mode 100644 index 000000000..afd220927 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_double_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_double_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/kll_double_n1000000_cpp.sk new file mode 100644 index 000000000..270b0f997 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_double_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_double_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/kll_double_n100000_cpp.sk new file mode 100644 index 000000000..be1539bd0 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_double_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_double_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/kll_double_n10000_cpp.sk new file mode 100644 index 000000000..49a9ab78f Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_double_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_double_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/kll_double_n1000_cpp.sk new file mode 100644 index 000000000..01c25b658 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_double_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_double_n100_cpp.sk b/serialization_test_data/cpp_generated_files/kll_double_n100_cpp.sk new file mode 100644 index 000000000..b0d578acd Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_double_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_double_n10_cpp.sk b/serialization_test_data/cpp_generated_files/kll_double_n10_cpp.sk new file mode 100644 index 000000000..fb526efa3 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_double_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_double_n1_cpp.sk b/serialization_test_data/cpp_generated_files/kll_double_n1_cpp.sk new file mode 100644 index 000000000..5eceb4061 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_double_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_float_n0_cpp.sk b/serialization_test_data/cpp_generated_files/kll_float_n0_cpp.sk new file mode 100644 index 000000000..afd220927 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_float_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_float_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/kll_float_n1000000_cpp.sk new file mode 100644 index 000000000..357a5bb62 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_float_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_float_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/kll_float_n100000_cpp.sk new file mode 100644 index 000000000..e6c94e59d Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_float_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_float_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/kll_float_n10000_cpp.sk new file mode 100644 index 000000000..66124f2ee Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_float_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_float_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/kll_float_n1000_cpp.sk new file mode 100644 index 000000000..89ec27d92 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_float_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_float_n100_cpp.sk b/serialization_test_data/cpp_generated_files/kll_float_n100_cpp.sk new file mode 100644 index 000000000..ad45e6415 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_float_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_float_n10_cpp.sk b/serialization_test_data/cpp_generated_files/kll_float_n10_cpp.sk new file mode 100644 index 000000000..1fd87d306 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_float_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_float_n1_cpp.sk b/serialization_test_data/cpp_generated_files/kll_float_n1_cpp.sk new file mode 100644 index 000000000..f7f9d22fc Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_float_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_string_n0_cpp.sk b/serialization_test_data/cpp_generated_files/kll_string_n0_cpp.sk new file mode 100644 index 000000000..afd220927 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_string_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_string_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/kll_string_n1000000_cpp.sk new file mode 100644 index 000000000..bfaea5967 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_string_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_string_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/kll_string_n100000_cpp.sk new file mode 100644 index 000000000..730ee7ed9 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_string_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_string_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/kll_string_n10000_cpp.sk new file mode 100644 index 000000000..cb8982e1b Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_string_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_string_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/kll_string_n1000_cpp.sk new file mode 100644 index 000000000..dd6d1acc5 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_string_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_string_n100_cpp.sk b/serialization_test_data/cpp_generated_files/kll_string_n100_cpp.sk new file mode 100644 index 000000000..8e0bedaa9 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_string_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_string_n10_cpp.sk b/serialization_test_data/cpp_generated_files/kll_string_n10_cpp.sk new file mode 100644 index 000000000..8cd25fcca Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_string_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/kll_string_n1_cpp.sk b/serialization_test_data/cpp_generated_files/kll_string_n1_cpp.sk new file mode 100644 index 000000000..38f8253cb Binary files /dev/null and b/serialization_test_data/cpp_generated_files/kll_string_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_double_n0_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_double_n0_cpp.sk new file mode 100644 index 000000000..0d8d09316 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_double_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_double_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_double_n1000000_cpp.sk new file mode 100644 index 000000000..d591111be Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_double_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_double_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_double_n100000_cpp.sk new file mode 100644 index 000000000..b3bac266b Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_double_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_double_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_double_n10000_cpp.sk new file mode 100644 index 000000000..c2d266645 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_double_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_double_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_double_n1000_cpp.sk new file mode 100644 index 000000000..ac38e35fe Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_double_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_double_n100_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_double_n100_cpp.sk new file mode 100644 index 000000000..7fdcc62f0 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_double_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_double_n10_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_double_n10_cpp.sk new file mode 100644 index 000000000..566b7d0ee Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_double_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_double_n1_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_double_n1_cpp.sk new file mode 100644 index 000000000..9dfb23e6c Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_double_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_string_n0_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_string_n0_cpp.sk new file mode 100644 index 000000000..0d8d09316 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_string_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_string_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_string_n1000000_cpp.sk new file mode 100644 index 000000000..b4eb34103 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_string_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_string_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_string_n100000_cpp.sk new file mode 100644 index 000000000..c5240cbf1 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_string_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_string_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_string_n10000_cpp.sk new file mode 100644 index 000000000..881987d91 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_string_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_string_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_string_n1000_cpp.sk new file mode 100644 index 000000000..f943cfc98 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_string_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_string_n100_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_string_n100_cpp.sk new file mode 100644 index 000000000..1af9f9f91 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_string_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_string_n10_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_string_n10_cpp.sk new file mode 100644 index 000000000..d35aed384 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_string_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/quantiles_string_n1_cpp.sk b/serialization_test_data/cpp_generated_files/quantiles_string_n1_cpp.sk new file mode 100644 index 000000000..895fdc110 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/quantiles_string_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/req_float_n0_cpp.sk b/serialization_test_data/cpp_generated_files/req_float_n0_cpp.sk new file mode 100644 index 000000000..1623b7283 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/req_float_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/req_float_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/req_float_n1000000_cpp.sk new file mode 100644 index 000000000..b06966a8f Binary files /dev/null and b/serialization_test_data/cpp_generated_files/req_float_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/req_float_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/req_float_n100000_cpp.sk new file mode 100644 index 000000000..299ea81df Binary files /dev/null and b/serialization_test_data/cpp_generated_files/req_float_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/req_float_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/req_float_n10000_cpp.sk new file mode 100644 index 000000000..5727cf480 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/req_float_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/req_float_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/req_float_n1000_cpp.sk new file mode 100644 index 000000000..13402eb96 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/req_float_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/req_float_n100_cpp.sk b/serialization_test_data/cpp_generated_files/req_float_n100_cpp.sk new file mode 100644 index 000000000..e5eabd63c Binary files /dev/null and b/serialization_test_data/cpp_generated_files/req_float_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/req_float_n10_cpp.sk b/serialization_test_data/cpp_generated_files/req_float_n10_cpp.sk new file mode 100644 index 000000000..157173c0b Binary files /dev/null and b/serialization_test_data/cpp_generated_files/req_float_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/req_float_n1_cpp.sk b/serialization_test_data/cpp_generated_files/req_float_n1_cpp.sk new file mode 100644 index 000000000..2bcd059ae Binary files /dev/null and b/serialization_test_data/cpp_generated_files/req_float_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_buf_n0_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n0_cpp.sk new file mode 100644 index 000000000..e84c2ea50 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_buf_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n1000000_cpp.sk new file mode 100644 index 000000000..e488b6a30 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_buf_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n100000_cpp.sk new file mode 100644 index 000000000..9616a8194 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_buf_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n10000_cpp.sk new file mode 100644 index 000000000..0958b673f Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_buf_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n1000_cpp.sk new file mode 100644 index 000000000..8a1bdff0c Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_buf_n100_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n100_cpp.sk new file mode 100644 index 000000000..d6d76074f Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_buf_n10_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n10_cpp.sk new file mode 100644 index 000000000..1bab9718b Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_buf_n1_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n1_cpp.sk new file mode 100644 index 000000000..802a0bde3 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_buf_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_n0_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_n0_cpp.sk new file mode 100644 index 000000000..e84c2ea50 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_n1000000_cpp.sk new file mode 100644 index 000000000..6b87e1eeb Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_n100000_cpp.sk new file mode 100644 index 000000000..fbb27272e Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_n10000_cpp.sk new file mode 100644 index 000000000..290ceadd8 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_n1000_cpp.sk new file mode 100644 index 000000000..7832fc376 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_n100_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_n100_cpp.sk new file mode 100644 index 000000000..9d1d60a90 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_n10_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_n10_cpp.sk new file mode 100644 index 000000000..2c1026eed Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_double_n1_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_double_n1_cpp.sk new file mode 100644 index 000000000..971919e7f Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_double_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_buf_n0_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n0_cpp.sk new file mode 100644 index 000000000..e84c2ea50 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_buf_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n1000000_cpp.sk new file mode 100644 index 000000000..4b97486a5 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_buf_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n100000_cpp.sk new file mode 100644 index 000000000..efe220d12 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_buf_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n10000_cpp.sk new file mode 100644 index 000000000..e7ceecf8d Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_buf_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n1000_cpp.sk new file mode 100644 index 000000000..830158a48 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_buf_n100_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n100_cpp.sk new file mode 100644 index 000000000..4e627704e Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_buf_n10_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n10_cpp.sk new file mode 100644 index 000000000..7f6e62d9d Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_buf_n1_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n1_cpp.sk new file mode 100644 index 000000000..7fea70f9b Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_buf_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_n0_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_n0_cpp.sk new file mode 100644 index 000000000..e84c2ea50 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_n1000000_cpp.sk new file mode 100644 index 000000000..99987486f Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_n100000_cpp.sk new file mode 100644 index 000000000..8e635dbeb Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_n10000_cpp.sk new file mode 100644 index 000000000..c89d39292 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_n1000_cpp.sk new file mode 100644 index 000000000..e5d099c7f Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_n100_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_n100_cpp.sk new file mode 100644 index 000000000..ae8a5ece3 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_n10_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_n10_cpp.sk new file mode 100644 index 000000000..63e5ce8a0 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tdigest_float_n1_cpp.sk b/serialization_test_data/cpp_generated_files/tdigest_float_n1_cpp.sk new file mode 100644 index 000000000..94e38d9dc Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tdigest_float_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_compressed_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/theta_compressed_n1000000_cpp.sk new file mode 100644 index 000000000..26e2371cf Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_compressed_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_compressed_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/theta_compressed_n100000_cpp.sk new file mode 100644 index 000000000..3998ae4c8 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_compressed_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_compressed_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/theta_compressed_n10000_cpp.sk new file mode 100644 index 000000000..33459ef50 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_compressed_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_compressed_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/theta_compressed_n1000_cpp.sk new file mode 100644 index 000000000..1fdec7903 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_compressed_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_compressed_n100_cpp.sk b/serialization_test_data/cpp_generated_files/theta_compressed_n100_cpp.sk new file mode 100644 index 000000000..6f8b4e934 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_compressed_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_compressed_n10_cpp.sk b/serialization_test_data/cpp_generated_files/theta_compressed_n10_cpp.sk new file mode 100644 index 000000000..6f81c038a --- /dev/null +++ b/serialization_test_data/cpp_generated_files/theta_compressed_n10_cpp.sk @@ -0,0 +1,2 @@ +>̓ +-T)P[Rc;"JHe0Bg?-}Hn P`i5 e5 B` \ No newline at end of file diff --git a/serialization_test_data/cpp_generated_files/theta_n0_cpp.sk b/serialization_test_data/cpp_generated_files/theta_n0_cpp.sk new file mode 100644 index 000000000..44730d3f0 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/theta_n1000000_cpp.sk new file mode 100644 index 000000000..292e294fd Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/theta_n100000_cpp.sk new file mode 100644 index 000000000..8b5c86104 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/theta_n10000_cpp.sk new file mode 100644 index 000000000..eb9db24b8 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/theta_n1000_cpp.sk new file mode 100644 index 000000000..65610e3f8 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_n100_cpp.sk b/serialization_test_data/cpp_generated_files/theta_n100_cpp.sk new file mode 100644 index 000000000..0ab7727d8 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_n10_cpp.sk b/serialization_test_data/cpp_generated_files/theta_n10_cpp.sk new file mode 100644 index 000000000..8c74f705c Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_n1_cpp.sk b/serialization_test_data/cpp_generated_files/theta_n1_cpp.sk new file mode 100644 index 000000000..e266ee5ec Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/theta_non_empty_no_entries_cpp.sk b/serialization_test_data/cpp_generated_files/theta_non_empty_no_entries_cpp.sk new file mode 100644 index 000000000..f6f3a1905 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/theta_non_empty_no_entries_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tuple_int_n0_cpp.sk b/serialization_test_data/cpp_generated_files/tuple_int_n0_cpp.sk new file mode 100644 index 000000000..a95f16347 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tuple_int_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tuple_int_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/tuple_int_n1000000_cpp.sk new file mode 100644 index 000000000..699d293bd Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tuple_int_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tuple_int_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/tuple_int_n100000_cpp.sk new file mode 100644 index 000000000..799c24fe1 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tuple_int_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tuple_int_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/tuple_int_n10000_cpp.sk new file mode 100644 index 000000000..57173baca Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tuple_int_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tuple_int_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/tuple_int_n1000_cpp.sk new file mode 100644 index 000000000..3ff49a8a3 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tuple_int_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tuple_int_n100_cpp.sk b/serialization_test_data/cpp_generated_files/tuple_int_n100_cpp.sk new file mode 100644 index 000000000..885632f6e Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tuple_int_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tuple_int_n10_cpp.sk b/serialization_test_data/cpp_generated_files/tuple_int_n10_cpp.sk new file mode 100644 index 000000000..6a5a5f41e Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tuple_int_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/tuple_int_n1_cpp.sk b/serialization_test_data/cpp_generated_files/tuple_int_n1_cpp.sk new file mode 100644 index 000000000..2e263f371 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/tuple_int_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/varopt_sketch_long_n0_cpp.sk b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n0_cpp.sk new file mode 100644 index 000000000..e4505fe12 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n0_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/varopt_sketch_long_n1000000_cpp.sk b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n1000000_cpp.sk new file mode 100644 index 000000000..ca97372f2 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n1000000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/varopt_sketch_long_n100000_cpp.sk b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n100000_cpp.sk new file mode 100644 index 000000000..cbc476e4c Binary files /dev/null and b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n100000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/varopt_sketch_long_n10000_cpp.sk b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n10000_cpp.sk new file mode 100644 index 000000000..77947e090 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n10000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/varopt_sketch_long_n1000_cpp.sk b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n1000_cpp.sk new file mode 100644 index 000000000..161fd4701 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n1000_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/varopt_sketch_long_n100_cpp.sk b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n100_cpp.sk new file mode 100644 index 000000000..0f9903d3a Binary files /dev/null and b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n100_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/varopt_sketch_long_n10_cpp.sk b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n10_cpp.sk new file mode 100644 index 000000000..f1ac8c072 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n10_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/varopt_sketch_long_n1_cpp.sk b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n1_cpp.sk new file mode 100644 index 000000000..86f6bc320 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/varopt_sketch_long_n1_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/varopt_sketch_long_sampling_cpp.sk b/serialization_test_data/cpp_generated_files/varopt_sketch_long_sampling_cpp.sk new file mode 100644 index 000000000..b57830f8a Binary files /dev/null and b/serialization_test_data/cpp_generated_files/varopt_sketch_long_sampling_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/varopt_sketch_string_exact_cpp.sk b/serialization_test_data/cpp_generated_files/varopt_sketch_string_exact_cpp.sk new file mode 100644 index 000000000..2da7e4ed2 Binary files /dev/null and b/serialization_test_data/cpp_generated_files/varopt_sketch_string_exact_cpp.sk differ diff --git a/serialization_test_data/cpp_generated_files/varopt_union_double_sampling_cpp.sk b/serialization_test_data/cpp_generated_files/varopt_union_double_sampling_cpp.sk new file mode 100644 index 000000000..d9149512d Binary files /dev/null and b/serialization_test_data/cpp_generated_files/varopt_union_double_sampling_cpp.sk differ diff --git a/serialization_test_data/go_generated_files/cpc_n0_go.sk b/serialization_test_data/go_generated_files/cpc_n0_go.sk new file mode 100644 index 000000000..a25dd58c8 Binary files /dev/null and b/serialization_test_data/go_generated_files/cpc_n0_go.sk differ diff --git a/serialization_test_data/go_generated_files/cpc_n100_go.sk b/serialization_test_data/go_generated_files/cpc_n100_go.sk new file mode 100644 index 000000000..f7288a2ad Binary files /dev/null and b/serialization_test_data/go_generated_files/cpc_n100_go.sk differ diff --git a/serialization_test_data/go_generated_files/cpc_n20000_go.sk b/serialization_test_data/go_generated_files/cpc_n20000_go.sk new file mode 100644 index 000000000..11cd238d3 Binary files /dev/null and b/serialization_test_data/go_generated_files/cpc_n20000_go.sk differ diff --git a/serialization_test_data/go_generated_files/cpc_n2000_go.sk b/serialization_test_data/go_generated_files/cpc_n2000_go.sk new file mode 100644 index 000000000..b3c1dfad3 Binary files /dev/null and b/serialization_test_data/go_generated_files/cpc_n2000_go.sk differ diff --git a/serialization_test_data/go_generated_files/cpc_n200_go.sk b/serialization_test_data/go_generated_files/cpc_n200_go.sk new file mode 100644 index 000000000..cc5afab38 Binary files /dev/null and b/serialization_test_data/go_generated_files/cpc_n200_go.sk differ diff --git a/serialization_test_data/go_generated_files/cpc_negative_one_go.sk b/serialization_test_data/go_generated_files/cpc_negative_one_go.sk new file mode 100644 index 000000000..476da8a1a Binary files /dev/null and b/serialization_test_data/go_generated_files/cpc_negative_one_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll4_n0_go.sk b/serialization_test_data/go_generated_files/hll4_n0_go.sk new file mode 100644 index 000000000..074868c23 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll4_n0_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll4_n1000000_go.sk b/serialization_test_data/go_generated_files/hll4_n1000000_go.sk new file mode 100644 index 000000000..9a8c62616 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll4_n1000000_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll4_n100000_go.sk b/serialization_test_data/go_generated_files/hll4_n100000_go.sk new file mode 100644 index 000000000..2b4b4dc7f Binary files /dev/null and b/serialization_test_data/go_generated_files/hll4_n100000_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll4_n10000_go.sk b/serialization_test_data/go_generated_files/hll4_n10000_go.sk new file mode 100644 index 000000000..e97b1815b Binary files /dev/null and b/serialization_test_data/go_generated_files/hll4_n10000_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll4_n1000_go.sk b/serialization_test_data/go_generated_files/hll4_n1000_go.sk new file mode 100644 index 000000000..a6b5f9aa2 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll4_n1000_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll4_n100_go.sk b/serialization_test_data/go_generated_files/hll4_n100_go.sk new file mode 100644 index 000000000..0e12ff4ac Binary files /dev/null and b/serialization_test_data/go_generated_files/hll4_n100_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll4_n10_go.sk b/serialization_test_data/go_generated_files/hll4_n10_go.sk new file mode 100644 index 000000000..e4ed655d7 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll4_n10_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll4_n1_go.sk b/serialization_test_data/go_generated_files/hll4_n1_go.sk new file mode 100644 index 000000000..1f4f6eedb Binary files /dev/null and b/serialization_test_data/go_generated_files/hll4_n1_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll6_n0_go.sk b/serialization_test_data/go_generated_files/hll6_n0_go.sk new file mode 100644 index 000000000..c31bd2693 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll6_n0_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll6_n1000000_go.sk b/serialization_test_data/go_generated_files/hll6_n1000000_go.sk new file mode 100644 index 000000000..42462d2d9 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll6_n1000000_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll6_n100000_go.sk b/serialization_test_data/go_generated_files/hll6_n100000_go.sk new file mode 100644 index 000000000..767f24f9a Binary files /dev/null and b/serialization_test_data/go_generated_files/hll6_n100000_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll6_n10000_go.sk b/serialization_test_data/go_generated_files/hll6_n10000_go.sk new file mode 100644 index 000000000..258da0889 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll6_n10000_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll6_n1000_go.sk b/serialization_test_data/go_generated_files/hll6_n1000_go.sk new file mode 100644 index 000000000..274e8b7ec Binary files /dev/null and b/serialization_test_data/go_generated_files/hll6_n1000_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll6_n100_go.sk b/serialization_test_data/go_generated_files/hll6_n100_go.sk new file mode 100644 index 000000000..71fc293ba Binary files /dev/null and b/serialization_test_data/go_generated_files/hll6_n100_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll6_n10_go.sk b/serialization_test_data/go_generated_files/hll6_n10_go.sk new file mode 100644 index 000000000..2a22d9137 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll6_n10_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll6_n1_go.sk b/serialization_test_data/go_generated_files/hll6_n1_go.sk new file mode 100644 index 000000000..3f2f5450b --- /dev/null +++ b/serialization_test_data/go_generated_files/hll6_n1_go.sk @@ -0,0 +1 @@ +  \ No newline at end of file diff --git a/serialization_test_data/go_generated_files/hll8_n0_go.sk b/serialization_test_data/go_generated_files/hll8_n0_go.sk new file mode 100644 index 000000000..5ecf871d9 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll8_n0_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll8_n1000000_go.sk b/serialization_test_data/go_generated_files/hll8_n1000000_go.sk new file mode 100644 index 000000000..e7f5f4821 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll8_n1000000_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll8_n100000_go.sk b/serialization_test_data/go_generated_files/hll8_n100000_go.sk new file mode 100644 index 000000000..c634e4986 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll8_n100000_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll8_n10000_go.sk b/serialization_test_data/go_generated_files/hll8_n10000_go.sk new file mode 100644 index 000000000..f8dfdb0c9 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll8_n10000_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll8_n1000_go.sk b/serialization_test_data/go_generated_files/hll8_n1000_go.sk new file mode 100644 index 000000000..761477d5f Binary files /dev/null and b/serialization_test_data/go_generated_files/hll8_n1000_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll8_n100_go.sk b/serialization_test_data/go_generated_files/hll8_n100_go.sk new file mode 100644 index 000000000..c2bfa4891 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll8_n100_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll8_n10_go.sk b/serialization_test_data/go_generated_files/hll8_n10_go.sk new file mode 100644 index 000000000..86277b3a1 Binary files /dev/null and b/serialization_test_data/go_generated_files/hll8_n10_go.sk differ diff --git a/serialization_test_data/go_generated_files/hll8_n1_go.sk b/serialization_test_data/go_generated_files/hll8_n1_go.sk new file mode 100644 index 000000000..fd3a97327 --- /dev/null +++ b/serialization_test_data/go_generated_files/hll8_n1_go.sk @@ -0,0 +1 @@ +  \ No newline at end of file diff --git a/serialization_test_data/java_generated_files/aod_1_n0_java.sk b/serialization_test_data/java_generated_files/aod_1_n0_java.sk new file mode 100644 index 000000000..8d2583d54 --- /dev/null +++ b/serialization_test_data/java_generated_files/aod_1_n0_java.sk @@ -0,0 +1 @@ + ̓ \ No newline at end of file diff --git a/serialization_test_data/java_generated_files/aod_1_n1000000_java.sk b/serialization_test_data/java_generated_files/aod_1_n1000000_java.sk new file mode 100644 index 000000000..e220427f8 Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_1_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_1_n100000_java.sk b/serialization_test_data/java_generated_files/aod_1_n100000_java.sk new file mode 100644 index 000000000..dda27e628 Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_1_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_1_n10000_java.sk b/serialization_test_data/java_generated_files/aod_1_n10000_java.sk new file mode 100644 index 000000000..8522d5a22 Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_1_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_1_n1000_java.sk b/serialization_test_data/java_generated_files/aod_1_n1000_java.sk new file mode 100644 index 000000000..3e48b2e27 Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_1_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_1_n100_java.sk b/serialization_test_data/java_generated_files/aod_1_n100_java.sk new file mode 100644 index 000000000..95b83d7c7 Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_1_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_1_n10_java.sk b/serialization_test_data/java_generated_files/aod_1_n10_java.sk new file mode 100644 index 000000000..8b4265ba5 Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_1_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_1_n1_java.sk b/serialization_test_data/java_generated_files/aod_1_n1_java.sk new file mode 100644 index 000000000..66943098f Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_1_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_1_non_empty_no_entries_java.sk b/serialization_test_data/java_generated_files/aod_1_non_empty_no_entries_java.sk new file mode 100644 index 000000000..f67106d7e Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_1_non_empty_no_entries_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_3_n0_java.sk b/serialization_test_data/java_generated_files/aod_3_n0_java.sk new file mode 100644 index 000000000..1579d9bce --- /dev/null +++ b/serialization_test_data/java_generated_files/aod_3_n0_java.sk @@ -0,0 +1 @@ + ̓ \ No newline at end of file diff --git a/serialization_test_data/java_generated_files/aod_3_n1000000_java.sk b/serialization_test_data/java_generated_files/aod_3_n1000000_java.sk new file mode 100644 index 000000000..085dfba35 Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_3_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_3_n100000_java.sk b/serialization_test_data/java_generated_files/aod_3_n100000_java.sk new file mode 100644 index 000000000..3fd09f041 Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_3_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_3_n10000_java.sk b/serialization_test_data/java_generated_files/aod_3_n10000_java.sk new file mode 100644 index 000000000..045d3dbe6 Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_3_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_3_n1000_java.sk b/serialization_test_data/java_generated_files/aod_3_n1000_java.sk new file mode 100644 index 000000000..2e7d2c998 Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_3_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_3_n100_java.sk b/serialization_test_data/java_generated_files/aod_3_n100_java.sk new file mode 100644 index 000000000..c87ec6155 Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_3_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_3_n10_java.sk b/serialization_test_data/java_generated_files/aod_3_n10_java.sk new file mode 100644 index 000000000..78c941b6c Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_3_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/aod_3_n1_java.sk b/serialization_test_data/java_generated_files/aod_3_n1_java.sk new file mode 100644 index 000000000..d0b493693 Binary files /dev/null and b/serialization_test_data/java_generated_files/aod_3_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_1_n0_java.sk b/serialization_test_data/java_generated_files/aos_1_n0_java.sk new file mode 100644 index 000000000..f98290af3 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_1_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_1_n1000000_java.sk b/serialization_test_data/java_generated_files/aos_1_n1000000_java.sk new file mode 100644 index 000000000..f94fa1133 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_1_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_1_n100000_java.sk b/serialization_test_data/java_generated_files/aos_1_n100000_java.sk new file mode 100644 index 000000000..964a0ed17 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_1_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_1_n10000_java.sk b/serialization_test_data/java_generated_files/aos_1_n10000_java.sk new file mode 100644 index 000000000..11792d02d Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_1_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_1_n1000_java.sk b/serialization_test_data/java_generated_files/aos_1_n1000_java.sk new file mode 100644 index 000000000..0b9737c31 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_1_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_1_n100_java.sk b/serialization_test_data/java_generated_files/aos_1_n100_java.sk new file mode 100644 index 000000000..07444735f Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_1_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_1_n10_java.sk b/serialization_test_data/java_generated_files/aos_1_n10_java.sk new file mode 100644 index 000000000..df2c84aa8 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_1_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_1_n1_java.sk b/serialization_test_data/java_generated_files/aos_1_n1_java.sk new file mode 100644 index 000000000..e9df675e5 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_1_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_1_non_empty_no_entries_java.sk b/serialization_test_data/java_generated_files/aos_1_non_empty_no_entries_java.sk new file mode 100644 index 000000000..75ae90eab Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_1_non_empty_no_entries_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_3_n0_java.sk b/serialization_test_data/java_generated_files/aos_3_n0_java.sk new file mode 100644 index 000000000..f98290af3 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_3_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_3_n1000000_java.sk b/serialization_test_data/java_generated_files/aos_3_n1000000_java.sk new file mode 100644 index 000000000..19a77794d Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_3_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_3_n100000_java.sk b/serialization_test_data/java_generated_files/aos_3_n100000_java.sk new file mode 100644 index 000000000..e28cf2b59 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_3_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_3_n10000_java.sk b/serialization_test_data/java_generated_files/aos_3_n10000_java.sk new file mode 100644 index 000000000..34c16e7a9 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_3_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_3_n1000_java.sk b/serialization_test_data/java_generated_files/aos_3_n1000_java.sk new file mode 100644 index 000000000..3b45f9d72 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_3_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_3_n100_java.sk b/serialization_test_data/java_generated_files/aos_3_n100_java.sk new file mode 100644 index 000000000..76a97f51e Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_3_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_3_n10_java.sk b/serialization_test_data/java_generated_files/aos_3_n10_java.sk new file mode 100644 index 000000000..285587028 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_3_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_3_n1_java.sk b/serialization_test_data/java_generated_files/aos_3_n1_java.sk new file mode 100644 index 000000000..04cc0afa3 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_3_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_empty_strings_java.sk b/serialization_test_data/java_generated_files/aos_empty_strings_java.sk new file mode 100644 index 000000000..14ca4c0ce Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_empty_strings_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_multikey_n0_java.sk b/serialization_test_data/java_generated_files/aos_multikey_n0_java.sk new file mode 100644 index 000000000..f98290af3 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_multikey_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_multikey_n1000000_java.sk b/serialization_test_data/java_generated_files/aos_multikey_n1000000_java.sk new file mode 100644 index 000000000..25afc1135 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_multikey_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_multikey_n100000_java.sk b/serialization_test_data/java_generated_files/aos_multikey_n100000_java.sk new file mode 100644 index 000000000..c1ef2988c Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_multikey_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_multikey_n10000_java.sk b/serialization_test_data/java_generated_files/aos_multikey_n10000_java.sk new file mode 100644 index 000000000..e602df86c Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_multikey_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_multikey_n1000_java.sk b/serialization_test_data/java_generated_files/aos_multikey_n1000_java.sk new file mode 100644 index 000000000..d3e2f87c5 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_multikey_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_multikey_n100_java.sk b/serialization_test_data/java_generated_files/aos_multikey_n100_java.sk new file mode 100644 index 000000000..028548d02 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_multikey_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_multikey_n10_java.sk b/serialization_test_data/java_generated_files/aos_multikey_n10_java.sk new file mode 100644 index 000000000..8ad56f42c Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_multikey_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_multikey_n1_java.sk b/serialization_test_data/java_generated_files/aos_multikey_n1_java.sk new file mode 100644 index 000000000..68cc504f3 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_multikey_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/aos_unicode_java.sk b/serialization_test_data/java_generated_files/aos_unicode_java.sk new file mode 100644 index 000000000..11cc146d3 Binary files /dev/null and b/serialization_test_data/java_generated_files/aos_unicode_java.sk differ diff --git a/serialization_test_data/java_generated_files/bf_n0_h3_java.sk b/serialization_test_data/java_generated_files/bf_n0_h3_java.sk new file mode 100644 index 000000000..9ee326b3d Binary files /dev/null and b/serialization_test_data/java_generated_files/bf_n0_h3_java.sk differ diff --git a/serialization_test_data/java_generated_files/bf_n0_h5_java.sk b/serialization_test_data/java_generated_files/bf_n0_h5_java.sk new file mode 100644 index 000000000..43f4d319b Binary files /dev/null and b/serialization_test_data/java_generated_files/bf_n0_h5_java.sk differ diff --git a/serialization_test_data/java_generated_files/bf_n10000_h3_java.sk b/serialization_test_data/java_generated_files/bf_n10000_h3_java.sk new file mode 100644 index 000000000..f61396867 Binary files /dev/null and b/serialization_test_data/java_generated_files/bf_n10000_h3_java.sk differ diff --git a/serialization_test_data/java_generated_files/bf_n10000_h5_java.sk b/serialization_test_data/java_generated_files/bf_n10000_h5_java.sk new file mode 100644 index 000000000..095084620 Binary files /dev/null and b/serialization_test_data/java_generated_files/bf_n10000_h5_java.sk differ diff --git a/serialization_test_data/java_generated_files/bf_n2000000_h3_java.sk b/serialization_test_data/java_generated_files/bf_n2000000_h3_java.sk new file mode 100644 index 000000000..7c1ea2fcb Binary files /dev/null and b/serialization_test_data/java_generated_files/bf_n2000000_h3_java.sk differ diff --git a/serialization_test_data/java_generated_files/bf_n2000000_h5_java.sk b/serialization_test_data/java_generated_files/bf_n2000000_h5_java.sk new file mode 100644 index 000000000..c17343b70 Binary files /dev/null and b/serialization_test_data/java_generated_files/bf_n2000000_h5_java.sk differ diff --git a/serialization_test_data/java_generated_files/bf_n30000000_h3_java.sk b/serialization_test_data/java_generated_files/bf_n30000000_h3_java.sk new file mode 100644 index 000000000..91028492a Binary files /dev/null and b/serialization_test_data/java_generated_files/bf_n30000000_h3_java.sk differ diff --git a/serialization_test_data/java_generated_files/bf_n30000000_h5_java.sk b/serialization_test_data/java_generated_files/bf_n30000000_h5_java.sk new file mode 100644 index 000000000..5239de408 Binary files /dev/null and b/serialization_test_data/java_generated_files/bf_n30000000_h5_java.sk differ diff --git a/serialization_test_data/java_generated_files/cpc_n0_java.sk b/serialization_test_data/java_generated_files/cpc_n0_java.sk new file mode 100644 index 000000000..a25dd58c8 Binary files /dev/null and b/serialization_test_data/java_generated_files/cpc_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/cpc_n100_java.sk b/serialization_test_data/java_generated_files/cpc_n100_java.sk new file mode 100644 index 000000000..f7288a2ad Binary files /dev/null and b/serialization_test_data/java_generated_files/cpc_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/cpc_n20000_java.sk b/serialization_test_data/java_generated_files/cpc_n20000_java.sk new file mode 100644 index 000000000..11cd238d3 Binary files /dev/null and b/serialization_test_data/java_generated_files/cpc_n20000_java.sk differ diff --git a/serialization_test_data/java_generated_files/cpc_n2000_java.sk b/serialization_test_data/java_generated_files/cpc_n2000_java.sk new file mode 100644 index 000000000..b3c1dfad3 Binary files /dev/null and b/serialization_test_data/java_generated_files/cpc_n2000_java.sk differ diff --git a/serialization_test_data/java_generated_files/cpc_n200_java.sk b/serialization_test_data/java_generated_files/cpc_n200_java.sk new file mode 100644 index 000000000..cc5afab38 Binary files /dev/null and b/serialization_test_data/java_generated_files/cpc_n200_java.sk differ diff --git a/serialization_test_data/java_generated_files/cpc_negative_one_java.sk b/serialization_test_data/java_generated_files/cpc_negative_one_java.sk new file mode 100644 index 000000000..10bb629a3 Binary files /dev/null and b/serialization_test_data/java_generated_files/cpc_negative_one_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_long_n0_java.sk b/serialization_test_data/java_generated_files/frequent_long_n0_java.sk new file mode 100644 index 000000000..12d493c6d Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_long_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_long_n1000000_java.sk b/serialization_test_data/java_generated_files/frequent_long_n1000000_java.sk new file mode 100644 index 000000000..bef5842f2 Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_long_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_long_n100000_java.sk b/serialization_test_data/java_generated_files/frequent_long_n100000_java.sk new file mode 100644 index 000000000..d3159f07d Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_long_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_long_n10000_java.sk b/serialization_test_data/java_generated_files/frequent_long_n10000_java.sk new file mode 100644 index 000000000..66043bb59 Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_long_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_long_n1000_java.sk b/serialization_test_data/java_generated_files/frequent_long_n1000_java.sk new file mode 100644 index 000000000..b9df3c7c7 Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_long_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_long_n100_java.sk b/serialization_test_data/java_generated_files/frequent_long_n100_java.sk new file mode 100644 index 000000000..4cfa8d830 Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_long_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_long_n10_java.sk b/serialization_test_data/java_generated_files/frequent_long_n10_java.sk new file mode 100644 index 000000000..8eefdb040 Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_long_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_long_n1_java.sk b/serialization_test_data/java_generated_files/frequent_long_n1_java.sk new file mode 100644 index 000000000..079515139 Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_long_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_string_ascii_java.sk b/serialization_test_data/java_generated_files/frequent_string_ascii_java.sk new file mode 100644 index 000000000..d5f434ae9 Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_string_ascii_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_string_n0_java.sk b/serialization_test_data/java_generated_files/frequent_string_n0_java.sk new file mode 100644 index 000000000..12d493c6d Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_string_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_string_n1000000_java.sk b/serialization_test_data/java_generated_files/frequent_string_n1000000_java.sk new file mode 100644 index 000000000..bfc342812 Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_string_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_string_n100000_java.sk b/serialization_test_data/java_generated_files/frequent_string_n100000_java.sk new file mode 100644 index 000000000..3f704416a Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_string_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_string_n10000_java.sk b/serialization_test_data/java_generated_files/frequent_string_n10000_java.sk new file mode 100644 index 000000000..4a6d9b53a Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_string_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_string_n1000_java.sk b/serialization_test_data/java_generated_files/frequent_string_n1000_java.sk new file mode 100644 index 000000000..f34d22763 Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_string_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_string_n100_java.sk b/serialization_test_data/java_generated_files/frequent_string_n100_java.sk new file mode 100644 index 000000000..8235b68b0 Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_string_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_string_n10_java.sk b/serialization_test_data/java_generated_files/frequent_string_n10_java.sk new file mode 100644 index 000000000..c5cda78fc Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_string_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_string_n1_java.sk b/serialization_test_data/java_generated_files/frequent_string_n1_java.sk new file mode 100644 index 000000000..b61ea204e Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_string_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/frequent_string_utf8_java.sk b/serialization_test_data/java_generated_files/frequent_string_utf8_java.sk new file mode 100644 index 000000000..75f888a5b Binary files /dev/null and b/serialization_test_data/java_generated_files/frequent_string_utf8_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll4_n0_java.sk b/serialization_test_data/java_generated_files/hll4_n0_java.sk new file mode 100644 index 000000000..074868c23 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll4_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll4_n1000000_java.sk b/serialization_test_data/java_generated_files/hll4_n1000000_java.sk new file mode 100644 index 000000000..9a8c62616 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll4_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll4_n100000_java.sk b/serialization_test_data/java_generated_files/hll4_n100000_java.sk new file mode 100644 index 000000000..2b4b4dc7f Binary files /dev/null and b/serialization_test_data/java_generated_files/hll4_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll4_n10000_java.sk b/serialization_test_data/java_generated_files/hll4_n10000_java.sk new file mode 100644 index 000000000..e97b1815b Binary files /dev/null and b/serialization_test_data/java_generated_files/hll4_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll4_n1000_java.sk b/serialization_test_data/java_generated_files/hll4_n1000_java.sk new file mode 100644 index 000000000..a6b5f9aa2 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll4_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll4_n100_java.sk b/serialization_test_data/java_generated_files/hll4_n100_java.sk new file mode 100644 index 000000000..0e12ff4ac Binary files /dev/null and b/serialization_test_data/java_generated_files/hll4_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll4_n10_java.sk b/serialization_test_data/java_generated_files/hll4_n10_java.sk new file mode 100644 index 000000000..e4ed655d7 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll4_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll4_n1_java.sk b/serialization_test_data/java_generated_files/hll4_n1_java.sk new file mode 100644 index 000000000..1f4f6eedb Binary files /dev/null and b/serialization_test_data/java_generated_files/hll4_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll6_n0_java.sk b/serialization_test_data/java_generated_files/hll6_n0_java.sk new file mode 100644 index 000000000..c31bd2693 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll6_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll6_n1000000_java.sk b/serialization_test_data/java_generated_files/hll6_n1000000_java.sk new file mode 100644 index 000000000..42462d2d9 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll6_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll6_n100000_java.sk b/serialization_test_data/java_generated_files/hll6_n100000_java.sk new file mode 100644 index 000000000..767f24f9a Binary files /dev/null and b/serialization_test_data/java_generated_files/hll6_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll6_n10000_java.sk b/serialization_test_data/java_generated_files/hll6_n10000_java.sk new file mode 100644 index 000000000..258da0889 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll6_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll6_n1000_java.sk b/serialization_test_data/java_generated_files/hll6_n1000_java.sk new file mode 100644 index 000000000..274e8b7ec Binary files /dev/null and b/serialization_test_data/java_generated_files/hll6_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll6_n100_java.sk b/serialization_test_data/java_generated_files/hll6_n100_java.sk new file mode 100644 index 000000000..71fc293ba Binary files /dev/null and b/serialization_test_data/java_generated_files/hll6_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll6_n10_java.sk b/serialization_test_data/java_generated_files/hll6_n10_java.sk new file mode 100644 index 000000000..2a22d9137 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll6_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll6_n1_java.sk b/serialization_test_data/java_generated_files/hll6_n1_java.sk new file mode 100644 index 000000000..3f2f5450b --- /dev/null +++ b/serialization_test_data/java_generated_files/hll6_n1_java.sk @@ -0,0 +1 @@ +  \ No newline at end of file diff --git a/serialization_test_data/java_generated_files/hll8_n0_java.sk b/serialization_test_data/java_generated_files/hll8_n0_java.sk new file mode 100644 index 000000000..5ecf871d9 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll8_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll8_n1000000_java.sk b/serialization_test_data/java_generated_files/hll8_n1000000_java.sk new file mode 100644 index 000000000..e7f5f4821 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll8_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll8_n100000_java.sk b/serialization_test_data/java_generated_files/hll8_n100000_java.sk new file mode 100644 index 000000000..c634e4986 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll8_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll8_n10000_java.sk b/serialization_test_data/java_generated_files/hll8_n10000_java.sk new file mode 100644 index 000000000..f8dfdb0c9 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll8_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll8_n1000_java.sk b/serialization_test_data/java_generated_files/hll8_n1000_java.sk new file mode 100644 index 000000000..761477d5f Binary files /dev/null and b/serialization_test_data/java_generated_files/hll8_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll8_n100_java.sk b/serialization_test_data/java_generated_files/hll8_n100_java.sk new file mode 100644 index 000000000..c2bfa4891 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll8_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll8_n10_java.sk b/serialization_test_data/java_generated_files/hll8_n10_java.sk new file mode 100644 index 000000000..86277b3a1 Binary files /dev/null and b/serialization_test_data/java_generated_files/hll8_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/hll8_n1_java.sk b/serialization_test_data/java_generated_files/hll8_n1_java.sk new file mode 100644 index 000000000..fd3a97327 --- /dev/null +++ b/serialization_test_data/java_generated_files/hll8_n1_java.sk @@ -0,0 +1 @@ +  \ No newline at end of file diff --git a/serialization_test_data/java_generated_files/kll_double_n0_java.sk b/serialization_test_data/java_generated_files/kll_double_n0_java.sk new file mode 100644 index 000000000..afd220927 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_double_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_double_n1000000_java.sk b/serialization_test_data/java_generated_files/kll_double_n1000000_java.sk new file mode 100644 index 000000000..13d9ba9b7 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_double_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_double_n100000_java.sk b/serialization_test_data/java_generated_files/kll_double_n100000_java.sk new file mode 100644 index 000000000..800cc4bdc Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_double_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_double_n10000_java.sk b/serialization_test_data/java_generated_files/kll_double_n10000_java.sk new file mode 100644 index 000000000..493c8819f Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_double_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_double_n1000_java.sk b/serialization_test_data/java_generated_files/kll_double_n1000_java.sk new file mode 100644 index 000000000..e0dc2df85 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_double_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_double_n100_java.sk b/serialization_test_data/java_generated_files/kll_double_n100_java.sk new file mode 100644 index 000000000..b0d578acd Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_double_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_double_n10_java.sk b/serialization_test_data/java_generated_files/kll_double_n10_java.sk new file mode 100644 index 000000000..fb526efa3 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_double_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_double_n1_java.sk b/serialization_test_data/java_generated_files/kll_double_n1_java.sk new file mode 100644 index 000000000..5eceb4061 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_double_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_float_n0_java.sk b/serialization_test_data/java_generated_files/kll_float_n0_java.sk new file mode 100644 index 000000000..afd220927 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_float_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_float_n1000000_java.sk b/serialization_test_data/java_generated_files/kll_float_n1000000_java.sk new file mode 100644 index 000000000..03bb877b4 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_float_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_float_n100000_java.sk b/serialization_test_data/java_generated_files/kll_float_n100000_java.sk new file mode 100644 index 000000000..644dc3066 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_float_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_float_n10000_java.sk b/serialization_test_data/java_generated_files/kll_float_n10000_java.sk new file mode 100644 index 000000000..b72794153 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_float_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_float_n1000_java.sk b/serialization_test_data/java_generated_files/kll_float_n1000_java.sk new file mode 100644 index 000000000..18eec2d69 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_float_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_float_n100_java.sk b/serialization_test_data/java_generated_files/kll_float_n100_java.sk new file mode 100644 index 000000000..ad45e6415 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_float_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_float_n10_java.sk b/serialization_test_data/java_generated_files/kll_float_n10_java.sk new file mode 100644 index 000000000..1fd87d306 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_float_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_float_n1_java.sk b/serialization_test_data/java_generated_files/kll_float_n1_java.sk new file mode 100644 index 000000000..f7f9d22fc Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_float_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_long_n0_java.sk b/serialization_test_data/java_generated_files/kll_long_n0_java.sk new file mode 100644 index 000000000..afd220927 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_long_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_long_n1000000_java.sk b/serialization_test_data/java_generated_files/kll_long_n1000000_java.sk new file mode 100644 index 000000000..9485aa037 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_long_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_long_n100000_java.sk b/serialization_test_data/java_generated_files/kll_long_n100000_java.sk new file mode 100644 index 000000000..c833066be Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_long_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_long_n10000_java.sk b/serialization_test_data/java_generated_files/kll_long_n10000_java.sk new file mode 100644 index 000000000..8c09b1b7f Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_long_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_long_n1000_java.sk b/serialization_test_data/java_generated_files/kll_long_n1000_java.sk new file mode 100644 index 000000000..61ec0e1e4 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_long_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_long_n100_java.sk b/serialization_test_data/java_generated_files/kll_long_n100_java.sk new file mode 100644 index 000000000..43eb95634 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_long_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_long_n10_java.sk b/serialization_test_data/java_generated_files/kll_long_n10_java.sk new file mode 100644 index 000000000..f935b894d Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_long_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_long_n1_java.sk b/serialization_test_data/java_generated_files/kll_long_n1_java.sk new file mode 100644 index 000000000..317ce973d Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_long_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_string_n0_java.sk b/serialization_test_data/java_generated_files/kll_string_n0_java.sk new file mode 100644 index 000000000..afd220927 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_string_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_string_n1000000_java.sk b/serialization_test_data/java_generated_files/kll_string_n1000000_java.sk new file mode 100644 index 000000000..92d45c9ba Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_string_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_string_n100000_java.sk b/serialization_test_data/java_generated_files/kll_string_n100000_java.sk new file mode 100644 index 000000000..c829421b7 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_string_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_string_n10000_java.sk b/serialization_test_data/java_generated_files/kll_string_n10000_java.sk new file mode 100644 index 000000000..6a79355aa Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_string_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_string_n1000_java.sk b/serialization_test_data/java_generated_files/kll_string_n1000_java.sk new file mode 100644 index 000000000..89770f75e Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_string_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_string_n100_java.sk b/serialization_test_data/java_generated_files/kll_string_n100_java.sk new file mode 100644 index 000000000..d7cf70708 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_string_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_string_n10_java.sk b/serialization_test_data/java_generated_files/kll_string_n10_java.sk new file mode 100644 index 000000000..51ff8f5c1 Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_string_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/kll_string_n1_java.sk b/serialization_test_data/java_generated_files/kll_string_n1_java.sk new file mode 100644 index 000000000..38f8253cb Binary files /dev/null and b/serialization_test_data/java_generated_files/kll_string_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_double_n0_java.sk b/serialization_test_data/java_generated_files/quantiles_double_n0_java.sk new file mode 100644 index 000000000..a94dac424 Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_double_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_double_n1000000_java.sk b/serialization_test_data/java_generated_files/quantiles_double_n1000000_java.sk new file mode 100644 index 000000000..55fad1c12 Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_double_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_double_n100000_java.sk b/serialization_test_data/java_generated_files/quantiles_double_n100000_java.sk new file mode 100644 index 000000000..5055247ac Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_double_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_double_n10000_java.sk b/serialization_test_data/java_generated_files/quantiles_double_n10000_java.sk new file mode 100644 index 000000000..519ad2c16 Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_double_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_double_n1000_java.sk b/serialization_test_data/java_generated_files/quantiles_double_n1000_java.sk new file mode 100644 index 000000000..3e34c2ee7 Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_double_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_double_n100_java.sk b/serialization_test_data/java_generated_files/quantiles_double_n100_java.sk new file mode 100644 index 000000000..2e341876a Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_double_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_double_n10_java.sk b/serialization_test_data/java_generated_files/quantiles_double_n10_java.sk new file mode 100644 index 000000000..b61c14f25 Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_double_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_double_n1_java.sk b/serialization_test_data/java_generated_files/quantiles_double_n1_java.sk new file mode 100644 index 000000000..7c291211f Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_double_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_string_n0_java.sk b/serialization_test_data/java_generated_files/quantiles_string_n0_java.sk new file mode 100644 index 000000000..3730a1f8f Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_string_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_string_n1000000_java.sk b/serialization_test_data/java_generated_files/quantiles_string_n1000000_java.sk new file mode 100644 index 000000000..ecc483962 Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_string_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_string_n100000_java.sk b/serialization_test_data/java_generated_files/quantiles_string_n100000_java.sk new file mode 100644 index 000000000..4481bd17f Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_string_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_string_n10000_java.sk b/serialization_test_data/java_generated_files/quantiles_string_n10000_java.sk new file mode 100644 index 000000000..3e2787930 Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_string_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_string_n1000_java.sk b/serialization_test_data/java_generated_files/quantiles_string_n1000_java.sk new file mode 100644 index 000000000..3649f09a5 Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_string_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_string_n100_java.sk b/serialization_test_data/java_generated_files/quantiles_string_n100_java.sk new file mode 100644 index 000000000..c2e763923 Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_string_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_string_n10_java.sk b/serialization_test_data/java_generated_files/quantiles_string_n10_java.sk new file mode 100644 index 000000000..f08aa2ff1 Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_string_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/quantiles_string_n1_java.sk b/serialization_test_data/java_generated_files/quantiles_string_n1_java.sk new file mode 100644 index 000000000..60ba4a04b Binary files /dev/null and b/serialization_test_data/java_generated_files/quantiles_string_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/req_float_n0_java.sk b/serialization_test_data/java_generated_files/req_float_n0_java.sk new file mode 100644 index 000000000..1623b7283 Binary files /dev/null and b/serialization_test_data/java_generated_files/req_float_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/req_float_n1000000_java.sk b/serialization_test_data/java_generated_files/req_float_n1000000_java.sk new file mode 100644 index 000000000..1ba0e1de1 Binary files /dev/null and b/serialization_test_data/java_generated_files/req_float_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/req_float_n100000_java.sk b/serialization_test_data/java_generated_files/req_float_n100000_java.sk new file mode 100644 index 000000000..56b477962 Binary files /dev/null and b/serialization_test_data/java_generated_files/req_float_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/req_float_n10000_java.sk b/serialization_test_data/java_generated_files/req_float_n10000_java.sk new file mode 100644 index 000000000..90b24980e Binary files /dev/null and b/serialization_test_data/java_generated_files/req_float_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/req_float_n1000_java.sk b/serialization_test_data/java_generated_files/req_float_n1000_java.sk new file mode 100644 index 000000000..ca19a7c6b Binary files /dev/null and b/serialization_test_data/java_generated_files/req_float_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/req_float_n100_java.sk b/serialization_test_data/java_generated_files/req_float_n100_java.sk new file mode 100644 index 000000000..10ea0cd6e Binary files /dev/null and b/serialization_test_data/java_generated_files/req_float_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/req_float_n10_java.sk b/serialization_test_data/java_generated_files/req_float_n10_java.sk new file mode 100644 index 000000000..157173c0b Binary files /dev/null and b/serialization_test_data/java_generated_files/req_float_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/req_float_n1_java.sk b/serialization_test_data/java_generated_files/req_float_n1_java.sk new file mode 100644 index 000000000..0cb92e04b Binary files /dev/null and b/serialization_test_data/java_generated_files/req_float_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_double_empty_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_double_empty_k128_java.sk new file mode 100644 index 000000000..cfe18e23b Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_double_empty_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_double_exact_n100_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_double_exact_n100_k128_java.sk new file mode 100644 index 000000000..90cf41e53 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_double_exact_n100_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_double_exact_n10_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_double_exact_n10_k128_java.sk new file mode 100644 index 000000000..691a9e057 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_double_exact_n10_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_double_exact_n128_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_double_exact_n128_k128_java.sk new file mode 100644 index 000000000..3740b205a Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_double_exact_n128_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_double_exact_n1_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_double_exact_n1_k128_java.sk new file mode 100644 index 000000000..94accd5bb Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_double_exact_n1_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_double_exact_n32_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_double_exact_n32_k128_java.sk new file mode 100644 index 000000000..2133d9920 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_double_exact_n32_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_double_sampling_n1000_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_double_sampling_n1000_k128_java.sk new file mode 100644 index 000000000..be8a23aad Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_double_sampling_n1000_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_double_sampling_n1000_k32_java.sk b/serialization_test_data/java_generated_files/reservoir_items_double_sampling_n1000_k32_java.sk new file mode 100644 index 000000000..fafccd473 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_double_sampling_n1000_k32_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_double_sampling_n1000_k64_java.sk b/serialization_test_data/java_generated_files/reservoir_items_double_sampling_n1000_k64_java.sk new file mode 100644 index 000000000..05fcde97a Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_double_sampling_n1000_k64_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_long_empty_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_long_empty_k128_java.sk new file mode 100644 index 000000000..cfe18e23b Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_long_empty_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_long_exact_n100_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_long_exact_n100_k128_java.sk new file mode 100644 index 000000000..f4502c0d5 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_long_exact_n100_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_long_exact_n10_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_long_exact_n10_k128_java.sk new file mode 100644 index 000000000..d5edac6fa Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_long_exact_n10_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_long_exact_n128_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_long_exact_n128_k128_java.sk new file mode 100644 index 000000000..6442791de Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_long_exact_n128_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_long_exact_n1_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_long_exact_n1_k128_java.sk new file mode 100644 index 000000000..94accd5bb Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_long_exact_n1_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_long_exact_n32_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_long_exact_n32_k128_java.sk new file mode 100644 index 000000000..8df355c17 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_long_exact_n32_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_long_sampling_n1000_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_long_sampling_n1000_k128_java.sk new file mode 100644 index 000000000..4c44fbe6e Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_long_sampling_n1000_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_long_sampling_n1000_k32_java.sk b/serialization_test_data/java_generated_files/reservoir_items_long_sampling_n1000_k32_java.sk new file mode 100644 index 000000000..840070392 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_long_sampling_n1000_k32_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_long_sampling_n1000_k64_java.sk b/serialization_test_data/java_generated_files/reservoir_items_long_sampling_n1000_k64_java.sk new file mode 100644 index 000000000..b11286619 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_long_sampling_n1000_k64_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_string_empty_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_string_empty_k128_java.sk new file mode 100644 index 000000000..cfe18e23b Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_string_empty_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_string_exact_n100_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_string_exact_n100_k128_java.sk new file mode 100644 index 000000000..85d73bd90 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_string_exact_n100_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_string_exact_n10_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_string_exact_n10_k128_java.sk new file mode 100644 index 000000000..54b50047b Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_string_exact_n10_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_string_exact_n128_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_string_exact_n128_k128_java.sk new file mode 100644 index 000000000..c21ebf268 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_string_exact_n128_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_string_exact_n1_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_string_exact_n1_k128_java.sk new file mode 100644 index 000000000..28742cadd Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_string_exact_n1_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_string_exact_n32_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_string_exact_n32_k128_java.sk new file mode 100644 index 000000000..e71a29f97 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_string_exact_n32_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_string_sampling_n1000_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_string_sampling_n1000_k128_java.sk new file mode 100644 index 000000000..618b3959c Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_string_sampling_n1000_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_string_sampling_n1000_k32_java.sk b/serialization_test_data/java_generated_files/reservoir_items_string_sampling_n1000_k32_java.sk new file mode 100644 index 000000000..807667f04 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_string_sampling_n1000_k32_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_string_sampling_n1000_k64_java.sk b/serialization_test_data/java_generated_files/reservoir_items_string_sampling_n1000_k64_java.sk new file mode 100644 index 000000000..206c5d7a0 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_string_sampling_n1000_k64_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_double_empty_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_double_empty_maxk128_java.sk new file mode 100644 index 000000000..3cb5c2a70 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_double_empty_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n100_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n100_maxk128_java.sk new file mode 100644 index 000000000..63953d118 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n100_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n10_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n10_maxk128_java.sk new file mode 100644 index 000000000..7fcc6b2ba Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n10_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n128_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n128_maxk128_java.sk new file mode 100644 index 000000000..777e42541 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n128_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n1_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n1_maxk128_java.sk new file mode 100644 index 000000000..f981fb10e Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n1_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n32_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n32_maxk128_java.sk new file mode 100644 index 000000000..e40f29afb Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n32_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_double_sampling_n1000_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_double_sampling_n1000_maxk128_java.sk new file mode 100644 index 000000000..8c62380ca Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_double_sampling_n1000_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_double_sampling_n1000_maxk32_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_double_sampling_n1000_maxk32_java.sk new file mode 100644 index 000000000..676a2a87d Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_double_sampling_n1000_maxk32_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_double_sampling_n1000_maxk64_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_double_sampling_n1000_maxk64_java.sk new file mode 100644 index 000000000..b340e23b1 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_double_sampling_n1000_maxk64_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_long_empty_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_long_empty_maxk128_java.sk new file mode 100644 index 000000000..3cb5c2a70 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_long_empty_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n100_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n100_maxk128_java.sk new file mode 100644 index 000000000..469a8263f Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n100_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n10_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n10_maxk128_java.sk new file mode 100644 index 000000000..3222d7989 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n10_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n128_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n128_maxk128_java.sk new file mode 100644 index 000000000..72598e897 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n128_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n1_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n1_maxk128_java.sk new file mode 100644 index 000000000..f981fb10e Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n1_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n32_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n32_maxk128_java.sk new file mode 100644 index 000000000..676b42f0a Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n32_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_long_sampling_n1000_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_long_sampling_n1000_maxk128_java.sk new file mode 100644 index 000000000..e72ac6fe0 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_long_sampling_n1000_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_long_sampling_n1000_maxk32_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_long_sampling_n1000_maxk32_java.sk new file mode 100644 index 000000000..ee5dcca02 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_long_sampling_n1000_maxk32_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_long_sampling_n1000_maxk64_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_long_sampling_n1000_maxk64_java.sk new file mode 100644 index 000000000..17e286b3c Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_long_sampling_n1000_maxk64_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_string_empty_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_string_empty_maxk128_java.sk new file mode 100644 index 000000000..3cb5c2a70 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_string_empty_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n100_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n100_maxk128_java.sk new file mode 100644 index 000000000..69ce37a37 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n100_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n10_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n10_maxk128_java.sk new file mode 100644 index 000000000..93b9382d8 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n10_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n128_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n128_maxk128_java.sk new file mode 100644 index 000000000..a9b8d3441 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n128_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n1_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n1_maxk128_java.sk new file mode 100644 index 000000000..776dc660d Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n1_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n32_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n32_maxk128_java.sk new file mode 100644 index 000000000..8209b023c Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n32_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_string_sampling_n1000_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_string_sampling_n1000_maxk128_java.sk new file mode 100644 index 000000000..1abadf2bd Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_string_sampling_n1000_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_string_sampling_n1000_maxk32_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_string_sampling_n1000_maxk32_java.sk new file mode 100644 index 000000000..57892af0b Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_string_sampling_n1000_maxk32_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_items_union_string_sampling_n1000_maxk64_java.sk b/serialization_test_data/java_generated_files/reservoir_items_union_string_sampling_n1000_maxk64_java.sk new file mode 100644 index 000000000..206b0f489 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_items_union_string_sampling_n1000_maxk64_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_empty_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_empty_k128_java.sk new file mode 100644 index 000000000..cfe18e23b Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_empty_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_exact_n100_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_exact_n100_k128_java.sk new file mode 100644 index 000000000..f4502c0d5 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_exact_n100_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_exact_n10_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_exact_n10_k128_java.sk new file mode 100644 index 000000000..d5edac6fa Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_exact_n10_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_exact_n128_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_exact_n128_k128_java.sk new file mode 100644 index 000000000..6442791de Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_exact_n128_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_exact_n1_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_exact_n1_k128_java.sk new file mode 100644 index 000000000..94accd5bb Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_exact_n1_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_exact_n32_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_exact_n32_k128_java.sk new file mode 100644 index 000000000..8df355c17 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_exact_n32_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_sampling_n1000_k128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_sampling_n1000_k128_java.sk new file mode 100644 index 000000000..4c44fbe6e Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_sampling_n1000_k128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_sampling_n1000_k32_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_sampling_n1000_k32_java.sk new file mode 100644 index 000000000..840070392 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_sampling_n1000_k32_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_sampling_n1000_k64_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_sampling_n1000_k64_java.sk new file mode 100644 index 000000000..b11286619 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_sampling_n1000_k64_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_union_empty_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_union_empty_maxk128_java.sk new file mode 100644 index 000000000..3cb5c2a70 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_union_empty_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n100_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n100_maxk128_java.sk new file mode 100644 index 000000000..469a8263f Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n100_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n10_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n10_maxk128_java.sk new file mode 100644 index 000000000..3222d7989 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n10_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n128_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n128_maxk128_java.sk new file mode 100644 index 000000000..72598e897 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n128_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n1_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n1_maxk128_java.sk new file mode 100644 index 000000000..f981fb10e Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n1_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n32_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n32_maxk128_java.sk new file mode 100644 index 000000000..676b42f0a Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_union_exact_n32_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_union_sampling_n1000_maxk128_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_union_sampling_n1000_maxk128_java.sk new file mode 100644 index 000000000..e72ac6fe0 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_union_sampling_n1000_maxk128_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_union_sampling_n1000_maxk32_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_union_sampling_n1000_maxk32_java.sk new file mode 100644 index 000000000..ee5dcca02 Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_union_sampling_n1000_maxk32_java.sk differ diff --git a/serialization_test_data/java_generated_files/reservoir_longs_union_sampling_n1000_maxk64_java.sk b/serialization_test_data/java_generated_files/reservoir_longs_union_sampling_n1000_maxk64_java.sk new file mode 100644 index 000000000..17e286b3c Binary files /dev/null and b/serialization_test_data/java_generated_files/reservoir_longs_union_sampling_n1000_maxk64_java.sk differ diff --git a/serialization_test_data/java_generated_files/tdigest_double_n0_java.sk b/serialization_test_data/java_generated_files/tdigest_double_n0_java.sk new file mode 100644 index 000000000..e84c2ea50 Binary files /dev/null and b/serialization_test_data/java_generated_files/tdigest_double_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/tdigest_double_n1000000_java.sk b/serialization_test_data/java_generated_files/tdigest_double_n1000000_java.sk new file mode 100644 index 000000000..6b87e1eeb Binary files /dev/null and b/serialization_test_data/java_generated_files/tdigest_double_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/tdigest_double_n100000_java.sk b/serialization_test_data/java_generated_files/tdigest_double_n100000_java.sk new file mode 100644 index 000000000..fbb27272e Binary files /dev/null and b/serialization_test_data/java_generated_files/tdigest_double_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/tdigest_double_n10000_java.sk b/serialization_test_data/java_generated_files/tdigest_double_n10000_java.sk new file mode 100644 index 000000000..290ceadd8 Binary files /dev/null and b/serialization_test_data/java_generated_files/tdigest_double_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/tdigest_double_n1000_java.sk b/serialization_test_data/java_generated_files/tdigest_double_n1000_java.sk new file mode 100644 index 000000000..7832fc376 Binary files /dev/null and b/serialization_test_data/java_generated_files/tdigest_double_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/tdigest_double_n100_java.sk b/serialization_test_data/java_generated_files/tdigest_double_n100_java.sk new file mode 100644 index 000000000..9d1d60a90 Binary files /dev/null and b/serialization_test_data/java_generated_files/tdigest_double_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/tdigest_double_n10_java.sk b/serialization_test_data/java_generated_files/tdigest_double_n10_java.sk new file mode 100644 index 000000000..2c1026eed Binary files /dev/null and b/serialization_test_data/java_generated_files/tdigest_double_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/tdigest_double_n1_java.sk b/serialization_test_data/java_generated_files/tdigest_double_n1_java.sk new file mode 100644 index 000000000..971919e7f Binary files /dev/null and b/serialization_test_data/java_generated_files/tdigest_double_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_compressed_n1000000_java.sk b/serialization_test_data/java_generated_files/theta_compressed_n1000000_java.sk new file mode 100644 index 000000000..26e2371cf Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_compressed_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_compressed_n100000_java.sk b/serialization_test_data/java_generated_files/theta_compressed_n100000_java.sk new file mode 100644 index 000000000..3998ae4c8 Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_compressed_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_compressed_n10000_java.sk b/serialization_test_data/java_generated_files/theta_compressed_n10000_java.sk new file mode 100644 index 000000000..33459ef50 Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_compressed_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_compressed_n1000_java.sk b/serialization_test_data/java_generated_files/theta_compressed_n1000_java.sk new file mode 100644 index 000000000..1fdec7903 Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_compressed_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_compressed_n100_java.sk b/serialization_test_data/java_generated_files/theta_compressed_n100_java.sk new file mode 100644 index 000000000..6f8b4e934 Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_compressed_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_compressed_n10_java.sk b/serialization_test_data/java_generated_files/theta_compressed_n10_java.sk new file mode 100644 index 000000000..6f81c038a --- /dev/null +++ b/serialization_test_data/java_generated_files/theta_compressed_n10_java.sk @@ -0,0 +1,2 @@ +>̓ +-T)P[Rc;"JHe0Bg?-}Hn P`i5 e5 B` \ No newline at end of file diff --git a/serialization_test_data/java_generated_files/theta_n0_java.sk b/serialization_test_data/java_generated_files/theta_n0_java.sk new file mode 100644 index 000000000..f6c647f8a Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_n1000000_java.sk b/serialization_test_data/java_generated_files/theta_n1000000_java.sk new file mode 100644 index 000000000..292e294fd Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_n100000_java.sk b/serialization_test_data/java_generated_files/theta_n100000_java.sk new file mode 100644 index 000000000..8b5c86104 Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_n10000_java.sk b/serialization_test_data/java_generated_files/theta_n10000_java.sk new file mode 100644 index 000000000..eb9db24b8 Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_n1000_java.sk b/serialization_test_data/java_generated_files/theta_n1000_java.sk new file mode 100644 index 000000000..65610e3f8 Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_n100_java.sk b/serialization_test_data/java_generated_files/theta_n100_java.sk new file mode 100644 index 000000000..0ab7727d8 Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_n10_java.sk b/serialization_test_data/java_generated_files/theta_n10_java.sk new file mode 100644 index 000000000..8c74f705c Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_n1_java.sk b/serialization_test_data/java_generated_files/theta_n1_java.sk new file mode 100644 index 000000000..1cc469c0f Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/theta_non_empty_no_entries_java.sk b/serialization_test_data/java_generated_files/theta_non_empty_no_entries_java.sk new file mode 100644 index 000000000..f6f3a1905 Binary files /dev/null and b/serialization_test_data/java_generated_files/theta_non_empty_no_entries_java.sk differ diff --git a/serialization_test_data/java_generated_files/tuple_int_n0_java.sk b/serialization_test_data/java_generated_files/tuple_int_n0_java.sk new file mode 100644 index 000000000..f98290af3 Binary files /dev/null and b/serialization_test_data/java_generated_files/tuple_int_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/tuple_int_n1000000_java.sk b/serialization_test_data/java_generated_files/tuple_int_n1000000_java.sk new file mode 100644 index 000000000..20247cfe2 Binary files /dev/null and b/serialization_test_data/java_generated_files/tuple_int_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/tuple_int_n100000_java.sk b/serialization_test_data/java_generated_files/tuple_int_n100000_java.sk new file mode 100644 index 000000000..8f84b93ba Binary files /dev/null and b/serialization_test_data/java_generated_files/tuple_int_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/tuple_int_n10000_java.sk b/serialization_test_data/java_generated_files/tuple_int_n10000_java.sk new file mode 100644 index 000000000..ca48b042a Binary files /dev/null and b/serialization_test_data/java_generated_files/tuple_int_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/tuple_int_n1000_java.sk b/serialization_test_data/java_generated_files/tuple_int_n1000_java.sk new file mode 100644 index 000000000..0fad9e7fe Binary files /dev/null and b/serialization_test_data/java_generated_files/tuple_int_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/tuple_int_n100_java.sk b/serialization_test_data/java_generated_files/tuple_int_n100_java.sk new file mode 100644 index 000000000..f5a79c03a Binary files /dev/null and b/serialization_test_data/java_generated_files/tuple_int_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/tuple_int_n10_java.sk b/serialization_test_data/java_generated_files/tuple_int_n10_java.sk new file mode 100644 index 000000000..3272e76e0 Binary files /dev/null and b/serialization_test_data/java_generated_files/tuple_int_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/tuple_int_n1_java.sk b/serialization_test_data/java_generated_files/tuple_int_n1_java.sk new file mode 100644 index 000000000..ae9969992 Binary files /dev/null and b/serialization_test_data/java_generated_files/tuple_int_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/varopt_sketch_long_n0_java.sk b/serialization_test_data/java_generated_files/varopt_sketch_long_n0_java.sk new file mode 100644 index 000000000..e4505fe12 Binary files /dev/null and b/serialization_test_data/java_generated_files/varopt_sketch_long_n0_java.sk differ diff --git a/serialization_test_data/java_generated_files/varopt_sketch_long_n1000000_java.sk b/serialization_test_data/java_generated_files/varopt_sketch_long_n1000000_java.sk new file mode 100644 index 000000000..f66e02a5e Binary files /dev/null and b/serialization_test_data/java_generated_files/varopt_sketch_long_n1000000_java.sk differ diff --git a/serialization_test_data/java_generated_files/varopt_sketch_long_n100000_java.sk b/serialization_test_data/java_generated_files/varopt_sketch_long_n100000_java.sk new file mode 100644 index 000000000..9ab28cd33 Binary files /dev/null and b/serialization_test_data/java_generated_files/varopt_sketch_long_n100000_java.sk differ diff --git a/serialization_test_data/java_generated_files/varopt_sketch_long_n10000_java.sk b/serialization_test_data/java_generated_files/varopt_sketch_long_n10000_java.sk new file mode 100644 index 000000000..e3fc5baa6 Binary files /dev/null and b/serialization_test_data/java_generated_files/varopt_sketch_long_n10000_java.sk differ diff --git a/serialization_test_data/java_generated_files/varopt_sketch_long_n1000_java.sk b/serialization_test_data/java_generated_files/varopt_sketch_long_n1000_java.sk new file mode 100644 index 000000000..551d05349 Binary files /dev/null and b/serialization_test_data/java_generated_files/varopt_sketch_long_n1000_java.sk differ diff --git a/serialization_test_data/java_generated_files/varopt_sketch_long_n100_java.sk b/serialization_test_data/java_generated_files/varopt_sketch_long_n100_java.sk new file mode 100644 index 000000000..2d8a3a260 Binary files /dev/null and b/serialization_test_data/java_generated_files/varopt_sketch_long_n100_java.sk differ diff --git a/serialization_test_data/java_generated_files/varopt_sketch_long_n10_java.sk b/serialization_test_data/java_generated_files/varopt_sketch_long_n10_java.sk new file mode 100644 index 000000000..f1ac8c072 Binary files /dev/null and b/serialization_test_data/java_generated_files/varopt_sketch_long_n10_java.sk differ diff --git a/serialization_test_data/java_generated_files/varopt_sketch_long_n1_java.sk b/serialization_test_data/java_generated_files/varopt_sketch_long_n1_java.sk new file mode 100644 index 000000000..86f6bc320 Binary files /dev/null and b/serialization_test_data/java_generated_files/varopt_sketch_long_n1_java.sk differ diff --git a/serialization_test_data/java_generated_files/varopt_sketch_long_sampling_java.sk b/serialization_test_data/java_generated_files/varopt_sketch_long_sampling_java.sk new file mode 100644 index 000000000..79abbe7b8 Binary files /dev/null and b/serialization_test_data/java_generated_files/varopt_sketch_long_sampling_java.sk differ diff --git a/serialization_test_data/java_generated_files/varopt_sketch_string_exact_java.sk b/serialization_test_data/java_generated_files/varopt_sketch_string_exact_java.sk new file mode 100644 index 000000000..2da7e4ed2 Binary files /dev/null and b/serialization_test_data/java_generated_files/varopt_sketch_string_exact_java.sk differ diff --git a/serialization_test_data/java_generated_files/varopt_union_double_sampling_java.sk b/serialization_test_data/java_generated_files/varopt_union_double_sampling_java.sk new file mode 100644 index 000000000..0eeb3a44f Binary files /dev/null and b/serialization_test_data/java_generated_files/varopt_union_double_sampling_java.sk differ diff --git a/src/main/java/org/apache/datasketches/common/ArrayOfBooleansSerDe.java b/src/main/java/org/apache/datasketches/common/ArrayOfBooleansSerDe.java deleted file mode 100644 index ac7283652..000000000 --- a/src/main/java/org/apache/datasketches/common/ArrayOfBooleansSerDe.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -/** - * Methods of serializing and deserializing arrays of Boolean as a bit array. - * - * @author Jon Malkin - */ -public class ArrayOfBooleansSerDe extends ArrayOfItemsSerDe { - - /** - * No argument constructor. - */ - public ArrayOfBooleansSerDe() { } - - /** - * Computes number of bytes needed for packed bit encoding of the array of booleans. Rounds - * partial bytes up to return a whole number of bytes. - * - * @param arrayLength Number of items in the array to serialize - * @return Number of bytes needed to encode the array - */ - public static int computeBytesNeeded(final int arrayLength) { - return (arrayLength >>> 3) + ((arrayLength & 0x7) > 0 ? 1 : 0); - } - - @Override - public byte[] serializeToByteArray(final Boolean item) { - Objects.requireNonNull(item, "Item must not be null"); - final byte[] bytes = new byte[1]; - bytes[0] = (item) ? (byte)1 : 0; - return bytes; - } - - @Override - public byte[] serializeToByteArray(final Boolean[] items) { - Objects.requireNonNull(items, "Items must not be null"); - final int bytesNeeded = computeBytesNeeded(items.length); - final byte[] bytes = new byte[bytesNeeded]; - final MemorySegment seg = MemorySegment.ofArray(bytes); - - byte val = 0; - for (int i = 0; i < items.length; ++i) { - if (items[i]) { - val |= 0x1 << (i & 0x7); - } - if ((i & 0x7) == 0x7) { - seg.set(JAVA_BYTE, i >>> 3, val); - val = 0; - } - } - // write out any remaining values (if val=0, still good to be explicit) - if ((items.length & 0x7) > 0) { - seg.set(JAVA_BYTE, bytesNeeded - 1, val); - } - return bytes; - } - - @Override - public Boolean[] deserializeFromMemorySegment(final MemorySegment seg, final int numItems) { - return deserializeFromMemorySegment(seg, 0, numItems); - } - - @Override - public Boolean[] deserializeFromMemorySegment(final MemorySegment seg, final long offsetBytes, final int numItems) { - Objects.requireNonNull(seg, "MemorySegment must not be null"); - if (numItems <= 0) { return new Boolean[0]; } - final int numBytes = computeBytesNeeded(numItems); - Util.checkBounds(offsetBytes, numBytes, seg.byteSize()); - final Boolean[] array = new Boolean[numItems]; - - byte srcVal = 0; - for (int i = 0, b = 0; i < numItems; ++i) { - if ((i & 0x7) == 0x0) { // should trigger on first iteration - srcVal = seg.get(JAVA_BYTE, offsetBytes + b++); - } - array[i] = ((srcVal >>> (i & 0x7)) & 0x1) == 1; - } - return array; - } - - @Override - public int sizeOf(final Boolean item) { - Objects.requireNonNull(item, "Item must not be null"); - return computeBytesNeeded(1); - } - - @Override //needs to override default due to the bit packing, which must be computed. - public int sizeOf(final Boolean[] items) { - Objects.requireNonNull(items, "Item must not be null"); - return computeBytesNeeded(items.length); - } - - @Override - public int sizeOf(final MemorySegment seg, final long offsetBytes, final int numItems) { - Objects.requireNonNull(seg, "MemorySegment must not be null"); - return computeBytesNeeded(numItems); - } - - @Override - public String toString(final Boolean item) { - if (item == null) { return "null"; } - return item ? "true" : "false"; - } - - @Override - public Class getClassOfT() { return Boolean.class; } -} diff --git a/src/main/java/org/apache/datasketches/common/ArrayOfDoublesSerDe.java b/src/main/java/org/apache/datasketches/common/ArrayOfDoublesSerDe.java deleted file mode 100644 index 87f8412a9..000000000 --- a/src/main/java/org/apache/datasketches/common/ArrayOfDoublesSerDe.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static org.apache.datasketches.common.ByteArrayUtil.putDoubleLE; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -/** - * Methods of serializing and deserializing arrays of Double. - * - * @author Alexander Saydakov - */ -public class ArrayOfDoublesSerDe extends ArrayOfItemsSerDe { - - /** - * No argument constructor. - */ - public ArrayOfDoublesSerDe() { } - - @Override - public byte[] serializeToByteArray(final Double item) { - Objects.requireNonNull(item, "Item must not be null"); - final byte[] byteArr = new byte[Double.BYTES]; - putDoubleLE(byteArr, 0, item.doubleValue()); - return byteArr; - } - - @Override - public byte[] serializeToByteArray(final Double[] items) { - Objects.requireNonNull(items, "Items must not be null"); - if (items.length == 0) { return new byte[0]; } - final byte[] bytes = new byte[Double.BYTES * items.length]; - final MemorySegment seg = MemorySegment.ofArray(bytes); - long offset = 0; - for (int i = 0; i < items.length; i++) { - seg.set(JAVA_DOUBLE_UNALIGNED, offset, items[i]); - offset += Double.BYTES; - } - return bytes; - } - - @Override - public Double[] deserializeFromMemorySegment(final MemorySegment seg, final int numItems) { - return deserializeFromMemorySegment(seg, 0, numItems); - } - - @Override - public Double[] deserializeFromMemorySegment(final MemorySegment seg, final long offsetBytes, final int numItems) { - Objects.requireNonNull(seg, "MemorySegment must not be null"); - if (numItems <= 0) { return new Double[0]; } - long offset = offsetBytes; - Util.checkBounds(offset, Double.BYTES * (long)numItems, seg.byteSize()); - final Double[] array = new Double[numItems]; - - for (int i = 0; i < numItems; i++) { - array[i] = seg.get(JAVA_DOUBLE_UNALIGNED, offset); - offset += Double.BYTES; - } - return array; - } - - @Override - public int sizeOf(final Double item) { - Objects.requireNonNull(item, "Item must not be null"); - return Double.BYTES; - } - - @Override //override because this is simpler - public int sizeOf(final Double[] items) { - Objects.requireNonNull(items, "Items must not be null"); - return items.length * Double.BYTES; - } - - @Override - public int sizeOf(final MemorySegment seg, final long offsetBytes, final int numItems) { - Objects.requireNonNull(seg, "MemorySegment must not be null"); - return numItems * Double.BYTES; - } - - @Override - public String toString(final Double item) { - if (item == null) { return "null"; } - return item.toString(); - } - - @Override - public Class getClassOfT() { return Double.class; } -} diff --git a/src/main/java/org/apache/datasketches/common/ArrayOfItemsSerDe.java b/src/main/java/org/apache/datasketches/common/ArrayOfItemsSerDe.java deleted file mode 100644 index 81f2d157c..000000000 --- a/src/main/java/org/apache/datasketches/common/ArrayOfItemsSerDe.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -/** - * Base class for serializing and deserializing custom types. - * @param Type of item - * - * @author Alexander Saydakov - */ -public abstract class ArrayOfItemsSerDe { - - /** - * No argument constructor. - */ - public ArrayOfItemsSerDe() { } - - /** - * Serialize a single unserialized item to a byte array. - * - * @param item the item to be serialized - * @return serialized representation of the given item - */ - public abstract byte[] serializeToByteArray(T item); - - /** - * Serialize an array of unserialized items to a byte array of contiguous serialized items. - * - * @param items array of items to be serialized - * @return contiguous, serialized representation of the given array of unserialized items - */ - public abstract byte[] serializeToByteArray(T[] items); - - /** - * Deserialize a contiguous sequence of serialized items from the given MemorySegment - * starting at a MemorySegment offset of zero and extending numItems. - * - * @param seg MemorySegment containing a contiguous sequence of serialized items - * @param numItems number of items in the contiguous serialized sequence. - * @return array of deserialized items - * @see #deserializeFromMemorySegment(MemorySegment, long, int) - */ - public T[] deserializeFromMemorySegment(final MemorySegment seg, final int numItems) { - return deserializeFromMemorySegment(seg, 0, numItems); - } - - /** - * Deserialize a contiguous sequence of serialized items from the given MemorySegment - * starting at the given MemorySegment offsetBytes and extending numItems. - * - * @param seg MemorySegment containing a contiguous sequence of serialized items - * @param offsetBytes the starting offset in the given MemorySegment. - * @param numItems number of items in the contiguous serialized sequence. - * @return array of deserialized items - */ - public abstract T[] deserializeFromMemorySegment(MemorySegment seg, long offsetBytes, int numItems); - - /** - * Returns the serialized size in bytes of a single unserialized item. - * @param item a specific item - * @return the serialized size in bytes of a single unserialized item. - */ - public abstract int sizeOf(T item); - - /** - * Returns the serialized size in bytes of the array of items. - * @param items an array of items. - * @return the serialized size in bytes of the array of items. - */ - public int sizeOf(final T[] items) { - Objects.requireNonNull(items, "Items must not be null"); - int totalBytes = 0; - for (int i = 0; i < items.length; i++) { - totalBytes += sizeOf(items[i]); - } - return totalBytes; - } - - /** - * Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment. - * The capacity of the given MemorySegment can be much larger that the required size of the items. - * @param seg the given MemorySegment. - * @param offsetBytes the starting offset in the given MemorySegment. - * @param numItems the number of serialized items contained in the MemorySegment - * @return the serialized size in bytes of the given number of items. - */ - public abstract int sizeOf(MemorySegment seg, long offsetBytes, int numItems); - - /** - * Returns a human readable string of an item. - * @param item a specific item - * @return a human readable string of an item. - */ - public abstract String toString(T item); - - /** - * Returns the concrete class of type T - * @return the concrete class of type T - */ - public abstract Class getClassOfT(); -} diff --git a/src/main/java/org/apache/datasketches/common/ArrayOfLongsSerDe.java b/src/main/java/org/apache/datasketches/common/ArrayOfLongsSerDe.java deleted file mode 100644 index 118901b89..000000000 --- a/src/main/java/org/apache/datasketches/common/ArrayOfLongsSerDe.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.ByteArrayUtil.putLongLE; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -/** - * Methods of serializing and deserializing arrays of Long. - * - * @author Alexander Saydakov - */ -public class ArrayOfLongsSerDe extends ArrayOfItemsSerDe { - - /** - * No argument constructor. - */ - public ArrayOfLongsSerDe() { } - - @Override - public byte[] serializeToByteArray(final Long item) { - Objects.requireNonNull(item, "Item must not be null"); - final byte[] byteArr = new byte[Long.BYTES]; - putLongLE(byteArr, 0, item.longValue()); - return byteArr; - } - - @Override - public byte[] serializeToByteArray(final Long[] items) { - Objects.requireNonNull(items, "Items must not be null"); - if (items.length == 0) { return new byte[0]; } - final byte[] bytes = new byte[Long.BYTES * items.length]; - final MemorySegment seg = MemorySegment.ofArray(bytes); - long offset = 0; - for (int i = 0; i < items.length; i++) { - seg.set(JAVA_LONG_UNALIGNED, offset, items[i]); - offset += Long.BYTES; - } - return bytes; - } - - @Override - public Long[] deserializeFromMemorySegment(final MemorySegment seg, final int numItems) { - return deserializeFromMemorySegment(seg, 0, numItems); - } - - @Override - public Long[] deserializeFromMemorySegment(final MemorySegment seg, final long offsetBytes, final int numItems) { - Objects.requireNonNull(seg, "MemorySegment must not be null"); - if (numItems <= 0) { return new Long[0]; } - long offset = offsetBytes; - Util.checkBounds(offset, Long.BYTES * (long)numItems, seg.byteSize()); - final Long[] array = new Long[numItems]; - for (int i = 0; i < numItems; i++) { - array[i] = seg.get(JAVA_LONG_UNALIGNED, offset); - offset += Long.BYTES; - } - return array; - } - - @Override - public int sizeOf(final Long item) { - Objects.requireNonNull(item, "Item must not be null"); - return Long.BYTES; - } - - @Override //override because this is simpler - public int sizeOf(final Long[] items) { - Objects.requireNonNull(items, "Items must not be null"); - return items.length * Long.BYTES; - } - - @Override - public int sizeOf(final MemorySegment seg, final long offsetBytes, final int numItems) { - Objects.requireNonNull(seg, "MemorySegment must not be null"); - return numItems * Long.BYTES; - } - - @Override - public String toString(final Long item) { - if (item == null) { return "null"; } - return item.toString(); - } - - @Override - public Class getClassOfT() { return Long.class; } -} diff --git a/src/main/java/org/apache/datasketches/common/ArrayOfNumbersSerDe.java b/src/main/java/org/apache/datasketches/common/ArrayOfNumbersSerDe.java deleted file mode 100644 index 797d8d3b0..000000000 --- a/src/main/java/org/apache/datasketches/common/ArrayOfNumbersSerDe.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.common.ByteArrayUtil.copyBytes; -import static org.apache.datasketches.common.ByteArrayUtil.putDoubleLE; -import static org.apache.datasketches.common.ByteArrayUtil.putFloatLE; -import static org.apache.datasketches.common.ByteArrayUtil.putIntLE; -import static org.apache.datasketches.common.ByteArrayUtil.putLongLE; -import static org.apache.datasketches.common.ByteArrayUtil.putShortLE; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -/** - * Methods of serializing and deserializing arrays of the object version of primitive types of - * Number. The array can be a mix of primitive object types. - * - *

This class serializes numbers with a leading byte (ASCII character) indicating the type. - * The class keeps the values byte aligned, even though only 3 bits are strictly necessary to - * encode one of the 6 different primitives with object types that extend Number.

- * - *

Classes handled are: Long, Integer, Short, - * Byte, Double, and Float.

- * - * @author Jon Malkin - */ -public class ArrayOfNumbersSerDe extends ArrayOfItemsSerDe { - // values selected to enable backwards compatibility - private static final byte LONG_INDICATOR = 12; - private static final byte INTEGER_INDICATOR = 9; - private static final byte SHORT_INDICATOR = 3; - private static final byte BYTE_INDICATOR = 2; - private static final byte DOUBLE_INDICATOR = 4; - private static final byte FLOAT_INDICATOR = 6; - - /** - * No argument constructor. - */ - public ArrayOfNumbersSerDe() { } - - @Override - public byte[] serializeToByteArray(final Number item) { - Objects.requireNonNull(item, "Item must not be null"); - final byte[] byteArr; - if (item instanceof Long) { - byteArr = new byte[Long.BYTES + 1]; - byteArr[0] = LONG_INDICATOR; - putLongLE(byteArr, 1, (Long)item); - } else if (item instanceof Integer) { - byteArr = new byte[Integer.BYTES + 1]; - byteArr[0] = INTEGER_INDICATOR; - putIntLE(byteArr, 1, (Integer)item); - } else if (item instanceof Short) { - byteArr = new byte[Short.BYTES + 1]; - byteArr[0] = SHORT_INDICATOR; - putShortLE(byteArr, 1, (Short)item); - } else if (item instanceof Byte) { - byteArr = new byte[Byte.BYTES + 1]; - byteArr[0] = BYTE_INDICATOR; - byteArr[1] = (byte)item; - } else if (item instanceof Double) { - byteArr = new byte[Double.BYTES + 1]; - byteArr[0] = DOUBLE_INDICATOR; - putDoubleLE(byteArr, 1, (Double)item); - } else if (item instanceof Float) { - byteArr = new byte[Float.BYTES + 1]; - byteArr[0] = FLOAT_INDICATOR; - putFloatLE(byteArr, 1, (Float)item); - } else { - throw new SketchesArgumentException( - "Item must be one of: Long, Integer, Short, Byte, Double, Float. " - + "item: " + item.toString()); - } - return byteArr; - } - - @Override - public byte[] serializeToByteArray(final Number[] items) { - Objects.requireNonNull(items, "Items must not be null"); - final int numItems = items.length; - int totalBytes = 0; - final byte[][] serialized2DArray = new byte[numItems][]; - for (int i = 0; i < numItems; i++) { - serialized2DArray[i] = serializeToByteArray(items[i]); - totalBytes += serialized2DArray[i].length; - } - final byte[] out = new byte[totalBytes]; - int offset = 0; - for (int i = 0; i < numItems; i++) { - final int itemLen = serialized2DArray[i].length; - copyBytes(serialized2DArray[i], 0, out, offset, itemLen); - offset += itemLen; - } - return out; - } - - @Override - public Number[] deserializeFromMemorySegment(final MemorySegment seg, final int numItems) { - return deserializeFromMemorySegment(seg, 0, numItems); - } - - @Override - public Number[] deserializeFromMemorySegment(final MemorySegment seg, final long offsetBytes, final int numItems) { - Objects.requireNonNull(seg, "MemorySegment must not be null"); - if (numItems <= 0) { return new Number[0]; } - final Number[] array = new Number[numItems]; - long offset = offsetBytes; - for (int i = 0; i < numItems; i++) { - Util.checkBounds(offset, Byte.BYTES, seg.byteSize()); - final byte typeId = seg.get(JAVA_BYTE, offset); - offset += Byte.BYTES; - - switch (typeId) { - case LONG_INDICATOR: - Util.checkBounds(offset, Long.BYTES, seg.byteSize()); - array[i] = seg.get(JAVA_LONG_UNALIGNED, offset); - offset += Long.BYTES; - break; - case INTEGER_INDICATOR: - Util.checkBounds(offset, Integer.BYTES, seg.byteSize()); - array[i] = seg.get(JAVA_INT_UNALIGNED, offset); - offset += Integer.BYTES; - break; - case SHORT_INDICATOR: - Util.checkBounds(offset, Short.BYTES, seg.byteSize()); - array[i] = seg.get(JAVA_SHORT_UNALIGNED, offset); - offset += Short.BYTES; - break; - case BYTE_INDICATOR: - Util.checkBounds(offset, Byte.BYTES, seg.byteSize()); - array[i] = seg.get(JAVA_BYTE, offset); - offset += Byte.BYTES; - break; - case DOUBLE_INDICATOR: - Util.checkBounds(offset, Double.BYTES, seg.byteSize()); - array[i] = seg.get(JAVA_DOUBLE_UNALIGNED, offset); - offset += Double.BYTES; - break; - case FLOAT_INDICATOR: - Util.checkBounds(offset, Float.BYTES, seg.byteSize()); - array[i] = seg.get(JAVA_FLOAT_UNALIGNED, offset); - offset += Float.BYTES; - break; - default: - throw new SketchesArgumentException( - "Item must be one of: Long, Integer, Short, Byte, Double, Float. " - + "index: " + i + ", typeId: " + typeId); - } - } - return array; - } - - @Override - public int sizeOf(final Number item) { - Objects.requireNonNull(item, "Item must not be null"); - if ( item instanceof Long) { return Byte.BYTES + Long.BYTES; } - else if ( item instanceof Integer) { return Byte.BYTES + Integer.BYTES; } - else if ( item instanceof Short) { return Byte.BYTES + Short.BYTES; } - else if ( item instanceof Byte) { return Byte.BYTES + Byte.BYTES; } - else if ( item instanceof Double) { return Byte.BYTES + Double.BYTES; } - else if ( item instanceof Float) { return Byte.BYTES + Float.BYTES; } - else { throw new SketchesArgumentException( - "Item must be one of: Long, Integer, Short, Byte, Double, Float. " - + "item: " + item.toString()); } - } - - @Override - public int sizeOf(final Number[] items) { - Objects.requireNonNull(items, "Items must not be null"); - int totalBytes = 0; - for (final Number item : items) { - totalBytes += sizeOf(item); - } - return totalBytes; - } - - @Override - public int sizeOf(final MemorySegment seg, final long offsetBytes, final int numItems) { - Objects.requireNonNull(seg, "MemorySegment must not be null"); - long offset = offsetBytes; - for (int i = 0; i < numItems; i++) { - Util.checkBounds(offset, Byte.BYTES, seg.byteSize()); - final byte typeId = seg.get(JAVA_BYTE, offset); - offset += Byte.BYTES; - - switch (typeId) { - case LONG_INDICATOR: - Util.checkBounds(offset, Long.BYTES, seg.byteSize()); - offset += Long.BYTES; - break; - case INTEGER_INDICATOR: - Util.checkBounds(offset, Integer.BYTES, seg.byteSize()); - offset += Integer.BYTES; - break; - case SHORT_INDICATOR: - Util.checkBounds(offset, Short.BYTES, seg.byteSize()); - offset += Short.BYTES; - break; - case BYTE_INDICATOR: - Util.checkBounds(offset, Byte.BYTES, seg.byteSize()); - offset += Byte.BYTES; - break; - case DOUBLE_INDICATOR: - Util.checkBounds(offset, Double.BYTES, seg.byteSize()); - offset += Double.BYTES; - break; - case FLOAT_INDICATOR: - Util.checkBounds(offset, Float.BYTES, seg.byteSize()); - offset += Float.BYTES; - break; - default: - throw new SketchesArgumentException( - "Item must be one of: Long, Integer, Short, Byte, Double, Float. " - + "index: " + i + ", typeId: " + typeId); - } - } - return (int)(offset - offsetBytes); - } - - @Override - public String toString(final Number item) { - if (item == null) { return "null"; } - return item.toString(); - } - - @Override - public Class getClassOfT() { return Number.class; } -} diff --git a/src/main/java/org/apache/datasketches/common/ArrayOfStringsSerDe.java b/src/main/java/org/apache/datasketches/common/ArrayOfStringsSerDe.java deleted file mode 100644 index 72e2ebea4..000000000 --- a/src/main/java/org/apache/datasketches/common/ArrayOfStringsSerDe.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.common.ByteArrayUtil.copyBytes; -import static org.apache.datasketches.common.ByteArrayUtil.putIntLE; - -import java.lang.foreign.MemorySegment; -import java.nio.charset.StandardCharsets; -import java.util.Objects; - -/** - * Methods of serializing and deserializing arrays of String. - * This class serializes strings in UTF-8 format, which is more compact compared to - * {@link ArrayOfUtf16StringsSerDe}. In an extreme case when all strings are in ASCII, - * this method is 2 times more compact, but it takes more time to encode and decode - * by a factor of 1.5 to 2. - * - *

The serialization - * - * @author Alexander Saydakov - */ -public class ArrayOfStringsSerDe extends ArrayOfItemsSerDe { - - /** - * No argument constructor. - */ - public ArrayOfStringsSerDe() { } - - @Override - public byte[] serializeToByteArray(final String item) { - Objects.requireNonNull(item, "Item must not be null"); - if (item.isEmpty()) { return new byte[] { 0, 0, 0, 0 }; } - final byte[] utf8ByteArr = item.getBytes(StandardCharsets.UTF_8); - final int numBytes = utf8ByteArr.length; - final byte[] out = new byte[numBytes + Integer.BYTES]; - copyBytes(utf8ByteArr, 0, out, 4, numBytes); - putIntLE(out, 0, numBytes); - return out; - } - - @Override - public byte[] serializeToByteArray(final String[] items) { - Objects.requireNonNull(items, "Items must not be null"); - if (items.length == 0) { return new byte[0]; } - int totalBytes = 0; - final int numItems = items.length; - final byte[][] serialized2DArray = new byte[numItems][]; - for (int i = 0; i < numItems; i++) { - serialized2DArray[i] = items[i].getBytes(StandardCharsets.UTF_8); - totalBytes += serialized2DArray[i].length + Integer.BYTES; - } - final byte[] bytesOut = new byte[totalBytes]; - int offset = 0; - for (int i = 0; i < numItems; i++) { - final int utf8len = serialized2DArray[i].length; - putIntLE(bytesOut, offset, utf8len); - offset += Integer.BYTES; - copyBytes(serialized2DArray[i], 0, bytesOut, offset, utf8len); - offset += utf8len; - } - return bytesOut; - } - - @Override - public String[] deserializeFromMemorySegment(final MemorySegment seg, final int numItems) { - return deserializeFromMemorySegment(seg, 0, numItems); - } - - @Override - public String[] deserializeFromMemorySegment(final MemorySegment seg, final long offsetBytes, final int numItems) { - Objects.requireNonNull(seg, "MemorySegment must not be null"); - if (numItems <= 0) { return new String[0]; } - final String[] array = new String[numItems]; - long offset = offsetBytes; - for (int i = 0; i < numItems; i++) { - Util.checkBounds(offset, Integer.BYTES, seg.byteSize()); - final int strLength = seg.get(JAVA_INT_UNALIGNED, offset); - offset += Integer.BYTES; - final byte[] utf8Bytes = new byte[strLength]; - Util.checkBounds(offset, strLength, seg.byteSize()); - MemorySegment.copy(seg, JAVA_BYTE, offset, utf8Bytes, 0, strLength); - offset += strLength; - array[i] = new String(utf8Bytes, StandardCharsets.UTF_8); - } - return array; - } - - @Override - public int sizeOf(final String item) { - Objects.requireNonNull(item, "Item must not be null"); - if (item.isEmpty()) { return Integer.BYTES; } - return item.getBytes(StandardCharsets.UTF_8).length + Integer.BYTES; - } - - @Override - public int sizeOf(final MemorySegment seg, final long offsetBytes, final int numItems) { - Objects.requireNonNull(seg, "MemorySegment must not be null"); - if (numItems <= 0) { return 0; } - long offset = offsetBytes; - final long segCap = seg.byteSize(); - for (int i = 0; i < numItems; i++) { - Util.checkBounds(offset, Integer.BYTES, segCap); - final int itemLenBytes = seg.get(JAVA_INT_UNALIGNED, offset); - offset += Integer.BYTES; - Util.checkBounds(offset, itemLenBytes, segCap); - offset += itemLenBytes; - } - return (int)(offset - offsetBytes); - } - - @Override - public String toString(final String item) { - if (item == null) { return "null"; } - return item; - } - - @Override - public Class getClassOfT() { return String.class; } -} diff --git a/src/main/java/org/apache/datasketches/common/ArrayOfUtf16StringsSerDe.java b/src/main/java/org/apache/datasketches/common/ArrayOfUtf16StringsSerDe.java deleted file mode 100644 index cde46fc95..000000000 --- a/src/main/java/org/apache/datasketches/common/ArrayOfUtf16StringsSerDe.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.common.ByteArrayUtil.copyBytes; -import static org.apache.datasketches.common.ByteArrayUtil.putIntLE; - -import java.lang.foreign.MemorySegment; -import java.nio.charset.StandardCharsets; -import java.util.Objects; - -/** - * Methods of serializing and deserializing arrays of String. - * This class serializes strings using internal Java representation as char[], where each char - * is a 16-bit code. The result is larger than one from {@link ArrayOfStringsSerDe}. - * In an extreme case when all strings are in ASCII, the size is doubled. However it takes - * less time to serialize and deserialize by a factor of 1.5 to 2. - * - * @author Alexander Saydakov - */ -public class ArrayOfUtf16StringsSerDe extends ArrayOfItemsSerDe { - - /** - * No argument constructor. - */ - public ArrayOfUtf16StringsSerDe() { } - - @Override - public byte[] serializeToByteArray(final String item) { - Objects.requireNonNull(item, "Item must not be null"); - final byte[] utf16ByteArr = item.getBytes(StandardCharsets.UTF_16); //includes BOM - final int numBytes = utf16ByteArr.length; - final byte[] out = new byte[numBytes + Integer.BYTES]; - copyBytes(utf16ByteArr, 0, out, 4, numBytes); - putIntLE(out, 0, numBytes); - return out; - } - - @Override - public byte[] serializeToByteArray(final String[] items) { - Objects.requireNonNull(items, "Items must not be null"); - int totalBytes = 0; - final int numItems = items.length; - final byte[][] serialized2DArray = new byte[numItems][]; - for (int i = 0; i < numItems; i++) { - serialized2DArray[i] = items[i].getBytes(StandardCharsets.UTF_16); - totalBytes += serialized2DArray[i].length + Integer.BYTES; - } - final byte[] bytesOut = new byte[totalBytes]; - int offset = 0; - for (int i = 0; i < numItems; i++) { - final int utf8len = serialized2DArray[i].length; - putIntLE(bytesOut, offset, utf8len); - offset += Integer.BYTES; - copyBytes(serialized2DArray[i], 0, bytesOut, offset, utf8len); - offset += utf8len; - } - return bytesOut; - } - - @Override - public String[] deserializeFromMemorySegment(final MemorySegment seg, final int numItems) { - return deserializeFromMemorySegment(seg, 0, numItems); - } - - @Override - public String[] deserializeFromMemorySegment(final MemorySegment seg, final long offsetBytes, final int numItems) { - Objects.requireNonNull(seg, "MemorySegment must not be null"); - if (numItems <= 0) { return new String[0]; } - final String[] array = new String[numItems]; - long offset = offsetBytes; - for (int i = 0; i < numItems; i++) { - Util.checkBounds(offset, Integer.BYTES, seg.byteSize()); - final int strLength = seg.get(JAVA_INT_UNALIGNED, offset); - offset += Integer.BYTES; - final byte[] utf16Bytes = new byte[strLength]; - Util.checkBounds(offset, strLength, seg.byteSize()); - MemorySegment.copy(seg, JAVA_BYTE, offset, utf16Bytes, 0, strLength); - offset += strLength; - array[i] = new String(utf16Bytes, StandardCharsets.UTF_16); - } - return array; - } - - @Override - public int sizeOf(final String item) { - Objects.requireNonNull(item, "Item must not be null"); - return item.getBytes(StandardCharsets.UTF_16).length + Integer.BYTES; - } - - @Override - public int sizeOf(final MemorySegment seg, final long offsetBytes, final int numItems) { - Objects.requireNonNull(seg, "MemorySegment must not be null"); - long offset = offsetBytes; - final long segCap = seg.byteSize(); - for (int i = 0; i < numItems; i++) { - Util.checkBounds(offset, Integer.BYTES, segCap); - final int itemLenBytes = seg.get(JAVA_INT_UNALIGNED, offset); - offset += Integer.BYTES; - Util.checkBounds(offset, itemLenBytes, segCap); - offset += itemLenBytes; - } - return (int)(offset - offsetBytes); - } - - @Override - public String toString(final String item) { - if (item == null) { return "null"; } - return item; - } - - @Override - public Class getClassOfT() { return String.class; } -} diff --git a/src/main/java/org/apache/datasketches/common/BoundsOnBinomialProportions.java b/src/main/java/org/apache/datasketches/common/BoundsOnBinomialProportions.java deleted file mode 100644 index af69a1c83..000000000 --- a/src/main/java/org/apache/datasketches/common/BoundsOnBinomialProportions.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -/** - * Confidence intervals for binomial proportions. - * - *

This class computes an approximation to the Clopper-Pearson confidence interval - * for a binomial proportion. Exact Clopper-Pearson intervals are strictly - * conservative, but these approximations are not.

- * - *

The main inputs are numbers n and k, which are not the same as other things - * that are called n and k in our sketching library. There is also a third - * parameter, numStdDev, that specifies the desired confidence level.

- *
    - *
  • n is the number of independent randomized trials. It is given and therefore known.
  • - *
  • p is the probability of a trial being a success. It is unknown.
  • - *
  • k is the number of trials (out of n) that turn out to be successes. It is - * a random variable governed by a binomial distribution. After any given - * batch of n independent trials, the random variable k has a specific - * value which is observed and is therefore known.
  • - *
  • pHat = k / n is an unbiased estimate of the unknown success - * probability p.
  • - *
- * - *

Alternatively, consider a coin with unknown heads probability p. Where - * n is the number of independent flips of that coin, and k is the number - * of times that the coin comes up heads during a given batch of n flips. - * This class computes a frequentist confidence interval [lowerBoundOnP, upperBoundOnP] for the - * unknown p.

- * - *

Conceptually, the desired confidence level is specified by a tail probability delta.

- * - *

Ideally, over a large ensemble of independent batches of trials, - * the fraction of batches in which the true p lies below lowerBoundOnP would be at most - * delta, and the fraction of batches in which the true p lies above upperBoundOnP - * would also be at most delta. - * - *

Setting aside the philosophical difficulties attaching to that statement, it isn't quite - * true because we are approximating the Clopper-Pearson interval.

- * - *

Finally, we point out that in this class's interface, the confidence parameter delta is - * not specified directly, but rather through a "number of standard deviations" numStdDev. - * The library effectively converts that to a delta via delta = normalCDF (-1.0 * numStdDev).

- * - *

It is perhaps worth emphasizing that the library is NOT merely adding and subtracting - * numStdDev standard deviations to the estimate. It is doing something better, that to some - * extent accounts for the fact that the binomial distribution has a non-gaussian shape.

- * - *

In particular, it is using an approximation to the inverse of the incomplete beta function - * that appears as formula 26.5.22 on page 945 of the "Handbook of Mathematical Functions" - * by Abramowitz and Stegun.

- * - * @author Kevin Lang - */ -public final class BoundsOnBinomialProportions { // confidence intervals for binomial proportions - - private BoundsOnBinomialProportions() {} - - /** - * Computes lower bound of approximate Clopper-Pearson confidence interval for a binomial - * proportion. - * - *

Implementation Notes:
- * The approximateLowerBoundOnP is defined with respect to the right tail of the binomial - * distribution.

- *
    - *
  • We want to solve for the p for which sumj,k,nbino(j;n,p) - * = delta.
  • - *
  • We now restate that in terms of the left tail.
  • - *
  • We want to solve for the p for which sumj,0,(k-1)bino(j;n,p) - * = 1 - delta.
  • - *
  • Define x = 1-p.
  • - *
  • We want to solve for the x for which Ix(n-k+1,k) = 1 - delta.
  • - *
  • We specify 1-delta via numStdDevs through the right tail of the standard normal - * distribution.
  • - *
  • Smaller values of numStdDevs correspond to bigger values of 1-delta and hence to smaller - * values of delta. In fact, usefully small values of delta correspond to negative values of - * numStdDevs.
  • - *
  • return p = 1-x.
  • - *
- * - * @param n is the number of trials. Must be non-negative. - * @param k is the number of successes. Must be non-negative, and cannot exceed n. - * @param numStdDevs the number of standard deviations defining the confidence interval - * @return the lower bound of the approximate Clopper-Pearson confidence interval for the - * unknown success probability. - */ - public static double approximateLowerBoundOnP(final long n, final long k, final double numStdDevs) { - checkInputs(n, k); - if (n == 0) { return 0.0; } // the coin was never flipped, so we know nothing - else if (k == 0) { return 0.0; } - else if (k == 1) { return (exactLowerBoundOnPForKequalsOne(n, deltaOfNumStdevs(numStdDevs))); } - else if (k == n) { return (exactLowerBoundOnPForKequalsN(n, deltaOfNumStdevs(numStdDevs))); } - else { - final double x = abramowitzStegunFormula26p5p22((n - k) + 1, k, (-1.0 * numStdDevs)); - return (1.0 - x); // which is p - } - } - - /** - * Computes upper bound of approximate Clopper-Pearson confidence interval for a binomial - * proportion. - * - *

Implementation Notes:
- * The approximateUpperBoundOnP is defined with respect to the left tail of the binomial - * distribution.

- *
    - *
  • We want to solve for the p for which sumj,0,kbino(j;n,p) - * = delta.
  • - *
  • Define x = 1-p.
  • - *
  • We want to solve for the x for which Ix(n-k,k+1) = delta.
  • - *
  • We specify delta via numStdDevs through the right tail of the standard normal - * distribution.
  • - *
  • Bigger values of numStdDevs correspond to smaller values of delta.
  • - *
  • return p = 1-x.
  • - *
- * @param n is the number of trials. Must be non-negative. - * @param k is the number of successes. Must be non-negative, and cannot exceed n. - * @param numStdDevs the number of standard deviations defining the confidence interval - * @return the upper bound of the approximate Clopper-Pearson confidence interval for the - * unknown success probability. - */ - public static double approximateUpperBoundOnP(final long n, final long k, final double numStdDevs) { - checkInputs(n, k); - if (n == 0) { return 1.0; } // the coin was never flipped, so we know nothing - else if (k == n) { return 1.0; } - else if (k == (n - 1)) { - return (exactUpperBoundOnPForKequalsNminusOne(n, deltaOfNumStdevs(numStdDevs))); - } - else if (k == 0) { - return (exactUpperBoundOnPForKequalsZero(n, deltaOfNumStdevs(numStdDevs))); - } - else { - final double x = abramowitzStegunFormula26p5p22(n - k, k + 1, numStdDevs); - return (1.0 - x); // which is p - } - } - - /** - * Computes an estimate of an unknown binomial proportion. - * @param n is the number of trials. Must be non-negative. - * @param k is the number of successes. Must be non-negative, and cannot exceed n. - * @return the estimate of the unknown binomial proportion. - */ - public static double estimateUnknownP(final long n, final long k) { - checkInputs(n, k); - if (n == 0) { return 0.5; } // the coin was never flipped, so we know nothing - else { return ((double) k / (double) n); } - } - - private static void checkInputs(final long n, final long k) { - if (n < 0) { throw new SketchesArgumentException("N must be non-negative"); } - if (k < 0) { throw new SketchesArgumentException("K must be non-negative"); } - if (k > n) { throw new SketchesArgumentException("K cannot exceed N"); } - } - - /** - * Computes an approximation to the erf() function. - * @param x is the input to the erf function - * @return returns erf(x), accurate to roughly 7 decimal digits. - */ - public static double erf(final double x) { - if (x < 0.0) { return (-1.0 * (erf_of_nonneg(-1.0 * x))); } - else { return (erf_of_nonneg(x)); } - } - - /** - * Computes an approximation to normalCDF(x). - * @param x is the input to the normalCDF function - * @return returns the approximation to normalCDF(x). - */ - public static double normalCDF(final double x) { - return (0.5 * (1.0 + (erf(x / (Math.sqrt(2.0)))))); - } - - //@formatter:off - // Abramowitz and Stegun formula 7.1.28, p. 88; Claims accuracy of about 7 decimal digits - private static double erf_of_nonneg(final double x) { - // The constants from the book - final double a1 = 0.07052_30784; - final double a3 = 0.00927_05272; - final double a5 = 0.00027_65672; - final double a2 = 0.04228_20123; - final double a4 = 0.00015_20143; - final double a6 = 0.00004_30638; - final double x2 = x * x; // x squared, x cubed, etc. - final double x3 = x2 * x; - final double x4 = x2 * x2; - final double x5 = x2 * x3; - final double x6 = x3 * x3; - final double sum = ( 1.0 - + (a1 * x) - + (a2 * x2) - + (a3 * x3) - + (a4 * x4) - + (a5 * x5) - + (a6 * x6) ); - final double sum2 = sum * sum; // raise the sum to the 16th power - final double sum4 = sum2 * sum2; - final double sum8 = sum4 * sum4; - final double sum16 = sum8 * sum8; - return (1.0 - (1.0 / sum16)); - } - //@formatter:on - - private static double deltaOfNumStdevs(final double kappa) { - return (normalCDF(-1.0 * kappa)); - } - - // Formula 26.5.22 on page 945 of Abramowitz & Stegun, which is an approximation - // of the inverse of the incomplete beta function I_x(a,b) = delta - // viewed as a scalar function of x. - // In other words, we specify delta, and it gives us x (with a and b held constant). - // However, delta is specified in an indirect way through yp which - // is the number of stdDevs that leaves delta probability in the right - // tail of a standard gaussian distribution. - - // We point out that the variable names correspond to those in the book, - // and it is worth keeping it that way so that it will always be easy to verify - // that the formula was typed in correctly. - - private static double abramowitzStegunFormula26p5p22(final double a, final double b, - final double yp) { - final double b2m1 = (2.0 * b) - 1.0; - final double a2m1 = (2.0 * a) - 1.0; - final double lambda = ((yp * yp) - 3.0) / 6.0; - final double htmp = (1.0 / a2m1) + (1.0 / b2m1); - final double h = 2.0 / htmp; - final double term1 = (yp * (Math.sqrt(h + lambda))) / h; - final double term2 = (1.0 / b2m1) - (1.0 / a2m1); - final double term3 = (lambda + (5.0 / 6.0)) - (2.0 / (3.0 * h)); - final double w = term1 - (term2 * term3); - final double xp = a / (a + (b * (Math.exp(2.0 * w)))); - return xp; - } - - // Formulas for some special cases. - - private static double exactUpperBoundOnPForKequalsZero(final double n, final double delta) { - return (1.0 - Math.pow(delta, (1.0 / n))); - } - - private static double exactLowerBoundOnPForKequalsN(final double n, final double delta) { - return (Math.pow(delta, (1.0 / n))); - } - - private static double exactLowerBoundOnPForKequalsOne(final double n, final double delta) { - return (1.0 - Math.pow((1.0 - delta), (1.0 / n))); - } - - private static double exactUpperBoundOnPForKequalsNminusOne(final double n, final double delta) { - return (Math.pow((1.0 - delta), (1.0 / n))); - } - -} diff --git a/src/main/java/org/apache/datasketches/common/BoundsOnRatiosInSampledSets.java b/src/main/java/org/apache/datasketches/common/BoundsOnRatiosInSampledSets.java deleted file mode 100644 index b65afe43a..000000000 --- a/src/main/java/org/apache/datasketches/common/BoundsOnRatiosInSampledSets.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static org.apache.datasketches.common.BoundsOnBinomialProportions.approximateLowerBoundOnP; -import static org.apache.datasketches.common.BoundsOnBinomialProportions.approximateUpperBoundOnP; - -/** - * This class is used to compute the bounds on the estimate of the ratio |B| / |A|, where: - *
    - *
  • |A| is the unknown size of a set A of unique identifiers.
  • - *
  • |B| is the unknown size of a subset B of A.
  • - *
  • a = |SA| is the observed size of a sample of A - * that was obtained by Bernoulli sampling with a known inclusion probability f.
  • - *
  • b = |SA ∩ B| is the observed size of a subset - * of SA.
  • - *
- * - * @author Kevin Lang - */ -public final class BoundsOnRatiosInSampledSets { - private static final double NUM_STD_DEVS = 2.0; //made a constant to simplify interface. - - private BoundsOnRatiosInSampledSets() {} - - /** - * Return the approximate lower bound based on a 95% confidence interval - * @param a See class javadoc - * @param b See class javadoc - * @param f the inclusion probability used to produce the set with size a and should - * generally be less than 0.5. Above this value, the results not be reliable. - * When f = 1.0 this returns the estimate. - * @return the approximate upper bound - */ - public static double getLowerBoundForBoverA(final long a, final long b, final double f) { - checkInputs(a, b, f); - if (a == 0) { return 0.0; } - if (f == 1.0) { return (double) b / a; } - return approximateLowerBoundOnP(a, b, NUM_STD_DEVS * hackyAdjuster(f)); - } - - /** - * Return the approximate upper bound based on a 95% confidence interval - * @param a See class javadoc - * @param b See class javadoc - * @param f the inclusion probability used to produce the set with size a. - * @return the approximate lower bound - */ - public static double getUpperBoundForBoverA(final long a, final long b, final double f) { - checkInputs(a, b, f); - if (a == 0) { return 1.0; } - if (f == 1.0) { return (double) b / a; } - return approximateUpperBoundOnP(a, b, NUM_STD_DEVS * hackyAdjuster(f)); - } - - /** - * Return the estimate of b over a - * @param a See class javadoc - * @param b See class javadoc - * @return the estimate of b over a - */ - public static double getEstimateOfBoverA(final long a, final long b) { - checkInputs(a, b, 0.3); - if (a == 0) { return 0.5; } - return (double) b / a; - } - - /** - * Return the estimate of A. See class javadoc. - * @param a See class javadoc - * @param f the inclusion probability used to produce the set with size a. - * @return the approximate lower bound - */ - public static double getEstimateOfA(final long a, final double f) { - checkInputs(a, 1, f); - return a / f; - } - - /** - * Return the estimate of B. See class javadoc. - * @param b See class javadoc - * @param f the inclusion probability used to produce the set with size b. - * @return the approximate lower bound - */ - public static double getEstimateOfB(final long b, final double f) { - checkInputs(b + 1, b, f); - return b / f; - } - - /** - * This hackyAdjuster is tightly coupled with the width of the confidence interval normally - * specified with number of standard deviations. To simplify this interface the number of - * standard deviations has been fixed to 2.0, which corresponds to a confidence interval of - * 95%. - * @param f the inclusion probability used to produce the set with size a. - * @return the hacky Adjuster - */ - private static double hackyAdjuster(final double f) { - final double tmp = Math.sqrt(1.0 - f); - return (f <= 0.5) ? tmp : tmp + (0.01 * (f - 0.5)); - } - - static void checkInputs(final long a, final long b, final double f) { - if ( ( (a - b) | (a) | (b) ) < 0) { //if any group goes negative - throw new SketchesArgumentException( - "a must be >= b and neither a nor b can be < 0: a = " + a + ", b = " + b); - } - if ((f > 1.0) || (f <= 0.0)) { - throw new SketchesArgumentException("Required: ((f <= 1.0) && (f > 0.0)): " + f); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/common/ByteArrayUtil.java b/src/main/java/org/apache/datasketches/common/ByteArrayUtil.java deleted file mode 100644 index abf16eede..000000000 --- a/src/main/java/org/apache/datasketches/common/ByteArrayUtil.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -/** - * Useful methods for byte arrays. - * @author Lee Rhodes - */ -public final class ByteArrayUtil { - - /** - * No argument constructor. - */ - public ByteArrayUtil() { } - - /** - * Copies bytes from source to target with offsets on both the source and target. - * @param source the given source - * @param srcStart the source starting index - * @param target the give target - * @param tgtStart the target starting index - * @param numBytes the number of bytes to be transferred. - */ - public static void copyBytes(final byte[] source, final int srcStart, - final byte[] target, final int tgtStart, final int numBytes) { - Util.checkBounds(srcStart, numBytes, source.length); - Util.checkBounds(tgtStart, numBytes, target.length); - for (int i = 0, j = srcStart, k = tgtStart; i < numBytes; i++) { - target[k++] = source[j++]; - } - } - - /** - * Get a short from the given byte array starting at the given offset - * in little endian order. - * There is no bounds checking. - * @param array source byte array - * @param offset source offset - * @return the short - */ - public static short getShortLE(final byte[] array, final int offset) { - return (short) ((array[offset ] & 0XFF ) - | ((array[offset + 1] & 0XFF) << 8)); - } - - /** - * Put the source short into the destination byte array starting at the given offset - * in little endian order. - * There is no bounds checking. - * @param array destination byte array - * @param offset destination offset - * @param value source short - */ - public static void putShortLE(final byte[] array, final int offset, final short value) { - array[offset ] = (byte) (value ); - array[offset + 1] = (byte) (value >>> 8); - } - - /** - * Get a short from the given byte array starting at the given offset - * in big endian order. - * There is no bounds checking. - * @param array source byte array - * @param offset source offset - * @return the short - */ - public static short getShortBE(final byte[] array, final int offset) { - return (short) ((array[offset + 1] & 0XFF ) - | ((array[offset ] & 0XFF) << 8)); - } - - /** - * Put the source short into the destination byte array starting at the given offset - * in big endian order. - * There is no bounds checking. - * @param array destination byte array - * @param offset destination offset - * @param value source short - */ - public static void putShortBE(final byte[] array, final int offset, final short value) { - array[offset + 1] = (byte) (value ); - array[offset ] = (byte) (value >>> 8); - } - - /** - * Get a int from the given byte array starting at the given offset - * in little endian order. - * There is no bounds checking. - * @param array source byte array - * @param offset source offset - * @return the int - */ - public static int getIntLE(final byte[] array, final int offset) { - return ( array[offset ] & 0XFF ) - | ((array[offset + 1] & 0XFF) << 8) - | ((array[offset + 2] & 0XFF) << 16) - | ((array[offset + 3] & 0XFF) << 24); - } - - /** - * Put the source int into the destination byte array starting at the given offset - * in little endian order. - * There is no bounds checking. - * @param array destination byte array - * @param offset destination offset - * @param value source int - */ - public static void putIntLE(final byte[] array, final int offset, final int value) { - array[offset ] = (byte) (value ); - array[offset + 1] = (byte) (value >>> 8); - array[offset + 2] = (byte) (value >>> 16); - array[offset + 3] = (byte) (value >>> 24); - } - - /** - * Get a int from the given byte array starting at the given offset - * in big endian order. - * There is no bounds checking. - * @param array source byte array - * @param offset source offset - * @return the int - */ - public static int getIntBE(final byte[] array, final int offset) { - return ( array[offset + 3] & 0XFF ) - | ((array[offset + 2] & 0XFF) << 8) - | ((array[offset + 1] & 0XFF) << 16) - | ((array[offset ] & 0XFF) << 24); - } - - /** - * Put the source int into the destination byte array starting at the given offset - * in big endian order. - * There is no bounds checking. - * @param array destination byte array - * @param offset destination offset - * @param value source int - */ - public static void putIntBE(final byte[] array, final int offset, final int value) { - array[offset + 3] = (byte) (value ); - array[offset + 2] = (byte) (value >>> 8); - array[offset + 1] = (byte) (value >>> 16); - array[offset ] = (byte) (value >>> 24); - } - - /** - * Get a long from the given byte array starting at the given offset - * in little endian order. - * There is no bounds checking. - * @param array source byte array - * @param offset source offset - * @return the long - */ - public static long getLongLE(final byte[] array, final int offset) { - return ( array[offset ] & 0XFFL ) - | ((array[offset + 1] & 0XFFL) << 8) - | ((array[offset + 2] & 0XFFL) << 16) - | ((array[offset + 3] & 0XFFL) << 24) - | ((array[offset + 4] & 0XFFL) << 32) - | ((array[offset + 5] & 0XFFL) << 40) - | ((array[offset + 6] & 0XFFL) << 48) - | ((array[offset + 7] & 0XFFL) << 56); - } - - /** - * Put the source long into the destination byte array starting at the given offset - * in little endian order. - * There is no bounds checking. - * @param array destination byte array - * @param offset destination offset - * @param value source long - */ - public static void putLongLE(final byte[] array, final int offset, final long value) { - array[offset ] = (byte) (value ); - array[offset + 1] = (byte) (value >>> 8); - array[offset + 2] = (byte) (value >>> 16); - array[offset + 3] = (byte) (value >>> 24); - array[offset + 4] = (byte) (value >>> 32); - array[offset + 5] = (byte) (value >>> 40); - array[offset + 6] = (byte) (value >>> 48); - array[offset + 7] = (byte) (value >>> 56); - } - - /** - * Get a long from the source byte array starting at the given offset - * in big endian order. - * There is no bounds checking. - * @param array source byte array - * @param offset source starting point - * @return the long - */ - public static long getLongBE(final byte[] array, final int offset) { - return ( array[offset + 7] & 0XFFL ) - | ((array[offset + 6] & 0XFFL) << 8) - | ((array[offset + 5] & 0XFFL) << 16) - | ((array[offset + 4] & 0XFFL) << 24) - | ((array[offset + 3] & 0XFFL) << 32) - | ((array[offset + 2] & 0XFFL) << 40) - | ((array[offset + 1] & 0XFFL) << 48) - | ((array[offset ] & 0XFFL) << 56); - } - - /** - * Put the source long into the destination byte array starting at the given offset - * in big endian order. - * There is no bounds checking. - * @param array destination byte array - * @param offset destination starting point - * @param value source long - */ - public static void putLongBE(final byte[] array, final int offset, final long value) { - array[offset + 7] = (byte) (value ); - array[offset + 6] = (byte) (value >>> 8); - array[offset + 5] = (byte) (value >>> 16); - array[offset + 4] = (byte) (value >>> 24); - array[offset + 3] = (byte) (value >>> 32); - array[offset + 2] = (byte) (value >>> 40); - array[offset + 1] = (byte) (value >>> 48); - array[offset ] = (byte) (value >>> 56); - } - - /** - * Get a float from the given byte array starting at the given offset - * in little endian order. - * There is no bounds checking. - * @param array source byte array - * @param offset source offset - * @return the float - */ - public static float getFloatLE(final byte[] array, final int offset) { - return Float.intBitsToFloat(getIntLE(array, offset)); - } - - /** - * Put the source float into the destination byte array starting at the given offset - * in little endian order. - * There is no bounds checking. - * @param array destination byte array - * @param offset destination offset - * @param value source float - */ - public static void putFloatLE(final byte[] array, final int offset, final float value) { - putIntLE(array, offset, Float.floatToRawIntBits(value)); - } - - /** - * Get a float from the given byte array starting at the given offset - * in big endian order. - * There is no bounds checking. - * @param array source byte array - * @param offset source offset - * @return the float - */ - public static float getFloatBE(final byte[] array, final int offset) { - return Float.intBitsToFloat(getIntBE(array, offset)); - } - - /** - * Put the source float into the destination byte array starting at the given offset - * in big endian order. - * There is no bounds checking. - * @param array destination byte array - * @param offset destination offset - * @param value source float - */ - public static void putFloatBE(final byte[] array, final int offset, final float value) { - putIntBE(array, offset, Float.floatToRawIntBits(value)); - } - - /** - * Get a double from the given byte array starting at the given offset - * in little endian order. - * There is no bounds checking. - * @param array source byte array - * @param offset source offset - * @return the double - */ - public static double getDoubleLE(final byte[] array, final int offset) { - return Double.longBitsToDouble(getLongLE(array, offset)); - } - - /** - * Put the source double into the destination byte array starting at the given offset - * in little endian order. - * There is no bounds checking. - * @param array destination byte array - * @param offset destination offset - * @param value source double - */ - public static void putDoubleLE(final byte[] array, final int offset, final double value) { - putLongLE(array, offset, Double.doubleToRawLongBits(value)); - } - - /** - * Get a double from the given byte array starting at the given offset - * in big endian order. - * There is no bounds checking. - * @param array source byte array - * @param offset source offset - * @return the double - */ - public static double getDoubleBE(final byte[] array, final int offset) { - return Double.longBitsToDouble(getLongBE(array, offset)); - } - - /** - * Put the source double into the destination byte array starting at the given offset - * in big endian order. - * There is no bounds checking. - * @param array destination byte array - * @param offset destination offset - * @param value source double - */ - public static void putDoubleBE(final byte[] array, final int offset, final double value) { - putLongBE(array, offset, Double.doubleToRawLongBits(value)); - } - -} diff --git a/src/main/java/org/apache/datasketches/common/Family.java b/src/main/java/org/apache/datasketches/common/Family.java deleted file mode 100644 index 032373685..000000000 --- a/src/main/java/org/apache/datasketches/common/Family.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import java.nio.ByteOrder; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -/** - * Defines the various families of sketch and set operation classes. A family defines a set of - * classes that share fundamental algorithms and behaviors. The classes within a family may - * still differ by how they are stored and accessed. For example, internally there are separate - * classes for the QuickSelect sketch algorithm that operate on the Java heap and off-heap. - * Not all of these families have parallel forms on and off-heap but are included for completeness. - * - * @author Lee Rhodes - */ -public enum Family { - /** - * The Alpha Sketch family is a member of the Theta Sketch Framework of sketches and is best - * suited for real-time processes where both the updating of the sketch and getting the estimate - * is performed directly on the sketch. In this situation the AlphaSketch has roughly a - * 30% improvement (~1/sqrt(2*k)) in its error distribution as compared to the QuickSelect - * (or similar KMV-derived) sketches. - * - *

If the AlphaSketch is fed into any ThetaSetOperation, the error distribution reverts back to the - * normal QuickSelect/KMV error distribution (~1/sqrt(k)). For this reason, the AlphaSketch - * does not have a sister class for off-heap operation. The AlphaSketch has a roughly 30% faster - * overall update time as compared to the QuickSelect sketch family.

- * - *

The AlphaSketch is created using the UpdatableThetaSketchBuilder(). - * See Alpha TCF and - * Theta Sketch Framework - */ - ALPHA(1, "Alpha", 3, 3), - - /** - * The QuickSelect Sketch family is a member of the Theta Sketch Framework of sketches and - * is the workhorse of the Theta Sketch Families and can be constructed for either on-heap or - * off-heap operation. - * The QuickSelect Sketch is created using the UpdatableThetaSketchBuilder(). - * See Quick Select TCF - */ - QUICKSELECT(2, "QuickSelect", 3, 3), - - /** - * The Compact Sketch family is a member of the Theta Sketch Framework of sketches. - * They are read-only and cannot be updated, but can participate in any of the Set Operations. - * The compact sketches are never created directly with a constructor or builder. - * Instead they are created as a result of the compact() - * method of an UpdatableThetaSketch or as a result of a getSketchSamples() of a ThetaSetOperation. - */ - COMPACT(3, "Compact", 1, 3), - - /** - * The Union family is an operation for the Theta Sketch Framework of sketches. - * The Union is constructed using the ThetaSetOperationBuilder(). - */ - UNION(4, "Union", 4, 4), - - /** - * The Intersection family is an operation for the Theta Sketch Framework of sketches. - * The ThetaIntersection is constructed using the ThetaSetOperationBuilder(). - */ - INTERSECTION(5, "Intersection", 3, 3), - - /** - * The A and not B family is an operation for the Theta Sketch Framework of sketches. - * The ThetaAnotB operation is constructed using the ThetaSetOperationBuilder(). - */ - A_NOT_B(6, "AnotB", 3, 3), - - /** - * The HLL family of sketches. (Not part of TSF.) - */ - HLL(7, "HLL", 1, 1), - - /** - * The Quantiles family of sketches. (Not part of TSF.) - */ - QUANTILES(8, "QUANTILES", 1, 2), - - /** - * The Tuple family of sketches is a large family of sketches that are extensions of the - * Theta Sketch Framework. - */ - TUPLE(9, "TUPLE", 1, 3), - - /** - * The Frequency family of sketches. (Not part of TSF.) - */ - FREQUENCY(10, "FREQUENCY", 1, 4), - - /** - * The Reservoir family of sketches. (Not part of TSF.) - */ - RESERVOIR(11, "RESERVOIR", 1, 2), - - /** - * The reservoir sampling family of Union operations. (Not part of TSF.) - */ - RESERVOIR_UNION(12, "RESERVOIR_UNION", 1, 1), - - /** - * The VarOpt family of sketches. (Not part of TSF.) - */ - VAROPT(13, "VAROPT", 1, 4), - - /** - * The VarOpt family of sketches. (Not part of TSF.) - */ - VAROPT_UNION(14, "VAROPT_UNION", 1, 4), - - /** - * KLL quantiles sketch - */ - KLL(15, "KLL", 1, 2), - - /** - * Compressed Probabilistic Counting (CPC) Sketch - */ - CPC(16, "CPC", 1, 5), - - /** - * Relative Error Quantiles Sketch - */ - REQ(17, "REQ", 1, 2), - - /** - * CountMin Sketch - */ - COUNTMIN(18, "COUNTMIN", 2, 2), - - /** - * Exact and Bounded, Probability Proportional to Size (EBPPS) - */ - EBPPS(19, "EBPPS", 1, 5), - - /** - * t-Digest for estimating quantiles and ranks - */ - TDIGEST(20, "TDigest", 1, 2), - - /** - * Bloom Filter - */ - BLOOMFILTER(21, "BLOOMFILTER", 3, 4); - - private static final Map lookupID = new HashMap<>(); - private static final Map lookupFamName = new HashMap<>(); - private final int id_; - private final String famName_; - private final int minPreLongs_; - private final int maxPreLongs_; - - static { - for (final Family f : values()) { - lookupID.put(f.getID(), f); - lookupFamName.put(f.getFamilyName().toUpperCase(Locale.US), f); - } - if (ByteOrder.nativeOrder() != ByteOrder.LITTLE_ENDIAN) { - throw new SketchesNotSupportedException("Machine Native Endianness must be LITTLE_ENDIAN."); - } - } - - Family(final int id, final String famName, final int minPreLongs, final int maxPreLongs) { - id_ = id; - famName_ = famName.toUpperCase(Locale.US); - minPreLongs_ = minPreLongs; - maxPreLongs_ = maxPreLongs; - } - - /** - * Returns the byte ID for this family - * @return the byte ID for this family - */ - @SuppressFBWarnings(value = "NM_CONFUSING", justification = "Harmless, will not fix") - public int getID() { - return id_; - } - - /** - * Checks the given Family ID - * @param id the given id, a value < 128. - */ - public void checkFamilyID(final int id) { - if (id != id_) { - throw new SketchesArgumentException( - "Possible Corruption: This Family " + toString() - + " does not match the ID of the given Family: " + idToFamily(id).toString()); - } - } - - /** - * Returns the name for this family - * @return the name for this family - */ - public String getFamilyName() { - return famName_; - } - - /** - * Returns the minimum preamble size for this family in longs - * @return the minimum preamble size for this family in longs - */ - public int getMinPreLongs() { - return minPreLongs_; - } - - /** - * Returns the maximum preamble size for this family in longs - * @return the maximum preamble size for this family in longs - */ - public int getMaxPreLongs() { - return maxPreLongs_; - } - - @Override - public String toString() { - return famName_; - } - - /** - * Returns the Family given the ID - * @param id the given ID - * @return the Family given the ID - */ - public static Family idToFamily(final int id) { - final Family f = lookupID.get(id); - if (f == null) { - throw new SketchesArgumentException("Possible Corruption: Illegal Family ID: " + id); - } - return f; - } - - /** - * Returns the Family given the family name - * @param famName the family name - * @return the Family given the family name - */ - public static Family stringToFamily(final String famName) { - final Family f = lookupFamName.get(famName.toUpperCase(Locale.US)); - if (f == null) { - throw new SketchesArgumentException("Possible Corruption: Illegal Family Name: " + famName); - } - return f; - } - -} diff --git a/src/main/java/org/apache/datasketches/common/MemorySegmentRequest.java b/src/main/java/org/apache/datasketches/common/MemorySegmentRequest.java deleted file mode 100644 index 8a10f277a..000000000 --- a/src/main/java/org/apache/datasketches/common/MemorySegmentRequest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import java.lang.foreign.MemorySegment; - -/** - * This is a callback interface to provide a means to request a new MemorySegment of a specified size. - * - * @author Lee Rhodes - */ -public interface MemorySegmentRequest { - - /** - * Request a new heap MemorySegment with the given newByteSize. - * Because we do not have a reference to an Arena, the default here is to - * allocate a new MemorySegment on the heap. It is up to the user to override this as appropriate. - * @param newByteSize The new byteSize being requested. - * @return new MemorySegment with the requested byteSize. - */ - default MemorySegment request(final long newByteSize) { - if (newByteSize > Integer.MAX_VALUE) { - throw new SketchesArgumentException("Requested size in bytes exceeds Integer.MAX_VALUE."); - } - return MemorySegment.ofArray(new byte[(int)newByteSize]); - } - - /** - * Request to close the given MemorySegment. - * Because we do not have a reference to an Arena, the default here is to do nothing. - * It is up to the user to override this as appropriate. - * @param prevSeg the previous MemorySegment to be closed. - */ - default void requestClose(final MemorySegment prevSeg) { - //Because the default request goes on the heap, this default is a no-op - } - - /** - * A convenience class that implements a default implementation. - */ - public static class Default implements MemorySegmentRequest { - - /** - * No argument constructor that creates the target for the static member DEFAULT. - */ - public Default() { } - } - - /** - * Create Default as static member. - */ - Default DEFAULT = new Default(); - -} diff --git a/src/main/java/org/apache/datasketches/common/MemorySegmentRequestExample.java b/src/main/java/org/apache/datasketches/common/MemorySegmentRequestExample.java deleted file mode 100644 index fbf2521b8..000000000 --- a/src/main/java/org/apache/datasketches/common/MemorySegmentRequestExample.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; -import java.util.Enumeration; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; - -/** - * This is an example of a possible implementation of the MemorySegmentRequest interface - * where all requested segments are allocated off-heap. A local ConcurrentHashMap tracks a newly created - * confined Arena for every new MemorySegment allocated off-heap. This allows individual segments to be freed - * immediately upon receiving the {@link #requestClose(MemorySegment) requestClose(MemorySegment)} call. - */ -public final class MemorySegmentRequestExample implements MemorySegmentRequest { - private final ConcurrentHashMap map = new ConcurrentHashMap<>(); - - /** - * No argument constructor. - */ - public MemorySegmentRequestExample() { } - - /** - * Request a new off-heap MemorySegment with the given newByteSeze. - * An internal confined Arena is created to exclusively manage the new segment and it is associated - * with the new segment with a ConcurrentHashMap. - */ - @Override - public synchronized MemorySegment request(final long newByteSize) { - final Arena arena = Arena.ofConfined(); - final MemorySegment seg = arena.allocate(newByteSize); - map.put(seg, arena); - return seg; - - } - - @Override - public synchronized void requestClose(final MemorySegment segKey) { - Objects.requireNonNull(segKey, "MemorySegment segKey must not be null"); - final Arena arena = map.get(segKey); - if (arena != null) { - if (arena.scope().isAlive()) { arena.close(); } - map.remove(segKey); - } else { - //ignore or - //throw new SketchesArgumentException("Given MemorySegment key is not mapped to an Arena!"); - } - } - - /** - * This closes any unclosed, off-heap MemorySegments and removes all mappings from the map. - */ - public synchronized void cleanup() { - for (final Enumeration e = map.elements(); e.hasMoreElements(); ) { - final Arena arena = e.nextElement(); - if (arena.scope().isAlive()) { arena.close(); } - } - map.clear(); - } - -} diff --git a/src/main/java/org/apache/datasketches/common/MemorySegmentStatus.java b/src/main/java/org/apache/datasketches/common/MemorySegmentStatus.java deleted file mode 100644 index 7e4ebcd38..000000000 --- a/src/main/java/org/apache/datasketches/common/MemorySegmentStatus.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; -import java.util.Optional; - -/** - * Methods for inquiring the status of a backing MemorySegment. - */ -public interface MemorySegmentStatus { - - /** - * Returns true if this object's internal data is backed by a MemorySegment, - * which may be on-heap or off-heap. - * @return true if this object's internal data is backed by a MemorySegment. - */ - boolean hasMemorySegment(); - - /** - * Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment. - * @return true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment. - */ - boolean isOffHeap(); - - /** - * Returns true if an internally referenced MemorySegment has the same backing resource as that, - * or equivalently, if their two memory regions overlap. This applies to both on-heap and off-heap MemorySegments. - * - *

Note: If both segments are on-heap and not read-only, it can be determined if they were derived from - * the same backing memory (array). However, this is not always possible off-heap. Because of this asymmetry, this definition - * of "isSameResource" is confined to the existence of an overlap.

- * - * @param that The given MemorySegment. - * @return true if an internally referenced MemorySegment has the same backing resource as that. - */ - boolean isSameResource(final MemorySegment that); - - /** - * Returns true if the two given MemorySegments have to the same backing resource, or equivalently, - * if the two memory regions overlap. This applies to both on-heap and off-heap MemorySegments. - * - *

Note: If both segments are on-heap and not read-only, it can be determined if they were derived from - * the same backing memory (array). However, this is not always possible off-heap. Because of this asymmetry, this definition - * of "isSameResource" is confined to the existence of an overlap.

- * - * @param seg1 The first given MemorySegment - * @param seg2 The second given MemorySegment - * @return true if the two given MemorySegments have to the same backing resource. - */ - static boolean isSameResource(final MemorySegment seg1, final MemorySegment seg2) { - Objects.requireNonNull(seg1, "MemorySegment seg1 must be non-null."); - Objects.requireNonNull(seg2, "MemorySegment seg2 must be non-null."); - final Optional opt = seg1.asOverlappingSlice(seg2); - return opt.isPresent(); - } - -} diff --git a/src/main/java/org/apache/datasketches/common/QuickSelect.java b/src/main/java/org/apache/datasketches/common/QuickSelect.java deleted file mode 100644 index aa32af575..000000000 --- a/src/main/java/org/apache/datasketches/common/QuickSelect.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -/** - * QuickSelect algorithm improved from Sedgewick. Gets the kth order value - * (1-based or 0-based) from the array. - * Warning! This changes the ordering of elements in the given array!
- * Also see:
- * blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html
- * See QuickSelectTest for examples and testNG tests. - * - * @author Lee Rhodes - */ -public final class QuickSelect { - - private QuickSelect() {} - - /** - * Gets the 0-based kth order statistic from the array. Warning! This changes the ordering - * of elements in the given array! - * - * @param arr The array to be re-arranged. - * @param lo The lowest 0-based index to be considered. - * @param hi The highest 0-based index to be considered. - * @param pivot The 0-based index of the value to pivot on. - * @return The value of the smallest (n)th element where n is 0-based. - */ - public static long select(final long[] arr, int lo, int hi, final int pivot) { - while (hi > lo) { - final int j = partition(arr, lo, hi); - if (j == pivot) { - return arr[pivot]; - } - if (j > pivot) { - hi = j - 1; - } - else { - lo = j + 1; - } - } - return arr[pivot]; - } - - /** - * Gets the 1-based kth order statistic from the array including any zero values in the - * array. Warning! This changes the ordering of elements in the given array! - * - * @param arr The hash array. - * @param pivot The 1-based index of the value that is chosen as the pivot for the array. - * After the operation all values below this 1-based index will be less than this value - * and all values above this index will be greater. The 0-based index of the pivot will be - * pivot-1. - * @return The value of the smallest (N)th element including zeros, where N is 1-based. - */ - public static long selectIncludingZeros(final long[] arr, final int pivot) { - final int arrSize = arr.length; - final int adj = pivot - 1; - return select(arr, 0, arrSize - 1, adj); - } - - /** - * Gets the 1-based kth order statistic from the array excluding any zero values in the - * array. Warning! This changes the ordering of elements in the given array! - * - * @param arr The hash array. - * @param nonZeros The number of non-zero values in the array. - * @param pivot The 1-based index of the value that is chosen as the pivot for the array. - * After the operation all values below this 1-based index will be less than this value - * and all values above this index will be greater. The 0-based index of the pivot will be - * pivot+arr.length-nonZeros-1. - * @return The value of the smallest (N)th element excluding zeros, where N is 1-based. - */ - public static long selectExcludingZeros(final long[] arr, final int nonZeros, final int pivot) { - if (pivot > nonZeros) { - return 0L; - } - final int arrSize = arr.length; - final int zeros = arrSize - nonZeros; - final int adjK = (pivot + zeros) - 1; - return select(arr, 0, arrSize - 1, adjK); - } - - /** - * Partition arr[] into arr[lo .. i-1], arr[i], arr[i+1,hi] - * - * @param arr The given array to partition - * @param lo the low index - * @param hi the high index - * @return the next partition value. Ultimately, the desired pivot. - */ - private static int partition(final long[] arr, final int lo, final int hi) { - int i = lo, j = hi + 1; //left and right scan indices - final long v = arr[lo]; //partitioning item value - while (true) { - //Scan right, scan left, check for scan complete, and exchange - while (arr[ ++i] < v) { - if (i == hi) { - break; - } - } - while (v < arr[ --j]) { - if (j == lo) { - break; - } - } - if (i >= j) { - break; - } - final long x = arr[i]; - arr[i] = arr[j]; - arr[j] = x; - } - //put v=arr[j] into position with a[lo .. j-1] <= a[j] <= a[j+1 .. hi] - final long x = arr[lo]; - arr[lo] = arr[j]; - arr[j] = x; - return j; - } - - //For double arrays - - /** - * Gets the 0-based kth order statistic from the array. Warning! This changes the ordering - * of elements in the given array! - * - * @param arr The array to be re-arranged. - * @param lo The lowest 0-based index to be considered. - * @param hi The highest 0-based index to be considered. - * @param pivot The 0-based smallest value to pivot on. - * @return The value of the smallest (n)th element where n is 0-based. - */ - public static double select(final double[] arr, int lo, int hi, final int pivot) { - while (hi > lo) { - final int j = partition(arr, lo, hi); - if (j == pivot) { - return arr[pivot]; - } - if (j > pivot) { - hi = j - 1; - } - else { - lo = j + 1; - } - } - return arr[pivot]; - } - - /** - * Gets the 1-based kth order statistic from the array including any zero values in the - * array. Warning! This changes the ordering of elements in the given array! - * - * @param arr The hash array. - * @param pivot The 1-based index of the value that is chosen as the pivot for the array. - * After the operation all values below this 1-based index will be less than this value - * and all values above this index will be greater. The 0-based index of the pivot will be - * pivot-1. - * @return The value of the smallest (N)th element including zeros, where N is 1-based. - */ - public static double selectIncludingZeros(final double[] arr, final int pivot) { - final int arrSize = arr.length; - final int adj = pivot - 1; - return select(arr, 0, arrSize - 1, adj); - } - - /** - * Gets the 1-based kth order statistic from the array excluding any zero values in the - * array. Warning! This changes the ordering of elements in the given array! - * - * @param arr The hash array. - * @param nonZeros The number of non-zero values in the array. - * @param pivot The 1-based index of the value that is chosen as the pivot for the array. - * After the operation all values below this 1-based index will be less than this value - * and all values above this index will be greater. The 0-based index of the pivot will be - * pivot+arr.length-nonZeros-1. - * @return The value of the smallest (N)th element excluding zeros, where N is 1-based. - */ - public static double selectExcludingZeros(final double[] arr, final int nonZeros, final int pivot) { - if (pivot > nonZeros) { - return 0L; - } - final int arrSize = arr.length; - final int zeros = arrSize - nonZeros; - final int adjK = (pivot + zeros) - 1; - return select(arr, 0, arrSize - 1, adjK); - } - - /** - * Partition arr[] into arr[lo .. i-1], arr[i], arr[i+1,hi] - * - * @param arr The given array to partition - * @param lo the low index - * @param hi the high index - * @return the next partition value. Ultimately, the desired pivot. - */ - private static int partition(final double[] arr, final int lo, final int hi) { - int i = lo, j = hi + 1; //left and right scan indices - final double v = arr[lo]; //partitioning item value - while (true) { - //Scan right, scan left, check for scan complete, and exchange - while (arr[ ++i] < v) { - if (i == hi) { - break; - } - } - while (v < arr[ --j]) { - if (j == lo) { - break; - } - } - if (i >= j) { - break; - } - final double x = arr[i]; - arr[i] = arr[j]; - arr[j] = x; - } - //put v=arr[j] into position with a[lo .. j-1] <= a[j] <= a[j+1 .. hi] - final double x = arr[lo]; - arr[lo] = arr[j]; - arr[j] = x; - return j; - } - -} diff --git a/src/main/java/org/apache/datasketches/common/ResizeFactor.java b/src/main/java/org/apache/datasketches/common/ResizeFactor.java deleted file mode 100644 index 5dfc8addc..000000000 --- a/src/main/java/org/apache/datasketches/common/ResizeFactor.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -/** - * For the Families that accept this configuration parameter, it controls the size multiple that - * affects how fast the internal cache grows, when more space is required. - * See Resize Factor - * - * @author Lee Rhodes - */ -public enum ResizeFactor { - /** - * Do not resize. Sketch will be configured to full size. - */ - X1(0), - /** - * Resize factor is 2. - */ - X2(1), - /** - * Resize factor is 4. - */ - X4(2), - /** - * Resize factor is 8. - */ - X8(3); - - private int lg_; - - ResizeFactor(final int lg) { - this.lg_ = lg; - } - - /** - * Returns the Log-base 2 of the Resize Factor - * @return the Log-base 2 of the Resize Factor - */ - public int lg() { - return lg_; - } - - /** - * Returns the Resize Factor given the Log-base 2 of the Resize Factor - * @param lg a value between zero and 3, inclusive. - * @return the Resize Factor given the Log-base 2 of the Resize Factor - */ - public static ResizeFactor getRF(final int lg) { - if (X1.lg() == lg) { return X1; } - if (X2.lg() == lg) { return X2; } - if (X4.lg() == lg) { return X4; } - return X8; - } - - /** - * Returns the Resize Factor - * @return the Resize Factor - */ - public int getValue() { - return 1 << lg_; - } -} diff --git a/src/main/java/org/apache/datasketches/common/SketchesArgumentException.java b/src/main/java/org/apache/datasketches/common/SketchesArgumentException.java deleted file mode 100644 index 4644f595b..000000000 --- a/src/main/java/org/apache/datasketches/common/SketchesArgumentException.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -/** - * Illegal Arguments Exception class for the library - * - * @author Lee Rhodes - */ -public class SketchesArgumentException extends SketchesException { - private static final long serialVersionUID = 1L; - - //other constructors to be added as needed. - - /** - * Constructs a new runtime exception with the specified detail message. The cause is not - * initialized, and may subsequently be initialized by a call to - * Throwable.initCause(java.lang.Throwable). - * - * @param message the detail message. The detail message is saved for later retrieval by the - * Throwable.getMessage() method. - */ - public SketchesArgumentException(final String message) { - super(message); - } -} diff --git a/src/main/java/org/apache/datasketches/common/SketchesException.java b/src/main/java/org/apache/datasketches/common/SketchesException.java deleted file mode 100644 index 83f427cb0..000000000 --- a/src/main/java/org/apache/datasketches/common/SketchesException.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -/** - * Exception class for the library - * - * @author Lee Rhodes - */ -public class SketchesException extends RuntimeException { - private static final long serialVersionUID = 1L; - - //other constructors to be added as needed. - - /** - * Constructs a new runtime exception with the specified detail message. The cause is not - * initialized, and may subsequently be initialized by a call to - * Throwable.initCause(java.lang.Throwable). - * - * @param message the detail message. The detail message is saved for later retrieval by the - * Throwable.getMessage() method. - */ - public SketchesException(final String message) { - super(message); - } - - /** - * Constructs a new runtime exception with the specified detail message and cause. - * - *

Note that the detail message associated with cause is not automatically incorporated - * in this runtime exception's detail message.

- * - * @param message the detail message (which is saved for later retrieval by the - * Throwable.getMessage() method). - * @param cause the cause (which is saved for later retrieval by the Throwable.getCause() - * method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.) - */ - public SketchesException(final String message, final Throwable cause) { - super(message, cause); - } - -} diff --git a/src/main/java/org/apache/datasketches/common/SketchesNotSupportedException.java b/src/main/java/org/apache/datasketches/common/SketchesNotSupportedException.java deleted file mode 100644 index e22cc1637..000000000 --- a/src/main/java/org/apache/datasketches/common/SketchesNotSupportedException.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -/** - * This operation or mode is not supported. - * - * @author Lee Rhodes - */ -public class SketchesNotSupportedException extends SketchesException { - private static final long serialVersionUID = 1L; - private static final String baseStr = "This operation or mode is not supported: "; - - //other constructors to be added as needed. - - /** - * Constructs a new runtime exception with the specified detail message. The cause is not - * initialized, and may subsequently be initialized by a call to - * Throwable.initCause(java.lang.Throwable). - * - * @param message the detail message which is appended to the base message:
- * "This operation or mode is not supported: ". - * - *

The detail message is saved for later retrieval by the Throwable.getMessage() method.

- */ - public SketchesNotSupportedException(final String message) { - super(baseStr + message); - } - -} diff --git a/src/main/java/org/apache/datasketches/common/SketchesReadOnlyException.java b/src/main/java/org/apache/datasketches/common/SketchesReadOnlyException.java deleted file mode 100644 index 59cf7a47c..000000000 --- a/src/main/java/org/apache/datasketches/common/SketchesReadOnlyException.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -/** - * Write operation attempted on a read-only class. - * - * @author Lee Rhodes - */ -public class SketchesReadOnlyException extends SketchesException { - private static final long serialVersionUID = 1L; - - //other constructors to be added as needed. - - /** - * Constructs a new runtime exception with the message: - * "Write operation attempted on a read-only class." - * - *

The cause is not initialized, and may subsequently be initialized by a call to - * Throwable.initCause(java.lang.Throwable). - */ - public SketchesReadOnlyException() { - super("Write operation attempted on a read-only class."); - } - - /** - * Constructs a new runtime exception with the specified detail message. The cause is not - * initialized, and may subsequently be initialized by a call to - * Throwable.initCause(java.lang.Throwable). - * - * @param message the detail message. The detail message is saved for later retrieval by the - * Throwable.getMessage() method. - */ - public SketchesReadOnlyException(final String message) { - super(message); - } -} diff --git a/src/main/java/org/apache/datasketches/common/SketchesStateException.java b/src/main/java/org/apache/datasketches/common/SketchesStateException.java deleted file mode 100644 index b3d3df90e..000000000 --- a/src/main/java/org/apache/datasketches/common/SketchesStateException.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -/** - * Illegal State Exception class for the library - * - * @author Lee Rhodes - */ -public class SketchesStateException extends SketchesException { - private static final long serialVersionUID = 1L; - - //other constructors to be added as needed. - - /** - * Constructs a new runtime exception with the specified detail message. The cause is not - * initialized, and may subsequently be initialized by a call to - * Throwable.initCause(java.lang.Throwable). - * - * @param message the detail message. The detail message is saved for later retrieval by the - * Throwable.getMessage() method. - */ - public SketchesStateException(final String message) { - super(message); - } -} diff --git a/src/main/java/org/apache/datasketches/common/SpecialValueLayouts.java b/src/main/java/org/apache/datasketches/common/SpecialValueLayouts.java deleted file mode 100644 index 292d5617f..000000000 --- a/src/main/java/org/apache/datasketches/common/SpecialValueLayouts.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import java.lang.foreign.ValueLayout; -import java.nio.ByteOrder; - -/** - * Value Layouts for Non-native Endianness - */ -public final class SpecialValueLayouts { - - private SpecialValueLayouts() { } - - /** - * The static final for NON ByteOrder.nativeOrder(). - */ - public static final ByteOrder NON_NATIVE_BYTE_ORDER = - (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN) ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; - - //Non-Native Endian Layouts - - /** - * The static final for NON ByteOrder.nativeOrder() char. - */ - public static final ValueLayout.OfChar JAVA_CHAR_UNALIGNED_NON_NATIVE = - ValueLayout.JAVA_CHAR_UNALIGNED.withOrder(NON_NATIVE_BYTE_ORDER); - - /** - * The static final for NON ByteOrder.nativeOrder() double. - */ - public static final ValueLayout.OfDouble JAVA_DOUBLE_UNALIGNED_NON_NATIVE = - ValueLayout.JAVA_DOUBLE_UNALIGNED.withOrder(NON_NATIVE_BYTE_ORDER); - - /** - * The static final for NON ByteOrder.nativeOrder() float. - */ - public static final ValueLayout.OfFloat JAVA_FLOAT_UNALIGNED_NON_NATIVE = - ValueLayout.JAVA_FLOAT_UNALIGNED.withOrder(NON_NATIVE_BYTE_ORDER); - - /** - * The static final for NON ByteOrder.nativeOrder() int. - */ - public static final ValueLayout.OfInt JAVA_INT_UNALIGNED_NON_NATIVE = - ValueLayout.JAVA_INT_UNALIGNED.withOrder(NON_NATIVE_BYTE_ORDER); - - /** - * The static final for NON ByteOrder.nativeOrder() long. - */ - public static final ValueLayout.OfLong JAVA_LONG_UNALIGNED_NON_NATIVE = - ValueLayout.JAVA_LONG_UNALIGNED.withOrder(NON_NATIVE_BYTE_ORDER); - - /** - * The static final for NON ByteOrder.nativeOrder() short. - */ - public static final ValueLayout.OfShort JAVA_SHORT_UNALIGNED_NON_NATIVE = - ValueLayout.JAVA_SHORT_UNALIGNED.withOrder(NON_NATIVE_BYTE_ORDER); - - //Big-Endian Layouts - - /** - * The static final for ByteOrder.BIG_ENDIAN char. - */ - public static final ValueLayout.OfChar JAVA_CHAR_UNALIGNED_BIG_ENDIAN = - ValueLayout.JAVA_CHAR_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN); - - /** - * The static final for ByteOrder.BIG_ENDIAN double. - */ - public static final ValueLayout.OfDouble JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN = - ValueLayout.JAVA_DOUBLE_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN); - - /** - * The static final for ByteOrder.BIG_ENDIAN float. - */ - public static final ValueLayout.OfFloat JAVA_FLOAT_UNALIGNED_BIG_ENDIAN = - ValueLayout.JAVA_FLOAT_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN); - - /** - * The static final for ByteOrder.BIG_ENDIAN int. - */ - public static final ValueLayout.OfInt JAVA_INT_UNALIGNED_BIG_ENDIAN = - ValueLayout.JAVA_INT_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN); - - /** - * The static final for ByteOrder.BIG_ENDIAN long. - */ - public static final ValueLayout.OfLong JAVA_LONG_UNALIGNED_BIG_ENDIAN = - ValueLayout.JAVA_LONG_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN); - - /** - * The static final for ByteOrder.BIG_ENDIAN short. - */ - public static final ValueLayout.OfShort JAVA_SHORT_UNALIGNED_BIG_ENDIAN = - ValueLayout.JAVA_SHORT_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN); - -} diff --git a/src/main/java/org/apache/datasketches/common/SuppressFBWarnings.java b/src/main/java/org/apache/datasketches/common/SuppressFBWarnings.java deleted file mode 100644 index c80421182..000000000 --- a/src/main/java/org/apache/datasketches/common/SuppressFBWarnings.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -/** - * Used to suppress SpotBug warnings. - * - * @author Lee Rhodes - */ -@Retention(RetentionPolicy.CLASS) -public @interface SuppressFBWarnings { - - /** - * A list of comma-separated, quoted SpotBugs warnings that are to be suppressed in the associated - * annotated element. The value can be a bug category, kind or pattern. - * @return list of relevant bug descriptors - */ - String[] value() default {}; - - /** - * Optional explanation for the suppression. - * @return explanation - */ - String justification() default ""; -} - diff --git a/src/main/java/org/apache/datasketches/common/Util.java b/src/main/java/org/apache/datasketches/common/Util.java deleted file mode 100644 index 7d70323e1..000000000 --- a/src/main/java/org/apache/datasketches/common/Util.java +++ /dev/null @@ -1,993 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static java.lang.Math.ceil; -import static java.lang.Math.floor; -import static java.lang.Math.log; -import static java.lang.Math.pow; -import static java.lang.Math.round; -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.hash.MurmurHash3.hash; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteOrder; -import java.util.Comparator; - -/** - * Common utility functions. - * - * @author Lee Rhodes - */ -@SuppressWarnings("unchecked") -public final class Util { - - static { - if (ByteOrder.nativeOrder() != ByteOrder.LITTLE_ENDIAN) { - throw new SketchesNotSupportedException("Machine Native Endianness must be LITTLE_ENDIAN."); - } - } - - /** - * The java line separator character as a String. - */ - public static final String LS = System.getProperty("line.separator"); - - /** - * The tab character - */ - public static final char TAB = '\t'; - - /** - * The natural logarithm of 2.0. - */ - public static final double LOG2 = log(2.0); - - /** - * The inverse golden ratio as an unsigned long. - */ - public static final long INVERSE_GOLDEN_U64 = 0x9e3779b97f4a7c13L; - - /** - * The inverse golden ratio as a fraction. - * This has more precision than using the formula: (Math.sqrt(5.0) - 1.0) / 2.0. - */ - public static final double INVERSE_GOLDEN = 0.6180339887498949025; - - /** - * Long.MAX_VALUE as a double. - */ - public static final double LONG_MAX_VALUE_AS_DOUBLE = Long.MAX_VALUE; - - /** - * The seed 9001 used in the sketch update methods is a prime number that - * was chosen very early on in experimental testing. Choosing a seed is somewhat arbitrary, and - * the author cannot prove that this particular seed is somehow superior to other seeds. There - * was some early Internet discussion that a seed of 0 did not produce as clean avalanche diagrams - * as non-zero seeds, but this may have been more related to the MurmurHash2 release, which did - * have some issues. As far as the author can determine, MurmurHash3 does not have these problems. - * - *

In order to perform set operations on two sketches it is critical that the same hash - * function and seed are identical for both sketches, otherwise the assumed 1:1 relationship - * between the original source key value and the hashed bit string would be violated. Once - * you have developed a history of stored sketches you are stuck with it. - * - *

WARNING: This seed is used internally by library sketches in different - * packages and thus must be declared public. However, this seed value must not be used by library - * users with the MurmurHash3 function. It should be viewed as existing for exclusive, private - * use by the library. - * - *

See Default Update Seed - */ - public static final long DEFAULT_UPDATE_SEED = 9001L; - - private Util() {} - - //Byte Conversions - - /** - * Returns an int extracted from a Little-Endian byte array. - * @param arr the given byte array - * @return an int extracted from a Little-Endian byte array. - */ - public static int bytesToInt(final byte[] arr) { - return (arr[3] << 24) - | ((arr[2] & 0xff) << 16) - | ((arr[1] & 0xff) << 8) - | (arr[0] & 0xff); - } - - /** - * Returns a long extracted from a Little-Endian byte array. - * @param arr the given byte array - * @return a long extracted from a Little-Endian byte array. - */ - public static long bytesToLong(final byte[] arr) { - return ((long)arr[7] << 56) - | (((long)arr[6] & 0xff) << 48) - | (((long)arr[5] & 0xff) << 40) - | (((long)arr[4] & 0xff) << 32) - | (((long)arr[3] & 0xff) << 24) - | (((long)arr[2] & 0xff) << 16) - | (((long)arr[1] & 0xff) << 8) - | ((long)arr[0] & 0xff); - } - - /** - * Returns a Little-Endian byte array extracted from the given int. - * @param v the given int - * @param arr a given array of 4 bytes that will be returned with the data - * @return a Little-Endian byte array extracted from the given int. - */ - public static byte[] intToBytes(final int v, final byte[] arr) { - arr[3] = (byte) (v >>> 24); - arr[2] = (byte) (v >>> 16); - arr[1] = (byte) (v >>> 8); - arr[0] = (byte) v; - return arr; - } - - /** - * Returns a Little-Endian byte array extracted from the given long. - * @param v the given long - * @param arr a given array of 8 bytes that will be returned with the data - * @return a Little-Endian byte array extracted from the given long. - */ - public static byte[] longToBytes(final long v, final byte[] arr) { - arr[7] = (byte) (v >>> 56); - arr[6] = (byte) (v >>> 48); - arr[5] = (byte) (v >>> 40); - arr[4] = (byte) (v >>> 32); - arr[3] = (byte) (v >>> 24); - arr[2] = (byte) (v >>> 16); - arr[1] = (byte) (v >>> 8); - arr[0] = (byte) v; - return arr; - } - - //Byte array conversions - - static long[] convertToLongArray(final byte[] byteArr, final boolean littleEndian) { - final int len = byteArr.length; - final long[] longArr = new long[(len / 8) + ((len % 8) != 0 ? 1 : 0)]; - int off = 0; - int longArrIdx = 0; - while (off < len) { - final int rem = Math.min(len - 1 - off, 7); - long tgt = 0; - if (littleEndian) { - for (int j = off + rem, k = 0; j >= off; --j, k++) { - tgt |= (byteArr[j] & 0XFFL) << (k * 8); - } - } else { //BE - for (int j = off + rem, k = rem; j >= off; --j, k--) { - tgt |= (byteArr[j] & 0XFFL) << (k * 8); - } - } - off += 8; - longArr[longArrIdx++] = tgt; - } - return longArr; - } - - //String Related - - /** - * Returns a string of spaced hex bytes in Big-Endian order. - * @param v the given long - * @return string of spaced hex bytes in Big-Endian order. - */ - public static String longToHexBytes(final long v) { - final long mask = 0XFFL; - final StringBuilder sb = new StringBuilder(); - for (int i = 8; i-- > 0; ) { - final String s = Long.toHexString((v >>> (i * 8)) & mask); - sb.append(zeroPad(s, 2)).append(" "); - } - return sb.toString(); - } - - /** - * Returns a string view of a byte array - * @param arr the given byte array - * @param signed set true if you want the byte values signed. - * @param littleEndian set true if you want Little-Endian order - * @param sep the separator string between bytes - * @return a string view of a byte array - */ - public static String bytesToString( - final byte[] arr, final boolean signed, final boolean littleEndian, final String sep) { - final StringBuilder sb = new StringBuilder(); - final int mask = signed ? 0XFFFFFFFF : 0XFF; - final int arrLen = arr.length; - if (littleEndian) { - for (int i = 0; i < (arrLen - 1); i++) { - sb.append(arr[i] & mask).append(sep); - } - sb.append(arr[arrLen - 1] & mask); - } else { - for (int i = arrLen; i-- > 1; ) { - sb.append(arr[i] & mask).append(sep); - } - sb.append(arr[0] & mask); - } - return sb.toString(); - } - - /** - * Returns the given time in nanoseconds formatted as Sec.mSec_uSec_nSec - * @param nS the given nanoseconds - * @return the given time in nanoseconds formatted as Sec.mSec_uSec_nSec - */ - public static String nanoSecToString(final long nS) { - final long rem_nS = (long)(nS % 1000.0); - final long rem_uS = (long)((nS / 1000.0) % 1000.0); - final long rem_mS = (long)((nS / 1000000.0) % 1000.0); - final long sec = (long)(nS / 1000000000.0); - final String nSstr = zeroPad(Long.toString(rem_nS), 3); - final String uSstr = zeroPad(Long.toString(rem_uS), 3); - final String mSstr = zeroPad(Long.toString(rem_mS), 3); - return String.format("%d.%3s_%3s_%3s", sec, mSstr, uSstr, nSstr); - } - - /** - * Returns the given time in milliseconds formatted as Hours:Min:Sec.mSec - * @param mS the given milliseconds - * @return the given time in milliseconds formatted as Hours:Min:Sec.mSec - */ - public static String milliSecToString(final long mS) { - final long rem_mS = (long)(mS % 1000.0); - final long rem_sec = (long)((mS / 1000.0) % 60.0); - final long rem_min = (long)((mS / 60000.0) % 60.0); - final long hr = (long)(mS / 3600000.0); - final String mSstr = zeroPad(Long.toString(rem_mS), 3); - final String secStr = zeroPad(Long.toString(rem_sec), 2); - final String minStr = zeroPad(Long.toString(rem_min), 2); - return String.format("%d:%2s:%2s.%3s", hr, minStr, secStr, mSstr); - } - - /** - * Prepend the given string with zeros. If the given string is equal or greater than the given - * field length, it will be returned without modification. - * @param s the given string - * @param fieldLength desired total field length including the given string - * @return the given string prepended with zeros. - */ - public static String zeroPad(final String s, final int fieldLength) { - return characterPad(s, fieldLength, '0', false); - } - - /** - * Prepend or postpend the given string with the given character to fill the given field length. - * If the given string is equal to or greater than the given field length, it will be returned - * without modification. - * @param s the given string - * @param fieldLength the desired field length - * @param padChar the desired pad character - * @param postpend if true append the pacCharacters to the end of the string. - * @return prepended or postpended given string with the given character to fill the given field length. - */ - public static String characterPad(final String s, final int fieldLength, final char padChar, final boolean postpend) { - final int sLen = s.length(); - if (sLen < fieldLength) { - final char[] cArr = new char[fieldLength - sLen]; - java.util.Arrays.fill(cArr, padChar); - final String addstr = String.valueOf(cArr); - return (postpend) ? s.concat(addstr) : addstr.concat(s); - } - return s; - } - - //Memory byte alignment - - /** - * Checks if parameter v is a multiple of 8 and greater than zero. - * @param v The parameter to check - * @param argName This name will be part of the error message if the check fails. - */ - public static void checkIfMultipleOf8AndGT0(final long v, final String argName) { - if (((v & 0X7L) == 0L) && (v > 0L)) { - return; - } - throw new SketchesArgumentException("The value of the parameter \"" + argName - + "\" must be a positive multiple of 8 and greater than zero: " + v); - } - - /** - * Returns true if v is a multiple of 8 and greater than zero - * @param v The parameter to check - * @return true if v is a multiple of 8 and greater than zero - */ - public static boolean isMultipleOf8AndGT0(final long v) { - return ((v & 0X7L) == 0L) && (v > 0L); - } - - //Powers of 2 or powers of base related - - /** - * Returns true if given long argument is exactly a positive power of 2. - * - * @param n The input argument. - * @return true if argument is exactly a positive power of 2. - */ - public static boolean isPowerOf2(final long n) { - return (n > 0) && ((n & (n - 1L)) == 0); //or (n > 0) && ((n & -n) == n) - } - - /** - * Checks the given long argument if it is a positive integer power of 2. - * If not, it throws an exception with the user supplied local argument name, if not null. - * @param n The input long argument must be a positive integer power of 2. - * @param argName Used in the thrown exception. It may be null. - * @throws SketchesArgumentException if not a positive integer power of 2. - */ - public static void checkIfPowerOf2(final long n, String argName) { - if (isPowerOf2(n)) { return; } - argName = (argName == null) ? "" : argName; - throw new SketchesArgumentException("The value of the argument \"" + argName + "\"" - + " must be a positive integer power of 2: " + n); - } - - /** - * Computes the int ceiling power of 2 within the range [1, 2^30]. This is the smallest positive power - * of 2 that is equal to or greater than the given n and a positive integer. - * - *

For: - *

    - *
  • n ≤ 1: returns 1
  • - *
  • 2^30 ≤ n ≤ 2^31 -1 : returns 2^30
  • - *
  • n == an exact power of 2 : returns n
  • - *
  • otherwise returns the smallest power of 2 ≥ n and equal to a positive integer
  • - *
- * - * @param n The input int argument. - * @return the ceiling power of 2. - */ - public static int ceilingPowerOf2(final int n) { - if (n <= 1) { return 1; } - final int topIntPwrOf2 = 1 << 30; - return n >= topIntPwrOf2 ? topIntPwrOf2 : Integer.highestOneBit((n - 1) << 1); - } - - /** - * Computes the long ceiling power of 2 within the range [1, 2^62]. This is the smallest positive power - * of 2 that is equal to or greater than the given n and a positive long. - * - *

For: - *

    - *
  • n ≤ 1: returns 1
  • - *
  • 2^62 ≤ n ≤ 2^63 -1 : returns 2^62
  • - *
  • n == an exact power of 2 : returns n
  • - *
  • otherwise returns the smallest power of 2 ≥ n and equal to a positive long
  • - *
- * - * @param n The input long argument. - * @return the ceiling power of 2. - */ - public static long ceilingPowerOf2(final long n) { - if (n <= 1L) { return 1L; } - final long topIntPwrOf2 = 1L << 62; - return n >= topIntPwrOf2 ? topIntPwrOf2 : Long.highestOneBit((n - 1L) << 1); - } - - /** - * Computes the floor power of 2 given n is in the range [1, 2^31-1]. - * This is the largest positive power of 2 that equal to or less than the given n and equal - * to a positive integer. - * - *

For: - *

    - *
  • n ≤ 1: returns 1
  • - *
  • 2^30 ≤ n ≤ 2^31 -1 : returns 2^30
  • - *
  • n == a power of 2 : returns n
  • - *
  • otherwise returns the largest power of 2 less than n and equal to a mathematical - * integer.
  • - *
- * - * @param n The given int argument. - * @return the floor power of 2 as an int. - */ - public static int floorPowerOf2(final int n) { - if (n <= 1) { return 1; } - return Integer.highestOneBit(n); - } - - /** - * Computes the floor power of 2 given n is in the range [1, 2^63-1]. - * This is the largest positive power of 2 that is equal to or less than the given n and - * equal to a positive integer. - * - *

For: - *

    - *
  • n ≤ 1: returns 1
  • - *
  • 2^62 ≤ n ≤ 2^63 -1 : returns 2^62
  • - *
  • n == a power of 2 : returns n
  • - *
  • otherwise returns the largest power of 2 less than n and equal to a mathematical - * integer.
  • - *
- * - * @param n The given long argument. - * @return the floor power of 2 as a long - */ - public static long floorPowerOf2(final long n) { - if (n <= 1) { return 1; } - return Long.highestOneBit(n); - } - - /** - * This is a long integer equivalent to Math.ceil(n / (double)(1 << k)) - * where: 0 < k ≤ 6 and n is a non-negative long. - * These limits are not checked for speed reasons. - * @param n the input dividend as a positive long greater than zero. - * @param k the input divisor exponent of 2 as a positive integer where 0 < k ≤ 6. - * @return the long integer equivalent to Math.ceil(n / 2^k). - */ - public static long ceilingMultiple2expK(final long n, final int k) { - final long mask = (1L << k) - 1L; - return (n & mask) > 0 ? (n >>> k) + 1 : n >>> k; - } - - /** - * Computes the inverse integer power of 2: 1/(2^exp) = 2^(-exp). - * @param exp a positive value between 0 and 1023 inclusive - * @return the inverse integer power of 2: 1/(2^exp) = 2^(-exp) - */ - public static double invPow2(final int exp) { - if ((exp | (1024 - exp - 1)) < 0) { - throw new SketchesArgumentException("exp cannot be negative or greater than 1023: " + exp); - } - return Double.longBitsToDouble((1023L - exp) << 52); - } - - /** - * Computes the next larger integer point in the power series - * point = 2( i / ppo ) given the current point in the series. - * For illustration, this can be used in a loop as follows: - * - *
{@code
-   *     int maxP = 1024;
-   *     int minP = 1;
-   *     int ppo = 2;
-   *
-   *     for (int p = minP; p <= maxP; p = pwr2SeriesNext(ppo, p)) {
-   *       System.out.print(p + " ");
-   *     }
-   *     //generates the following series:
-   *     //1 2 3 4 6 8 11 16 23 32 45 64 91 128 181 256 362 512 724 1024
-   * }
- * - * @param ppo Points-Per-Octave, or the number of points per integer powers of 2 in the series. - * @param curPoint the current point of the series. Must be ≥ 1. - * @return the next point in the power series. - */ - public static long pwr2SeriesNext(final int ppo, final long curPoint) { - final long cur = curPoint < 1L ? 1L : curPoint; - int gi = (int)round(log2(cur) * ppo); //current generating index - long next; - do { - next = round(pow(2.0, (double) ++gi / ppo)); - } while ( next <= curPoint); - return next; - } - - /** - * Computes the previous, smaller integer point in the power series - * point = 2( i / ppo ) given the current point in the series. - * For illustration, this can be used in a loop as follows: - * - *
{@code
-   *     int maxP = 1024;
-   *     int minP = 1;
-   *     int ppo = 2;
-   *
-   *     for (int p = maxP; p >= minP; p = pwr2SeriesPrev(ppo, p)) {
-   *       System.out.print(p + " ");
-   *     }
-   *     //generates the following series:
-   *     //1024 724 512 362 256 181 128 91 64 45 32 23 16 11 8 6 4 3 2 1
-   * }
- * - * @param ppo Points-Per-Octave, or the number of points per integer powers of 2 in the series. - * @param curPoint the current point of the series. Must be ≥ 1. - * @return the previous, smaller point in the power series. - * A returned value of zero terminates the series. - */ - public static int pwr2SeriesPrev(final int ppo, final int curPoint) { - if (curPoint <= 1) { return 0; } - int gi = (int)round(log2(curPoint) * ppo); //current generating index - int prev; - do { - prev = (int)round(pow(2.0, (double) --gi / ppo)); - } while (prev >= curPoint); - return prev; - } - - /** - * Computes the next larger double in the power series - * point = logBase( i / ppb ) given the current point in the series. - * For illustration, this can be used in a loop as follows: - * - *
{@code
-   *     double maxP = 1024.0;
-   *     double minP = 1.0;
-   *     int ppb = 2;
-   *     double logBase = 2.0;
-   *
-   *     for (double p = minP; p <= maxP; p = powerSeriesNextDouble(ppb, p, true, logBase)) {
-   *       System.out.print(p + " ");
-   *     }
-   *     //generates the following series:
-   *     //1 2 3 4 6 8 11 16 23 32 45 64 91 128 181 256 362 512 724 1024
-   * }
- * - * @param ppb Points-Per-Base, or the number of points per integer powers of base in the series. - * @param curPoint the current point of the series. Must be ≥ 1.0. - * @param roundToLong if true the output will be rounded to the nearest long. - * @param logBase the desired base of the logarithms - * @return the next point in the power series. - */ - public static double powerSeriesNextDouble(final int ppb, final double curPoint, - final boolean roundToLong, final double logBase) { - final double cur = curPoint < 1.0 ? 1.0 : curPoint; - double gi = round(logBaseOfX(logBase, cur) * ppb ); //current generating index - double next; - do { - final double n = pow(logBase, ++gi / ppb); - next = roundToLong ? round(n) : n; - } while (next <= cur); - return next; - } - - /** - * Returns the ceiling of a given n given a base, where the ceiling is an integral power of the base. - * This is the smallest positive power of base that is equal to or greater than the given n - * and equal to a mathematical integer. - * The result of this function is consistent with {@link #ceilingPowerOf2(int)} for values - * less than one. I.e., if n < 1, the result is 1. - * - *

The formula is: baseceiling(logbase(x))

- * - * @param base The number in the expression ⌈basen⌉. - * @param n The input argument. - * @return the ceiling power of base as a double and equal to a mathematical integer. - */ - public static double ceilingPowerBaseOfDouble(final double base, final double n) { - final double x = n < 1.0 ? 1.0 : n; - return Math.round(pow(base, ceil(logBaseOfX(base, x)))); - } - - /** - * Computes the floor of a given n given base, where the floor is an integral power of the base. - * This is the largest positive power of base that is equal to or less than the given n - * and equal to a mathematical integer. - * The result of this function is consistent with {@link #floorPowerOf2(int)} for values - * less than one. I.e., if n < 1, the result is 1. - * - *

The formula is: basefloor(logbase(x))

- * - * @param base The number in the expression ⌊basen⌋. - * @param n The input argument. - * @return the floor power of 2 and equal to a mathematical integer. - */ - public static double floorPowerBaseOfDouble(final double base, final double n) { - final double x = n < 1.0 ? 1.0 : n; - return Math.round(pow(base, floor(logBaseOfX(base, x)))); - } - - // Logarithm related - - /** - * The log2(value) - * @param value the given value - * @return log2(value) - */ - public static double log2(final double value) { - return log(value) / LOG2; - } - - /** - * Returns the logbase(x). Example, if base = 2.0: logB(2.0, x) = log(x) / log(2.0). - * @param base The number in the expression log(x) / log(base). - * @param x the given value - * @return the logbase(x) - */ - public static double logBaseOfX(final double base, final double x) { - return log(x) / log(base); - } - - /** - * Returns the number of one bits following the lowest-order ("rightmost") zero-bit in the - * two's complement binary representation of the specified long value, or 64 if the value is equal - * to minus one. - * @param v the value whose number of trailing ones is to be computed. - * @return the number of one bits following the lowest-order ("rightmost") zero-bit in the - * two's complement binary representation of the specified long value, or 64 if the value is equal - * to minus one. - */ - public static int numberOfTrailingOnes(final long v) { - return Long.numberOfTrailingZeros(~v); - } - - /** - * Returns the number of one bits preceding the highest-order ("leftmost") zero-bit in the - * two's complement binary representation of the specified long value, or 64 if the value is equal - * to minus one. - * @param v the value whose number of leading ones is to be computed. - * @return the number of one bits preceding the lowest-order ("rightmost") zero-bit in the - * two's complement binary representation of the specified long value, or 64 if the value is equal - * to minus one. - */ - public static int numberOfLeadingOnes(final long v) { - return Long.numberOfLeadingZeros(~v); - } - - /** - * Returns the log2 of the given int value if it is an exact power of 2 and greater than zero. - * If not, it throws an exception with the user supplied local argument name. - * @param powerOf2 must be a power of 2 and greater than zero. - * @param argName the argument name used in the exception if thrown. - * @return the log2 of the given value if it is an exact power of 2 and greater than zero. - * @throws SketchesArgumentException if not a power of 2 nor greater than zero. - */ - public static int exactLog2OfInt(final int powerOf2, final String argName) { - checkIfPowerOf2(powerOf2, argName); - return Integer.numberOfTrailingZeros(powerOf2); - } - - /** - * Returns the log2 of the given long value if it is an exact power of 2 and greater than zero. - * If not, it throws an exception with the user supplied local argument name. - * @param powerOf2 must be a power of 2 and greater than zero. - * @param argName the argument name used in the exception if thrown. - * @return the log2 of the given value if it is an exact power of 2 and greater than zero. - * @throws SketchesArgumentException if not a power of 2 nor greater than zero. - */ - public static int exactLog2OfLong(final long powerOf2, final String argName) { - checkIfPowerOf2(powerOf2, argName); - return Long.numberOfTrailingZeros(powerOf2); - } - - /** - * Returns the log2 of the given int value if it is an exact power of 2 and greater than zero. - * If not, it throws an exception. - * @param powerOf2 must be a power of 2 and greater than zero. - * @return the log2 of the given int value if it is an exact power of 2 and greater than zero. - */ - public static int exactLog2OfInt(final int powerOf2) { - if (!isPowerOf2(powerOf2)) { - throw new SketchesArgumentException("Argument 'powerOf2' must be a positive power of 2."); - } - return Long.numberOfTrailingZeros(powerOf2); - } - - /** - * Returns the log2 of the given long value if it is an exact power of 2 and greater than zero. - * If not, it throws an exception. - * @param powerOf2 must be a power of 2 and greater than zero. - * @return the log2 of the given long value if it is an exact power of 2 and greater than zero. - */ - public static int exactLog2OfLong(final long powerOf2) { - if (!isPowerOf2(powerOf2)) { - throw new SketchesArgumentException("Argument 'powerOf2' must be a positive power of 2."); - } - return Long.numberOfTrailingZeros(powerOf2); - } - - //Checks that throw - - /** - * Check the requested offset and length against the allocated size. - * The invariants equation is: {@code 0 <= reqOff <= reqLen <= reqOff + reqLen <= allocSize}. - * If this equation is violated an {@link SketchesArgumentException} will be thrown. - * @param reqOff the requested offset - * @param reqLen the requested length - * @param allocSize the allocated size. - */ - public static void checkBounds(final long reqOff, final long reqLen, final long allocSize) { - if ((reqOff | reqLen | (reqOff + reqLen) | (allocSize - (reqOff + reqLen))) < 0) { - throw new SketchesArgumentException("Bounds Violation: " - + "reqOffset: " + reqOff + ", reqLength: " + reqLen - + ", (reqOff + reqLen): " + (reqOff + reqLen) + ", allocSize: " + allocSize); - } - } - - /** - * Checks the given parameter to make sure it is positive and between 0.0 inclusive and 1.0 - * inclusive. - * - * @param p - * See Sampling Probability, p - * @param argName Used in the thrown exception. - */ - public static void checkProbability(final double p, final String argName) { - if ((p >= 0.0) && (p <= 1.0)) { - return; - } - throw new SketchesArgumentException("The value of the parameter \"" + argName - + "\" must be between 0.0 inclusive and 1.0 inclusive: " + p); - } - - //Boolean Checks - - /** - * Unsigned compare with longs. - * @param n1 A long to be treated as if unsigned. - * @param n2 A long to be treated as if unsigned. - * @return true if n1 > n2. - */ - public static boolean isLessThanUnsigned(final long n1, final long n2) { - return (n1 < n2) ^ ((n1 < 0) != (n2 < 0)); - } - - /** - * Returns true if given n is even. - * @param n the given n - * @return true if given n is even. - */ - public static boolean isEven(final long n) { - return (n & 1L) == 0; - } - - /** - * Returns true if given n is odd. - * @param n the given n - * @return true if given n is odd. - */ - public static boolean isOdd(final long n) { - return (n & 1L) == 1L; - } - - //Other - - /** - * Returns a one if the bit at bitPos is a one, otherwise zero. - * @param number the number to examine - * @param bitPos the given zero-based bit position, where the least significant - * bit is at position zero. - * @return a one if the bit at bitPos is a one, otherwise zero. - */ - public static int bitAt(final long number, final int bitPos) { - return (number & (1L << bitPos)) > 0 ? 1 : 0; - } - - /** - * Computes the number of decimal digits of the number n - * @param n the given number - * @return the number of decimal digits of the number n - */ - public static int numDigits(long n) { - if ((n % 10) == 0) { n++; } - return (int) ceil(log(n) / log(10)); - } - - /** - * Converts the given number to a string prepended with spaces, if necessary, to - * match the given length. - * - *

For example, assume a sequence of integers from 1 to 1000. The largest value has - * four decimal digits. Convert the entire sequence of strings to the form " 1" to "1000". - * When these strings are sorted they will be in numerical sequence: " 1", " 2", ... "1000".

- * - * @param number the given number - * @param length the desired string length. - * @return the given number to a string prepended with spaces - */ - public static String longToFixedLengthString(final long number, final int length) { - final String num = Long.toString(number); - return characterPad(num, length, ' ', false); - } - - //Generic tests - - /** - * Finds the minimum of two generic items - * @param the type - * @param item1 item one - * @param item2 item two - * @param c the given comparator - * @return the minimum value - */ - public static Object minT(final Object item1, final Object item2, final Comparator c) { - return c.compare((T)item1, (T)item2) <= 0 ? item1 : item2; - } - - /** - * Finds the maximum of two generic items - * @param the type - * @param item1 item one - * @param item2 item two - * @param c the given comparator - * @return the maximum value - */ - public static Object maxT(final Object item1, final Object item2, final Comparator c) { - return c.compare((T)item1, (T)item2) >= 0 ? item1 : item2; - } - - /** - * Is item1 Less-Than item2? - * @param the type - * @param item1 item one - * @param item2 item two - * @param c the given comparator - * @return true if item1 Less-Than item2 - */ - public static boolean lt(final Object item1, final Object item2, final Comparator c) { - return c.compare((T)item1, (T)item2) < 0; - } - - /** - * Is item1 Less-Than-Or-Equal-To item2? - * @param the type - * @param item1 item one - * @param item2 item two - * @param c the given comparator - * @return true if item1 Less-Than-Or-Equal-To item2 - */ - public static boolean le(final Object item1, final Object item2, final Comparator c) { - return c.compare((T)item1, (T)item2) <= 0; - } - - //MemorySegment related - - /** - * Clears all bytes of this MemorySegment to zero. - * @param seg the given MemorySegment - */ - public static void clear(final MemorySegment seg) { - seg.fill((byte)0); - } - - /** - * Clears a portion of this MemorySegment to zero. - * @param seg the given MemorySegment - * @param offsetBytes offset bytes relative to this MemorySegment start - * @param lengthBytes the length in bytes - */ - public static void clear(final MemorySegment seg, final long offsetBytes, final long lengthBytes) { - final MemorySegment slice = seg.asSlice(offsetBytes, lengthBytes); - slice.fill((byte)0); - } - - /** - * Clears the bits defined by the bitMask - * @param seg the given MemorySegment - * @param offsetBytes offset bytes relative to this Memory start. - * @param bitMask the bits set to one will be cleared - */ - public static void clearBits(final MemorySegment seg, final long offsetBytes, final byte bitMask) { - final byte b = seg.get(JAVA_BYTE, offsetBytes); - seg.set(JAVA_BYTE, offsetBytes, (byte)(b & ~bitMask)); - } - - /** - * Returns true if both segments have the same contents and the same length. - * @param seg1 the given MemorySegment #1 - * @param seg2 the given MemorySegment #2 - * @return true if both segments have the same contents and the same length. - */ - public static boolean equalContents(final MemorySegment seg1, final MemorySegment seg2) { - if (seg1.byteSize() != seg2.byteSize()) { return false; } - return equalContents(seg1, 0, seg2, 0, seg1.byteSize()); - } - - /** - * Returns true if both segments have the same content for the specified region. - * @param seg1 the given MemorySegment #1 - * @param seg1offsetBytes the starting offset for MemorySegment #1 in bytes. - * @param seg2 the given MemorySegment #2 - * @param seg2offsetBytes the starting offset for MemorySegment #2 in bytes. - * @param lengthBytes the length of the region to be compared, in bytes. - * @return true, if both segments have the content for the specified region. - */ - public static boolean equalContents( - final MemorySegment seg1, - final long seg1offsetBytes, - final MemorySegment seg2, - final long seg2offsetBytes, - final long lengthBytes) { - if (seg1.equals(seg2) && (seg1.byteSize() == seg2.byteSize())) { return true; } //identical segments - final long seg1EndOff = seg1offsetBytes + lengthBytes; - final long seg2EndOff = seg2offsetBytes + lengthBytes; - return MemorySegment.mismatch(seg1, seg1offsetBytes, seg1EndOff, seg2, seg2offsetBytes, seg2EndOff) == -1; - } - - /** - * Fills a portion of this Memory region to the given byte value. - * @param seg the given MemorySegment - * @param offsetBytes offset bytes relative to this Memory start - * @param lengthBytes the length in bytes - * @param value the given byte value - */ - public static void fill(final MemorySegment seg, final long offsetBytes, final long lengthBytes, final byte value) { - final MemorySegment slice = seg.asSlice(offsetBytes, lengthBytes); - slice.fill(value); - } - - /** - * Request a new heap MemorySegment with the given capacityBytes and either 8-byte aligned or one byte aligned. - * - *

If aligned is true, the returned MemorySegment will be constructed from a long[] array, - * and, as a result, it will have a memory alignment of 8 bytes. - * If the requested capacity is not exactly divisible by eight, the returned size - * will be rolled up to the next multiple of eight bytes.

- * - *

If aligned is false, the returned MemorySegment will be constructed from a byte[] array, - * and have a memory alignment of 1 byte. - * - * @param capacityBytes The new capacity being requested. It must not be negative and cannot exceed Integer.MAX_VALUE. - * @param aligned if true, the new heap segment will have an alignment of 8 bytes, otherwise the alignment will be 1 byte. - * @return a new MemorySegment with the requested capacity and alignment. - */ - public static MemorySegment alignedHeapSegment(final int capacityBytes, final boolean aligned) { - if (aligned) { - final int lenLongs = capacityBytes >>> 3; - final long[] array = ((capacityBytes & 0x7) == 0) - ? new long[lenLongs] - : new long[lenLongs + 1]; - return MemorySegment.ofArray(array); - } - return MemorySegment.ofArray(new byte[capacityBytes]); - } - - /** - * Sets the bits defined by the bitMask - * @param seg the given MemorySegment - * @param offsetBytes offset bytes relative to this MemorySegment start - * @param bitMask the bits set to one will be set - */ - public static void setBits(final MemorySegment seg, final long offsetBytes, final byte bitMask) { - final byte b = seg.get(JAVA_BYTE, offsetBytes); - seg.set(JAVA_BYTE, offsetBytes, (byte)(b | bitMask)); - } - - /** - * Computes and checks the 16-bit seed hash from the given long seed. - * The seed hash may not be zero in order to maintain compatibility with older serialized - * versions that did not have this concept. - * @param seed See Update Hash Seed - * @return the seed hash. - */ - public static short computeSeedHash(final long seed) { - final long[] seedArr = {seed}; - final short seedHash = (short)(hash(seedArr, 0L)[0] & 0xFFFFL); - if (seedHash == 0) { - throw new SketchesArgumentException( - "The given seed: " + seed + " produced a seedHash of zero. " - + "You must choose a different seed."); - } - return seedHash; - } - - /** - * Check if the two seed hashes are equal. If not, throw an SketchesArgumentException. - * @param seedHashA the seedHash A - * @param seedHashB the seedHash B - * @return seedHashA if they are equal - */ - public static short checkSeedHashes(final short seedHashA, final short seedHashB) { - if (seedHashA != seedHashB) { - throw new SketchesArgumentException( - "Incompatible Seed Hashes. " + Integer.toHexString(seedHashA & 0XFFFF) - + ", " + Integer.toHexString(seedHashB & 0XFFFF)); - } - return seedHashA; - } - -} diff --git a/src/main/java/org/apache/datasketches/common/package-info.java b/src/main/java/org/apache/datasketches/common/package-info.java deleted file mode 100644 index 0fbaab76d..000000000 --- a/src/main/java/org/apache/datasketches/common/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package is for common classes that may be used across all the sketch families. - */ -package org.apache.datasketches.common; diff --git a/src/main/java/org/apache/datasketches/common/positional/PositionInvariantsException.java b/src/main/java/org/apache/datasketches/common/positional/PositionInvariantsException.java deleted file mode 100644 index ef327a564..000000000 --- a/src/main/java/org/apache/datasketches/common/positional/PositionInvariantsException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common.positional; - -/** - * Position operation violation. - * - * @author Lee Rhodes - */ -public class PositionInvariantsException extends RuntimeException { - private static final long serialVersionUID = 1L; - - /** - * The associated position operation violated one of the positional invariants. - * - *

The invariants equation is {@code 0 <= start <= position <= end <= capacity}.

- * - * @param details of the violation. - */ - public PositionInvariantsException(final String details) { - super(details); - } -} - diff --git a/src/main/java/org/apache/datasketches/common/positional/Positional.java b/src/main/java/org/apache/datasketches/common/positional/Positional.java deleted file mode 100644 index 4cbb163b4..000000000 --- a/src/main/java/org/apache/datasketches/common/positional/Positional.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common.positional; - -/** - * Defines the relative positional API. - * This is different from and simpler than Java ByteBuffer positional API. - *
  • All based on longs instead of ints.
  • - *
  • Eliminated "mark". Mark is rarely used and confusing with its silent side effects.
  • - *
  • The invariants are {@code 0 <= start <= position <= end <= capacity}.
  • - *
  • It always starts up as (0, 0, capacity, capacity).
  • - *
  • You set (start, position, end) in one call with - * {@link #setStartPositionEnd(long, long, long)}
  • - *
  • Position can be set directly or indirectly when using the positional get/put methods. - *
  • Added incrementPosition(long), which is much easier when you know the increment.
  • - *
  • This approach eliminated a number of methods and checks, and has no unseen side effects, - * e.g., mark being invalidated.
  • - *
  • Clearer method naming (IMHO).
  • - *
- * - * @author Lee Rhodes - */ -public interface Positional { - - /** - * Gets an instance of this Positional. - * @param capacity the upper limit of positional range. - * @return an instance of Positional. - */ - static Positional getInstance(final long capacity) { - return new PositionalImpl(capacity); - } - - /** - * Increments the current position by the given increment. - * @param increment the given increment - * @return this Positional - */ - Positional incrementPosition(long increment); - - /** - * Gets the end position - * @return the end position - */ - long getEnd(); - - /** - * Gets the current position - * @return the current position - */ - long getPosition(); - - /** - * Gets start position - * @return start position - */ - long getStart(); - - /** - * The number of elements remaining between the current position and the end position - * @return {@code (end - position)} - */ - long getRemaining(); - - /** - * Returns true if there are elements remaining between the current position and the end position - * @return {@code (end - position) > 0} - */ - boolean hasRemaining(); - - /** - * Resets the current position to the start position, - * This does not modify any data. - * @return this Positional - */ - Positional resetPosition(); - - /** - * Sets the current position. - * Checks that the positional invariants are not violated. - * @param position the given current position. - * @return this Positional - * @throws PositionInvariantsException if positional invariants have been violated. - */ - Positional setPosition(long position); - - /** - * Sets start position, current position, and end position. - * Checks that the positional invariants are not violated. - * @param start the start position in the buffer - * @param position the current position between the start and end - * @param end the end position in the buffer - * @return this Positional - * @throws PositionInvariantsException if positional invariants have been violated. - */ - Positional setStartPositionEnd( - long start, - long position, - long end); - -} diff --git a/src/main/java/org/apache/datasketches/common/positional/PositionalImpl.java b/src/main/java/org/apache/datasketches/common/positional/PositionalImpl.java deleted file mode 100644 index 01e89eb23..000000000 --- a/src/main/java/org/apache/datasketches/common/positional/PositionalImpl.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common.positional; - -/** - * This implements the positional API. - * This is different from and simpler than Java BufferImpl positional approach. - *
  • All based on longs instead of ints.
  • - *
  • Eliminated "mark". Rarely used and confusing with its silent side effects.
  • - *
  • The invariants are {@code 0 <= start <= position <= end <= capacity}.
  • - *
  • It always starts up as (0, 0, capacity, capacity).
  • - *
  • You set (start, position, end) in one call with setStartPositionEnd(long, long, long)
  • - *
  • Position can be set directly or indirectly when using the positional get/put methods. - *
  • Added incrementPosition(long), which is much easier when you know the increment.
  • - *
  • This approach eliminated a number of methods and checks, and has no unseen side effects, - * e.g., mark being invalidated.
  • - *
  • Clearer method naming (IMHO).
  • - *
- * - * @author Lee Rhodes - */ -class PositionalImpl implements Positional { - private final long capacity; - private long start = 0; - private long pos = 0; - private long end; - - /** - * Construct with total capacity. - * @param capacity the upper limit of positional range. - */ - PositionalImpl( - final long capacity) { - this.capacity = end = capacity; - } - - @Override - public final PositionalImpl incrementPosition(final long increment) { - pos += increment; - return this; - } - - @Override - public final long getEnd() { - return end; - } - - @Override - public final long getPosition() { - return pos; - } - - @Override - public final long getStart() { - return start; - } - - @Override - public final long getRemaining() { - return end - pos; - } - - @Override - public final boolean hasRemaining() { - return (end - pos) > 0; - } - - @Override - public final PositionalImpl resetPosition() { - pos = start; - return this; - } - - @Override - public final PositionalImpl setPosition(final long position) { - checkInvariants(start, position, end, capacity); - pos = position; - return this; - } - - @Override - public final PositionalImpl setStartPositionEnd(final long start, final long position, final long end) { - checkInvariants(start, position, end, capacity); - this.start = start; - this.end = end; - pos = position; - return this; - } - - //RESTRICTED - - /** - * The invariants equation is: {@code 0 <= start <= position <= end <= capacity}. - * If this equation is violated an PositionInvariantsException will be thrown. - * @param start the lowest start position - * @param pos the current position - * @param end the highest position - * @param cap the capacity of the backing resource. - */ - private static final void checkInvariants(final long start, final long pos, final long end, - final long cap) { - if ((start | pos | end | cap | (pos - start) | (end - pos) | (cap - end) ) < 0L) { - throw new PositionInvariantsException( - "Violation of Invariants: " - + "start: " + start - + " <= pos: " + pos - + " <= end: " + end - + " <= cap: " + cap - + "; (pos - start): " + (pos - start) - + ", (end - pos): " + (end - pos) - + ", (cap - end): " + (cap - end) - ); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/common/positional/PositionalSegment.java b/src/main/java/org/apache/datasketches/common/positional/PositionalSegment.java deleted file mode 100644 index 192b56271..000000000 --- a/src/main/java/org/apache/datasketches/common/positional/PositionalSegment.java +++ /dev/null @@ -1,486 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common.positional; - -import java.lang.foreign.MemorySegment; - -/** - * Defines the API for relative positional access to a MemorySegment. - * - * @author Lee Rhodes - */ -public interface PositionalSegment extends Positional { - - /** - * Gets an instance of this PositionalSegment. - * @param seg the given MemorySegment to create the PositionalSegment from. - * @return a new PositionalSegment. - */ - static PositionalSegment wrap(final MemorySegment seg) { - return new PositionalSegmentImpl(seg); - } - - /** - * Returns a slice of this PositionalSegment at the current position. - * The end of the slice is the end of the underlying segment. - * @return a slice of this PositionalSegment at the current position. - */ - PositionalSegment asSlice(); - - /** - * Returns the underlying MemorySegment. - * The current start, position and end are ignored. - * @return the underlying MemorySegment - */ - MemorySegment getMemorySegment(); - - //PRIMITIVE getX() and getXArray() - - /** - * Gets the boolean value at the current position. - * Increments the position by Byte.BYTES. - * @return the boolean at the current position - */ - boolean getBoolean(); - - /** - * Gets the boolean value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @return the boolean at the given offset - */ - boolean getBoolean(long offsetBytes); - - //intentionally removed getBooleanArray(...) - - /** - * Gets the byte value at the current position. - * Increments the position by Byte.BYTES. - * @return the byte at the current position - */ - byte getByte(); - - /** - * Gets the byte value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @return the byte at the given offset - */ - byte getByte(long offsetBytes); - - /** - * Gets the byte array at the current position. - * Increments the position by Byte.BYTES * (lengthBytes - dstOffsetBytes). - * @param dstArray The preallocated destination array. - * @param dstOffsetBytes offset in array units - * @param lengthBytes number of array units to transfer - */ - void getByteArray( - byte[] dstArray, - int dstOffsetBytes, - int lengthBytes); - - /** - * Gets the char value at the current position. - * Increments the position by Character.BYTES. - * @return the char at the current position - */ - char getChar(); - - /** - * Gets the char value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @return the char at the given offset - */ - char getChar(long offsetBytes); - - /** - * Gets the char array at the current position. - * Increments the position by Character.BYTES * (lengthChars - dstOffsetChars). - * @param dstArray The preallocated destination array. - * @param dstOffsetChars offset in array units - * @param lengthChars number of array units to transfer - */ - void getCharArray( - char[] dstArray, - int dstOffsetChars, - int lengthChars); - - /** - * Gets the double value at the current position. - * Increments the position by Double.BYTES. - * @return the double at the current position - */ - double getDouble(); - - /** - * Gets the double value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @return the double at the given offset - */ - double getDouble(long offsetBytes); - - /** - * Gets the double array at the current position. - * Increments the position by Double.BYTES * (lengthDoubles - dstOffsetDoubles). - * @param dstArray The preallocated destination array. - * @param dstOffsetDoubles offset in array units - * @param lengthDoubles number of array units to transfer - */ - void getDoubleArray( - double[] dstArray, - int dstOffsetDoubles, - int lengthDoubles); - - /** - * Gets the float value at the current position. - * Increments the position by Float.BYTES. - * @return the float at the current position - */ - float getFloat(); - - /** - * Gets the float value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @return the float at the given offset - */ - float getFloat(long offsetBytes); - - /** - * Gets the float array at the current position. - * Increments the position by Float.BYTES * (lengthFloats - dstOffsetFloats). - * @param dstArray The preallocated destination array. - * @param dstOffsetFloats offset in array units - * @param lengthFloats number of array units to transfer - */ - void getFloatArray( - float[] dstArray, - int dstOffsetFloats, - int lengthFloats); - - /** - * Gets the int value at the current position. - * Increments the position by Integer.BYTES. - * @return the int at the current position - */ - int getInt(); - - /** - * Gets the int value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @return the int at the given offset - */ - int getInt(long offsetBytes); - - /** - * Gets the int array at the current position. - * Increments the position by Integer.BYTES * (lengthInts - dstOffsetInts). - * @param dstArray The preallocated destination array. - * @param dstOffsetInts offset in array units - * @param lengthInts number of array units to transfer - */ - void getIntArray( - int[] dstArray, - int dstOffsetInts, - int lengthInts); - - /** - * Gets the long value at the current position. - * Increments the position by Long.BYTES. - * @return the long at the current position - */ - long getLong(); - - /** - * Gets the long value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @return the long at the given offset - */ - long getLong(long offsetBytes); - - /** - * Gets the long array at the current position. - * Increments the position by Long.BYTES * (lengthLongs - dstOffsetLongs). - * @param dstArray The preallocated destination array. - * @param dstOffsetLongs offset in array units - * @param lengthLongs number of array units to transfer - */ - void getLongArray( - long[] dstArray, - int dstOffsetLongs, - int lengthLongs); - - /** - * Gets the short value at the current position. - * Increments the position by Short.BYTES. - * @return the short at the current position - */ - short getShort(); - - /** - * Gets the short value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @return the short at the given offset - */ - short getShort(long offsetBytes); - - /** - * Gets the short array at the current position. - * Increments the position by Short.BYTES * (lengthShorts - dstOffsetShorts). - * @param dstArray The preallocated destination array. - * @param dstOffsetShorts offset in array units - * @param lengthShorts number of array units to transfer - */ - void getShortArray( - short[] dstArray, - int dstOffsetShorts, - int lengthShorts); - - //PRIMITIVE setX() and setXArray() - - /** - * Sets the boolean value at the current position. - * Increments the position by Byte.BYTES. - * @param value the value to put - */ - void setBoolean(boolean value); - - /** - * Sets the boolean value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start. - * @param value the value to put - */ - void setBoolean( - long offsetBytes, - boolean value); - - //intentionally removed putBooleanArray(...) - - /** - * Sets the byte value at the current position. - * Increments the position by Byte.BYTES. - * @param value the value to put - */ - void setByte(byte value); - - /** - * Sets the byte value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @param value the value to put - */ - void setByte( - long offsetBytes, - byte value); - - /** - * Sets the byte array at the current position. - * Increments the position by Byte.BYTES * (lengthBytes - srcOffsetBytes). - * @param srcArray The source array. - * @param srcOffsetBytes offset in array units - * @param lengthBytes number of array units to transfer - */ - void setByteArray( - byte[] srcArray, - int srcOffsetBytes, - int lengthBytes); - - /** - * Sets the char value at the current position. - * Increments the position by Character.BYTES. - * @param value the value to put - */ - void setChar(char value); - - /** - * Sets the char value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @param value the value to put - */ - void setChar( - long offsetBytes, - char value); - - /** - * Sets the char array at the current position. - * Increments the position by Character.BYTES * (lengthChars - srcOffsetChars). - * @param srcArray The source array. - * @param srcOffsetChars offset in array units - * @param lengthChars number of array units to transfer - */ - void setCharArray( - char[] srcArray, - int srcOffsetChars, - int lengthChars); - - /** - * Sets the double value at the current position. - * Increments the position by Double.BYTES. - * @param value the value to put - */ - void setDouble(double value); - - /** - * Sets the double value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @param value the value to put - */ - void setDouble( - long offsetBytes, - double value); - - /** - * Sets the double array at the current position. - * Increments the position by Double.BYTES * (lengthDoubles - srcOffsetDoubles). - * @param srcArray The source array. - * @param srcOffsetDoubles offset in array units - * @param lengthDoubles number of array units to transfer - */ - void setDoubleArray( - double[] srcArray, - int srcOffsetDoubles, - int lengthDoubles); - - /** - * Sets the float value at the current position. - * Increments the position by Float.BYTES. - * @param value the value to put - */ - void setFloat(float value); - - /** - * Sets the float value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @param value the value to put - */ - void setFloat( - long offsetBytes, - float value); - - /** - * Sets the float array at the current position. - * Increments the position by Float.BYTES * (lengthFloats - srcOffsetFloats). - * @param srcArray The source array. - * @param srcOffsetFloats offset in array units - * @param lengthFloats number of array units to transfer - */ - void setFloatArray( - float[] srcArray, - int srcOffsetFloats, - int lengthFloats); - - /** - * Sets the int value at the current position. - * Increments the position by Integer.BYTES. - * @param value the value to put - */ - void setInt(int value); - - /** - * Sets the int value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @param value the value to put - */ - void setInt( - long offsetBytes, - int value); - - /** - * Sets the int array at the current position. - * Increments the position by Integer.BYTES * (lengthInts - srcOffsetInts). - * @param srcArray The source array. - * @param srcOffsetInts offset in array units - * @param lengthInts number of array units to transfer - */ - void setIntArray( - int[] srcArray, - int srcOffsetInts, - int lengthInts); - - /** - * Sets the long value at the current position. - * Increments the position by Long.BYTES. - * @param value the value to put - */ - void setLong(long value); - - /** - * Sets the long value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @param value the value to put - */ - void setLong( - long offsetBytes, - long value); - - /** - * Sets the long array at the current position. - * Increments the position by Long.BYTES * (lengthLongs - srcOffsetLongs). - * @param srcArray The source array. - * @param srcOffsetLongs offset in array units - * @param lengthLongs number of array units to transfer - */ - void setLongArray( - long[] srcArray, - int srcOffsetLongs, - int lengthLongs); - - /** - * Sets the short value at the current position. - * Increments the position by Short.BYTES. - * @param value the value to put - */ - void setShort(short value); - - /** - * Sets the short value at the given offset. - * This does not change the position. - * @param offsetBytes offset bytes relative to this MemorySegment start - * @param value the value to put - */ - void setShort( - long offsetBytes, - short value); - - /** - * Sets the short array at the current position. - * Increments the position by Short.BYTES * (lengthShorts - srcOffsetShorts). - * @param srcArray The source array. - * @param srcOffsetShorts offset in array units - * @param lengthShorts number of array units to transfer - */ - void setShortArray( - short[] srcArray, - int srcOffsetShorts, - int lengthShorts); - -} diff --git a/src/main/java/org/apache/datasketches/common/positional/PositionalSegmentImpl.java b/src/main/java/org/apache/datasketches/common/positional/PositionalSegmentImpl.java deleted file mode 100644 index 380f0bb20..000000000 --- a/src/main/java/org/apache/datasketches/common/positional/PositionalSegmentImpl.java +++ /dev/null @@ -1,336 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common.positional; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_CHAR_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -/** - * Implementation of PositionalSegment - * - * @author Lee Rhodes - */ -final class PositionalSegmentImpl extends PositionalImpl implements PositionalSegment { - private static final byte SHORT_SHIFT = 1; - private static final byte CHAR_SHIFT = 1; - private static final byte INT_SHIFT = 2; - private static final byte LONG_SHIFT = 3; - private static final byte FLOAT_SHIFT = 2; - private static final byte DOUBLE_SHIFT = 3; - - private final MemorySegment seg; - - /** - * Constructs with the given MemorySegment - * @param seg the given MemorySegment - */ - PositionalSegmentImpl(final MemorySegment seg) { - super(seg.byteSize()); - this.seg = seg; - } - - @Override - public PositionalSegment asSlice() { - final MemorySegment slice = seg.asSlice(getPosition()); - return new PositionalSegmentImpl(slice); - } - - @Override - public MemorySegment getMemorySegment() { - return seg; - } - - //PRIMITIVE getX() and getXArray() - - @Override - public boolean getBoolean() { - return getByte() != 0; - } - - @Override - public boolean getBoolean(final long offsetBytes) { - return getByte(offsetBytes) != 0; - } - - @Override - public byte getByte() { - final byte aByte = seg.get(JAVA_BYTE, getPosition()); - incrementPosition(Byte.BYTES); - return aByte; - } - - @Override - public byte getByte(final long offsetBytes) { - return seg.get(JAVA_BYTE, offsetBytes); - } - - @Override - public void getByteArray(final byte[] dstArray, final int dstOffsetBytes, final int lengthBytes) { - MemorySegment.copy(seg, JAVA_BYTE, getPosition(), dstArray, dstOffsetBytes, lengthBytes); - incrementPosition(lengthBytes); - } - - @Override - public char getChar() { - final char achar = seg.get(JAVA_CHAR_UNALIGNED, getPosition()); - incrementPosition(Character.BYTES); - return achar; - } - - @Override - public char getChar(final long offsetBytes) { - return seg.get(JAVA_CHAR_UNALIGNED, offsetBytes); - } - - @Override - public void getCharArray(final char[] dstArray, final int dstOffsetChars, final int lengthChars) { - MemorySegment.copy(seg, JAVA_CHAR_UNALIGNED, getPosition(), dstArray, dstOffsetChars, lengthChars); - incrementPosition(lengthChars << CHAR_SHIFT); - } - - @Override - public double getDouble() { - final double dbl = seg.get(JAVA_DOUBLE_UNALIGNED, getPosition()); - incrementPosition(Double.BYTES); - return dbl; - } - - @Override - public double getDouble(final long offsetBytes) { - return seg.get(JAVA_DOUBLE_UNALIGNED, offsetBytes); - } - - @Override - public void getDoubleArray(final double[] dstArray, final int dstOffsetDoubles, final int lengthDoubles) { - MemorySegment.copy(seg, JAVA_DOUBLE_UNALIGNED, getPosition(), dstArray, dstOffsetDoubles, lengthDoubles); - incrementPosition(lengthDoubles << DOUBLE_SHIFT); - } - - @Override - public float getFloat() { - final float flt = seg.get(JAVA_FLOAT_UNALIGNED, getPosition()); - incrementPosition(Float.BYTES); - return flt; - } - - @Override - public float getFloat(final long offsetBytes) { - return seg.get(JAVA_FLOAT_UNALIGNED, offsetBytes); - } - - @Override - public void getFloatArray(final float[] dstArray, final int dstOffsetFloats, final int lengthFloats) { - MemorySegment.copy(seg, JAVA_FLOAT_UNALIGNED, getPosition(), dstArray, dstOffsetFloats, lengthFloats); - incrementPosition(lengthFloats << FLOAT_SHIFT); - } - - @Override - public int getInt() { - final int i = seg.get(JAVA_INT_UNALIGNED, getPosition()); - incrementPosition(Integer.BYTES); - return i; - } - - @Override - public int getInt(final long offsetBytes) { - return seg.get(JAVA_INT_UNALIGNED, offsetBytes); - } - - @Override - public void getIntArray(final int[] dstArray, final int dstOffsetInts, final int lengthInts) { - MemorySegment.copy(seg, JAVA_INT_UNALIGNED, getPosition(), dstArray, dstOffsetInts, lengthInts); - incrementPosition(lengthInts << INT_SHIFT); - } - - @Override - public long getLong() { - final long along = seg.get(JAVA_LONG_UNALIGNED, getPosition()); - incrementPosition(Long.BYTES); - return along; - } - - @Override - public long getLong(final long offsetBytes) { - return seg.get(JAVA_LONG_UNALIGNED, offsetBytes); - } - - @Override - public void getLongArray(final long[] dstArray, final int dstOffsetLongs, final int lengthLongs) { - MemorySegment.copy(seg, JAVA_LONG_UNALIGNED, getPosition(), dstArray, dstOffsetLongs, lengthLongs); - incrementPosition(lengthLongs << LONG_SHIFT); - } - - @Override - public short getShort() { - final short ashort = seg.get(JAVA_SHORT_UNALIGNED, getPosition()); - incrementPosition(Short.BYTES); - return ashort; - } - - @Override - public short getShort(final long offsetBytes) { - return seg.get(JAVA_SHORT_UNALIGNED, offsetBytes); - } - - @Override - public void getShortArray(final short[] dstArray, final int dstOffsetShorts, final int lengthShorts) { - MemorySegment.copy(seg, JAVA_SHORT_UNALIGNED, getPosition(), dstArray, dstOffsetShorts, lengthShorts); - incrementPosition(lengthShorts << SHORT_SHIFT); - } - - //PRIMITIVE setX() and setXArray() implementations - - @Override - public void setBoolean(final boolean value) { - setByte(value ? (byte)1 : 0); - } - - @Override - public void setBoolean(final long offsetBytes, final boolean value) { - setByte(offsetBytes, value ? (byte)1 : 0); - } - - @Override - public void setByte(final byte value) { - seg.set(JAVA_BYTE, getPosition(), value); - incrementPosition(Byte.BYTES); - } - - @Override - public void setByte(final long offsetBytes, final byte value) { - seg.set(JAVA_BYTE, offsetBytes, value); - } - - @Override - public void setByteArray(final byte[] srcArray, final int srcOffsetBytes, final int lengthBytes) { - MemorySegment.copy(srcArray, srcOffsetBytes, seg, JAVA_BYTE, getPosition(), lengthBytes); - incrementPosition(lengthBytes); - } - - @Override - public void setChar(final char value) { - seg.set(JAVA_CHAR_UNALIGNED, getPosition(), value); - incrementPosition(Character.BYTES); - } - - @Override - public void setChar(final long offsetBytes, final char value) { - seg.set(JAVA_CHAR_UNALIGNED, offsetBytes, value); - } - - @Override - public void setCharArray(final char[] srcArray, final int srcOffsetChars, final int lengthChars) { - MemorySegment.copy(srcArray, srcOffsetChars, seg, JAVA_CHAR_UNALIGNED, getPosition(), lengthChars); - incrementPosition(lengthChars << CHAR_SHIFT); - } - - @Override - public void setDouble(final double value) { - seg.set(JAVA_DOUBLE_UNALIGNED, getPosition(), value); - incrementPosition(Double.BYTES); - } - - @Override - public void setDouble(final long offsetBytes, final double value) { - seg.set(JAVA_DOUBLE_UNALIGNED, offsetBytes, value); - } - - @Override - public void setDoubleArray(final double[] srcArray, final int srcOffsetDoubles, final int lengthDoubles) { - MemorySegment.copy(srcArray, srcOffsetDoubles, seg, JAVA_DOUBLE_UNALIGNED, getPosition(), lengthDoubles); - incrementPosition(lengthDoubles << DOUBLE_SHIFT); - } - - @Override - public void setFloat(final float value) { - seg.set(JAVA_FLOAT_UNALIGNED, getPosition(), value); - incrementPosition(Float.BYTES); - } - - @Override - public void setFloat(final long offsetBytes, final float value) { - seg.set(JAVA_FLOAT_UNALIGNED, offsetBytes, value); - } - - @Override - public void setFloatArray(final float[] srcArray, final int srcOffsetFloats, final int lengthFloats) { - MemorySegment.copy(srcArray, srcOffsetFloats, seg, JAVA_FLOAT_UNALIGNED, getPosition(), lengthFloats); - incrementPosition(lengthFloats << FLOAT_SHIFT); - } - - @Override - public void setInt(final int value) { - seg.set(JAVA_INT_UNALIGNED, getPosition(), value); - incrementPosition(Integer.BYTES); - } - - @Override - public void setInt(final long offsetBytes, final int value) { - seg.set(JAVA_INT_UNALIGNED, offsetBytes, value); - } - - @Override - public void setIntArray(final int[] srcArray, final int srcOffsetInts, final int lengthInts) { - MemorySegment.copy(srcArray, srcOffsetInts, seg, JAVA_INT_UNALIGNED, getPosition(), lengthInts); - incrementPosition(lengthInts << INT_SHIFT); - } - - @Override - public void setLong(final long value) { - seg.set(JAVA_LONG_UNALIGNED, getPosition(), value); - incrementPosition(Long.BYTES); - } - - @Override - public void setLong(final long offsetBytes, final long value) { - seg.set(JAVA_LONG_UNALIGNED, offsetBytes, value); - } - - @Override - public void setLongArray(final long[] srcArray, final int srcOffsetLongs, final int lengthLongs) { - MemorySegment.copy(srcArray, srcOffsetLongs, seg, JAVA_LONG_UNALIGNED, getPosition(), lengthLongs); - incrementPosition(lengthLongs << LONG_SHIFT); - } - - @Override - public void setShort(final short value) { - seg.set(JAVA_SHORT_UNALIGNED, getPosition(), value); - incrementPosition(Short.BYTES); - } - - @Override - public void setShort(final long offsetBytes, final short value) { - seg.set(JAVA_SHORT_UNALIGNED, offsetBytes, value); - } - - @Override - public void setShortArray(final short[] srcArray, final int srcOffsetShorts, final int lengthShorts) { - MemorySegment.copy(srcArray, srcOffsetShorts, seg, JAVA_SHORT_UNALIGNED, getPosition(), lengthShorts); - incrementPosition(lengthShorts << SHORT_SHIFT); - } - -} diff --git a/src/main/java/org/apache/datasketches/common/positional/package-info.java b/src/main/java/org/apache/datasketches/common/positional/package-info.java deleted file mode 100644 index 9049e3573..000000000 --- a/src/main/java/org/apache/datasketches/common/positional/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package provides the classes that define and implement a relative positional API. - * - * @see org.apache.datasketches.common.positional.Positional - * - * @author Lee Rhodes - */ -package org.apache.datasketches.common.positional; diff --git a/src/main/java/org/apache/datasketches/count/CountMinSketch.java b/src/main/java/org/apache/datasketches/count/CountMinSketch.java deleted file mode 100644 index 9bf576e13..000000000 --- a/src/main/java/org/apache/datasketches/count/CountMinSketch.java +++ /dev/null @@ -1,493 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.count; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; - -import java.lang.foreign.MemorySegment; -import java.nio.charset.StandardCharsets; -import java.util.Random; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.common.positional.PositionalSegment; -import org.apache.datasketches.hash.MurmurHash3; - -/** - * Java implementation of the CountMin sketch data structure of Cormode and Muthukrishnan. - * This implementation is inspired by and compatible with the datasketches-cpp version by Charlie Dickens. - * - * The CountMin sketch is a probabilistic data structure that provides frequency estimates for items - * in a data stream. It uses multiple hash functions to distribute items across a two-dimensional array, - * providing approximate counts with configurable error bounds. - * - * Reference: http://dimacs.rutgers.edu/~graham/pubs/papers/cm-full.pdf - */ -public class CountMinSketch { - private final byte numHashes_; - private final int numBuckets_; - private final long seed_; - private final long[] hashSeeds_; - private final long[] sketchArray_; - private long totalWeight_; - - // Thread-local MemorySegment to avoid allocations in hot paths with explicit endianness control - private static final ThreadLocal LONG_SEGMENT = - ThreadLocal.withInitial(() -> MemorySegment.ofArray(new byte[Long.BYTES])); - - private enum Flag { - IS_EMPTY; - - int mask() { - return 1 << ordinal(); - } - } - - /** - * Creates a CountMin sketch with given number of hash functions and buckets, - * and a user-specified seed. - * - * @param numHashes The number of hash functions to apply to items - * @param numBuckets Array size for each of the hashing function - * @param seed The base hash seed - */ - CountMinSketch(final byte numHashes, final int numBuckets, final long seed) { - // Validate numHashes - if (numHashes <= 0) { - throw new SketchesArgumentException("Number of hash functions must be positive, got: " + numHashes); - } - - // Validate numBuckets with clear mathematical justification - if (numBuckets <= 0) { - throw new SketchesArgumentException("Number of buckets must be positive, got: " + numBuckets); - } - if (numBuckets < 3) { - throw new SketchesArgumentException("Number of buckets must be at least 3 to ensure relative error ≤ 1.0. " - + "With " + numBuckets + " buckets, relative error would be " + String.format("%.3f", Math.exp(1.0) / numBuckets)); - } - - // Check for potential overflow in array size calculation - // Use long arithmetic to detect overflow before casting - final long totalSize = (long) numHashes * (long) numBuckets; - if (totalSize > Integer.MAX_VALUE) { - throw new SketchesArgumentException("Sketch array size would overflow: " + numHashes + " * " + numBuckets - + " = " + totalSize + " > " + Integer.MAX_VALUE); - } - - // This check is to ensure later compatibility with a Java implementation whose maximum size can only - // be 2^31-1. We check only against 2^30 for simplicity. - if (totalSize >= (1L << 30)) { - throw new SketchesArgumentException("Sketch would require excessive memory: " + numHashes + " * " + numBuckets - + " = " + totalSize + " elements (~" + String.format("%d", (totalSize * Long.BYTES) / (1024 * 1024 * 1024)) + " GB). " - + "Consider reducing numHashes or numBuckets."); - } - - numHashes_ = numHashes; - numBuckets_ = numBuckets; - seed_ = seed; - hashSeeds_ = new long[numHashes]; - sketchArray_ = new long[(int) totalSize]; - totalWeight_ = 0; - - final Random rand = new Random(seed); - for (int i = 0; i < numHashes; i++) { - hashSeeds_[i] = rand.nextLong(); - } - } - - /** - * Efficiently converts a long to byte array using thread-local MemorySegment with explicit endianness. - */ - private static byte[] longToBytes(final long value) { - final MemorySegment segment = LONG_SEGMENT.get(); - segment.set(JAVA_LONG_UNALIGNED, 0, value); - return segment.toArray(JAVA_BYTE); - } - - private long[] getHashes(final byte[] item) { - final long[] updateLocations = new long[numHashes_]; - - for (int i = 0; i < numHashes_; i++) { - final long[] index = MurmurHash3.hash(item, hashSeeds_[i]); - updateLocations[i] = (i * (long)numBuckets_) + Math.floorMod(index[0], numBuckets_); - } - - return updateLocations; - } - - /** - * Checks if the CountMinSketch has processed any items. - * @return True if the sketch is empty, otherwise false. - */ - public boolean isEmpty() { - return totalWeight_ == 0; - } - - /** - * Returns the number of hash functions used in this sketch. - * @return The number of hash functions. - */ - public byte getNumHashes_() { - return numHashes_; - } - - /** - * Returns the number of buckets per hash function. - * @return The number of buckets. - */ - public int getNumBuckets_() { - return numBuckets_; - } - - /** - * Returns the hash seed used by this sketch. - * @return The seed value. - */ - public long getSeed_() { - return seed_; - } - - /** - * Returns the total weight of all items inserted into the sketch. - * @return The total weight. - */ - public long getTotalWeight_() { - return totalWeight_; - } - - /** - * Returns the relative error of the sketch. - * @return The relative error. - */ - public double getRelativeError() { - return Math.exp(1.0) / numBuckets_; - } - - /** - * Suggests an appropriate number of hash functions to use for a given confidence level. - * @param confidence The desired confidence level between 0 and 1. - * @return Suggested number of hash functions. - */ - public static byte suggestNumHashes(final double confidence) { - if ((confidence < 0) || (confidence > 1)) { - throw new SketchesException("Confidence must be between 0 and 1.0 (inclusive)."); - } - final int value = (int) Math.ceil(Math.log(1.0 / (1.0 - confidence))); - return (byte) Math.min(value, 127); - } - - /** - * Suggests an appropriate number of buckets per hash function for a given relative error. - * @param relativeError The desired relative error. - * @return Suggested number of buckets. - */ - public static int suggestNumBuckets(final double relativeError) { - if (relativeError < 0.) { - throw new SketchesException("Relative error must be at least 0."); - } - return (int) Math.ceil(Math.exp(1.0) / relativeError); - } - - /** - * Updates the sketch with the provided item and weight. - * @param item The item to update. - * @param weight The weight of the item. - */ - public void update(final long item, final long weight) { - update(longToBytes(item), weight); - } - - /** - * Updates the sketch with the provided item and weight. - * @param item The item to update. - * @param weight The weight of the item. - */ - public void update(final String item, final long weight) { - if ((item == null) || item.isEmpty()) { - return; - } - final byte[] strByte = item.getBytes(StandardCharsets.UTF_8); - update(strByte, weight); - } - - /** - * Updates the sketch with the provided item and weight. - * @param item The item to update. - * @param weight The weight of the item. - */ - public void update(final byte[] item, final long weight) { - if (item.length == 0) { - return; - } - - totalWeight_ += weight > 0 ? weight : -weight; - final long[] hashLocations = getHashes(item); - for (final long h : hashLocations) { - sketchArray_[(int) h] += weight; - } - } - - /** - * Returns the estimated frequency for the given item. - * @param item The item to estimate. - * @return Estimated frequency. - */ - public long getEstimate(final long item) { - return getEstimate(longToBytes(item)); - } - - /** - * Returns the estimated frequency for the given item. - * @param item The item to estimate. - * @return Estimated frequency. - */ - public long getEstimate(final String item) { - if ((item == null) || item.isEmpty()) { - return 0; - } - - final byte[] strByte = item.getBytes(StandardCharsets.UTF_8); - return getEstimate(strByte); - } - - /** - * Returns the estimated frequency for the given item. - * @param item The item to estimate. - * @return Estimated frequency. - */ - public long getEstimate(final byte[] item) { - if (item.length == 0) { - return 0; - } - - final long[] hashLocations = getHashes(item); - long res = sketchArray_[(int) hashLocations[0]]; - // Start from index 1 to avoid processing first element twice - for (int i = 1; i < hashLocations.length; i++) { - res = Math.min(res, sketchArray_[(int) hashLocations[i]]); - } - - return res; - } - - /** - * Returns the upper bound of the estimated frequency for the given item. - * @param item The item to estimate. - * @return Upper bound of estimated frequency. - */ - public long getUpperBound(final long item) { - return getUpperBound(longToBytes(item)); - } - - /** - * Returns the upper bound of the estimated frequency for the given item. - * @param item The item to estimate. - * @return Upper bound of estimated frequency. - */ - public long getUpperBound(final String item) { - if ((item == null) || item.isEmpty()) { - return 0; - } - - final byte[] strByte = item.getBytes(StandardCharsets.UTF_8); - return getUpperBound(strByte); - } - - /** - * Returns the upper bound of the estimated frequency for the given item. - * @param item The item to estimate. - * @return Upper bound of estimated frequency. - */ - public long getUpperBound(final byte[] item) { - if (item.length == 0) { - return 0; - } - - return getEstimate(item) + (long)(getRelativeError() * getTotalWeight_()); - } - - /** - * Returns the lower bound of the estimated frequency for the given item. - * @param item The item to estimate. - * @return Lower bound of estimated frequency. - */ - public long getLowerBound(final long item) { - return getLowerBound(longToBytes(item)); - } - - /** - * Returns the lower bound of the estimated frequency for the given item. - * @param item The item to estimate. - * @return Lower bound of estimated frequency. - */ - public long getLowerBound(final String item) { - if ((item == null) || item.isEmpty()) { - return 0; - } - - final byte[] strByte = item.getBytes(StandardCharsets.UTF_8); - return getLowerBound(strByte); - } - - /** - * Returns the lower bound of the estimated frequency for the given item. - * @param item The item to estimate. - * @return Lower bound of estimated frequency. - */ - public long getLowerBound(final byte[] item) { - return getEstimate(item); - } - - /** - * Merges another CountMinSketch into this one. The sketches must have the same configuration. - * @param other The other sketch to merge. - */ - public void merge(final CountMinSketch other) { - if (this == other) { - throw new SketchesException("Cannot merge a sketch with itself"); - } - - final boolean acceptableConfig = (getNumBuckets_() == other.getNumBuckets_()) - && (getNumHashes_() == other.getNumHashes_()) && (getSeed_() == other.getSeed_()); - - if (!acceptableConfig) { - throw new SketchesException("Incompatible sketch configuration."); - } - - for (int i = 0; i < sketchArray_.length; i++) { - sketchArray_[i] += other.sketchArray_[i]; - } - - totalWeight_ += other.getTotalWeight_(); - } - - /** - * Returns the serialized size in bytes. - */ - private int getSerializedSizeBytes() { - final int preambleBytes = Family.COUNTMIN.getMinPreLongs() * Long.BYTES; - if (isEmpty()) { - return preambleBytes; - } - return preambleBytes + Long.BYTES + (sketchArray_.length * Long.BYTES); - } - - /** - * Returns the sketch as a byte array. - * @return the result byte array - */ - public byte[] toByteArray() { - final int serializedSizeBytes = getSerializedSizeBytes(); - final byte[] bytes = new byte[serializedSizeBytes]; - final PositionalSegment posSeg = PositionalSegment.wrap(MemorySegment.ofArray(bytes)); - - // Long 0 - final int preambleLongs = Family.COUNTMIN.getMinPreLongs(); - posSeg.setByte((byte) preambleLongs); - final int serialVersion = 1; - posSeg.setByte((byte) serialVersion); - final int familyId = Family.COUNTMIN.getID(); - posSeg.setByte((byte) familyId); - final int flagsByte = isEmpty() ? Flag.IS_EMPTY.mask() : 0; - posSeg.setByte((byte) flagsByte); - final int NULL_32 = 0; - posSeg.setInt(NULL_32); - - // Long 1 - posSeg.setInt(numBuckets_); - posSeg.setByte(numHashes_); - final short hashSeed = Util.computeSeedHash(seed_); - posSeg.setShort(hashSeed); - final byte NULL_8 = 0; - posSeg.setByte(NULL_8); - - if (isEmpty()) { - return bytes; - } - - posSeg.setLong(totalWeight_); - - for (final long w: sketchArray_) { - posSeg.setLong(w); - } - - return bytes; - } - - /** - * Deserializes a CountMinSketch from the provided byte array. - * @param b The byte array containing the serialized sketch. - * @param seed The seed used during serialization. - * @return The deserialized CountMinSketch. - */ - public static CountMinSketch deserialize(final byte[] b, final long seed) { - final PositionalSegment posSeg = PositionalSegment.wrap(MemorySegment.ofArray(b)); - - final byte preambleLongs = posSeg.getByte(); - final byte serialVersion = posSeg.getByte(); - final byte familyId = posSeg.getByte(); - final byte flagsByte = posSeg.getByte(); - posSeg.getInt(); // skip NULL_32 - - // Validate serialization format - final int expectedPreambleLongs = Family.COUNTMIN.getMinPreLongs(); - if (preambleLongs != expectedPreambleLongs) { - throw new SketchesArgumentException("Preamble longs mismatch: expected " + expectedPreambleLongs - + ", actual " + preambleLongs); - } - final int expectedSerialVersion = 1; - if (serialVersion != expectedSerialVersion) { - throw new SketchesArgumentException("Serial version mismatch: expected " + expectedSerialVersion - + ", actual " + serialVersion); - } - final int expectedFamilyId = Family.COUNTMIN.getID(); - if (familyId != expectedFamilyId) { - throw new SketchesArgumentException("Family ID mismatch: expected " + expectedFamilyId - + ", actual " + familyId); - } - - final int numBuckets = posSeg.getInt(); - final byte numHashes = posSeg.getByte(); - final short seedHash = posSeg.getShort(); - posSeg.getByte(); // skip NULL_8 - - if (seedHash != Util.computeSeedHash(seed)) { - throw new SketchesArgumentException("Incompatible seed hashes: " + seedHash + ", " - + Util.computeSeedHash(seed)); - } - - final CountMinSketch cms = new CountMinSketch(numHashes, numBuckets, seed); - final boolean empty = (flagsByte & Flag.IS_EMPTY.mask()) > 0; - if (empty) { - return cms; - } - final long w = posSeg.getLong(); - cms.totalWeight_ = w; - - for (int i = 0; i < cms.sketchArray_.length; i++) { - cms.sketchArray_[i] = posSeg.getLong(); - } - - return cms; - } -} diff --git a/src/main/java/org/apache/datasketches/count/package-info.java b/src/main/java/org/apache/datasketches/count/package-info.java deleted file mode 100644 index c363f1d4a..000000000 --- a/src/main/java/org/apache/datasketches/count/package-info.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package in intended for implementations of the the Count Sketch and the Count-min Sketch both of which can be used to estimate - * frequency-moments of a stream of distinct elements. They are different from the unique counting sketches (HLL, Theta, CPC, etc.) - * and different from the Frequent-Items Sketch. - * - *

A Count-Min sketch is a probabilistic data structure that estimates the frequency of items in a large data stream using a - * fixed amount of memory. It uses a 2D array of counters and multiple hash functions to map each item to a position in every row. - * To estimate an item's frequency, it takes the minimum count from all the positions it hashes to, which provides an overestimate - * that is guaranteed to be greater than or equal to the true count.

- * - *

A Count sketch is a type of dimensionality reduction that is particularly efficient in statistics, machine learning and - * algorithms. It was invented by Moses Charikar, Kevin Chen and Martin Farach-Colton in an effort to speed up the AMS Sketch by - * Alon, Matias and Szegedy for approximating the frequency moments of streams[4] (these calculations require counting of the - * number of occurrences for the distinct elements of the stream).

- * - * @see https://en.wikipedia.org/wiki/Count_sketch - * @see https://en.wikipedia.org/wiki/Count%E2%80%93min_sketch - * - */ - -package org.apache.datasketches.count; diff --git a/src/main/java/org/apache/datasketches/cpc/BitMatrix.java b/src/main/java/org/apache/datasketches/cpc/BitMatrix.java deleted file mode 100644 index ecf27b70f..000000000 --- a/src/main/java/org/apache/datasketches/cpc/BitMatrix.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.hash.MurmurHash3.hash; - -import java.util.Arrays; - -import org.apache.datasketches.common.Util; - -/** - * Used only in test. - * @author Lee Rhodes - * @author Kevin Lang - */ -class BitMatrix { - private final int lgK; - private final long seed; - private long numCoupons; - private long[] bitMatrix; - private boolean numCouponsInvalid; //only used if we allowed merges - - BitMatrix(final int lgK) { - this(lgK, Util.DEFAULT_UPDATE_SEED); - } - - BitMatrix(final int lgK, final long seed) { - this.lgK = lgK; - this.seed = seed; - bitMatrix = new long[1 << lgK]; - numCoupons = 0; - numCouponsInvalid = false; - } - - //leaves lgK and seed untouched - void reset() { - Arrays.fill(bitMatrix, 0); - numCoupons = 0; - numCouponsInvalid = false; - } - - long getNumCoupons() { - if (numCouponsInvalid) { - numCoupons = countCoupons(bitMatrix); - numCouponsInvalid = false; - } - return numCoupons; - } - - long[] getMatrix() { - return bitMatrix; - } - - /** - * Present the given long as a potential unique item. - * - * @param datum The given long datum. - */ - public void update(final long datum) { - final long[] data = { datum }; - final long[] harr = hash(data, seed); - hashUpdate(harr[0], harr[1]); - } - - private void hashUpdate(final long hash0, final long hash1) { - int col = Long.numberOfLeadingZeros(hash1); - if (col > 63) { col = 63; } // clip so that 0 <= col <= 63 - final long kMask = (1L << lgK) - 1L; - int row = (int) (hash0 & kMask); - final int rowCol = (row << 6) | col; - - // Avoid the hash table's "empty" value which is (2^26 -1, 63) (all ones) by changing it - // to the pair (2^26 - 2, 63), which effectively merges the two cells. - // This case is *extremely* unlikely, but we might as well handle it. - // It can't happen at all if lgK (or maxLgK) < 26. - if (rowCol == -1) { row ^= 1; } //set the LSB of row to 0 - - final long oldPattern = bitMatrix[row]; - final long newPattern = oldPattern | (1L << col); - if (newPattern != oldPattern) { - numCoupons++; - bitMatrix[row] = newPattern; - } - } - - static long countCoupons(final long[] bitMatrix) { - long count = 0; - final int len = bitMatrix.length; - for (int i = 0; i < len; i++) { count += Long.bitCount(bitMatrix[i]); } - return count; - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/CompressedState.java b/src/main/java/org/apache/datasketches/cpc/CompressedState.java deleted file mode 100644 index a0e88df50..000000000 --- a/src/main/java/org/apache/datasketches/cpc/CompressedState.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.cpc.PreambleUtil.checkCapacity; -import static org.apache.datasketches.cpc.PreambleUtil.checkLoPreamble; -import static org.apache.datasketches.cpc.PreambleUtil.getDefinedPreInts; -import static org.apache.datasketches.cpc.PreambleUtil.getFiCol; -import static org.apache.datasketches.cpc.PreambleUtil.getFormatOrdinal; -import static org.apache.datasketches.cpc.PreambleUtil.getHipAccum; -import static org.apache.datasketches.cpc.PreambleUtil.getKxP; -import static org.apache.datasketches.cpc.PreambleUtil.getLgK; -import static org.apache.datasketches.cpc.PreambleUtil.getNumCoupons; -import static org.apache.datasketches.cpc.PreambleUtil.getNumSv; -import static org.apache.datasketches.cpc.PreambleUtil.getPreInts; -import static org.apache.datasketches.cpc.PreambleUtil.getSeedHash; -import static org.apache.datasketches.cpc.PreambleUtil.getSvLengthInts; -import static org.apache.datasketches.cpc.PreambleUtil.getSvStream; -import static org.apache.datasketches.cpc.PreambleUtil.getWLengthInts; -import static org.apache.datasketches.cpc.PreambleUtil.getWStream; -import static org.apache.datasketches.cpc.PreambleUtil.isCompressed; -import static org.apache.datasketches.cpc.PreambleUtil.putEmptyHip; -import static org.apache.datasketches.cpc.PreambleUtil.putEmptyMerged; -import static org.apache.datasketches.cpc.PreambleUtil.putPinnedSlidingHip; -import static org.apache.datasketches.cpc.PreambleUtil.putPinnedSlidingHipNoSv; -import static org.apache.datasketches.cpc.PreambleUtil.putPinnedSlidingMerged; -import static org.apache.datasketches.cpc.PreambleUtil.putPinnedSlidingMergedNoSv; -import static org.apache.datasketches.cpc.PreambleUtil.putSparseHybridHip; -import static org.apache.datasketches.cpc.PreambleUtil.putSparseHybridMerged; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Util; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -final class CompressedState { - private boolean csvIsValid = false; - private boolean windowIsValid = false; - final int lgK; - final short seedHash; - int fiCol = 0; - boolean mergeFlag = false; //compliment of HIP Flag - long numCoupons = 0; - - double kxp; - double hipEstAccum = 0.0; - - int numCsv = 0; - int[] csvStream = null; //may be longer than required - int csvLengthInts = 0; - int[] cwStream = null; //may be longer than required - int cwLengthInts = 0; - - //int cpcRequiredBytes = 0; - - private CompressedState(final int lgK, final short seedHash) { - this.lgK = lgK; - this.seedHash = seedHash; - kxp = 1 << lgK; - } - - static CompressedState compress(final CpcSketch source) { - final short seedHash = Util.computeSeedHash(source.seed); - final CompressedState target = new CompressedState(source.lgK, seedHash); - target.fiCol = source.fiCol; - target.mergeFlag = source.mergeFlag; - - target.numCoupons = source.numCoupons; - target.kxp = source.kxp; - target.hipEstAccum = source.hipEstAccum; - - target.csvIsValid = source.pairTable != null; - target.windowIsValid = (source.slidingWindow != null); - CpcCompression.compress(source, target); - return target; - } - - Flavor getFlavor() { - return CpcUtil.determineFlavor(lgK, numCoupons); - } - - Format getFormat() { - final int ordinal = ((cwLengthInts > 0) ? 4 : 0) - | ((numCsv > 0) ? 2 : 0) - | ( mergeFlag ? 0 : 1 ); //complement of HIP - return Format.ordinalToFormat(ordinal); - } - - int getWindowOffset() { - return CpcUtil.determineCorrectOffset(lgK, numCoupons); - } - - long getRequiredSerializedBytes() { - final Format format = getFormat(); - final int preInts = getDefinedPreInts(format); - return 4L * (preInts + csvLengthInts + cwLengthInts); - } - - static CompressedState importFromSegment(final MemorySegment seg) { - checkLoPreamble(seg); - rtAssert(isCompressed(seg)); - final int lgK = getLgK(seg); - final short seedHash = getSeedHash(seg); - final CompressedState state = new CompressedState(lgK, seedHash); - final int fmtOrd = getFormatOrdinal(seg); - final Format format = Format.ordinalToFormat(fmtOrd); - state.mergeFlag = ((fmtOrd & 1) <= 0); //merge flag is complement of HIP - state.csvIsValid = (fmtOrd & 2) > 0; - state.windowIsValid = (fmtOrd & 4) > 0; - - switch (format) { - case EMPTY_MERGED : - case EMPTY_HIP : { - checkCapacity(seg.byteSize(), 8L); - break; - } - case SPARSE_HYBRID_MERGED : { - //state.fiCol = getFiCol(seg; - state.numCoupons = getNumCoupons(seg); - state.numCsv = (int) state.numCoupons; //only true for sparse_hybrid - state.csvLengthInts = getSvLengthInts(seg); - //state.cwLength = getCwLength(seg; - //state.kxp = getKxP(seg; - //state.hipEstAccum = getHipAccum(seg; - checkCapacity(seg.byteSize(), state.getRequiredSerializedBytes()); - //state.cwStream = getCwStream(seg; - state.csvStream = getSvStream(seg); - break; - } - case SPARSE_HYBRID_HIP : { - //state.fiCol = getFiCol(seg; - state.numCoupons = getNumCoupons(seg); - state.numCsv = (int) state.numCoupons; //only true for sparse_hybrid - state.csvLengthInts = getSvLengthInts(seg); - //state.cwLength = getCwLength(seg; - state.kxp = getKxP(seg); - state.hipEstAccum = getHipAccum(seg); - checkCapacity(seg.byteSize(), state.getRequiredSerializedBytes()); - //state.cwStream = getCwStream(seg; - state.csvStream = getSvStream(seg); - break; - } - case PINNED_SLIDING_MERGED_NOSV : { - state.fiCol = getFiCol(seg); - state.numCoupons = getNumCoupons(seg); - //state.numCsv = getNumCsv(seg; - //state.csvLength = getCsvLength(seg; - state.cwLengthInts = getWLengthInts(seg); - //state.kxp = getKxP(seg; - //state.hipEstAccum = getHipAccum(seg; - checkCapacity(seg.byteSize(), state.getRequiredSerializedBytes()); - state.cwStream = getWStream(seg); - //state.csvStream = getCsvStream(seg; - break; - } - case PINNED_SLIDING_HIP_NOSV : { - state.fiCol = getFiCol(seg); - state.numCoupons = getNumCoupons(seg); - //state.numCsv = getNumCsv(seg; - //state.csvLength = getCsvLength(seg; - state.cwLengthInts = getWLengthInts(seg); - state.kxp = getKxP(seg); - state.hipEstAccum = getHipAccum(seg); - checkCapacity(seg.byteSize(), state.getRequiredSerializedBytes()); - state.cwStream = getWStream(seg); - //state.csvStream = getCsvStream(seg; - break; - } - case PINNED_SLIDING_MERGED : { - state.fiCol = getFiCol(seg); - state.numCoupons = getNumCoupons(seg); - state.numCsv = getNumSv(seg); - state.csvLengthInts = getSvLengthInts(seg); - state.cwLengthInts = getWLengthInts(seg); - //state.kxp = getKxP(seg; - //state.hipEstAccum = getHipAccum(seg; - checkCapacity(seg.byteSize(), state.getRequiredSerializedBytes()); - state.cwStream = getWStream(seg); - state.csvStream = getSvStream(seg); - break; - } - case PINNED_SLIDING_HIP : { - state.fiCol = getFiCol(seg); - state.numCoupons = getNumCoupons(seg); - state.numCsv = getNumSv(seg); - state.csvLengthInts = getSvLengthInts(seg); - state.cwLengthInts = getWLengthInts(seg); - state.kxp = getKxP(seg); - state.hipEstAccum = getHipAccum(seg); - checkCapacity(seg.byteSize(), state.getRequiredSerializedBytes()); - state.cwStream = getWStream(seg); - state.csvStream = getSvStream(seg); - break; - } - } - checkCapacity(seg.byteSize(), - 4L * (getPreInts(seg) + state.csvLengthInts + state.cwLengthInts)); - return state; - } - - void exportToSegment(final MemorySegment wseg) { - final Format format = getFormat(); - switch (format) { - case EMPTY_MERGED : { - putEmptyMerged(wseg, lgK, seedHash); - break; - } - case EMPTY_HIP : { - putEmptyHip(wseg, lgK, seedHash); - break; - } - case SPARSE_HYBRID_MERGED : { - putSparseHybridMerged(wseg, - lgK, - (int) numCoupons, //unsigned - csvLengthInts, - seedHash, - csvStream); - break; - } - case SPARSE_HYBRID_HIP : { - putSparseHybridHip(wseg, - lgK, - (int) numCoupons, //unsigned - csvLengthInts, - kxp, - hipEstAccum, - seedHash, - csvStream); - break; - } - case PINNED_SLIDING_MERGED_NOSV : { - putPinnedSlidingMergedNoSv(wseg, - lgK, - fiCol, - (int) numCoupons, //unsigned - cwLengthInts, - seedHash, - cwStream); - break; - } - case PINNED_SLIDING_HIP_NOSV : { - putPinnedSlidingHipNoSv(wseg, - lgK, - fiCol, - (int) numCoupons, //unsigned - cwLengthInts, - kxp, - hipEstAccum, - seedHash, - cwStream); - break; - } - case PINNED_SLIDING_MERGED : { - putPinnedSlidingMerged(wseg, - lgK, - fiCol, - (int) numCoupons, //unsigned - numCsv, - csvLengthInts, - cwLengthInts, - seedHash, - csvStream, - cwStream); - break; - } - case PINNED_SLIDING_HIP : { - putPinnedSlidingHip(wseg, - lgK, - fiCol, - (int) numCoupons, //unsigned - numCsv, - kxp, - hipEstAccum, - csvLengthInts, - cwLengthInts, - seedHash, - csvStream, - cwStream); - break; - } - } - } - - @Override - public String toString() { - return toString(this, false); - } - - public static String toString(final CompressedState state, final boolean detail) { - final StringBuilder sb = new StringBuilder(); - sb.append("CompressedState").append(LS); - sb.append(" Flavor : ").append(state.getFlavor()).append(LS); - sb.append(" Format : ").append(state.getFormat()).append(LS); - sb.append(" lgK : ").append(state.lgK).append(LS); - sb.append(" seedHash : ").append(state.seedHash).append(LS); - sb.append(" fiCol : ").append(state.fiCol).append(LS); - sb.append(" mergeFlag : ").append(state.mergeFlag).append(LS); - sb.append(" csvStream : ").append(state.csvIsValid).append(LS); - sb.append(" cwStream : ").append(state.windowIsValid).append(LS); - sb.append(" numCoupons : ").append(state.numCoupons).append(LS); - sb.append(" kxp : ").append(state.kxp).append(LS); - sb.append(" hipAccum : ").append(state.hipEstAccum).append(LS); - sb.append(" numCsv : ").append(state.numCsv).append(LS); - sb.append(" csvLengthInts : ").append(state.csvLengthInts).append(LS); - sb.append(" csLength : ").append(state.cwLengthInts).append(LS); - if (detail) { - if (state.csvStream != null) { - sb.append(" CsvStream : ").append(LS); - for (int i = 0; i < state.csvLengthInts; i++) { - sb.append(String.format("%8d %12d" + LS, i, state.csvStream[i])); - } - } - if (state.cwStream != null) { - sb.append(" CwStream : ").append(LS); - for (int i = 0; i < state.cwLengthInts; i++) { - sb.append(String.format("%8d %12d" + LS, i, state.cwStream[i])); - } - } - } - return sb.toString(); - } - -} - diff --git a/src/main/java/org/apache/datasketches/cpc/CompressionCharacterization.java b/src/main/java/org/apache/datasketches/cpc/CompressionCharacterization.java deleted file mode 100644 index 32c52ef28..000000000 --- a/src/main/java/org/apache/datasketches/cpc/CompressionCharacterization.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.common.Util.INVERSE_GOLDEN_U64; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.common.Util.log2; -import static org.apache.datasketches.common.Util.powerSeriesNextDouble; -import static org.apache.datasketches.cpc.CompressedState.importFromSegment; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert; - -import java.lang.foreign.MemorySegment; -import java.io.PrintStream; -import java.io.PrintWriter; - -import org.apache.datasketches.common.SuppressFBWarnings; -import org.apache.datasketches.common.Util; - -/** - * This code is used both by unit tests, for short running tests, - * and by the characterization repository for longer running, more exhaustive testing. To be - * accessible for both, this code is part of the main hierarchy. It is not used during normal - * production runtime. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -public class CompressionCharacterization { - private String hfmt; - private String dfmt; - private String[] hStrArr; - private long vIn = 0; - - //inputs - private final int lgMinK; - private final int lgMaxK; //inclusive - private final int lgMinT; //Trials at end - private final int lgMaxT; //Trials at start - private final int lgMulK; //multiplier of K to produce maxU - private final int uPPO; - private final int incLgK; //increment of lgK - private final PrintStream ps; - private final PrintWriter pw; - - //intermediates - private CpcSketch[] streamSketches; - private CompressedState[] compressedStates1; - private MemorySegment[] segArr; - private CompressedState[] compressedStates2; - private CpcSketch[] unCompressedSketches; - - /** - * Only used in test. - * @param lgMinK min lgK - * @param lgMaxK max lgK - * @param lgMinT min lgTrials - * @param lgMaxT max lgTrials - * @param lgMulK lg multiple - * @param uPPO unique axis Points Per Octave - * @param incLgK increment lgK - * @param pS PrintStream - * @param pW PrintWriter - */ - @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "This is OK here") - public CompressionCharacterization( - final int lgMinK, - final int lgMaxK, - final int lgMinT, - final int lgMaxT, - final int lgMulK, - final int uPPO, - final int incLgK, - final PrintStream pS, - final PrintWriter pW) { - this.lgMinK = lgMinK; - this.lgMaxK = lgMaxK; - this.lgMinT = lgMinT; - this.lgMaxT = lgMaxT; - this.lgMulK = lgMulK; - this.uPPO = Math.max(uPPO, 1); - this.incLgK = Math.max(incLgK, 1); - ps = pS; - pw = pW; - assembleFormats(); - } - - /** - * Only used in test - */ - public void start() { - printf(hfmt, (Object[]) hStrArr); //print header - doRangeOfLgK(); - } - - private void doRangeOfLgK() { - for (int lgK = lgMinK; lgK <= lgMaxK; lgK += incLgK) { - doRangeOfNAtLgK(lgK); - } - } - - private void doRangeOfNAtLgK(final int lgK) { - long n = 1; - final int lgMaxN = lgK + lgMulK; - final long maxN = 1L << lgMaxN; - final double slope = -(double)(lgMaxT - lgMinT) / lgMaxN; - - while (n <= maxN) { - final double lgT = (slope * log2(n)) + lgMaxT; - final int totTrials = Math.max(ceilingPowerOf2((int) Math.pow(2.0, lgT)), (1 << lgMinT)); - doTrialsAtLgKAtN(lgK, n, totTrials); - n = Math.round(powerSeriesNextDouble(uPPO, n, true, 2.0)); - } - } - - private void doTrialsAtLgKAtN(final int lgK, final long n, final int totalTrials) { - final int k = 1 << lgK; - final int minNK = (int) ((k < n) ? k : n); - final double nOverK = (double) n / k; - final int lgTotTrials = Integer.numberOfTrailingZeros(totalTrials); - final int lgWaves = Math.max(lgTotTrials - 10, 0); - final int trialsPerWave = 1 << (lgTotTrials - lgWaves); - //printf("%d %d %d %d\n", totalTrials, lgTotTrials, 1 << lgWaves, trialsPerWave); - streamSketches = new CpcSketch[trialsPerWave]; - compressedStates1 = new CompressedState[trialsPerWave]; - segArr = new MemorySegment[trialsPerWave]; - compressedStates2 = new CompressedState[trialsPerWave]; - unCompressedSketches = new CpcSketch[trialsPerWave]; - - - //update: fill, compress, uncompress sketches arrays in waves - long totalC = 0; - long totalW = 0; - long sumCtor_nS = 0; - long sumUpd_nS = 0; - long sumCom_nS = 0; - long sumSer_nS = 0; - long sumDes_nS = 0; - long sumUnc_nS = 0; - long sumEqu_nS = 0; - long nanoStart, nanoEnd; - final long start = System.currentTimeMillis(); - //Wave Loop - for (int w = 0; w < (1 << lgWaves); w++) { - - //Construct array with sketches loop - nanoStart = System.nanoTime(); - for (int trial = 0; trial < trialsPerWave; trial++) { - final CpcSketch sketch = new CpcSketch(lgK); - streamSketches[trial] = sketch; - } - nanoEnd = System.nanoTime(); - sumCtor_nS += nanoEnd - nanoStart; - nanoStart = nanoEnd; - - //Sketch Update loop - for (int trial = 0; trial < trialsPerWave; trial++) { - final CpcSketch sketch = streamSketches[trial]; - for (long i = 0; i < n; i++) { //increment loop - sketch.update(vIn += INVERSE_GOLDEN_U64); - } - } - nanoEnd = System.nanoTime(); - sumUpd_nS += nanoEnd - nanoStart; - nanoStart = nanoEnd; - - //Compress loop - for (int trial = 0; trial < trialsPerWave; trial++) { - final CpcSketch sketch = streamSketches[trial]; - final CompressedState state = CompressedState.compress(sketch); - compressedStates1[trial] = state; - totalC += sketch.numCoupons; - totalW += state.csvLengthInts + state.cwLengthInts; - } - nanoEnd = System.nanoTime(); - sumCom_nS += nanoEnd - nanoStart; - nanoStart = nanoEnd; - - //State to MemorySegment loop - for (int trial = 0; trial < trialsPerWave; trial++) { - final CompressedState state = compressedStates1[trial]; - final long cap = state.getRequiredSerializedBytes(); - final MemorySegment wseg = MemorySegment.ofArray(new byte[(int) cap]); - state.exportToSegment(wseg); - segArr[trial] = wseg; - } - - nanoEnd = System.nanoTime(); - sumSer_nS += nanoEnd - nanoStart; - nanoStart = nanoEnd; - - //MemorySegment to State loop - for (int trial = 0; trial < trialsPerWave; trial++) { - final MemorySegment seg = segArr[trial]; - final CompressedState state = importFromSegment(seg); - compressedStates2[trial] = state; - } - - nanoEnd = System.nanoTime(); - sumDes_nS += nanoEnd - nanoStart; - nanoStart = nanoEnd; - - //Uncompress loop - for (int trial = 0; trial < trialsPerWave; trial++) { - final CompressedState state = compressedStates2[trial]; - CpcSketch uncSk = null; - uncSk = CpcSketch.uncompress(state, Util.DEFAULT_UPDATE_SEED); - unCompressedSketches[trial] = uncSk; - } - - nanoEnd = System.nanoTime(); - sumUnc_nS += nanoEnd - nanoStart; - nanoStart = nanoEnd; - - //Equals check - for (int trial = 0; trial < trialsPerWave; trial++) { - rtAssert(TestUtil.specialEquals(streamSketches[trial], unCompressedSketches[trial], false, false)); - } - - nanoEnd = System.nanoTime(); - sumEqu_nS += nanoEnd - nanoStart; - nanoStart = nanoEnd; - - } // end wave loop - - final double total_S = (System.currentTimeMillis() - start) / 1E3; - final double avgC = (1.0 * totalC) / totalTrials; - final double avgCoK = avgC / k; - final double avgWords = (1.0 * totalW) / totalTrials; - final double avgBytes = (4.0 * totalW) / totalTrials; - - final double avgCtor_nS = Math.round((double) sumCtor_nS / totalTrials); - - final double avgUpd_nS = Math.round((double) sumUpd_nS / totalTrials); - final double avgUpd_nSperN = avgUpd_nS / n; - - final double avgCom_nS = Math.round((double) sumCom_nS / totalTrials); - final double avgCom_nSper2C = avgCom_nS / (2.0 * avgC); - final double avgCom_nSperK = avgCom_nS / k; - - final double avgSer_nS = Math.round((double) sumSer_nS / totalTrials); - final double avgSer_nSperW = avgSer_nS / avgWords; - - final double avgDes_nS = Math.round((double) sumDes_nS / totalTrials); - final double avgDes_nSperW = avgDes_nS / avgWords; - - - final double avgUnc_nS = Math.round((double) sumUnc_nS / totalTrials); - final double avgUnc_nSper2C = avgUnc_nS / (2.0 * avgC); - final double avgUnc_nSperK = avgUnc_nS / k; - - final double avgEqu_nS = Math.round((double) sumEqu_nS / totalTrials); - final double avgEqu_nSperMinNK = avgEqu_nS / minNK; - - - final int len = unCompressedSketches.length; - final Flavor finFlavor = unCompressedSketches[len - 1].getFlavor(); - final String offStr = Integer.toString(unCompressedSketches[len - 1].windowOffset); - final String flavorOff = finFlavor.toString() + String.format("%2s", offStr); - printf(dfmt, - lgK, - totalTrials, - n, - minNK, - avgCoK, - flavorOff, - nOverK, - avgBytes, - avgCtor_nS, - avgUpd_nS, - avgCom_nS, - avgSer_nS, - avgDes_nS, - avgUnc_nS, - avgEqu_nS, - avgUpd_nSperN, - avgCom_nSper2C, - avgCom_nSperK, - avgSer_nSperW, - avgDes_nSperW, - avgUnc_nSper2C, - avgUnc_nSperK, - avgEqu_nSperMinNK, - total_S); - } - - private void printf(final String format, final Object ... args) { - if (ps != null) { ps.printf(format, args); } - if (pw != null) { pw.printf(format, args); } - } - - private void assembleFormats() { - final String[][] assy = { - {"lgK", "%3s", "%3d"}, - {"Trials", "%9s", "%9d"}, - {"n", "%12s", "%12d"}, - {"MinKN", "%9s", "%9d"}, - {"AvgC/K", "%9s", "%9.4g"}, - {"FinFlavor", "%11s", "%11s"}, - {"N/K", "%9s", "%9.4g"}, - {"AvgBytes", "%9s", "%9.0f"}, - {"AvgCtor_nS", "%11s", "%11.0f"}, - {"AvgUpd_nS", "%10s", "%10.4e"}, - {"AvgCom_nS", "%10s", "%10.0f"}, - {"AvgSer_nS", "%10s", "%10.2f"}, - {"AvgDes_nS", "%10s", "%10.2f"}, - {"AvgUnc_nS", "%10s", "%10.0f"}, - {"AvgEqu_nS", "%10s", "%10.0f"}, - {"AvgUpd_nSperN", "%14s", "%14.2f"}, - {"AvgCom_nSper2C", "%15s", "%15.4g"}, - {"AvgCom_nSperK", "%14s", "%14.4g"}, - {"AvgSer_nSperW", "%14s", "%14.2f"}, - {"AvgDes_nSperW", "%14s", "%14.2f"}, - {"AvgUnc_nSper2C", "%15s", "%15.4g"}, - {"AvgUnc_nSperK", "%14s", "%14.4g"}, - {"AvgEqu_nSperMinNK", "%18s", "%18.4g"}, - {"Total_S", "%8s", "%8.3f"} - }; - final int cols = assy.length; - hStrArr = new String[cols]; - final StringBuilder headerFmt = new StringBuilder(); - final StringBuilder dataFmt = new StringBuilder(); - headerFmt.append(LS + "Compression Characterization" + LS); - for (int i = 0; i < cols; i++) { - hStrArr[i] = assy[i][0]; - headerFmt.append(assy[i][1]); - headerFmt.append((i < (cols - 1)) ? "\t" : LS); - dataFmt.append(assy[i][2]); - dataFmt.append((i < (cols - 1)) ? "\t" : LS); - } - hfmt = headerFmt.toString(); - dfmt = dataFmt.toString(); - } -} diff --git a/src/main/java/org/apache/datasketches/cpc/CompressionData.java b/src/main/java/org/apache/datasketches/cpc/CompressionData.java deleted file mode 100644 index aa1c73a4d..000000000 --- a/src/main/java/org/apache/datasketches/cpc/CompressionData.java +++ /dev/null @@ -1,6118 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -/** - * The 23 length-limited Huffman codes in this file were created by the ocaml program - * "generateHuffmanCodes.ml", which was compiled and run as follows: - * - *

~/ocaml-4.03.0/bin/ocamlopt -o generateHuffmanCodes columnProbabilities.ml generateHuffmanCodes.ml - * - *

./generateHuffmanCodes > raw-encoding-tables.c - * - *

Some manual cutting and pasting was then done to transfer the contents - * of that file into this one. - * - *

Only the encoding tables are defined by this file. The decoding tables - * (which are exact inverses) are created at library startup time by the function - * makeDecodingTable (), which is defined in fm85Compression.c. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -final class CompressionData { - - private static byte[] makeInversePermutation(final byte[]encodePermu) { - final int length = encodePermu.length; - final byte[] inverse = new byte[length]; - - for (int i = 0; i < length; i++) { - inverse[encodePermu[i]] = (byte) i; - } - for (int i = 0; i < length; i++) { - assert ((encodePermu[inverse[i]] & 0XFF) == i); - } - return inverse; - } - - /** - * Given an encoding table that maps unsigned bytes to codewords - * of length at most 12, this builds a size-4096 decoding table. - * - *

The second argument is typically 256, but can be other values such as 65. - * @param encodingTable unsigned - * @param numByteValues size of encoding table - * @return one segment of the decoding table - */ - private static short[] makeDecodingTable(final short[] encodingTable, final int numByteValues) { - final short[] decodingTable = new short[4096]; - - for (int byteValue = 0; byteValue < numByteValues; byteValue++) { - final int encodingEntry = encodingTable[byteValue] & 0xFFFF; - final int codeValue = encodingEntry & 0xfff; - final int codeLength = encodingEntry >> 12; - final int decodingEntry = (codeLength << 8) | byteValue; - final int garbageLength = 12 - codeLength; - final int numCopies = 1 << garbageLength; - - for (int garbageBits = 0; garbageBits < numCopies; garbageBits++) { - final int extendedCodeValue = codeValue | (garbageBits << codeLength); - decodingTable[extendedCodeValue & 0xfff] = (short) decodingEntry; - } - } - return (decodingTable); - } - - /** - * These short arrays are being treated as unsigned - * @param decodingTable unsigned - * @param encodingTable unsigned - */ - static void validateDecodingTable(final short[] decodingTable, final short[] encodingTable) { - for (int decodeThis = 0; decodeThis < 4096; decodeThis++) { - final int tmpD = decodingTable[decodeThis] & 0xFFFF; - final int decodedByte = tmpD & 0xff; - final int decodedLength = tmpD >> 8; - - final int tmpE = encodingTable[decodedByte] & 0xFFFF; - final int encodedBitpattern = tmpE & 0xfff; - final int encodedLength = tmpE >> 12; - - // encodedBitpattern++; // uncomment this line to force failure when testing this method - // encodedLength++; // uncomment this line to force failure when testing this method - - assert (decodedLength == encodedLength) - : "deLen: " + decodedLength + ", enLen: " + encodedLength; - assert (encodedBitpattern == (decodeThis & ((1 << decodedLength) - 1))); - } - } - - private static void makeTheDecodingTables() { - lengthLimitedUnaryDecodingTable65 = makeDecodingTable(lengthLimitedUnaryEncodingTable65, 65); - validateDecodingTable(lengthLimitedUnaryDecodingTable65, lengthLimitedUnaryEncodingTable65); - - for (int i = 0; i < (16 + 6); i++) { - decodingTablesForHighEntropyByte[i] = makeDecodingTable(encodingTablesForHighEntropyByte[i], 256); - validateDecodingTable(decodingTablesForHighEntropyByte[i], encodingTablesForHighEntropyByte[i]); - } - - for (int i = 0; i < 16; i++) { - columnPermutationsForDecoding[i] = makeInversePermutation(columnPermutationsForEncoding[i]); - } - } - - /** - * These decoding tables are created at library startup time by inverting the encoding tables. - * Sixteen tables for the steady state (chosen based on the "phase" of C/K). - * Six more tables for the gradual transition between warmup mode and the steady state. - */ - static short[][] decodingTablesForHighEntropyByte = new short[22][]; - - /** - * Sixteen Encoding Tables for the Steady State. - */ - static short[][] encodingTablesForHighEntropyByte = new short[][] //[22][256] - { - // (table 0 of 22) (steady 0 of 16) (phase = 0.031250000 = 1.0 / 32.0) - // entropy: 4.4619200780464778333 - // avg_length: 4.5415773046232610355; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x9017, // ( 9, 23) 0 - (short) 0x5009, // ( 5, 9) 1 - (short) 0x7033, // ( 7, 51) 2 - (short) 0x3002, // ( 3, 2) 3 - (short) 0x9117, // ( 9, 279) 4 - (short) 0x5019, // ( 5, 25) 5 - (short) 0x7073, // ( 7, 115) 6 - (short) 0x2000, // ( 2, 0) 7 - (short) 0xa177, // (10, 375) 8 - (short) 0x601d, // ( 6, 29) 9 - (short) 0x803b, // ( 8, 59) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0xa377, // (10, 887) 12 - (short) 0x5005, // ( 5, 5) 13 - (short) 0x80bb, // ( 8, 187) 14 - (short) 0x3006, // ( 3, 6) 15 - (short) 0xb0cf, // (11, 207) 16 - (short) 0x700b, // ( 7, 11) 17 - (short) 0xa0f7, // (10, 247) 18 - (short) 0x5015, // ( 5, 21) 19 - (short) 0xb4cf, // (11, 1231) 20 - (short) 0x704b, // ( 7, 75) 21 - (short) 0x9097, // ( 9, 151) 22 - (short) 0x500d, // ( 5, 13) 23 - (short) 0xc4af, // (12, 1199) 24 - (short) 0x807b, // ( 8, 123) 25 - (short) 0xa2f7, // (10, 759) 26 - (short) 0x603d, // ( 6, 61) 27 - (short) 0xccaf, // (12, 3247) 28 - (short) 0x80fb, // ( 8, 251) 29 - (short) 0xa1f7, // (10, 503) 30 - (short) 0x6003, // ( 6, 3) 31 - (short) 0xc2af, // (12, 687) 32 - (short) 0x8007, // ( 8, 7) 33 - (short) 0xb2cf, // (11, 719) 34 - (short) 0x6023, // ( 6, 35) 35 - (short) 0xcaaf, // (12, 2735) 36 - (short) 0x8087, // ( 8, 135) 37 - (short) 0xa3f7, // (10, 1015) 38 - (short) 0x6013, // ( 6, 19) 39 - (short) 0xc6af, // (12, 1711) 40 - (short) 0x9197, // ( 9, 407) 41 - (short) 0xceaf, // (12, 3759) 42 - (short) 0x702b, // ( 7, 43) 43 - (short) 0xc1af, // (12, 431) 44 - (short) 0x9057, // ( 9, 87) 45 - (short) 0xb6cf, // (11, 1743) 46 - (short) 0x706b, // ( 7, 107) 47 - (short) 0xc9af, // (12, 2479) 48 - (short) 0xa00f, // (10, 15) 49 - (short) 0xc5af, // (12, 1455) 50 - (short) 0x8047, // ( 8, 71) 51 - (short) 0xcdaf, // (12, 3503) 52 - (short) 0xa20f, // (10, 527) 53 - (short) 0xc3af, // (12, 943) 54 - (short) 0x80c7, // ( 8, 199) 55 - (short) 0xcbaf, // (12, 2991) 56 - (short) 0xb1cf, // (11, 463) 57 - (short) 0xc7af, // (12, 1967) 58 - (short) 0x9157, // ( 9, 343) 59 - (short) 0xcfaf, // (12, 4015) 60 - (short) 0xb5cf, // (11, 1487) 61 - (short) 0xc06f, // (12, 111) 62 - (short) 0x90d7, // ( 9, 215) 63 - (short) 0xc86f, // (12, 2159) 64 - (short) 0x91d7, // ( 9, 471) 65 - (short) 0xc46f, // (12, 1135) 66 - (short) 0x701b, // ( 7, 27) 67 - (short) 0xcc6f, // (12, 3183) 68 - (short) 0x9037, // ( 9, 55) 69 - (short) 0xb3cf, // (11, 975) 70 - (short) 0x705b, // ( 7, 91) 71 - (short) 0xc26f, // (12, 623) 72 - (short) 0xa10f, // (10, 271) 73 - (short) 0xca6f, // (12, 2671) 74 - (short) 0x8027, // ( 8, 39) 75 - (short) 0xc66f, // (12, 1647) 76 - (short) 0xa30f, // (10, 783) 77 - (short) 0xce6f, // (12, 3695) 78 - (short) 0x80a7, // ( 8, 167) 79 - (short) 0xc16f, // (12, 367) 80 - (short) 0xb7cf, // (11, 1999) 81 - (short) 0xc96f, // (12, 2415) 82 - (short) 0x9137, // ( 9, 311) 83 - (short) 0xc56f, // (12, 1391) 84 - (short) 0xb02f, // (11, 47) 85 - (short) 0xcd6f, // (12, 3439) 86 - (short) 0x90b7, // ( 9, 183) 87 - (short) 0xc36f, // (12, 879) 88 - (short) 0xcb6f, // (12, 2927) 89 - (short) 0xc76f, // (12, 1903) 90 - (short) 0xa08f, // (10, 143) 91 - (short) 0xcf6f, // (12, 3951) 92 - (short) 0xc0ef, // (12, 239) 93 - (short) 0xc8ef, // (12, 2287) 94 - (short) 0xa28f, // (10, 655) 95 - (short) 0xc4ef, // (12, 1263) 96 - (short) 0xccef, // (12, 3311) 97 - (short) 0xc2ef, // (12, 751) 98 - (short) 0xa18f, // (10, 399) 99 - (short) 0xcaef, // (12, 2799) 100 - (short) 0xc6ef, // (12, 1775) 101 - (short) 0xceef, // (12, 3823) 102 - (short) 0xa38f, // (10, 911) 103 - (short) 0xc1ef, // (12, 495) 104 - (short) 0xc9ef, // (12, 2543) 105 - (short) 0xc5ef, // (12, 1519) 106 - (short) 0xb42f, // (11, 1071) 107 - (short) 0xcdef, // (12, 3567) 108 - (short) 0xc3ef, // (12, 1007) 109 - (short) 0xcbef, // (12, 3055) 110 - (short) 0xb22f, // (11, 559) 111 - (short) 0xc7ef, // (12, 2031) 112 - (short) 0xcfef, // (12, 4079) 113 - (short) 0xc01f, // (12, 31) 114 - (short) 0xc81f, // (12, 2079) 115 - (short) 0xc41f, // (12, 1055) 116 - (short) 0xcc1f, // (12, 3103) 117 - (short) 0xc21f, // (12, 543) 118 - (short) 0xca1f, // (12, 2591) 119 - (short) 0xc61f, // (12, 1567) 120 - (short) 0xce1f, // (12, 3615) 121 - (short) 0xc11f, // (12, 287) 122 - (short) 0xc91f, // (12, 2335) 123 - (short) 0xc51f, // (12, 1311) 124 - (short) 0xcd1f, // (12, 3359) 125 - (short) 0xc31f, // (12, 799) 126 - (short) 0xcb1f, // (12, 2847) 127 - (short) 0xc71f, // (12, 1823) 128 - (short) 0xa04f, // (10, 79) 129 - (short) 0xcf1f, // (12, 3871) 130 - (short) 0x8067, // ( 8, 103) 131 - (short) 0xc09f, // (12, 159) 132 - (short) 0xa24f, // (10, 591) 133 - (short) 0xc89f, // (12, 2207) 134 - (short) 0x80e7, // ( 8, 231) 135 - (short) 0xc49f, // (12, 1183) 136 - (short) 0xb62f, // (11, 1583) 137 - (short) 0xcc9f, // (12, 3231) 138 - (short) 0x91b7, // ( 9, 439) 139 - (short) 0xc29f, // (12, 671) 140 - (short) 0xb12f, // (11, 303) 141 - (short) 0xca9f, // (12, 2719) 142 - (short) 0x9077, // ( 9, 119) 143 - (short) 0xc69f, // (12, 1695) 144 - (short) 0xce9f, // (12, 3743) 145 - (short) 0xc19f, // (12, 415) 146 - (short) 0xa14f, // (10, 335) 147 - (short) 0xc99f, // (12, 2463) 148 - (short) 0xc59f, // (12, 1439) 149 - (short) 0xcd9f, // (12, 3487) 150 - (short) 0xa34f, // (10, 847) 151 - (short) 0xc39f, // (12, 927) 152 - (short) 0xcb9f, // (12, 2975) 153 - (short) 0xc79f, // (12, 1951) 154 - (short) 0xb52f, // (11, 1327) 155 - (short) 0xcf9f, // (12, 3999) 156 - (short) 0xc05f, // (12, 95) 157 - (short) 0xc85f, // (12, 2143) 158 - (short) 0xb32f, // (11, 815) 159 - (short) 0xc45f, // (12, 1119) 160 - (short) 0xcc5f, // (12, 3167) 161 - (short) 0xc25f, // (12, 607) 162 - (short) 0xb72f, // (11, 1839) 163 - (short) 0xca5f, // (12, 2655) 164 - (short) 0xc65f, // (12, 1631) 165 - (short) 0xce5f, // (12, 3679) 166 - (short) 0xb0af, // (11, 175) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 1 of 22) (steady 1 of 16) (phase = 0.093750000 = 3.0 / 32.0) - // entropy: 4.4574755684414029133 - // avg_length: 4.5336306265208552446; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0xa177, // (10, 375) 0 - (short) 0x5009, // ( 5, 9) 1 - (short) 0x803b, // ( 8, 59) 2 - (short) 0x3002, // ( 3, 2) 3 - (short) 0x9017, // ( 9, 23) 4 - (short) 0x5019, // ( 5, 25) 5 - (short) 0x700b, // ( 7, 11) 6 - (short) 0x2000, // ( 2, 0) 7 - (short) 0xb34f, // (11, 847) 8 - (short) 0x601d, // ( 6, 29) 9 - (short) 0x9117, // ( 9, 279) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0xa377, // (10, 887) 12 - (short) 0x603d, // ( 6, 61) 13 - (short) 0x80bb, // ( 8, 187) 14 - (short) 0x3006, // ( 3, 6) 15 - (short) 0xc4af, // (12, 1199) 16 - (short) 0x704b, // ( 7, 75) 17 - (short) 0xa0f7, // (10, 247) 18 - (short) 0x5005, // ( 5, 5) 19 - (short) 0xb74f, // (11, 1871) 20 - (short) 0x702b, // ( 7, 43) 21 - (short) 0x9097, // ( 9, 151) 22 - (short) 0x5015, // ( 5, 21) 23 - (short) 0xccaf, // (12, 3247) 24 - (short) 0x807b, // ( 8, 123) 25 - (short) 0xb0cf, // (11, 207) 26 - (short) 0x6003, // ( 6, 3) 27 - (short) 0xc2af, // (12, 687) 28 - (short) 0x80fb, // ( 8, 251) 29 - (short) 0xa2f7, // (10, 759) 30 - (short) 0x500d, // ( 5, 13) 31 - (short) 0xcaaf, // (12, 2735) 32 - (short) 0x8007, // ( 8, 7) 33 - (short) 0xb4cf, // (11, 1231) 34 - (short) 0x6023, // ( 6, 35) 35 - (short) 0xc6af, // (12, 1711) 36 - (short) 0x8087, // ( 8, 135) 37 - (short) 0xa1f7, // (10, 503) 38 - (short) 0x6013, // ( 6, 19) 39 - (short) 0xceaf, // (12, 3759) 40 - (short) 0x9197, // ( 9, 407) 41 - (short) 0xc1af, // (12, 431) 42 - (short) 0x706b, // ( 7, 107) 43 - (short) 0xc9af, // (12, 2479) 44 - (short) 0x9057, // ( 9, 87) 45 - (short) 0xb2cf, // (11, 719) 46 - (short) 0x6033, // ( 6, 51) 47 - (short) 0xc5af, // (12, 1455) 48 - (short) 0xa3f7, // (10, 1015) 49 - (short) 0xcdaf, // (12, 3503) 50 - (short) 0x8047, // ( 8, 71) 51 - (short) 0xc3af, // (12, 943) 52 - (short) 0xa00f, // (10, 15) 53 - (short) 0xcbaf, // (12, 2991) 54 - (short) 0x80c7, // ( 8, 199) 55 - (short) 0xc7af, // (12, 1967) 56 - (short) 0xb6cf, // (11, 1743) 57 - (short) 0xcfaf, // (12, 4015) 58 - (short) 0x9157, // ( 9, 343) 59 - (short) 0xc06f, // (12, 111) 60 - (short) 0xb1cf, // (11, 463) 61 - (short) 0xc86f, // (12, 2159) 62 - (short) 0x90d7, // ( 9, 215) 63 - (short) 0xc46f, // (12, 1135) 64 - (short) 0x91d7, // ( 9, 471) 65 - (short) 0xcc6f, // (12, 3183) 66 - (short) 0x701b, // ( 7, 27) 67 - (short) 0xc26f, // (12, 623) 68 - (short) 0x9037, // ( 9, 55) 69 - (short) 0xb5cf, // (11, 1487) 70 - (short) 0x705b, // ( 7, 91) 71 - (short) 0xca6f, // (12, 2671) 72 - (short) 0xa20f, // (10, 527) 73 - (short) 0xc66f, // (12, 1647) 74 - (short) 0x8027, // ( 8, 39) 75 - (short) 0xce6f, // (12, 3695) 76 - (short) 0xa10f, // (10, 271) 77 - (short) 0xc16f, // (12, 367) 78 - (short) 0x80a7, // ( 8, 167) 79 - (short) 0xc96f, // (12, 2415) 80 - (short) 0xb3cf, // (11, 975) 81 - (short) 0xc56f, // (12, 1391) 82 - (short) 0x9137, // ( 9, 311) 83 - (short) 0xcd6f, // (12, 3439) 84 - (short) 0xb7cf, // (11, 1999) 85 - (short) 0xc36f, // (12, 879) 86 - (short) 0x90b7, // ( 9, 183) 87 - (short) 0xcb6f, // (12, 2927) 88 - (short) 0xc76f, // (12, 1903) 89 - (short) 0xcf6f, // (12, 3951) 90 - (short) 0xa30f, // (10, 783) 91 - (short) 0xc0ef, // (12, 239) 92 - (short) 0xc8ef, // (12, 2287) 93 - (short) 0xc4ef, // (12, 1263) 94 - (short) 0xa08f, // (10, 143) 95 - (short) 0xccef, // (12, 3311) 96 - (short) 0xc2ef, // (12, 751) 97 - (short) 0xcaef, // (12, 2799) 98 - (short) 0xa28f, // (10, 655) 99 - (short) 0xc6ef, // (12, 1775) 100 - (short) 0xceef, // (12, 3823) 101 - (short) 0xc1ef, // (12, 495) 102 - (short) 0xa18f, // (10, 399) 103 - (short) 0xc9ef, // (12, 2543) 104 - (short) 0xc5ef, // (12, 1519) 105 - (short) 0xcdef, // (12, 3567) 106 - (short) 0xb02f, // (11, 47) 107 - (short) 0xc3ef, // (12, 1007) 108 - (short) 0xcbef, // (12, 3055) 109 - (short) 0xc7ef, // (12, 2031) 110 - (short) 0xb42f, // (11, 1071) 111 - (short) 0xcfef, // (12, 4079) 112 - (short) 0xc01f, // (12, 31) 113 - (short) 0xc81f, // (12, 2079) 114 - (short) 0xc41f, // (12, 1055) 115 - (short) 0xcc1f, // (12, 3103) 116 - (short) 0xc21f, // (12, 543) 117 - (short) 0xca1f, // (12, 2591) 118 - (short) 0xc61f, // (12, 1567) 119 - (short) 0xce1f, // (12, 3615) 120 - (short) 0xc11f, // (12, 287) 121 - (short) 0xc91f, // (12, 2335) 122 - (short) 0xc51f, // (12, 1311) 123 - (short) 0xcd1f, // (12, 3359) 124 - (short) 0xc31f, // (12, 799) 125 - (short) 0xcb1f, // (12, 2847) 126 - (short) 0xc71f, // (12, 1823) 127 - (short) 0xcf1f, // (12, 3871) 128 - (short) 0xa38f, // (10, 911) 129 - (short) 0xc09f, // (12, 159) 130 - (short) 0x8067, // ( 8, 103) 131 - (short) 0xc89f, // (12, 2207) 132 - (short) 0xa04f, // (10, 79) 133 - (short) 0xc49f, // (12, 1183) 134 - (short) 0x80e7, // ( 8, 231) 135 - (short) 0xcc9f, // (12, 3231) 136 - (short) 0xb22f, // (11, 559) 137 - (short) 0xc29f, // (12, 671) 138 - (short) 0x91b7, // ( 9, 439) 139 - (short) 0xca9f, // (12, 2719) 140 - (short) 0xb62f, // (11, 1583) 141 - (short) 0xc69f, // (12, 1695) 142 - (short) 0x9077, // ( 9, 119) 143 - (short) 0xce9f, // (12, 3743) 144 - (short) 0xc19f, // (12, 415) 145 - (short) 0xc99f, // (12, 2463) 146 - (short) 0xa24f, // (10, 591) 147 - (short) 0xc59f, // (12, 1439) 148 - (short) 0xcd9f, // (12, 3487) 149 - (short) 0xc39f, // (12, 927) 150 - (short) 0xa14f, // (10, 335) 151 - (short) 0xcb9f, // (12, 2975) 152 - (short) 0xc79f, // (12, 1951) 153 - (short) 0xcf9f, // (12, 3999) 154 - (short) 0xb12f, // (11, 303) 155 - (short) 0xc05f, // (12, 95) 156 - (short) 0xc85f, // (12, 2143) 157 - (short) 0xc45f, // (12, 1119) 158 - (short) 0xb52f, // (11, 1327) 159 - (short) 0xcc5f, // (12, 3167) 160 - (short) 0xc25f, // (12, 607) 161 - (short) 0xca5f, // (12, 2655) 162 - (short) 0xb32f, // (11, 815) 163 - (short) 0xc65f, // (12, 1631) 164 - (short) 0xce5f, // (12, 3679) 165 - (short) 0xc15f, // (12, 351) 166 - (short) 0xb72f, // (11, 1839) 167 - (short) 0xc95f, // (12, 2399) 168 - (short) 0xc55f, // (12, 1375) 169 - (short) 0xcd5f, // (12, 3423) 170 - (short) 0xc35f, // (12, 863) 171 - (short) 0xcb5f, // (12, 2911) 172 - (short) 0xc75f, // (12, 1887) 173 - (short) 0xcf5f, // (12, 3935) 174 - (short) 0xb0af, // (11, 175) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 2 of 22) (steady 2 of 16) (phase = 0.156250000 = 5.0 / 32.0) - // entropy: 4.4520619712441886762 - // avg_length: 4.5253989110544479146; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0xa177, // (10, 375) 0 - (short) 0x5009, // ( 5, 9) 1 - (short) 0x803b, // ( 8, 59) 2 - (short) 0x3002, // ( 3, 2) 3 - (short) 0xa377, // (10, 887) 4 - (short) 0x5019, // ( 5, 25) 5 - (short) 0x80bb, // ( 8, 187) 6 - (short) 0x2000, // ( 2, 0) 7 - (short) 0xb34f, // (11, 847) 8 - (short) 0x601d, // ( 6, 29) 9 - (short) 0x9057, // ( 9, 87) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0xb74f, // (11, 1871) 12 - (short) 0x603d, // ( 6, 61) 13 - (short) 0x807b, // ( 8, 123) 14 - (short) 0x3006, // ( 3, 6) 15 - (short) 0xc72f, // (12, 1839) 16 - (short) 0x700b, // ( 7, 11) 17 - (short) 0xa0f7, // (10, 247) 18 - (short) 0x5005, // ( 5, 5) 19 - (short) 0xcf2f, // (12, 3887) 20 - (short) 0x704b, // ( 7, 75) 21 - (short) 0xa2f7, // (10, 759) 22 - (short) 0x5015, // ( 5, 21) 23 - (short) 0xc0af, // (12, 175) 24 - (short) 0x80fb, // ( 8, 251) 25 - (short) 0xb0cf, // (11, 207) 26 - (short) 0x6003, // ( 6, 3) 27 - (short) 0xc8af, // (12, 2223) 28 - (short) 0x8007, // ( 8, 7) 29 - (short) 0xa1f7, // (10, 503) 30 - (short) 0x500d, // ( 5, 13) 31 - (short) 0xc4af, // (12, 1199) 32 - (short) 0x8087, // ( 8, 135) 33 - (short) 0xb4cf, // (11, 1231) 34 - (short) 0x6023, // ( 6, 35) 35 - (short) 0xccaf, // (12, 3247) 36 - (short) 0x8047, // ( 8, 71) 37 - (short) 0xb2cf, // (11, 719) 38 - (short) 0x6013, // ( 6, 19) 39 - (short) 0xc2af, // (12, 687) 40 - (short) 0x9157, // ( 9, 343) 41 - (short) 0xcaaf, // (12, 2735) 42 - (short) 0x702b, // ( 7, 43) 43 - (short) 0xc6af, // (12, 1711) 44 - (short) 0x90d7, // ( 9, 215) 45 - (short) 0xceaf, // (12, 3759) 46 - (short) 0x6033, // ( 6, 51) 47 - (short) 0xc1af, // (12, 431) 48 - (short) 0xa3f7, // (10, 1015) 49 - (short) 0xc9af, // (12, 2479) 50 - (short) 0x80c7, // ( 8, 199) 51 - (short) 0xc5af, // (12, 1455) 52 - (short) 0xa00f, // (10, 15) 53 - (short) 0xcdaf, // (12, 3503) 54 - (short) 0x8027, // ( 8, 39) 55 - (short) 0xc3af, // (12, 943) 56 - (short) 0xb6cf, // (11, 1743) 57 - (short) 0xcbaf, // (12, 2991) 58 - (short) 0x91d7, // ( 9, 471) 59 - (short) 0xc7af, // (12, 1967) 60 - (short) 0xb1cf, // (11, 463) 61 - (short) 0xcfaf, // (12, 4015) 62 - (short) 0x80a7, // ( 8, 167) 63 - (short) 0xc06f, // (12, 111) 64 - (short) 0x9037, // ( 9, 55) 65 - (short) 0xc86f, // (12, 2159) 66 - (short) 0x706b, // ( 7, 107) 67 - (short) 0xc46f, // (12, 1135) 68 - (short) 0x9137, // ( 9, 311) 69 - (short) 0xcc6f, // (12, 3183) 70 - (short) 0x701b, // ( 7, 27) 71 - (short) 0xc26f, // (12, 623) 72 - (short) 0xa20f, // (10, 527) 73 - (short) 0xca6f, // (12, 2671) 74 - (short) 0x8067, // ( 8, 103) 75 - (short) 0xc66f, // (12, 1647) 76 - (short) 0xa10f, // (10, 271) 77 - (short) 0xce6f, // (12, 3695) 78 - (short) 0x705b, // ( 7, 91) 79 - (short) 0xc16f, // (12, 367) 80 - (short) 0xb5cf, // (11, 1487) 81 - (short) 0xc96f, // (12, 2415) 82 - (short) 0x90b7, // ( 9, 183) 83 - (short) 0xc56f, // (12, 1391) 84 - (short) 0xb3cf, // (11, 975) 85 - (short) 0xcd6f, // (12, 3439) 86 - (short) 0x91b7, // ( 9, 439) 87 - (short) 0xc36f, // (12, 879) 88 - (short) 0xcb6f, // (12, 2927) 89 - (short) 0xc76f, // (12, 1903) 90 - (short) 0xa30f, // (10, 783) 91 - (short) 0xcf6f, // (12, 3951) 92 - (short) 0xc0ef, // (12, 239) 93 - (short) 0xc8ef, // (12, 2287) 94 - (short) 0xa08f, // (10, 143) 95 - (short) 0xc4ef, // (12, 1263) 96 - (short) 0xccef, // (12, 3311) 97 - (short) 0xc2ef, // (12, 751) 98 - (short) 0xa28f, // (10, 655) 99 - (short) 0xcaef, // (12, 2799) 100 - (short) 0xc6ef, // (12, 1775) 101 - (short) 0xceef, // (12, 3823) 102 - (short) 0xa18f, // (10, 399) 103 - (short) 0xc1ef, // (12, 495) 104 - (short) 0xc9ef, // (12, 2543) 105 - (short) 0xc5ef, // (12, 1519) 106 - (short) 0xb7cf, // (11, 1999) 107 - (short) 0xcdef, // (12, 3567) 108 - (short) 0xc3ef, // (12, 1007) 109 - (short) 0xcbef, // (12, 3055) 110 - (short) 0xb02f, // (11, 47) 111 - (short) 0xc7ef, // (12, 2031) 112 - (short) 0xcfef, // (12, 4079) 113 - (short) 0xc01f, // (12, 31) 114 - (short) 0xc81f, // (12, 2079) 115 - (short) 0xc41f, // (12, 1055) 116 - (short) 0xcc1f, // (12, 3103) 117 - (short) 0xc21f, // (12, 543) 118 - (short) 0xca1f, // (12, 2591) 119 - (short) 0xc61f, // (12, 1567) 120 - (short) 0xce1f, // (12, 3615) 121 - (short) 0xc11f, // (12, 287) 122 - (short) 0xc91f, // (12, 2335) 123 - (short) 0xc51f, // (12, 1311) 124 - (short) 0xcd1f, // (12, 3359) 125 - (short) 0xc31f, // (12, 799) 126 - (short) 0xcb1f, // (12, 2847) 127 - (short) 0xc71f, // (12, 1823) 128 - (short) 0xa38f, // (10, 911) 129 - (short) 0xcf1f, // (12, 3871) 130 - (short) 0x80e7, // ( 8, 231) 131 - (short) 0xc09f, // (12, 159) 132 - (short) 0xa04f, // (10, 79) 133 - (short) 0xc89f, // (12, 2207) 134 - (short) 0x8017, // ( 8, 23) 135 - (short) 0xc49f, // (12, 1183) 136 - (short) 0xb42f, // (11, 1071) 137 - (short) 0xcc9f, // (12, 3231) 138 - (short) 0x9077, // ( 9, 119) 139 - (short) 0xc29f, // (12, 671) 140 - (short) 0xb22f, // (11, 559) 141 - (short) 0xca9f, // (12, 2719) 142 - (short) 0x8097, // ( 8, 151) 143 - (short) 0xc69f, // (12, 1695) 144 - (short) 0xce9f, // (12, 3743) 145 - (short) 0xc19f, // (12, 415) 146 - (short) 0xa24f, // (10, 591) 147 - (short) 0xc99f, // (12, 2463) 148 - (short) 0xc59f, // (12, 1439) 149 - (short) 0xcd9f, // (12, 3487) 150 - (short) 0xa14f, // (10, 335) 151 - (short) 0xc39f, // (12, 927) 152 - (short) 0xcb9f, // (12, 2975) 153 - (short) 0xc79f, // (12, 1951) 154 - (short) 0xb62f, // (11, 1583) 155 - (short) 0xcf9f, // (12, 3999) 156 - (short) 0xc05f, // (12, 95) 157 - (short) 0xc85f, // (12, 2143) 158 - (short) 0xb12f, // (11, 303) 159 - (short) 0xc45f, // (12, 1119) 160 - (short) 0xcc5f, // (12, 3167) 161 - (short) 0xc25f, // (12, 607) 162 - (short) 0xb52f, // (11, 1327) 163 - (short) 0xca5f, // (12, 2655) 164 - (short) 0xc65f, // (12, 1631) 165 - (short) 0xce5f, // (12, 3679) 166 - (short) 0xb32f, // (11, 815) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 3 of 22) (steady 3 of 16) (phase = 0.218750000 = 7.0 / 32.0) - // entropy: 4.4457680500675866853 - // avg_length: 4.5181192844586535173; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0xb24f, // (11, 591) 0 - (short) 0x601d, // ( 6, 29) 1 - (short) 0x9097, // ( 9, 151) 2 - (short) 0x3002, // ( 3, 2) 3 - (short) 0xa1f7, // (10, 503) 4 - (short) 0x5005, // ( 5, 5) 5 - (short) 0x807b, // ( 8, 123) 6 - (short) 0x2000, // ( 2, 0) 7 - (short) 0xc52f, // (12, 1327) 8 - (short) 0x603d, // ( 6, 61) 9 - (short) 0x9197, // ( 9, 407) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0xb64f, // (11, 1615) 12 - (short) 0x6003, // ( 6, 3) 13 - (short) 0x9057, // ( 9, 87) 14 - (short) 0x3006, // ( 3, 6) 15 - (short) 0xcd2f, // (12, 3375) 16 - (short) 0x80fb, // ( 8, 251) 17 - (short) 0xb14f, // (11, 335) 18 - (short) 0x5015, // ( 5, 21) 19 - (short) 0xc32f, // (12, 815) 20 - (short) 0x702b, // ( 7, 43) 21 - (short) 0xa3f7, // (10, 1015) 22 - (short) 0x4009, // ( 4, 9) 23 - (short) 0xcb2f, // (12, 2863) 24 - (short) 0x8007, // ( 8, 7) 25 - (short) 0xb54f, // (11, 1359) 26 - (short) 0x6023, // ( 6, 35) 27 - (short) 0xc72f, // (12, 1839) 28 - (short) 0x8087, // ( 8, 135) 29 - (short) 0xb34f, // (11, 847) 30 - (short) 0x500d, // ( 5, 13) 31 - (short) 0xcf2f, // (12, 3887) 32 - (short) 0x9157, // ( 9, 343) 33 - (short) 0xc0af, // (12, 175) 34 - (short) 0x6013, // ( 6, 19) 35 - (short) 0xc8af, // (12, 2223) 36 - (short) 0x8047, // ( 8, 71) 37 - (short) 0xb74f, // (11, 1871) 38 - (short) 0x6033, // ( 6, 51) 39 - (short) 0xc4af, // (12, 1199) 40 - (short) 0x90d7, // ( 9, 215) 41 - (short) 0xccaf, // (12, 3247) 42 - (short) 0x706b, // ( 7, 107) 43 - (short) 0xc2af, // (12, 687) 44 - (short) 0x91d7, // ( 9, 471) 45 - (short) 0xcaaf, // (12, 2735) 46 - (short) 0x600b, // ( 6, 11) 47 - (short) 0xc6af, // (12, 1711) 48 - (short) 0xb0cf, // (11, 207) 49 - (short) 0xceaf, // (12, 3759) 50 - (short) 0x80c7, // ( 8, 199) 51 - (short) 0xc1af, // (12, 431) 52 - (short) 0xa00f, // (10, 15) 53 - (short) 0xc9af, // (12, 2479) 54 - (short) 0x8027, // ( 8, 39) 55 - (short) 0xc5af, // (12, 1455) 56 - (short) 0xb4cf, // (11, 1231) 57 - (short) 0xcdaf, // (12, 3503) 58 - (short) 0x9037, // ( 9, 55) 59 - (short) 0xc3af, // (12, 943) 60 - (short) 0xb2cf, // (11, 719) 61 - (short) 0xcbaf, // (12, 2991) 62 - (short) 0x80a7, // ( 8, 167) 63 - (short) 0xc7af, // (12, 1967) 64 - (short) 0xa20f, // (10, 527) 65 - (short) 0xcfaf, // (12, 4015) 66 - (short) 0x701b, // ( 7, 27) 67 - (short) 0xc06f, // (12, 111) 68 - (short) 0x9137, // ( 9, 311) 69 - (short) 0xc86f, // (12, 2159) 70 - (short) 0x705b, // ( 7, 91) 71 - (short) 0xc46f, // (12, 1135) 72 - (short) 0xb6cf, // (11, 1743) 73 - (short) 0xcc6f, // (12, 3183) 74 - (short) 0x8067, // ( 8, 103) 75 - (short) 0xc26f, // (12, 623) 76 - (short) 0xa10f, // (10, 271) 77 - (short) 0xca6f, // (12, 2671) 78 - (short) 0x703b, // ( 7, 59) 79 - (short) 0xc66f, // (12, 1647) 80 - (short) 0xce6f, // (12, 3695) 81 - (short) 0xc16f, // (12, 367) 82 - (short) 0x90b7, // ( 9, 183) 83 - (short) 0xc96f, // (12, 2415) 84 - (short) 0xb1cf, // (11, 463) 85 - (short) 0xc56f, // (12, 1391) 86 - (short) 0x91b7, // ( 9, 439) 87 - (short) 0xcd6f, // (12, 3439) 88 - (short) 0xc36f, // (12, 879) 89 - (short) 0xcb6f, // (12, 2927) 90 - (short) 0xa30f, // (10, 783) 91 - (short) 0xc76f, // (12, 1903) 92 - (short) 0xcf6f, // (12, 3951) 93 - (short) 0xc0ef, // (12, 239) 94 - (short) 0x9077, // ( 9, 119) 95 - (short) 0xc8ef, // (12, 2287) 96 - (short) 0xc4ef, // (12, 1263) 97 - (short) 0xccef, // (12, 3311) 98 - (short) 0xa08f, // (10, 143) 99 - (short) 0xc2ef, // (12, 751) 100 - (short) 0xcaef, // (12, 2799) 101 - (short) 0xc6ef, // (12, 1775) 102 - (short) 0xa28f, // (10, 655) 103 - (short) 0xceef, // (12, 3823) 104 - (short) 0xc1ef, // (12, 495) 105 - (short) 0xc9ef, // (12, 2543) 106 - (short) 0xb5cf, // (11, 1487) 107 - (short) 0xc5ef, // (12, 1519) 108 - (short) 0xcdef, // (12, 3567) 109 - (short) 0xc3ef, // (12, 1007) 110 - (short) 0xb3cf, // (11, 975) 111 - (short) 0xcbef, // (12, 3055) 112 - (short) 0xc7ef, // (12, 2031) 113 - (short) 0xcfef, // (12, 4079) 114 - (short) 0xc01f, // (12, 31) 115 - (short) 0xc81f, // (12, 2079) 116 - (short) 0xc41f, // (12, 1055) 117 - (short) 0xcc1f, // (12, 3103) 118 - (short) 0xc21f, // (12, 543) 119 - (short) 0xca1f, // (12, 2591) 120 - (short) 0xc61f, // (12, 1567) 121 - (short) 0xce1f, // (12, 3615) 122 - (short) 0xc11f, // (12, 287) 123 - (short) 0xc91f, // (12, 2335) 124 - (short) 0xc51f, // (12, 1311) 125 - (short) 0xcd1f, // (12, 3359) 126 - (short) 0xc31f, // (12, 799) 127 - (short) 0xcb1f, // (12, 2847) 128 - (short) 0xb7cf, // (11, 1999) 129 - (short) 0xc71f, // (12, 1823) 130 - (short) 0x80e7, // ( 8, 231) 131 - (short) 0xcf1f, // (12, 3871) 132 - (short) 0xa18f, // (10, 399) 133 - (short) 0xc09f, // (12, 159) 134 - (short) 0x8017, // ( 8, 23) 135 - (short) 0xc89f, // (12, 2207) 136 - (short) 0xc49f, // (12, 1183) 137 - (short) 0xcc9f, // (12, 3231) 138 - (short) 0x9177, // ( 9, 375) 139 - (short) 0xc29f, // (12, 671) 140 - (short) 0xb02f, // (11, 47) 141 - (short) 0xca9f, // (12, 2719) 142 - (short) 0x90f7, // ( 9, 247) 143 - (short) 0xc69f, // (12, 1695) 144 - (short) 0xce9f, // (12, 3743) 145 - (short) 0xc19f, // (12, 415) 146 - (short) 0xa38f, // (10, 911) 147 - (short) 0xc99f, // (12, 2463) 148 - (short) 0xc59f, // (12, 1439) 149 - (short) 0xcd9f, // (12, 3487) 150 - (short) 0xa04f, // (10, 79) 151 - (short) 0xc39f, // (12, 927) 152 - (short) 0xcb9f, // (12, 2975) 153 - (short) 0xc79f, // (12, 1951) 154 - (short) 0xb42f, // (11, 1071) 155 - (short) 0xcf9f, // (12, 3999) 156 - (short) 0xc05f, // (12, 95) 157 - (short) 0xc85f, // (12, 2143) 158 - (short) 0xb22f, // (11, 559) 159 - (short) 0xc45f, // (12, 1119) 160 - (short) 0xcc5f, // (12, 3167) 161 - (short) 0xc25f, // (12, 607) 162 - (short) 0xb62f, // (11, 1583) 163 - (short) 0xca5f, // (12, 2655) 164 - (short) 0xc65f, // (12, 1631) 165 - (short) 0xce5f, // (12, 3679) 166 - (short) 0xb12f, // (11, 303) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 4 of 22) (steady 4 of 16) (phase = 0.281250000 = 9.0 / 32.0) - // entropy: 4.4386754570568340839 - // avg_length: 4.5071584786605640716; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0xb24f, // (11, 591) 0 - (short) 0x601d, // ( 6, 29) 1 - (short) 0x9057, // ( 9, 87) 2 - (short) 0x3002, // ( 3, 2) 3 - (short) 0xb64f, // (11, 1615) 4 - (short) 0x5005, // ( 5, 5) 5 - (short) 0x807b, // ( 8, 123) 6 - (short) 0x2000, // ( 2, 0) 7 - (short) 0xc32f, // (12, 815) 8 - (short) 0x700b, // ( 7, 11) 9 - (short) 0xa0f7, // (10, 247) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0xb14f, // (11, 335) 12 - (short) 0x603d, // ( 6, 61) 13 - (short) 0x9157, // ( 9, 343) 14 - (short) 0x3006, // ( 3, 6) 15 - (short) 0xcb2f, // (12, 2863) 16 - (short) 0x80fb, // ( 8, 251) 17 - (short) 0xb54f, // (11, 1359) 18 - (short) 0x5015, // ( 5, 21) 19 - (short) 0xc72f, // (12, 1839) 20 - (short) 0x704b, // ( 7, 75) 21 - (short) 0xa2f7, // (10, 759) 22 - (short) 0x4009, // ( 4, 9) 23 - (short) 0xcf2f, // (12, 3887) 24 - (short) 0x8007, // ( 8, 7) 25 - (short) 0xb34f, // (11, 847) 26 - (short) 0x6003, // ( 6, 3) 27 - (short) 0xc0af, // (12, 175) 28 - (short) 0x8087, // ( 8, 135) 29 - (short) 0xb74f, // (11, 1871) 30 - (short) 0x500d, // ( 5, 13) 31 - (short) 0xc8af, // (12, 2223) 32 - (short) 0x90d7, // ( 9, 215) 33 - (short) 0xc4af, // (12, 1199) 34 - (short) 0x6023, // ( 6, 35) 35 - (short) 0xccaf, // (12, 3247) 36 - (short) 0x8047, // ( 8, 71) 37 - (short) 0xb0cf, // (11, 207) 38 - (short) 0x6013, // ( 6, 19) 39 - (short) 0xc2af, // (12, 687) 40 - (short) 0xa1f7, // (10, 503) 41 - (short) 0xcaaf, // (12, 2735) 42 - (short) 0x702b, // ( 7, 43) 43 - (short) 0xc6af, // (12, 1711) 44 - (short) 0x91d7, // ( 9, 471) 45 - (short) 0xceaf, // (12, 3759) 46 - (short) 0x6033, // ( 6, 51) 47 - (short) 0xc1af, // (12, 431) 48 - (short) 0xb4cf, // (11, 1231) 49 - (short) 0xc9af, // (12, 2479) 50 - (short) 0x80c7, // ( 8, 199) 51 - (short) 0xc5af, // (12, 1455) 52 - (short) 0xa3f7, // (10, 1015) 53 - (short) 0xcdaf, // (12, 3503) 54 - (short) 0x706b, // ( 7, 107) 55 - (short) 0xc3af, // (12, 943) 56 - (short) 0xb2cf, // (11, 719) 57 - (short) 0xcbaf, // (12, 2991) 58 - (short) 0x9037, // ( 9, 55) 59 - (short) 0xc7af, // (12, 1967) 60 - (short) 0xb6cf, // (11, 1743) 61 - (short) 0xcfaf, // (12, 4015) 62 - (short) 0x8027, // ( 8, 39) 63 - (short) 0xc06f, // (12, 111) 64 - (short) 0xa00f, // (10, 15) 65 - (short) 0xc86f, // (12, 2159) 66 - (short) 0x701b, // ( 7, 27) 67 - (short) 0xc46f, // (12, 1135) 68 - (short) 0x9137, // ( 9, 311) 69 - (short) 0xcc6f, // (12, 3183) 70 - (short) 0x705b, // ( 7, 91) 71 - (short) 0xc26f, // (12, 623) 72 - (short) 0xb1cf, // (11, 463) 73 - (short) 0xca6f, // (12, 2671) 74 - (short) 0x80a7, // ( 8, 167) 75 - (short) 0xc66f, // (12, 1647) 76 - (short) 0xa20f, // (10, 527) 77 - (short) 0xce6f, // (12, 3695) 78 - (short) 0x703b, // ( 7, 59) 79 - (short) 0xc16f, // (12, 367) 80 - (short) 0xc96f, // (12, 2415) 81 - (short) 0xc56f, // (12, 1391) 82 - (short) 0x90b7, // ( 9, 183) 83 - (short) 0xcd6f, // (12, 3439) 84 - (short) 0xb5cf, // (11, 1487) 85 - (short) 0xc36f, // (12, 879) 86 - (short) 0x8067, // ( 8, 103) 87 - (short) 0xcb6f, // (12, 2927) 88 - (short) 0xc76f, // (12, 1903) 89 - (short) 0xcf6f, // (12, 3951) 90 - (short) 0xa10f, // (10, 271) 91 - (short) 0xc0ef, // (12, 239) 92 - (short) 0xc8ef, // (12, 2287) 93 - (short) 0xc4ef, // (12, 1263) 94 - (short) 0x91b7, // ( 9, 439) 95 - (short) 0xccef, // (12, 3311) 96 - (short) 0xc2ef, // (12, 751) 97 - (short) 0xcaef, // (12, 2799) 98 - (short) 0xa30f, // (10, 783) 99 - (short) 0xc6ef, // (12, 1775) 100 - (short) 0xceef, // (12, 3823) 101 - (short) 0xc1ef, // (12, 495) 102 - (short) 0xa08f, // (10, 143) 103 - (short) 0xc9ef, // (12, 2543) 104 - (short) 0xc5ef, // (12, 1519) 105 - (short) 0xcdef, // (12, 3567) 106 - (short) 0xb3cf, // (11, 975) 107 - (short) 0xc3ef, // (12, 1007) 108 - (short) 0xcbef, // (12, 3055) 109 - (short) 0xc7ef, // (12, 2031) 110 - (short) 0xa28f, // (10, 655) 111 - (short) 0xcfef, // (12, 4079) 112 - (short) 0xc01f, // (12, 31) 113 - (short) 0xc81f, // (12, 2079) 114 - (short) 0xc41f, // (12, 1055) 115 - (short) 0xcc1f, // (12, 3103) 116 - (short) 0xc21f, // (12, 543) 117 - (short) 0xca1f, // (12, 2591) 118 - (short) 0xb7cf, // (11, 1999) 119 - (short) 0xc61f, // (12, 1567) 120 - (short) 0xce1f, // (12, 3615) 121 - (short) 0xc11f, // (12, 287) 122 - (short) 0xc91f, // (12, 2335) 123 - (short) 0xc51f, // (12, 1311) 124 - (short) 0xcd1f, // (12, 3359) 125 - (short) 0xc31f, // (12, 799) 126 - (short) 0xcb1f, // (12, 2847) 127 - (short) 0xc71f, // (12, 1823) 128 - (short) 0xb02f, // (11, 47) 129 - (short) 0xcf1f, // (12, 3871) 130 - (short) 0x80e7, // ( 8, 231) 131 - (short) 0xc09f, // (12, 159) 132 - (short) 0xa18f, // (10, 399) 133 - (short) 0xc89f, // (12, 2207) 134 - (short) 0x8017, // ( 8, 23) 135 - (short) 0xc49f, // (12, 1183) 136 - (short) 0xcc9f, // (12, 3231) 137 - (short) 0xc29f, // (12, 671) 138 - (short) 0x9077, // ( 9, 119) 139 - (short) 0xca9f, // (12, 2719) 140 - (short) 0xb42f, // (11, 1071) 141 - (short) 0xc69f, // (12, 1695) 142 - (short) 0x8097, // ( 8, 151) 143 - (short) 0xce9f, // (12, 3743) 144 - (short) 0xc19f, // (12, 415) 145 - (short) 0xc99f, // (12, 2463) 146 - (short) 0xa38f, // (10, 911) 147 - (short) 0xc59f, // (12, 1439) 148 - (short) 0xcd9f, // (12, 3487) 149 - (short) 0xc39f, // (12, 927) 150 - (short) 0x9177, // ( 9, 375) 151 - (short) 0xcb9f, // (12, 2975) 152 - (short) 0xc79f, // (12, 1951) 153 - (short) 0xcf9f, // (12, 3999) 154 - (short) 0xb22f, // (11, 559) 155 - (short) 0xc05f, // (12, 95) 156 - (short) 0xc85f, // (12, 2143) 157 - (short) 0xc45f, // (12, 1119) 158 - (short) 0xa04f, // (10, 79) 159 - (short) 0xcc5f, // (12, 3167) 160 - (short) 0xc25f, // (12, 607) 161 - (short) 0xca5f, // (12, 2655) 162 - (short) 0xb62f, // (11, 1583) 163 - (short) 0xc65f, // (12, 1631) 164 - (short) 0xce5f, // (12, 3679) 165 - (short) 0xc15f, // (12, 351) 166 - (short) 0xb12f, // (11, 303) 167 - (short) 0xc95f, // (12, 2399) 168 - (short) 0xc55f, // (12, 1375) 169 - (short) 0xcd5f, // (12, 3423) 170 - (short) 0xc35f, // (12, 863) 171 - (short) 0xcb5f, // (12, 2911) 172 - (short) 0xc75f, // (12, 1887) 173 - (short) 0xcf5f, // (12, 3935) 174 - (short) 0xb52f, // (11, 1327) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 5 of 22) (steady 5 of 16) (phase = 0.343750000 = 11.0 / 32.0) - // entropy: 4.4308578632493116345 - // avg_length: 4.4996166821663301505; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0xc12f, // (12, 303) 0 - (short) 0x601d, // ( 6, 29) 1 - (short) 0x9057, // ( 9, 87) 2 - (short) 0x3002, // ( 3, 2) 3 - (short) 0xb14f, // (11, 335) 4 - (short) 0x5005, // ( 5, 5) 5 - (short) 0x807b, // ( 8, 123) 6 - (short) 0x2000, // ( 2, 0) 7 - (short) 0xc92f, // (12, 2351) 8 - (short) 0x700b, // ( 7, 11) 9 - (short) 0xa1f7, // (10, 503) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0xc52f, // (12, 1327) 12 - (short) 0x603d, // ( 6, 61) 13 - (short) 0x9157, // ( 9, 343) 14 - (short) 0x3006, // ( 3, 6) 15 - (short) 0xcd2f, // (12, 3375) 16 - (short) 0x80fb, // ( 8, 251) 17 - (short) 0xb54f, // (11, 1359) 18 - (short) 0x5015, // ( 5, 21) 19 - (short) 0xc32f, // (12, 815) 20 - (short) 0x704b, // ( 7, 75) 21 - (short) 0xa3f7, // (10, 1015) 22 - (short) 0x4009, // ( 4, 9) 23 - (short) 0xcb2f, // (12, 2863) 24 - (short) 0x8007, // ( 8, 7) 25 - (short) 0xc72f, // (12, 1839) 26 - (short) 0x6003, // ( 6, 3) 27 - (short) 0xcf2f, // (12, 3887) 28 - (short) 0x8087, // ( 8, 135) 29 - (short) 0xb34f, // (11, 847) 30 - (short) 0x500d, // ( 5, 13) 31 - (short) 0xc0af, // (12, 175) 32 - (short) 0x90d7, // ( 9, 215) 33 - (short) 0xc8af, // (12, 2223) 34 - (short) 0x6023, // ( 6, 35) 35 - (short) 0xc4af, // (12, 1199) 36 - (short) 0x8047, // ( 8, 71) 37 - (short) 0xb74f, // (11, 1871) 38 - (short) 0x6013, // ( 6, 19) 39 - (short) 0xccaf, // (12, 3247) 40 - (short) 0xa00f, // (10, 15) 41 - (short) 0xc2af, // (12, 687) 42 - (short) 0x702b, // ( 7, 43) 43 - (short) 0xcaaf, // (12, 2735) 44 - (short) 0x91d7, // ( 9, 471) 45 - (short) 0xc6af, // (12, 1711) 46 - (short) 0x6033, // ( 6, 51) 47 - (short) 0xceaf, // (12, 3759) 48 - (short) 0xb0cf, // (11, 207) 49 - (short) 0xc1af, // (12, 431) 50 - (short) 0x80c7, // ( 8, 199) 51 - (short) 0xc9af, // (12, 2479) 52 - (short) 0xa20f, // (10, 527) 53 - (short) 0xc5af, // (12, 1455) 54 - (short) 0x706b, // ( 7, 107) 55 - (short) 0xcdaf, // (12, 3503) 56 - (short) 0xc3af, // (12, 943) 57 - (short) 0xcbaf, // (12, 2991) 58 - (short) 0x9037, // ( 9, 55) 59 - (short) 0xc7af, // (12, 1967) 60 - (short) 0xb4cf, // (11, 1231) 61 - (short) 0xcfaf, // (12, 4015) 62 - (short) 0x8027, // ( 8, 39) 63 - (short) 0xc06f, // (12, 111) 64 - (short) 0xa10f, // (10, 271) 65 - (short) 0xc86f, // (12, 2159) 66 - (short) 0x701b, // ( 7, 27) 67 - (short) 0xc46f, // (12, 1135) 68 - (short) 0x9137, // ( 9, 311) 69 - (short) 0xcc6f, // (12, 3183) 70 - (short) 0x705b, // ( 7, 91) 71 - (short) 0xc26f, // (12, 623) 72 - (short) 0xb2cf, // (11, 719) 73 - (short) 0xca6f, // (12, 2671) 74 - (short) 0x80a7, // ( 8, 167) 75 - (short) 0xc66f, // (12, 1647) 76 - (short) 0xa30f, // (10, 783) 77 - (short) 0xce6f, // (12, 3695) 78 - (short) 0x703b, // ( 7, 59) 79 - (short) 0xc16f, // (12, 367) 80 - (short) 0xc96f, // (12, 2415) 81 - (short) 0xc56f, // (12, 1391) 82 - (short) 0x90b7, // ( 9, 183) 83 - (short) 0xcd6f, // (12, 3439) 84 - (short) 0xb6cf, // (11, 1743) 85 - (short) 0xc36f, // (12, 879) 86 - (short) 0x8067, // ( 8, 103) 87 - (short) 0xcb6f, // (12, 2927) 88 - (short) 0xc76f, // (12, 1903) 89 - (short) 0xcf6f, // (12, 3951) 90 - (short) 0xa08f, // (10, 143) 91 - (short) 0xc0ef, // (12, 239) 92 - (short) 0xc8ef, // (12, 2287) 93 - (short) 0xc4ef, // (12, 1263) 94 - (short) 0x91b7, // ( 9, 439) 95 - (short) 0xccef, // (12, 3311) 96 - (short) 0xc2ef, // (12, 751) 97 - (short) 0xcaef, // (12, 2799) 98 - (short) 0xa28f, // (10, 655) 99 - (short) 0xc6ef, // (12, 1775) 100 - (short) 0xceef, // (12, 3823) 101 - (short) 0xc1ef, // (12, 495) 102 - (short) 0x9077, // ( 9, 119) 103 - (short) 0xc9ef, // (12, 2543) 104 - (short) 0xc5ef, // (12, 1519) 105 - (short) 0xcdef, // (12, 3567) 106 - (short) 0xb1cf, // (11, 463) 107 - (short) 0xc3ef, // (12, 1007) 108 - (short) 0xcbef, // (12, 3055) 109 - (short) 0xc7ef, // (12, 2031) 110 - (short) 0xa18f, // (10, 399) 111 - (short) 0xcfef, // (12, 4079) 112 - (short) 0xc01f, // (12, 31) 113 - (short) 0xc81f, // (12, 2079) 114 - (short) 0xc41f, // (12, 1055) 115 - (short) 0xcc1f, // (12, 3103) 116 - (short) 0xc21f, // (12, 543) 117 - (short) 0xca1f, // (12, 2591) 118 - (short) 0xb5cf, // (11, 1487) 119 - (short) 0xc61f, // (12, 1567) 120 - (short) 0xce1f, // (12, 3615) 121 - (short) 0xc11f, // (12, 287) 122 - (short) 0xc91f, // (12, 2335) 123 - (short) 0xc51f, // (12, 1311) 124 - (short) 0xcd1f, // (12, 3359) 125 - (short) 0xc31f, // (12, 799) 126 - (short) 0xcb1f, // (12, 2847) 127 - (short) 0xc71f, // (12, 1823) 128 - (short) 0xb3cf, // (11, 975) 129 - (short) 0xcf1f, // (12, 3871) 130 - (short) 0x80e7, // ( 8, 231) 131 - (short) 0xc09f, // (12, 159) 132 - (short) 0xa38f, // (10, 911) 133 - (short) 0xc89f, // (12, 2207) 134 - (short) 0x8017, // ( 8, 23) 135 - (short) 0xc49f, // (12, 1183) 136 - (short) 0xcc9f, // (12, 3231) 137 - (short) 0xc29f, // (12, 671) 138 - (short) 0x9177, // ( 9, 375) 139 - (short) 0xca9f, // (12, 2719) 140 - (short) 0xb7cf, // (11, 1999) 141 - (short) 0xc69f, // (12, 1695) 142 - (short) 0x8097, // ( 8, 151) 143 - (short) 0xce9f, // (12, 3743) 144 - (short) 0xc19f, // (12, 415) 145 - (short) 0xc99f, // (12, 2463) 146 - (short) 0xa04f, // (10, 79) 147 - (short) 0xc59f, // (12, 1439) 148 - (short) 0xcd9f, // (12, 3487) 149 - (short) 0xc39f, // (12, 927) 150 - (short) 0x90f7, // ( 9, 247) 151 - (short) 0xcb9f, // (12, 2975) 152 - (short) 0xc79f, // (12, 1951) 153 - (short) 0xcf9f, // (12, 3999) 154 - (short) 0xb02f, // (11, 47) 155 - (short) 0xc05f, // (12, 95) 156 - (short) 0xc85f, // (12, 2143) 157 - (short) 0xc45f, // (12, 1119) 158 - (short) 0xa24f, // (10, 591) 159 - (short) 0xcc5f, // (12, 3167) 160 - (short) 0xc25f, // (12, 607) 161 - (short) 0xca5f, // (12, 2655) 162 - (short) 0xb42f, // (11, 1071) 163 - (short) 0xc65f, // (12, 1631) 164 - (short) 0xce5f, // (12, 3679) 165 - (short) 0xc15f, // (12, 351) 166 - (short) 0xb22f, // (11, 559) 167 - (short) 0xc95f, // (12, 2399) 168 - (short) 0xc55f, // (12, 1375) 169 - (short) 0xcd5f, // (12, 3423) 170 - (short) 0xc35f, // (12, 863) 171 - (short) 0xcb5f, // (12, 2911) 172 - (short) 0xc75f, // (12, 1887) 173 - (short) 0xcf5f, // (12, 3935) 174 - (short) 0xb62f, // (11, 1583) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 6 of 22) (steady 6 of 16) (phase = 0.406250000 = 13.0 / 32.0) - // entropy: 4.4310364988500126060 - // avg_length: 4.5051134111084252254; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x601d, // ( 6, 29) 0 - (short) 0x3002, // ( 3, 2) 1 - (short) 0x603d, // ( 6, 61) 2 - (short) 0x2000, // ( 2, 0) 3 - (short) 0x700b, // ( 7, 11) 4 - (short) 0x4001, // ( 4, 1) 5 - (short) 0x6003, // ( 6, 3) 6 - (short) 0x3006, // ( 3, 6) 7 - (short) 0x807b, // ( 8, 123) 8 - (short) 0x5005, // ( 5, 5) 9 - (short) 0x704b, // ( 7, 75) 10 - (short) 0x4009, // ( 4, 9) 11 - (short) 0x9097, // ( 9, 151) 12 - (short) 0x6023, // ( 6, 35) 13 - (short) 0x80fb, // ( 8, 251) 14 - (short) 0x5015, // ( 5, 21) 15 - (short) 0x9197, // ( 9, 407) 16 - (short) 0x6013, // ( 6, 19) 17 - (short) 0x8007, // ( 8, 7) 18 - (short) 0x500d, // ( 5, 13) 19 - (short) 0xa0f7, // (10, 247) 20 - (short) 0x702b, // ( 7, 43) 21 - (short) 0x9057, // ( 9, 87) 22 - (short) 0x6033, // ( 6, 51) 23 - (short) 0xb14f, // (11, 335) 24 - (short) 0x8087, // ( 8, 135) 25 - (short) 0xa2f7, // (10, 759) 26 - (short) 0x706b, // ( 7, 107) 27 - (short) 0xb54f, // (11, 1359) 28 - (short) 0x9157, // ( 9, 343) 29 - (short) 0xa1f7, // (10, 503) 30 - (short) 0x8047, // ( 8, 71) 31 - (short) 0xa3f7, // (10, 1015) 32 - (short) 0x701b, // ( 7, 27) 33 - (short) 0x90d7, // ( 9, 215) 34 - (short) 0x705b, // ( 7, 91) 35 - (short) 0xb34f, // (11, 847) 36 - (short) 0x80c7, // ( 8, 199) 37 - (short) 0xa00f, // (10, 15) 38 - (short) 0x703b, // ( 7, 59) 39 - (short) 0xc32f, // (12, 815) 40 - (short) 0x91d7, // ( 9, 471) 41 - (short) 0xb74f, // (11, 1871) 42 - (short) 0x8027, // ( 8, 39) 43 - (short) 0xcb2f, // (12, 2863) 44 - (short) 0xa20f, // (10, 527) 45 - (short) 0xb0cf, // (11, 207) 46 - (short) 0x9037, // ( 9, 55) 47 - (short) 0xc72f, // (12, 1839) 48 - (short) 0xa10f, // (10, 271) 49 - (short) 0xcf2f, // (12, 3887) 50 - (short) 0x9137, // ( 9, 311) 51 - (short) 0xc0af, // (12, 175) 52 - (short) 0xb4cf, // (11, 1231) 53 - (short) 0xc8af, // (12, 2223) 54 - (short) 0xa30f, // (10, 783) 55 - (short) 0xc4af, // (12, 1199) 56 - (short) 0xccaf, // (12, 3247) 57 - (short) 0xc2af, // (12, 687) 58 - (short) 0xb2cf, // (11, 719) 59 - (short) 0xcaaf, // (12, 2735) 60 - (short) 0xc6af, // (12, 1711) 61 - (short) 0xceaf, // (12, 3759) 62 - (short) 0xb6cf, // (11, 1743) 63 - (short) 0xb1cf, // (11, 463) 64 - (short) 0x80a7, // ( 8, 167) 65 - (short) 0xa08f, // (10, 143) 66 - (short) 0x8067, // ( 8, 103) 67 - (short) 0xc1af, // (12, 431) 68 - (short) 0x90b7, // ( 9, 183) 69 - (short) 0xb5cf, // (11, 1487) 70 - (short) 0x80e7, // ( 8, 231) 71 - (short) 0xc9af, // (12, 2479) 72 - (short) 0xa28f, // (10, 655) 73 - (short) 0xc5af, // (12, 1455) 74 - (short) 0x91b7, // ( 9, 439) 75 - (short) 0xcdaf, // (12, 3503) 76 - (short) 0xb3cf, // (11, 975) 77 - (short) 0xc3af, // (12, 943) 78 - (short) 0xa18f, // (10, 399) 79 - (short) 0xcbaf, // (12, 2991) 80 - (short) 0xb7cf, // (11, 1999) 81 - (short) 0xc7af, // (12, 1967) 82 - (short) 0xa38f, // (10, 911) 83 - (short) 0xcfaf, // (12, 4015) 84 - (short) 0xc06f, // (12, 111) 85 - (short) 0xc86f, // (12, 2159) 86 - (short) 0xb02f, // (11, 47) 87 - (short) 0xc46f, // (12, 1135) 88 - (short) 0xcc6f, // (12, 3183) 89 - (short) 0xc26f, // (12, 623) 90 - (short) 0xca6f, // (12, 2671) 91 - (short) 0xc66f, // (12, 1647) 92 - (short) 0xce6f, // (12, 3695) 93 - (short) 0xc16f, // (12, 367) 94 - (short) 0xc96f, // (12, 2415) 95 - (short) 0xc56f, // (12, 1391) 96 - (short) 0xcd6f, // (12, 3439) 97 - (short) 0xc36f, // (12, 879) 98 - (short) 0xb42f, // (11, 1071) 99 - (short) 0xcb6f, // (12, 2927) 100 - (short) 0xc76f, // (12, 1903) 101 - (short) 0xcf6f, // (12, 3951) 102 - (short) 0xc0ef, // (12, 239) 103 - (short) 0xc8ef, // (12, 2287) 104 - (short) 0xc4ef, // (12, 1263) 105 - (short) 0xccef, // (12, 3311) 106 - (short) 0xc2ef, // (12, 751) 107 - (short) 0xcaef, // (12, 2799) 108 - (short) 0xc6ef, // (12, 1775) 109 - (short) 0xceef, // (12, 3823) 110 - (short) 0xc1ef, // (12, 495) 111 - (short) 0xc9ef, // (12, 2543) 112 - (short) 0xc5ef, // (12, 1519) 113 - (short) 0xcdef, // (12, 3567) 114 - (short) 0xc3ef, // (12, 1007) 115 - (short) 0xcbef, // (12, 3055) 116 - (short) 0xc7ef, // (12, 2031) 117 - (short) 0xcfef, // (12, 4079) 118 - (short) 0xc01f, // (12, 31) 119 - (short) 0xc81f, // (12, 2079) 120 - (short) 0xc41f, // (12, 1055) 121 - (short) 0xcc1f, // (12, 3103) 122 - (short) 0xc21f, // (12, 543) 123 - (short) 0xca1f, // (12, 2591) 124 - (short) 0xc61f, // (12, 1567) 125 - (short) 0xce1f, // (12, 3615) 126 - (short) 0xc11f, // (12, 287) 127 - (short) 0xc91f, // (12, 2335) 128 - (short) 0x9077, // ( 9, 119) 129 - (short) 0xb22f, // (11, 559) 130 - (short) 0x8017, // ( 8, 23) 131 - (short) 0xc51f, // (12, 1311) 132 - (short) 0xa04f, // (10, 79) 133 - (short) 0xcd1f, // (12, 3359) 134 - (short) 0x9177, // ( 9, 375) 135 - (short) 0xc31f, // (12, 799) 136 - (short) 0xb62f, // (11, 1583) 137 - (short) 0xcb1f, // (12, 2847) 138 - (short) 0xa24f, // (10, 591) 139 - (short) 0xc71f, // (12, 1823) 140 - (short) 0xcf1f, // (12, 3871) 141 - (short) 0xc09f, // (12, 159) 142 - (short) 0xb12f, // (11, 303) 143 - (short) 0xc89f, // (12, 2207) 144 - (short) 0xc49f, // (12, 1183) 145 - (short) 0xcc9f, // (12, 3231) 146 - (short) 0xb52f, // (11, 1327) 147 - (short) 0xc29f, // (12, 671) 148 - (short) 0xca9f, // (12, 2719) 149 - (short) 0xc69f, // (12, 1695) 150 - (short) 0xce9f, // (12, 3743) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 7 of 22) (steady 7 of 16) (phase = 0.468750000 = 15.0 / 32.0) - // entropy: 4.4417871821766841123 - // avg_length: 4.5206419191518980583; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x700b, // ( 7, 11) 0 - (short) 0x3002, // ( 3, 2) 1 - (short) 0x601d, // ( 6, 29) 2 - (short) 0x2000, // ( 2, 0) 3 - (short) 0x704b, // ( 7, 75) 4 - (short) 0x4001, // ( 4, 1) 5 - (short) 0x603d, // ( 6, 61) 6 - (short) 0x3006, // ( 3, 6) 7 - (short) 0x8007, // ( 8, 7) 8 - (short) 0x5005, // ( 5, 5) 9 - (short) 0x702b, // ( 7, 43) 10 - (short) 0x4009, // ( 4, 9) 11 - (short) 0x9097, // ( 9, 151) 12 - (short) 0x6003, // ( 6, 3) 13 - (short) 0x8087, // ( 8, 135) 14 - (short) 0x5015, // ( 5, 21) 15 - (short) 0x9197, // ( 9, 407) 16 - (short) 0x6023, // ( 6, 35) 17 - (short) 0x8047, // ( 8, 71) 18 - (short) 0x500d, // ( 5, 13) 19 - (short) 0xa0f7, // (10, 247) 20 - (short) 0x706b, // ( 7, 107) 21 - (short) 0x9057, // ( 9, 87) 22 - (short) 0x6013, // ( 6, 19) 23 - (short) 0xb14f, // (11, 335) 24 - (short) 0x80c7, // ( 8, 199) 25 - (short) 0xa2f7, // (10, 759) 26 - (short) 0x701b, // ( 7, 27) 27 - (short) 0xc52f, // (12, 1327) 28 - (short) 0x9157, // ( 9, 343) 29 - (short) 0xb54f, // (11, 1359) 30 - (short) 0x8027, // ( 8, 39) 31 - (short) 0xa1f7, // (10, 503) 32 - (short) 0x705b, // ( 7, 91) 33 - (short) 0x90d7, // ( 9, 215) 34 - (short) 0x6033, // ( 6, 51) 35 - (short) 0xb34f, // (11, 847) 36 - (short) 0x80a7, // ( 8, 167) 37 - (short) 0xa3f7, // (10, 1015) 38 - (short) 0x703b, // ( 7, 59) 39 - (short) 0xcd2f, // (12, 3375) 40 - (short) 0x91d7, // ( 9, 471) 41 - (short) 0xb74f, // (11, 1871) 42 - (short) 0x8067, // ( 8, 103) 43 - (short) 0xc32f, // (12, 815) 44 - (short) 0xa00f, // (10, 15) 45 - (short) 0xcb2f, // (12, 2863) 46 - (short) 0x9037, // ( 9, 55) 47 - (short) 0xc72f, // (12, 1839) 48 - (short) 0xa20f, // (10, 527) 49 - (short) 0xcf2f, // (12, 3887) 50 - (short) 0x9137, // ( 9, 311) 51 - (short) 0xc0af, // (12, 175) 52 - (short) 0xb0cf, // (11, 207) 53 - (short) 0xc8af, // (12, 2223) 54 - (short) 0xa10f, // (10, 271) 55 - (short) 0xc4af, // (12, 1199) 56 - (short) 0xccaf, // (12, 3247) 57 - (short) 0xc2af, // (12, 687) 58 - (short) 0xb4cf, // (11, 1231) 59 - (short) 0xcaaf, // (12, 2735) 60 - (short) 0xc6af, // (12, 1711) 61 - (short) 0xceaf, // (12, 3759) 62 - (short) 0xb2cf, // (11, 719) 63 - (short) 0xb6cf, // (11, 1743) 64 - (short) 0x80e7, // ( 8, 231) 65 - (short) 0xa30f, // (10, 783) 66 - (short) 0x707b, // ( 7, 123) 67 - (short) 0xc1af, // (12, 431) 68 - (short) 0x90b7, // ( 9, 183) 69 - (short) 0xb1cf, // (11, 463) 70 - (short) 0x8017, // ( 8, 23) 71 - (short) 0xc9af, // (12, 2479) 72 - (short) 0xa08f, // (10, 143) 73 - (short) 0xc5af, // (12, 1455) 74 - (short) 0x91b7, // ( 9, 439) 75 - (short) 0xcdaf, // (12, 3503) 76 - (short) 0xb5cf, // (11, 1487) 77 - (short) 0xc3af, // (12, 943) 78 - (short) 0xa28f, // (10, 655) 79 - (short) 0xcbaf, // (12, 2991) 80 - (short) 0xb3cf, // (11, 975) 81 - (short) 0xc7af, // (12, 1967) 82 - (short) 0xa18f, // (10, 399) 83 - (short) 0xcfaf, // (12, 4015) 84 - (short) 0xc06f, // (12, 111) 85 - (short) 0xc86f, // (12, 2159) 86 - (short) 0xb7cf, // (11, 1999) 87 - (short) 0xc46f, // (12, 1135) 88 - (short) 0xcc6f, // (12, 3183) 89 - (short) 0xc26f, // (12, 623) 90 - (short) 0xca6f, // (12, 2671) 91 - (short) 0xc66f, // (12, 1647) 92 - (short) 0xce6f, // (12, 3695) 93 - (short) 0xc16f, // (12, 367) 94 - (short) 0xc96f, // (12, 2415) 95 - (short) 0xc56f, // (12, 1391) 96 - (short) 0xcd6f, // (12, 3439) 97 - (short) 0xc36f, // (12, 879) 98 - (short) 0xb02f, // (11, 47) 99 - (short) 0xcb6f, // (12, 2927) 100 - (short) 0xc76f, // (12, 1903) 101 - (short) 0xcf6f, // (12, 3951) 102 - (short) 0xc0ef, // (12, 239) 103 - (short) 0xc8ef, // (12, 2287) 104 - (short) 0xc4ef, // (12, 1263) 105 - (short) 0xccef, // (12, 3311) 106 - (short) 0xc2ef, // (12, 751) 107 - (short) 0xcaef, // (12, 2799) 108 - (short) 0xc6ef, // (12, 1775) 109 - (short) 0xceef, // (12, 3823) 110 - (short) 0xc1ef, // (12, 495) 111 - (short) 0xc9ef, // (12, 2543) 112 - (short) 0xc5ef, // (12, 1519) 113 - (short) 0xcdef, // (12, 3567) 114 - (short) 0xc3ef, // (12, 1007) 115 - (short) 0xcbef, // (12, 3055) 116 - (short) 0xc7ef, // (12, 2031) 117 - (short) 0xcfef, // (12, 4079) 118 - (short) 0xc01f, // (12, 31) 119 - (short) 0xc81f, // (12, 2079) 120 - (short) 0xc41f, // (12, 1055) 121 - (short) 0xcc1f, // (12, 3103) 122 - (short) 0xc21f, // (12, 543) 123 - (short) 0xca1f, // (12, 2591) 124 - (short) 0xc61f, // (12, 1567) 125 - (short) 0xce1f, // (12, 3615) 126 - (short) 0xc11f, // (12, 287) 127 - (short) 0xc91f, // (12, 2335) 128 - (short) 0xa38f, // (10, 911) 129 - (short) 0xb42f, // (11, 1071) 130 - (short) 0x9077, // ( 9, 119) 131 - (short) 0xc51f, // (12, 1311) 132 - (short) 0xa04f, // (10, 79) 133 - (short) 0xcd1f, // (12, 3359) 134 - (short) 0x9177, // ( 9, 375) 135 - (short) 0xc31f, // (12, 799) 136 - (short) 0xb22f, // (11, 559) 137 - (short) 0xcb1f, // (12, 2847) 138 - (short) 0xa24f, // (10, 591) 139 - (short) 0xc71f, // (12, 1823) 140 - (short) 0xcf1f, // (12, 3871) 141 - (short) 0xc09f, // (12, 159) 142 - (short) 0xb62f, // (11, 1583) 143 - (short) 0xc89f, // (12, 2207) 144 - (short) 0xc49f, // (12, 1183) 145 - (short) 0xcc9f, // (12, 3231) 146 - (short) 0xb12f, // (11, 303) 147 - (short) 0xc29f, // (12, 671) 148 - (short) 0xca9f, // (12, 2719) 149 - (short) 0xc69f, // (12, 1695) 150 - (short) 0xce9f, // (12, 3743) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 8 of 22) (steady 8 of 16) (phase = 0.531250000 = 17.0 / 32.0) - // entropy: 4.4505873338397474726 - // avg_length: 4.5270058771550303334; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x7033, // ( 7, 51) 0 - (short) 0x4006, // ( 4, 6) 1 - (short) 0x601d, // ( 6, 29) 2 - (short) 0x2000, // ( 2, 0) 3 - (short) 0x7073, // ( 7, 115) 4 - (short) 0x400e, // ( 4, 14) 5 - (short) 0x603d, // ( 6, 61) 6 - (short) 0x3002, // ( 3, 2) 7 - (short) 0x807b, // ( 8, 123) 8 - (short) 0x5005, // ( 5, 5) 9 - (short) 0x700b, // ( 7, 11) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0x9097, // ( 9, 151) 12 - (short) 0x5015, // ( 5, 21) 13 - (short) 0x80fb, // ( 8, 251) 14 - (short) 0x4009, // ( 4, 9) 15 - (short) 0xa0f7, // (10, 247) 16 - (short) 0x6003, // ( 6, 3) 17 - (short) 0x8007, // ( 8, 7) 18 - (short) 0x500d, // ( 5, 13) 19 - (short) 0xa2f7, // (10, 759) 20 - (short) 0x704b, // ( 7, 75) 21 - (short) 0x9197, // ( 9, 407) 22 - (short) 0x6023, // ( 6, 35) 23 - (short) 0xb34f, // (11, 847) 24 - (short) 0x8087, // ( 8, 135) 25 - (short) 0xa1f7, // (10, 503) 26 - (short) 0x702b, // ( 7, 43) 27 - (short) 0xb74f, // (11, 1871) 28 - (short) 0x8047, // ( 8, 71) 29 - (short) 0xa3f7, // (10, 1015) 30 - (short) 0x706b, // ( 7, 107) 31 - (short) 0xb0cf, // (11, 207) 32 - (short) 0x701b, // ( 7, 27) 33 - (short) 0x9057, // ( 9, 87) 34 - (short) 0x6013, // ( 6, 19) 35 - (short) 0xb4cf, // (11, 1231) 36 - (short) 0x80c7, // ( 8, 199) 37 - (short) 0xa00f, // (10, 15) 38 - (short) 0x705b, // ( 7, 91) 39 - (short) 0xc72f, // (12, 1839) 40 - (short) 0x9157, // ( 9, 343) 41 - (short) 0xb2cf, // (11, 719) 42 - (short) 0x8027, // ( 8, 39) 43 - (short) 0xcf2f, // (12, 3887) 44 - (short) 0x90d7, // ( 9, 215) 45 - (short) 0xb6cf, // (11, 1743) 46 - (short) 0x80a7, // ( 8, 167) 47 - (short) 0xc0af, // (12, 175) 48 - (short) 0xa20f, // (10, 527) 49 - (short) 0xc8af, // (12, 2223) 50 - (short) 0x91d7, // ( 9, 471) 51 - (short) 0xc4af, // (12, 1199) 52 - (short) 0xa10f, // (10, 271) 53 - (short) 0xccaf, // (12, 3247) 54 - (short) 0x9037, // ( 9, 55) 55 - (short) 0xc2af, // (12, 687) 56 - (short) 0xcaaf, // (12, 2735) 57 - (short) 0xc6af, // (12, 1711) 58 - (short) 0xb1cf, // (11, 463) 59 - (short) 0xceaf, // (12, 3759) 60 - (short) 0xc1af, // (12, 431) 61 - (short) 0xc9af, // (12, 2479) 62 - (short) 0xb5cf, // (11, 1487) 63 - (short) 0xc5af, // (12, 1455) 64 - (short) 0x8067, // ( 8, 103) 65 - (short) 0xa30f, // (10, 783) 66 - (short) 0x703b, // ( 7, 59) 67 - (short) 0xcdaf, // (12, 3503) 68 - (short) 0x9137, // ( 9, 311) 69 - (short) 0xb3cf, // (11, 975) 70 - (short) 0x80e7, // ( 8, 231) 71 - (short) 0xc3af, // (12, 943) 72 - (short) 0xa08f, // (10, 143) 73 - (short) 0xcbaf, // (12, 2991) 74 - (short) 0x90b7, // ( 9, 183) 75 - (short) 0xc7af, // (12, 1967) 76 - (short) 0xa28f, // (10, 655) 77 - (short) 0xcfaf, // (12, 4015) 78 - (short) 0x91b7, // ( 9, 439) 79 - (short) 0xc06f, // (12, 111) 80 - (short) 0xb7cf, // (11, 1999) 81 - (short) 0xc86f, // (12, 2159) 82 - (short) 0xa18f, // (10, 399) 83 - (short) 0xc46f, // (12, 1135) 84 - (short) 0xb02f, // (11, 47) 85 - (short) 0xcc6f, // (12, 3183) 86 - (short) 0xa38f, // (10, 911) 87 - (short) 0xc26f, // (12, 623) 88 - (short) 0xca6f, // (12, 2671) 89 - (short) 0xc66f, // (12, 1647) 90 - (short) 0xce6f, // (12, 3695) 91 - (short) 0xc16f, // (12, 367) 92 - (short) 0xc96f, // (12, 2415) 93 - (short) 0xc56f, // (12, 1391) 94 - (short) 0xcd6f, // (12, 3439) 95 - (short) 0xc36f, // (12, 879) 96 - (short) 0xcb6f, // (12, 2927) 97 - (short) 0xc76f, // (12, 1903) 98 - (short) 0xb42f, // (11, 1071) 99 - (short) 0xcf6f, // (12, 3951) 100 - (short) 0xc0ef, // (12, 239) 101 - (short) 0xc8ef, // (12, 2287) 102 - (short) 0xb22f, // (11, 559) 103 - (short) 0xc4ef, // (12, 1263) 104 - (short) 0xccef, // (12, 3311) 105 - (short) 0xc2ef, // (12, 751) 106 - (short) 0xcaef, // (12, 2799) 107 - (short) 0xc6ef, // (12, 1775) 108 - (short) 0xceef, // (12, 3823) 109 - (short) 0xc1ef, // (12, 495) 110 - (short) 0xc9ef, // (12, 2543) 111 - (short) 0xc5ef, // (12, 1519) 112 - (short) 0xcdef, // (12, 3567) 113 - (short) 0xc3ef, // (12, 1007) 114 - (short) 0xcbef, // (12, 3055) 115 - (short) 0xc7ef, // (12, 2031) 116 - (short) 0xcfef, // (12, 4079) 117 - (short) 0xc01f, // (12, 31) 118 - (short) 0xc81f, // (12, 2079) 119 - (short) 0xc41f, // (12, 1055) 120 - (short) 0xcc1f, // (12, 3103) 121 - (short) 0xc21f, // (12, 543) 122 - (short) 0xca1f, // (12, 2591) 123 - (short) 0xc61f, // (12, 1567) 124 - (short) 0xce1f, // (12, 3615) 125 - (short) 0xc11f, // (12, 287) 126 - (short) 0xc91f, // (12, 2335) 127 - (short) 0xc51f, // (12, 1311) 128 - (short) 0x9077, // ( 9, 119) 129 - (short) 0xcd1f, // (12, 3359) 130 - (short) 0x8017, // ( 8, 23) 131 - (short) 0xc31f, // (12, 799) 132 - (short) 0xa04f, // (10, 79) 133 - (short) 0xcb1f, // (12, 2847) 134 - (short) 0x9177, // ( 9, 375) 135 - (short) 0xc71f, // (12, 1823) 136 - (short) 0xb62f, // (11, 1583) 137 - (short) 0xcf1f, // (12, 3871) 138 - (short) 0xa24f, // (10, 591) 139 - (short) 0xc09f, // (12, 159) 140 - (short) 0xb12f, // (11, 303) 141 - (short) 0xc89f, // (12, 2207) 142 - (short) 0xa14f, // (10, 335) 143 - (short) 0xc49f, // (12, 1183) 144 - (short) 0xcc9f, // (12, 3231) 145 - (short) 0xc29f, // (12, 671) 146 - (short) 0xb52f, // (11, 1327) 147 - (short) 0xca9f, // (12, 2719) 148 - (short) 0xc69f, // (12, 1695) 149 - (short) 0xce9f, // (12, 3743) 150 - (short) 0xb32f, // (11, 815) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 9 of 22) (steady 9 of 16) (phase = 0.593750000 = 19.0 / 32.0) - // entropy: 4.4575203029748040606 - // avg_length: 4.5315465600684730063; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x7033, // ( 7, 51) 0 - (short) 0x4006, // ( 4, 6) 1 - (short) 0x601d, // ( 6, 29) 2 - (short) 0x2000, // ( 2, 0) 3 - (short) 0x7073, // ( 7, 115) 4 - (short) 0x400e, // ( 4, 14) 5 - (short) 0x603d, // ( 6, 61) 6 - (short) 0x3002, // ( 3, 2) 7 - (short) 0x9097, // ( 9, 151) 8 - (short) 0x5005, // ( 5, 5) 9 - (short) 0x700b, // ( 7, 11) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0x9197, // ( 9, 407) 12 - (short) 0x6003, // ( 6, 3) 13 - (short) 0x807b, // ( 8, 123) 14 - (short) 0x4009, // ( 4, 9) 15 - (short) 0xa0f7, // (10, 247) 16 - (short) 0x6023, // ( 6, 35) 17 - (short) 0x80fb, // ( 8, 251) 18 - (short) 0x5015, // ( 5, 21) 19 - (short) 0xa2f7, // (10, 759) 20 - (short) 0x704b, // ( 7, 75) 21 - (short) 0x9057, // ( 9, 87) 22 - (short) 0x500d, // ( 5, 13) 23 - (short) 0xb34f, // (11, 847) 24 - (short) 0x8007, // ( 8, 7) 25 - (short) 0xa1f7, // (10, 503) 26 - (short) 0x702b, // ( 7, 43) 27 - (short) 0xc72f, // (12, 1839) 28 - (short) 0x8087, // ( 8, 135) 29 - (short) 0xa3f7, // (10, 1015) 30 - (short) 0x706b, // ( 7, 107) 31 - (short) 0xb74f, // (11, 1871) 32 - (short) 0x701b, // ( 7, 27) 33 - (short) 0x9157, // ( 9, 343) 34 - (short) 0x6013, // ( 6, 19) 35 - (short) 0xb0cf, // (11, 207) 36 - (short) 0x8047, // ( 8, 71) 37 - (short) 0xa00f, // (10, 15) 38 - (short) 0x705b, // ( 7, 91) 39 - (short) 0xcf2f, // (12, 3887) 40 - (short) 0x90d7, // ( 9, 215) 41 - (short) 0xb4cf, // (11, 1231) 42 - (short) 0x80c7, // ( 8, 199) 43 - (short) 0xc0af, // (12, 175) 44 - (short) 0x91d7, // ( 9, 471) 45 - (short) 0xb2cf, // (11, 719) 46 - (short) 0x8027, // ( 8, 39) 47 - (short) 0xc8af, // (12, 2223) 48 - (short) 0xa20f, // (10, 527) 49 - (short) 0xc4af, // (12, 1199) 50 - (short) 0x9037, // ( 9, 55) 51 - (short) 0xccaf, // (12, 3247) 52 - (short) 0xa10f, // (10, 271) 53 - (short) 0xc2af, // (12, 687) 54 - (short) 0x9137, // ( 9, 311) 55 - (short) 0xcaaf, // (12, 2735) 56 - (short) 0xc6af, // (12, 1711) 57 - (short) 0xceaf, // (12, 3759) 58 - (short) 0xa30f, // (10, 783) 59 - (short) 0xc1af, // (12, 431) 60 - (short) 0xc9af, // (12, 2479) 61 - (short) 0xc5af, // (12, 1455) 62 - (short) 0xb6cf, // (11, 1743) 63 - (short) 0xcdaf, // (12, 3503) 64 - (short) 0x80a7, // ( 8, 167) 65 - (short) 0xb1cf, // (11, 463) 66 - (short) 0x703b, // ( 7, 59) 67 - (short) 0xc3af, // (12, 943) 68 - (short) 0x90b7, // ( 9, 183) 69 - (short) 0xb5cf, // (11, 1487) 70 - (short) 0x8067, // ( 8, 103) 71 - (short) 0xcbaf, // (12, 2991) 72 - (short) 0xa08f, // (10, 143) 73 - (short) 0xc7af, // (12, 1967) 74 - (short) 0x91b7, // ( 9, 439) 75 - (short) 0xcfaf, // (12, 4015) 76 - (short) 0xa28f, // (10, 655) 77 - (short) 0xc06f, // (12, 111) 78 - (short) 0x9077, // ( 9, 119) 79 - (short) 0xc86f, // (12, 2159) 80 - (short) 0xb3cf, // (11, 975) 81 - (short) 0xc46f, // (12, 1135) 82 - (short) 0xa18f, // (10, 399) 83 - (short) 0xcc6f, // (12, 3183) 84 - (short) 0xb7cf, // (11, 1999) 85 - (short) 0xc26f, // (12, 623) 86 - (short) 0xa38f, // (10, 911) 87 - (short) 0xca6f, // (12, 2671) 88 - (short) 0xc66f, // (12, 1647) 89 - (short) 0xce6f, // (12, 3695) 90 - (short) 0xb02f, // (11, 47) 91 - (short) 0xc16f, // (12, 367) 92 - (short) 0xc96f, // (12, 2415) 93 - (short) 0xc56f, // (12, 1391) 94 - (short) 0xcd6f, // (12, 3439) 95 - (short) 0xc36f, // (12, 879) 96 - (short) 0xcb6f, // (12, 2927) 97 - (short) 0xc76f, // (12, 1903) 98 - (short) 0xb42f, // (11, 1071) 99 - (short) 0xcf6f, // (12, 3951) 100 - (short) 0xc0ef, // (12, 239) 101 - (short) 0xc8ef, // (12, 2287) 102 - (short) 0xb22f, // (11, 559) 103 - (short) 0xc4ef, // (12, 1263) 104 - (short) 0xccef, // (12, 3311) 105 - (short) 0xc2ef, // (12, 751) 106 - (short) 0xcaef, // (12, 2799) 107 - (short) 0xc6ef, // (12, 1775) 108 - (short) 0xceef, // (12, 3823) 109 - (short) 0xc1ef, // (12, 495) 110 - (short) 0xc9ef, // (12, 2543) 111 - (short) 0xc5ef, // (12, 1519) 112 - (short) 0xcdef, // (12, 3567) 113 - (short) 0xc3ef, // (12, 1007) 114 - (short) 0xcbef, // (12, 3055) 115 - (short) 0xc7ef, // (12, 2031) 116 - (short) 0xcfef, // (12, 4079) 117 - (short) 0xc01f, // (12, 31) 118 - (short) 0xc81f, // (12, 2079) 119 - (short) 0xc41f, // (12, 1055) 120 - (short) 0xcc1f, // (12, 3103) 121 - (short) 0xc21f, // (12, 543) 122 - (short) 0xca1f, // (12, 2591) 123 - (short) 0xc61f, // (12, 1567) 124 - (short) 0xce1f, // (12, 3615) 125 - (short) 0xc11f, // (12, 287) 126 - (short) 0xc91f, // (12, 2335) 127 - (short) 0xc51f, // (12, 1311) 128 - (short) 0x9177, // ( 9, 375) 129 - (short) 0xcd1f, // (12, 3359) 130 - (short) 0x80e7, // ( 8, 231) 131 - (short) 0xc31f, // (12, 799) 132 - (short) 0xa04f, // (10, 79) 133 - (short) 0xcb1f, // (12, 2847) 134 - (short) 0x8017, // ( 8, 23) 135 - (short) 0xc71f, // (12, 1823) 136 - (short) 0xb62f, // (11, 1583) 137 - (short) 0xcf1f, // (12, 3871) 138 - (short) 0xa24f, // (10, 591) 139 - (short) 0xc09f, // (12, 159) 140 - (short) 0xb12f, // (11, 303) 141 - (short) 0xc89f, // (12, 2207) 142 - (short) 0xa14f, // (10, 335) 143 - (short) 0xc49f, // (12, 1183) 144 - (short) 0xcc9f, // (12, 3231) 145 - (short) 0xc29f, // (12, 671) 146 - (short) 0xb52f, // (11, 1327) 147 - (short) 0xca9f, // (12, 2719) 148 - (short) 0xc69f, // (12, 1695) 149 - (short) 0xce9f, // (12, 3743) 150 - (short) 0xb32f, // (11, 815) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 10 of 22) (steady 10 of 16) (phase = 0.656250000 = 21.0 / 32.0) - // entropy: 4.4626765653088611430 - // avg_length: 4.5373141251902122661; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x700b, // ( 7, 11) 0 - (short) 0x4006, // ( 4, 6) 1 - (short) 0x601d, // ( 6, 29) 2 - (short) 0x2000, // ( 2, 0) 3 - (short) 0x807b, // ( 8, 123) 4 - (short) 0x400e, // ( 4, 14) 5 - (short) 0x603d, // ( 6, 61) 6 - (short) 0x3002, // ( 3, 2) 7 - (short) 0x9017, // ( 9, 23) 8 - (short) 0x5005, // ( 5, 5) 9 - (short) 0x704b, // ( 7, 75) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0x9117, // ( 9, 279) 12 - (short) 0x6003, // ( 6, 3) 13 - (short) 0x80fb, // ( 8, 251) 14 - (short) 0x4009, // ( 4, 9) 15 - (short) 0xa177, // (10, 375) 16 - (short) 0x6023, // ( 6, 35) 17 - (short) 0x9097, // ( 9, 151) 18 - (short) 0x5015, // ( 5, 21) 19 - (short) 0xa377, // (10, 887) 20 - (short) 0x702b, // ( 7, 43) 21 - (short) 0x9197, // ( 9, 407) 22 - (short) 0x500d, // ( 5, 13) 23 - (short) 0xb34f, // (11, 847) 24 - (short) 0x8007, // ( 8, 7) 25 - (short) 0xa0f7, // (10, 247) 26 - (short) 0x706b, // ( 7, 107) 27 - (short) 0xc0af, // (12, 175) 28 - (short) 0x8087, // ( 8, 135) 29 - (short) 0xa2f7, // (10, 759) 30 - (short) 0x701b, // ( 7, 27) 31 - (short) 0xb74f, // (11, 1871) 32 - (short) 0x8047, // ( 8, 71) 33 - (short) 0xa1f7, // (10, 503) 34 - (short) 0x6013, // ( 6, 19) 35 - (short) 0xb0cf, // (11, 207) 36 - (short) 0x80c7, // ( 8, 199) 37 - (short) 0xa3f7, // (10, 1015) 38 - (short) 0x6033, // ( 6, 51) 39 - (short) 0xc8af, // (12, 2223) 40 - (short) 0x9057, // ( 9, 87) 41 - (short) 0xb4cf, // (11, 1231) 42 - (short) 0x8027, // ( 8, 39) 43 - (short) 0xc4af, // (12, 1199) 44 - (short) 0x9157, // ( 9, 343) 45 - (short) 0xb2cf, // (11, 719) 46 - (short) 0x80a7, // ( 8, 167) 47 - (short) 0xccaf, // (12, 3247) 48 - (short) 0xa00f, // (10, 15) 49 - (short) 0xc2af, // (12, 687) 50 - (short) 0x90d7, // ( 9, 215) 51 - (short) 0xcaaf, // (12, 2735) 52 - (short) 0xa20f, // (10, 527) 53 - (short) 0xc6af, // (12, 1711) 54 - (short) 0x91d7, // ( 9, 471) 55 - (short) 0xceaf, // (12, 3759) 56 - (short) 0xb6cf, // (11, 1743) 57 - (short) 0xc1af, // (12, 431) 58 - (short) 0xa10f, // (10, 271) 59 - (short) 0xc9af, // (12, 2479) 60 - (short) 0xc5af, // (12, 1455) 61 - (short) 0xcdaf, // (12, 3503) 62 - (short) 0xa30f, // (10, 783) 63 - (short) 0xc3af, // (12, 943) 64 - (short) 0x9037, // ( 9, 55) 65 - (short) 0xb1cf, // (11, 463) 66 - (short) 0x705b, // ( 7, 91) 67 - (short) 0xcbaf, // (12, 2991) 68 - (short) 0x9137, // ( 9, 311) 69 - (short) 0xb5cf, // (11, 1487) 70 - (short) 0x703b, // ( 7, 59) 71 - (short) 0xc7af, // (12, 1967) 72 - (short) 0xa08f, // (10, 143) 73 - (short) 0xcfaf, // (12, 4015) 74 - (short) 0x90b7, // ( 9, 183) 75 - (short) 0xc06f, // (12, 111) 76 - (short) 0xa28f, // (10, 655) 77 - (short) 0xc86f, // (12, 2159) 78 - (short) 0x91b7, // ( 9, 439) 79 - (short) 0xc46f, // (12, 1135) 80 - (short) 0xb3cf, // (11, 975) 81 - (short) 0xcc6f, // (12, 3183) 82 - (short) 0xa18f, // (10, 399) 83 - (short) 0xc26f, // (12, 623) 84 - (short) 0xb7cf, // (11, 1999) 85 - (short) 0xca6f, // (12, 2671) 86 - (short) 0xa38f, // (10, 911) 87 - (short) 0xc66f, // (12, 1647) 88 - (short) 0xce6f, // (12, 3695) 89 - (short) 0xc16f, // (12, 367) 90 - (short) 0xb02f, // (11, 47) 91 - (short) 0xc96f, // (12, 2415) 92 - (short) 0xc56f, // (12, 1391) 93 - (short) 0xcd6f, // (12, 3439) 94 - (short) 0xb42f, // (11, 1071) 95 - (short) 0xc36f, // (12, 879) 96 - (short) 0xcb6f, // (12, 2927) 97 - (short) 0xc76f, // (12, 1903) 98 - (short) 0xb22f, // (11, 559) 99 - (short) 0xcf6f, // (12, 3951) 100 - (short) 0xc0ef, // (12, 239) 101 - (short) 0xc8ef, // (12, 2287) 102 - (short) 0xb62f, // (11, 1583) 103 - (short) 0xc4ef, // (12, 1263) 104 - (short) 0xccef, // (12, 3311) 105 - (short) 0xc2ef, // (12, 751) 106 - (short) 0xcaef, // (12, 2799) 107 - (short) 0xc6ef, // (12, 1775) 108 - (short) 0xceef, // (12, 3823) 109 - (short) 0xc1ef, // (12, 495) 110 - (short) 0xc9ef, // (12, 2543) 111 - (short) 0xc5ef, // (12, 1519) 112 - (short) 0xcdef, // (12, 3567) 113 - (short) 0xc3ef, // (12, 1007) 114 - (short) 0xcbef, // (12, 3055) 115 - (short) 0xc7ef, // (12, 2031) 116 - (short) 0xcfef, // (12, 4079) 117 - (short) 0xc01f, // (12, 31) 118 - (short) 0xc81f, // (12, 2079) 119 - (short) 0xc41f, // (12, 1055) 120 - (short) 0xcc1f, // (12, 3103) 121 - (short) 0xc21f, // (12, 543) 122 - (short) 0xca1f, // (12, 2591) 123 - (short) 0xc61f, // (12, 1567) 124 - (short) 0xce1f, // (12, 3615) 125 - (short) 0xc11f, // (12, 287) 126 - (short) 0xc91f, // (12, 2335) 127 - (short) 0xc51f, // (12, 1311) 128 - (short) 0x9077, // ( 9, 119) 129 - (short) 0xcd1f, // (12, 3359) 130 - (short) 0x8067, // ( 8, 103) 131 - (short) 0xc31f, // (12, 799) 132 - (short) 0xa04f, // (10, 79) 133 - (short) 0xcb1f, // (12, 2847) 134 - (short) 0x80e7, // ( 8, 231) 135 - (short) 0xc71f, // (12, 1823) 136 - (short) 0xb12f, // (11, 303) 137 - (short) 0xcf1f, // (12, 3871) 138 - (short) 0xa24f, // (10, 591) 139 - (short) 0xc09f, // (12, 159) 140 - (short) 0xb52f, // (11, 1327) 141 - (short) 0xc89f, // (12, 2207) 142 - (short) 0xa14f, // (10, 335) 143 - (short) 0xc49f, // (12, 1183) 144 - (short) 0xcc9f, // (12, 3231) 145 - (short) 0xc29f, // (12, 671) 146 - (short) 0xb32f, // (11, 815) 147 - (short) 0xca9f, // (12, 2719) 148 - (short) 0xc69f, // (12, 1695) 149 - (short) 0xce9f, // (12, 3743) 150 - (short) 0xb72f, // (11, 1839) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 11 of 22) (steady 11 of 16) (phase = 0.718750000 = 23.0 / 32.0) - // entropy: 4.4661524304421691411 - // avg_length: 4.5443750890419041255; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x803b, // ( 8, 59) 0 - (short) 0x4006, // ( 4, 6) 1 - (short) 0x601d, // ( 6, 29) 2 - (short) 0x2000, // ( 2, 0) 3 - (short) 0x80bb, // ( 8, 187) 4 - (short) 0x400e, // ( 4, 14) 5 - (short) 0x603d, // ( 6, 61) 6 - (short) 0x3002, // ( 3, 2) 7 - (short) 0x9017, // ( 9, 23) 8 - (short) 0x5005, // ( 5, 5) 9 - (short) 0x807b, // ( 8, 123) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0x9117, // ( 9, 279) 12 - (short) 0x6003, // ( 6, 3) 13 - (short) 0x80fb, // ( 8, 251) 14 - (short) 0x4009, // ( 4, 9) 15 - (short) 0xa177, // (10, 375) 16 - (short) 0x6023, // ( 6, 35) 17 - (short) 0x9097, // ( 9, 151) 18 - (short) 0x5015, // ( 5, 21) 19 - (short) 0xa377, // (10, 887) 20 - (short) 0x702b, // ( 7, 43) 21 - (short) 0x9197, // ( 9, 407) 22 - (short) 0x500d, // ( 5, 13) 23 - (short) 0xb34f, // (11, 847) 24 - (short) 0x8007, // ( 8, 7) 25 - (short) 0xa0f7, // (10, 247) 26 - (short) 0x6013, // ( 6, 19) 27 - (short) 0xc0af, // (12, 175) 28 - (short) 0x8087, // ( 8, 135) 29 - (short) 0xa2f7, // (10, 759) 30 - (short) 0x706b, // ( 7, 107) 31 - (short) 0xb74f, // (11, 1871) 32 - (short) 0x8047, // ( 8, 71) 33 - (short) 0xa1f7, // (10, 503) 34 - (short) 0x6033, // ( 6, 51) 35 - (short) 0xb0cf, // (11, 207) 36 - (short) 0x80c7, // ( 8, 199) 37 - (short) 0xa3f7, // (10, 1015) 38 - (short) 0x600b, // ( 6, 11) 39 - (short) 0xc8af, // (12, 2223) 40 - (short) 0x9057, // ( 9, 87) 41 - (short) 0xb4cf, // (11, 1231) 42 - (short) 0x8027, // ( 8, 39) 43 - (short) 0xc4af, // (12, 1199) 44 - (short) 0x9157, // ( 9, 343) 45 - (short) 0xb2cf, // (11, 719) 46 - (short) 0x80a7, // ( 8, 167) 47 - (short) 0xccaf, // (12, 3247) 48 - (short) 0xa00f, // (10, 15) 49 - (short) 0xc2af, // (12, 687) 50 - (short) 0x90d7, // ( 9, 215) 51 - (short) 0xcaaf, // (12, 2735) 52 - (short) 0xa20f, // (10, 527) 53 - (short) 0xc6af, // (12, 1711) 54 - (short) 0x91d7, // ( 9, 471) 55 - (short) 0xceaf, // (12, 3759) 56 - (short) 0xb6cf, // (11, 1743) 57 - (short) 0xc1af, // (12, 431) 58 - (short) 0xa10f, // (10, 271) 59 - (short) 0xc9af, // (12, 2479) 60 - (short) 0xc5af, // (12, 1455) 61 - (short) 0xcdaf, // (12, 3503) 62 - (short) 0xa30f, // (10, 783) 63 - (short) 0xc3af, // (12, 943) 64 - (short) 0x9037, // ( 9, 55) 65 - (short) 0xb1cf, // (11, 463) 66 - (short) 0x701b, // ( 7, 27) 67 - (short) 0xcbaf, // (12, 2991) 68 - (short) 0x9137, // ( 9, 311) 69 - (short) 0xb5cf, // (11, 1487) 70 - (short) 0x705b, // ( 7, 91) 71 - (short) 0xc7af, // (12, 1967) 72 - (short) 0xa08f, // (10, 143) 73 - (short) 0xcfaf, // (12, 4015) 74 - (short) 0x90b7, // ( 9, 183) 75 - (short) 0xc06f, // (12, 111) 76 - (short) 0xa28f, // (10, 655) 77 - (short) 0xc86f, // (12, 2159) 78 - (short) 0x91b7, // ( 9, 439) 79 - (short) 0xc46f, // (12, 1135) 80 - (short) 0xb3cf, // (11, 975) 81 - (short) 0xcc6f, // (12, 3183) 82 - (short) 0xa18f, // (10, 399) 83 - (short) 0xc26f, // (12, 623) 84 - (short) 0xb7cf, // (11, 1999) 85 - (short) 0xca6f, // (12, 2671) 86 - (short) 0xa38f, // (10, 911) 87 - (short) 0xc66f, // (12, 1647) 88 - (short) 0xce6f, // (12, 3695) 89 - (short) 0xc16f, // (12, 367) 90 - (short) 0xb02f, // (11, 47) 91 - (short) 0xc96f, // (12, 2415) 92 - (short) 0xc56f, // (12, 1391) 93 - (short) 0xcd6f, // (12, 3439) 94 - (short) 0xb42f, // (11, 1071) 95 - (short) 0xc36f, // (12, 879) 96 - (short) 0xcb6f, // (12, 2927) 97 - (short) 0xc76f, // (12, 1903) 98 - (short) 0xb22f, // (11, 559) 99 - (short) 0xcf6f, // (12, 3951) 100 - (short) 0xc0ef, // (12, 239) 101 - (short) 0xc8ef, // (12, 2287) 102 - (short) 0xb62f, // (11, 1583) 103 - (short) 0xc4ef, // (12, 1263) 104 - (short) 0xccef, // (12, 3311) 105 - (short) 0xc2ef, // (12, 751) 106 - (short) 0xcaef, // (12, 2799) 107 - (short) 0xc6ef, // (12, 1775) 108 - (short) 0xceef, // (12, 3823) 109 - (short) 0xc1ef, // (12, 495) 110 - (short) 0xc9ef, // (12, 2543) 111 - (short) 0xc5ef, // (12, 1519) 112 - (short) 0xcdef, // (12, 3567) 113 - (short) 0xc3ef, // (12, 1007) 114 - (short) 0xcbef, // (12, 3055) 115 - (short) 0xc7ef, // (12, 2031) 116 - (short) 0xcfef, // (12, 4079) 117 - (short) 0xc01f, // (12, 31) 118 - (short) 0xc81f, // (12, 2079) 119 - (short) 0xc41f, // (12, 1055) 120 - (short) 0xcc1f, // (12, 3103) 121 - (short) 0xc21f, // (12, 543) 122 - (short) 0xca1f, // (12, 2591) 123 - (short) 0xc61f, // (12, 1567) 124 - (short) 0xce1f, // (12, 3615) 125 - (short) 0xc11f, // (12, 287) 126 - (short) 0xc91f, // (12, 2335) 127 - (short) 0xc51f, // (12, 1311) 128 - (short) 0xa04f, // (10, 79) 129 - (short) 0xcd1f, // (12, 3359) 130 - (short) 0x8067, // ( 8, 103) 131 - (short) 0xc31f, // (12, 799) 132 - (short) 0xa24f, // (10, 591) 133 - (short) 0xcb1f, // (12, 2847) 134 - (short) 0x80e7, // ( 8, 231) 135 - (short) 0xc71f, // (12, 1823) 136 - (short) 0xb12f, // (11, 303) 137 - (short) 0xcf1f, // (12, 3871) 138 - (short) 0x9077, // ( 9, 119) 139 - (short) 0xc09f, // (12, 159) 140 - (short) 0xb52f, // (11, 1327) 141 - (short) 0xc89f, // (12, 2207) 142 - (short) 0xa14f, // (10, 335) 143 - (short) 0xc49f, // (12, 1183) 144 - (short) 0xcc9f, // (12, 3231) 145 - (short) 0xc29f, // (12, 671) 146 - (short) 0xb32f, // (11, 815) 147 - (short) 0xca9f, // (12, 2719) 148 - (short) 0xc69f, // (12, 1695) 149 - (short) 0xce9f, // (12, 3743) 150 - (short) 0xb72f, // (11, 1839) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 12 of 22) (steady 12 of 16) (phase = 0.781250000 = 25.0 / 32.0) - // entropy: 4.4680486273043946710 - // avg_length: 4.5521643785256946657; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x807b, // ( 8, 123) 0 - (short) 0x4006, // ( 4, 6) 1 - (short) 0x601d, // ( 6, 29) 2 - (short) 0x2000, // ( 2, 0) 3 - (short) 0x80fb, // ( 8, 251) 4 - (short) 0x400e, // ( 4, 14) 5 - (short) 0x700b, // ( 7, 11) 6 - (short) 0x3002, // ( 3, 2) 7 - (short) 0x9097, // ( 9, 151) 8 - (short) 0x5005, // ( 5, 5) 9 - (short) 0x8007, // ( 8, 7) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0x9197, // ( 9, 407) 12 - (short) 0x603d, // ( 6, 61) 13 - (short) 0x8087, // ( 8, 135) 14 - (short) 0x4009, // ( 4, 9) 15 - (short) 0xa177, // (10, 375) 16 - (short) 0x704b, // ( 7, 75) 17 - (short) 0x9057, // ( 9, 87) 18 - (short) 0x5015, // ( 5, 21) 19 - (short) 0xb34f, // (11, 847) 20 - (short) 0x702b, // ( 7, 43) 21 - (short) 0x9157, // ( 9, 343) 22 - (short) 0x500d, // ( 5, 13) 23 - (short) 0xc72f, // (12, 1839) 24 - (short) 0x8047, // ( 8, 71) 25 - (short) 0xa377, // (10, 887) 26 - (short) 0x6003, // ( 6, 3) 27 - (short) 0xcf2f, // (12, 3887) 28 - (short) 0x80c7, // ( 8, 199) 29 - (short) 0xa0f7, // (10, 247) 30 - (short) 0x6023, // ( 6, 35) 31 - (short) 0xc0af, // (12, 175) 32 - (short) 0x8027, // ( 8, 39) 33 - (short) 0xa2f7, // (10, 759) 34 - (short) 0x6013, // ( 6, 19) 35 - (short) 0xc8af, // (12, 2223) 36 - (short) 0x80a7, // ( 8, 167) 37 - (short) 0xa1f7, // (10, 503) 38 - (short) 0x6033, // ( 6, 51) 39 - (short) 0xc4af, // (12, 1199) 40 - (short) 0x90d7, // ( 9, 215) 41 - (short) 0xb74f, // (11, 1871) 42 - (short) 0x706b, // ( 7, 107) 43 - (short) 0xccaf, // (12, 3247) 44 - (short) 0x91d7, // ( 9, 471) 45 - (short) 0xb0cf, // (11, 207) 46 - (short) 0x701b, // ( 7, 27) 47 - (short) 0xc2af, // (12, 687) 48 - (short) 0xa3f7, // (10, 1015) 49 - (short) 0xcaaf, // (12, 2735) 50 - (short) 0x9037, // ( 9, 55) 51 - (short) 0xc6af, // (12, 1711) 52 - (short) 0xa00f, // (10, 15) 53 - (short) 0xceaf, // (12, 3759) 54 - (short) 0x9137, // ( 9, 311) 55 - (short) 0xc1af, // (12, 431) 56 - (short) 0xb4cf, // (11, 1231) 57 - (short) 0xc9af, // (12, 2479) 58 - (short) 0xa20f, // (10, 527) 59 - (short) 0xc5af, // (12, 1455) 60 - (short) 0xb2cf, // (11, 719) 61 - (short) 0xcdaf, // (12, 3503) 62 - (short) 0xa10f, // (10, 271) 63 - (short) 0xc3af, // (12, 943) 64 - (short) 0x90b7, // ( 9, 183) 65 - (short) 0xb6cf, // (11, 1743) 66 - (short) 0x705b, // ( 7, 91) 67 - (short) 0xcbaf, // (12, 2991) 68 - (short) 0x91b7, // ( 9, 439) 69 - (short) 0xb1cf, // (11, 463) 70 - (short) 0x703b, // ( 7, 59) 71 - (short) 0xc7af, // (12, 1967) 72 - (short) 0xa30f, // (10, 783) 73 - (short) 0xcfaf, // (12, 4015) 74 - (short) 0x8067, // ( 8, 103) 75 - (short) 0xc06f, // (12, 111) 76 - (short) 0xa08f, // (10, 143) 77 - (short) 0xc86f, // (12, 2159) 78 - (short) 0x9077, // ( 9, 119) 79 - (short) 0xc46f, // (12, 1135) 80 - (short) 0xb5cf, // (11, 1487) 81 - (short) 0xcc6f, // (12, 3183) 82 - (short) 0xa28f, // (10, 655) 83 - (short) 0xc26f, // (12, 623) 84 - (short) 0xb3cf, // (11, 975) 85 - (short) 0xca6f, // (12, 2671) 86 - (short) 0xa18f, // (10, 399) 87 - (short) 0xc66f, // (12, 1647) 88 - (short) 0xce6f, // (12, 3695) 89 - (short) 0xc16f, // (12, 367) 90 - (short) 0xb7cf, // (11, 1999) 91 - (short) 0xc96f, // (12, 2415) 92 - (short) 0xc56f, // (12, 1391) 93 - (short) 0xcd6f, // (12, 3439) 94 - (short) 0xb02f, // (11, 47) 95 - (short) 0xc36f, // (12, 879) 96 - (short) 0xcb6f, // (12, 2927) 97 - (short) 0xc76f, // (12, 1903) 98 - (short) 0xb42f, // (11, 1071) 99 - (short) 0xcf6f, // (12, 3951) 100 - (short) 0xc0ef, // (12, 239) 101 - (short) 0xc8ef, // (12, 2287) 102 - (short) 0xb22f, // (11, 559) 103 - (short) 0xc4ef, // (12, 1263) 104 - (short) 0xccef, // (12, 3311) 105 - (short) 0xc2ef, // (12, 751) 106 - (short) 0xcaef, // (12, 2799) 107 - (short) 0xc6ef, // (12, 1775) 108 - (short) 0xceef, // (12, 3823) 109 - (short) 0xc1ef, // (12, 495) 110 - (short) 0xc9ef, // (12, 2543) 111 - (short) 0xc5ef, // (12, 1519) 112 - (short) 0xcdef, // (12, 3567) 113 - (short) 0xc3ef, // (12, 1007) 114 - (short) 0xcbef, // (12, 3055) 115 - (short) 0xc7ef, // (12, 2031) 116 - (short) 0xcfef, // (12, 4079) 117 - (short) 0xc01f, // (12, 31) 118 - (short) 0xc81f, // (12, 2079) 119 - (short) 0xc41f, // (12, 1055) 120 - (short) 0xcc1f, // (12, 3103) 121 - (short) 0xc21f, // (12, 543) 122 - (short) 0xca1f, // (12, 2591) 123 - (short) 0xc61f, // (12, 1567) 124 - (short) 0xce1f, // (12, 3615) 125 - (short) 0xc11f, // (12, 287) 126 - (short) 0xc91f, // (12, 2335) 127 - (short) 0xc51f, // (12, 1311) 128 - (short) 0xa38f, // (10, 911) 129 - (short) 0xcd1f, // (12, 3359) 130 - (short) 0x80e7, // ( 8, 231) 131 - (short) 0xc31f, // (12, 799) 132 - (short) 0xa04f, // (10, 79) 133 - (short) 0xcb1f, // (12, 2847) 134 - (short) 0x8017, // ( 8, 23) 135 - (short) 0xc71f, // (12, 1823) 136 - (short) 0xb62f, // (11, 1583) 137 - (short) 0xcf1f, // (12, 3871) 138 - (short) 0xa24f, // (10, 591) 139 - (short) 0xc09f, // (12, 159) 140 - (short) 0xb12f, // (11, 303) 141 - (short) 0xc89f, // (12, 2207) 142 - (short) 0xa14f, // (10, 335) 143 - (short) 0xc49f, // (12, 1183) 144 - (short) 0xcc9f, // (12, 3231) 145 - (short) 0xc29f, // (12, 671) 146 - (short) 0xb52f, // (11, 1327) 147 - (short) 0xca9f, // (12, 2719) 148 - (short) 0xc69f, // (12, 1695) 149 - (short) 0xce9f, // (12, 3743) 150 - (short) 0xb32f, // (11, 815) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 13 of 22) (steady 13 of 16) (phase = 0.843750000 = 27.0 / 32.0) - // entropy: 4.4684687952964843305 - // avg_length: 4.5509169030369793774; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x803b, // ( 8, 59) 0 - (short) 0x4006, // ( 4, 6) 1 - (short) 0x7033, // ( 7, 51) 2 - (short) 0x3002, // ( 3, 2) 3 - (short) 0x80bb, // ( 8, 187) 4 - (short) 0x400e, // ( 4, 14) 5 - (short) 0x7073, // ( 7, 115) 6 - (short) 0x2000, // ( 2, 0) 7 - (short) 0xa0f7, // (10, 247) 8 - (short) 0x601d, // ( 6, 29) 9 - (short) 0x807b, // ( 8, 123) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0xa2f7, // (10, 759) 12 - (short) 0x5005, // ( 5, 5) 13 - (short) 0x80fb, // ( 8, 251) 14 - (short) 0x4009, // ( 4, 9) 15 - (short) 0xb34f, // (11, 847) 16 - (short) 0x700b, // ( 7, 11) 17 - (short) 0x9057, // ( 9, 87) 18 - (short) 0x5015, // ( 5, 21) 19 - (short) 0xb74f, // (11, 1871) 20 - (short) 0x704b, // ( 7, 75) 21 - (short) 0x9157, // ( 9, 343) 22 - (short) 0x500d, // ( 5, 13) 23 - (short) 0xc72f, // (12, 1839) 24 - (short) 0x8007, // ( 8, 7) 25 - (short) 0xa1f7, // (10, 503) 26 - (short) 0x603d, // ( 6, 61) 27 - (short) 0xcf2f, // (12, 3887) 28 - (short) 0x8087, // ( 8, 135) 29 - (short) 0xa3f7, // (10, 1015) 30 - (short) 0x6003, // ( 6, 3) 31 - (short) 0xc0af, // (12, 175) 32 - (short) 0x8047, // ( 8, 71) 33 - (short) 0xa00f, // (10, 15) 34 - (short) 0x6023, // ( 6, 35) 35 - (short) 0xc8af, // (12, 2223) 36 - (short) 0x80c7, // ( 8, 199) 37 - (short) 0xa20f, // (10, 527) 38 - (short) 0x6013, // ( 6, 19) 39 - (short) 0xc4af, // (12, 1199) 40 - (short) 0x90d7, // ( 9, 215) 41 - (short) 0xb0cf, // (11, 207) 42 - (short) 0x702b, // ( 7, 43) 43 - (short) 0xccaf, // (12, 3247) 44 - (short) 0x91d7, // ( 9, 471) 45 - (short) 0xb4cf, // (11, 1231) 46 - (short) 0x706b, // ( 7, 107) 47 - (short) 0xc2af, // (12, 687) 48 - (short) 0xa10f, // (10, 271) 49 - (short) 0xcaaf, // (12, 2735) 50 - (short) 0x8027, // ( 8, 39) 51 - (short) 0xc6af, // (12, 1711) 52 - (short) 0xa30f, // (10, 783) 53 - (short) 0xceaf, // (12, 3759) 54 - (short) 0x80a7, // ( 8, 167) 55 - (short) 0xc1af, // (12, 431) 56 - (short) 0xb2cf, // (11, 719) 57 - (short) 0xc9af, // (12, 2479) 58 - (short) 0xa08f, // (10, 143) 59 - (short) 0xc5af, // (12, 1455) 60 - (short) 0xb6cf, // (11, 1743) 61 - (short) 0xcdaf, // (12, 3503) 62 - (short) 0xa28f, // (10, 655) 63 - (short) 0xc3af, // (12, 943) 64 - (short) 0x9037, // ( 9, 55) 65 - (short) 0xb1cf, // (11, 463) 66 - (short) 0x701b, // ( 7, 27) 67 - (short) 0xcbaf, // (12, 2991) 68 - (short) 0x9137, // ( 9, 311) 69 - (short) 0xb5cf, // (11, 1487) 70 - (short) 0x705b, // ( 7, 91) 71 - (short) 0xc7af, // (12, 1967) 72 - (short) 0xa18f, // (10, 399) 73 - (short) 0xcfaf, // (12, 4015) 74 - (short) 0x8067, // ( 8, 103) 75 - (short) 0xc06f, // (12, 111) 76 - (short) 0xa38f, // (10, 911) 77 - (short) 0xc86f, // (12, 2159) 78 - (short) 0x80e7, // ( 8, 231) 79 - (short) 0xc46f, // (12, 1135) 80 - (short) 0xb3cf, // (11, 975) 81 - (short) 0xcc6f, // (12, 3183) 82 - (short) 0x90b7, // ( 9, 183) 83 - (short) 0xc26f, // (12, 623) 84 - (short) 0xb7cf, // (11, 1999) 85 - (short) 0xca6f, // (12, 2671) 86 - (short) 0x91b7, // ( 9, 439) 87 - (short) 0xc66f, // (12, 1647) 88 - (short) 0xce6f, // (12, 3695) 89 - (short) 0xc16f, // (12, 367) 90 - (short) 0xb02f, // (11, 47) 91 - (short) 0xc96f, // (12, 2415) 92 - (short) 0xc56f, // (12, 1391) 93 - (short) 0xcd6f, // (12, 3439) 94 - (short) 0xb42f, // (11, 1071) 95 - (short) 0xc36f, // (12, 879) 96 - (short) 0xcb6f, // (12, 2927) 97 - (short) 0xc76f, // (12, 1903) 98 - (short) 0xb22f, // (11, 559) 99 - (short) 0xcf6f, // (12, 3951) 100 - (short) 0xc0ef, // (12, 239) 101 - (short) 0xc8ef, // (12, 2287) 102 - (short) 0xb62f, // (11, 1583) 103 - (short) 0xc4ef, // (12, 1263) 104 - (short) 0xccef, // (12, 3311) 105 - (short) 0xc2ef, // (12, 751) 106 - (short) 0xcaef, // (12, 2799) 107 - (short) 0xc6ef, // (12, 1775) 108 - (short) 0xceef, // (12, 3823) 109 - (short) 0xc1ef, // (12, 495) 110 - (short) 0xc9ef, // (12, 2543) 111 - (short) 0xc5ef, // (12, 1519) 112 - (short) 0xcdef, // (12, 3567) 113 - (short) 0xc3ef, // (12, 1007) 114 - (short) 0xcbef, // (12, 3055) 115 - (short) 0xc7ef, // (12, 2031) 116 - (short) 0xcfef, // (12, 4079) 117 - (short) 0xc01f, // (12, 31) 118 - (short) 0xc81f, // (12, 2079) 119 - (short) 0xc41f, // (12, 1055) 120 - (short) 0xcc1f, // (12, 3103) 121 - (short) 0xc21f, // (12, 543) 122 - (short) 0xca1f, // (12, 2591) 123 - (short) 0xc61f, // (12, 1567) 124 - (short) 0xce1f, // (12, 3615) 125 - (short) 0xc11f, // (12, 287) 126 - (short) 0xc91f, // (12, 2335) 127 - (short) 0xc51f, // (12, 1311) 128 - (short) 0xa04f, // (10, 79) 129 - (short) 0xcd1f, // (12, 3359) 130 - (short) 0x8017, // ( 8, 23) 131 - (short) 0xc31f, // (12, 799) 132 - (short) 0xa24f, // (10, 591) 133 - (short) 0xcb1f, // (12, 2847) 134 - (short) 0x8097, // ( 8, 151) 135 - (short) 0xc71f, // (12, 1823) 136 - (short) 0xb12f, // (11, 303) 137 - (short) 0xcf1f, // (12, 3871) 138 - (short) 0x9077, // ( 9, 119) 139 - (short) 0xc09f, // (12, 159) 140 - (short) 0xb52f, // (11, 1327) 141 - (short) 0xc89f, // (12, 2207) 142 - (short) 0x9177, // ( 9, 375) 143 - (short) 0xc49f, // (12, 1183) 144 - (short) 0xcc9f, // (12, 3231) 145 - (short) 0xc29f, // (12, 671) 146 - (short) 0xb32f, // (11, 815) 147 - (short) 0xca9f, // (12, 2719) 148 - (short) 0xc69f, // (12, 1695) 149 - (short) 0xce9f, // (12, 3743) 150 - (short) 0xa14f, // (10, 335) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 14 of 22) (steady 14 of 16) (phase = 0.906250000 = 29.0 / 32.0) - // entropy: 4.4675179140944036860 - // avg_length: 4.5477235350841240802; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x9017, // ( 9, 23) 0 - (short) 0x4006, // ( 4, 6) 1 - (short) 0x7033, // ( 7, 51) 2 - (short) 0x3002, // ( 3, 2) 3 - (short) 0x9117, // ( 9, 279) 4 - (short) 0x400e, // ( 4, 14) 5 - (short) 0x7073, // ( 7, 115) 6 - (short) 0x2000, // ( 2, 0) 7 - (short) 0xa177, // (10, 375) 8 - (short) 0x601d, // ( 6, 29) 9 - (short) 0x803b, // ( 8, 59) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0xa377, // (10, 887) 12 - (short) 0x5005, // ( 5, 5) 13 - (short) 0x80bb, // ( 8, 187) 14 - (short) 0x4009, // ( 4, 9) 15 - (short) 0xb0cf, // (11, 207) 16 - (short) 0x700b, // ( 7, 11) 17 - (short) 0x9097, // ( 9, 151) 18 - (short) 0x5015, // ( 5, 21) 19 - (short) 0xb4cf, // (11, 1231) 20 - (short) 0x704b, // ( 7, 75) 21 - (short) 0x9197, // ( 9, 407) 22 - (short) 0x500d, // ( 5, 13) 23 - (short) 0xc4af, // (12, 1199) 24 - (short) 0x807b, // ( 8, 123) 25 - (short) 0xa0f7, // (10, 247) 26 - (short) 0x603d, // ( 6, 61) 27 - (short) 0xccaf, // (12, 3247) 28 - (short) 0x80fb, // ( 8, 251) 29 - (short) 0xa2f7, // (10, 759) 30 - (short) 0x6003, // ( 6, 3) 31 - (short) 0xc2af, // (12, 687) 32 - (short) 0x8007, // ( 8, 7) 33 - (short) 0xa1f7, // (10, 503) 34 - (short) 0x6023, // ( 6, 35) 35 - (short) 0xcaaf, // (12, 2735) 36 - (short) 0x8087, // ( 8, 135) 37 - (short) 0xa3f7, // (10, 1015) 38 - (short) 0x6013, // ( 6, 19) 39 - (short) 0xc6af, // (12, 1711) 40 - (short) 0x9057, // ( 9, 87) 41 - (short) 0xb2cf, // (11, 719) 42 - (short) 0x702b, // ( 7, 43) 43 - (short) 0xceaf, // (12, 3759) 44 - (short) 0x9157, // ( 9, 343) 45 - (short) 0xb6cf, // (11, 1743) 46 - (short) 0x706b, // ( 7, 107) 47 - (short) 0xc1af, // (12, 431) 48 - (short) 0xa00f, // (10, 15) 49 - (short) 0xc9af, // (12, 2479) 50 - (short) 0x8047, // ( 8, 71) 51 - (short) 0xc5af, // (12, 1455) 52 - (short) 0xa20f, // (10, 527) 53 - (short) 0xcdaf, // (12, 3503) 54 - (short) 0x80c7, // ( 8, 199) 55 - (short) 0xc3af, // (12, 943) 56 - (short) 0xb1cf, // (11, 463) 57 - (short) 0xcbaf, // (12, 2991) 58 - (short) 0xa10f, // (10, 271) 59 - (short) 0xc7af, // (12, 1967) 60 - (short) 0xb5cf, // (11, 1487) 61 - (short) 0xcfaf, // (12, 4015) 62 - (short) 0x90d7, // ( 9, 215) 63 - (short) 0xc06f, // (12, 111) 64 - (short) 0x91d7, // ( 9, 471) 65 - (short) 0xb3cf, // (11, 975) 66 - (short) 0x701b, // ( 7, 27) 67 - (short) 0xc86f, // (12, 2159) 68 - (short) 0x9037, // ( 9, 55) 69 - (short) 0xb7cf, // (11, 1999) 70 - (short) 0x705b, // ( 7, 91) 71 - (short) 0xc46f, // (12, 1135) 72 - (short) 0xa30f, // (10, 783) 73 - (short) 0xcc6f, // (12, 3183) 74 - (short) 0x8027, // ( 8, 39) 75 - (short) 0xc26f, // (12, 623) 76 - (short) 0xa08f, // (10, 143) 77 - (short) 0xca6f, // (12, 2671) 78 - (short) 0x80a7, // ( 8, 167) 79 - (short) 0xc66f, // (12, 1647) 80 - (short) 0xb02f, // (11, 47) 81 - (short) 0xce6f, // (12, 3695) 82 - (short) 0x9137, // ( 9, 311) 83 - (short) 0xc16f, // (12, 367) 84 - (short) 0xb42f, // (11, 1071) 85 - (short) 0xc96f, // (12, 2415) 86 - (short) 0x90b7, // ( 9, 183) 87 - (short) 0xc56f, // (12, 1391) 88 - (short) 0xcd6f, // (12, 3439) 89 - (short) 0xc36f, // (12, 879) 90 - (short) 0xb22f, // (11, 559) 91 - (short) 0xcb6f, // (12, 2927) 92 - (short) 0xc76f, // (12, 1903) 93 - (short) 0xcf6f, // (12, 3951) 94 - (short) 0xa28f, // (10, 655) 95 - (short) 0xc0ef, // (12, 239) 96 - (short) 0xc8ef, // (12, 2287) 97 - (short) 0xc4ef, // (12, 1263) 98 - (short) 0xa18f, // (10, 399) 99 - (short) 0xccef, // (12, 3311) 100 - (short) 0xc2ef, // (12, 751) 101 - (short) 0xcaef, // (12, 2799) 102 - (short) 0xa38f, // (10, 911) 103 - (short) 0xc6ef, // (12, 1775) 104 - (short) 0xceef, // (12, 3823) 105 - (short) 0xc1ef, // (12, 495) 106 - (short) 0xc9ef, // (12, 2543) 107 - (short) 0xc5ef, // (12, 1519) 108 - (short) 0xcdef, // (12, 3567) 109 - (short) 0xc3ef, // (12, 1007) 110 - (short) 0xb62f, // (11, 1583) 111 - (short) 0xcbef, // (12, 3055) 112 - (short) 0xc7ef, // (12, 2031) 113 - (short) 0xcfef, // (12, 4079) 114 - (short) 0xc01f, // (12, 31) 115 - (short) 0xc81f, // (12, 2079) 116 - (short) 0xc41f, // (12, 1055) 117 - (short) 0xcc1f, // (12, 3103) 118 - (short) 0xc21f, // (12, 543) 119 - (short) 0xca1f, // (12, 2591) 120 - (short) 0xc61f, // (12, 1567) 121 - (short) 0xce1f, // (12, 3615) 122 - (short) 0xc11f, // (12, 287) 123 - (short) 0xc91f, // (12, 2335) 124 - (short) 0xc51f, // (12, 1311) 125 - (short) 0xcd1f, // (12, 3359) 126 - (short) 0xc31f, // (12, 799) 127 - (short) 0xcb1f, // (12, 2847) 128 - (short) 0xa04f, // (10, 79) 129 - (short) 0xc71f, // (12, 1823) 130 - (short) 0x8067, // ( 8, 103) 131 - (short) 0xcf1f, // (12, 3871) 132 - (short) 0xa24f, // (10, 591) 133 - (short) 0xc09f, // (12, 159) 134 - (short) 0x80e7, // ( 8, 231) 135 - (short) 0xc89f, // (12, 2207) 136 - (short) 0xb12f, // (11, 303) 137 - (short) 0xc49f, // (12, 1183) 138 - (short) 0x91b7, // ( 9, 439) 139 - (short) 0xcc9f, // (12, 3231) 140 - (short) 0xb52f, // (11, 1327) 141 - (short) 0xc29f, // (12, 671) 142 - (short) 0x9077, // ( 9, 119) 143 - (short) 0xca9f, // (12, 2719) 144 - (short) 0xc69f, // (12, 1695) 145 - (short) 0xce9f, // (12, 3743) 146 - (short) 0xa14f, // (10, 335) 147 - (short) 0xc19f, // (12, 415) 148 - (short) 0xc99f, // (12, 2463) 149 - (short) 0xc59f, // (12, 1439) 150 - (short) 0xa34f, // (10, 847) 151 - (short) 0xcd9f, // (12, 3487) 152 - (short) 0xc39f, // (12, 927) 153 - (short) 0xcb9f, // (12, 2975) 154 - (short) 0xc79f, // (12, 1951) 155 - (short) 0xcf9f, // (12, 3999) 156 - (short) 0xc05f, // (12, 95) 157 - (short) 0xc85f, // (12, 2143) 158 - (short) 0xb32f, // (11, 815) 159 - (short) 0xc45f, // (12, 1119) 160 - (short) 0xcc5f, // (12, 3167) 161 - (short) 0xc25f, // (12, 607) 162 - (short) 0xb72f, // (11, 1839) 163 - (short) 0xca5f, // (12, 2655) 164 - (short) 0xc65f, // (12, 1631) 165 - (short) 0xce5f, // (12, 3679) 166 - (short) 0xb0af, // (11, 175) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 15 of 22) (steady 15 of 16) (phase = 0.968750000 = 31.0 / 32.0) - // entropy: 4.4653007097343397902 - // avg_length: 4.5480722016259509388; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x9017, // ( 9, 23) 0 - (short) 0x4006, // ( 4, 6) 1 - (short) 0x7033, // ( 7, 51) 2 - (short) 0x3002, // ( 3, 2) 3 - (short) 0x9117, // ( 9, 279) 4 - (short) 0x400e, // ( 4, 14) 5 - (short) 0x7073, // ( 7, 115) 6 - (short) 0x2000, // ( 2, 0) 7 - (short) 0xa0f7, // (10, 247) 8 - (short) 0x601d, // ( 6, 29) 9 - (short) 0x803b, // ( 8, 59) 10 - (short) 0x4001, // ( 4, 1) 11 - (short) 0xa2f7, // (10, 759) 12 - (short) 0x5005, // ( 5, 5) 13 - (short) 0x80bb, // ( 8, 187) 14 - (short) 0x4009, // ( 4, 9) 15 - (short) 0xb0cf, // (11, 207) 16 - (short) 0x700b, // ( 7, 11) 17 - (short) 0x9097, // ( 9, 151) 18 - (short) 0x5015, // ( 5, 21) 19 - (short) 0xb4cf, // (11, 1231) 20 - (short) 0x704b, // ( 7, 75) 21 - (short) 0x9197, // ( 9, 407) 22 - (short) 0x500d, // ( 5, 13) 23 - (short) 0xc0af, // (12, 175) 24 - (short) 0x807b, // ( 8, 123) 25 - (short) 0xb2cf, // (11, 719) 26 - (short) 0x603d, // ( 6, 61) 27 - (short) 0xc8af, // (12, 2223) 28 - (short) 0x80fb, // ( 8, 251) 29 - (short) 0xa1f7, // (10, 503) 30 - (short) 0x6003, // ( 6, 3) 31 - (short) 0xc4af, // (12, 1199) 32 - (short) 0x8007, // ( 8, 7) 33 - (short) 0xb6cf, // (11, 1743) 34 - (short) 0x6023, // ( 6, 35) 35 - (short) 0xccaf, // (12, 3247) 36 - (short) 0x8087, // ( 8, 135) 37 - (short) 0xa3f7, // (10, 1015) 38 - (short) 0x6013, // ( 6, 19) 39 - (short) 0xc2af, // (12, 687) 40 - (short) 0x9057, // ( 9, 87) 41 - (short) 0xcaaf, // (12, 2735) 42 - (short) 0x702b, // ( 7, 43) 43 - (short) 0xc6af, // (12, 1711) 44 - (short) 0x9157, // ( 9, 343) 45 - (short) 0xb1cf, // (11, 463) 46 - (short) 0x706b, // ( 7, 107) 47 - (short) 0xceaf, // (12, 3759) 48 - (short) 0xa00f, // (10, 15) 49 - (short) 0xc1af, // (12, 431) 50 - (short) 0x8047, // ( 8, 71) 51 - (short) 0xc9af, // (12, 2479) 52 - (short) 0xa20f, // (10, 527) 53 - (short) 0xc5af, // (12, 1455) 54 - (short) 0x80c7, // ( 8, 199) 55 - (short) 0xcdaf, // (12, 3503) 56 - (short) 0xb5cf, // (11, 1487) 57 - (short) 0xc3af, // (12, 943) 58 - (short) 0x90d7, // ( 9, 215) 59 - (short) 0xcbaf, // (12, 2991) 60 - (short) 0xb3cf, // (11, 975) 61 - (short) 0xc7af, // (12, 1967) 62 - (short) 0x91d7, // ( 9, 471) 63 - (short) 0xcfaf, // (12, 4015) 64 - (short) 0x9037, // ( 9, 55) 65 - (short) 0xc06f, // (12, 111) 66 - (short) 0x701b, // ( 7, 27) 67 - (short) 0xc86f, // (12, 2159) 68 - (short) 0x9137, // ( 9, 311) 69 - (short) 0xb7cf, // (11, 1999) 70 - (short) 0x705b, // ( 7, 91) 71 - (short) 0xc46f, // (12, 1135) 72 - (short) 0xa10f, // (10, 271) 73 - (short) 0xcc6f, // (12, 3183) 74 - (short) 0x8027, // ( 8, 39) 75 - (short) 0xc26f, // (12, 623) 76 - (short) 0xa30f, // (10, 783) 77 - (short) 0xca6f, // (12, 2671) 78 - (short) 0x80a7, // ( 8, 167) 79 - (short) 0xc66f, // (12, 1647) 80 - (short) 0xb02f, // (11, 47) 81 - (short) 0xce6f, // (12, 3695) 82 - (short) 0x90b7, // ( 9, 183) 83 - (short) 0xc16f, // (12, 367) 84 - (short) 0xb42f, // (11, 1071) 85 - (short) 0xc96f, // (12, 2415) 86 - (short) 0x91b7, // ( 9, 439) 87 - (short) 0xc56f, // (12, 1391) 88 - (short) 0xcd6f, // (12, 3439) 89 - (short) 0xc36f, // (12, 879) 90 - (short) 0xa08f, // (10, 143) 91 - (short) 0xcb6f, // (12, 2927) 92 - (short) 0xc76f, // (12, 1903) 93 - (short) 0xcf6f, // (12, 3951) 94 - (short) 0xa28f, // (10, 655) 95 - (short) 0xc0ef, // (12, 239) 96 - (short) 0xc8ef, // (12, 2287) 97 - (short) 0xc4ef, // (12, 1263) 98 - (short) 0xa18f, // (10, 399) 99 - (short) 0xccef, // (12, 3311) 100 - (short) 0xc2ef, // (12, 751) 101 - (short) 0xcaef, // (12, 2799) 102 - (short) 0xa38f, // (10, 911) 103 - (short) 0xc6ef, // (12, 1775) 104 - (short) 0xceef, // (12, 3823) 105 - (short) 0xc1ef, // (12, 495) 106 - (short) 0xc9ef, // (12, 2543) 107 - (short) 0xc5ef, // (12, 1519) 108 - (short) 0xcdef, // (12, 3567) 109 - (short) 0xc3ef, // (12, 1007) 110 - (short) 0xb22f, // (11, 559) 111 - (short) 0xcbef, // (12, 3055) 112 - (short) 0xc7ef, // (12, 2031) 113 - (short) 0xcfef, // (12, 4079) 114 - (short) 0xc01f, // (12, 31) 115 - (short) 0xc81f, // (12, 2079) 116 - (short) 0xc41f, // (12, 1055) 117 - (short) 0xcc1f, // (12, 3103) 118 - (short) 0xc21f, // (12, 543) 119 - (short) 0xca1f, // (12, 2591) 120 - (short) 0xc61f, // (12, 1567) 121 - (short) 0xce1f, // (12, 3615) 122 - (short) 0xc11f, // (12, 287) 123 - (short) 0xc91f, // (12, 2335) 124 - (short) 0xc51f, // (12, 1311) 125 - (short) 0xcd1f, // (12, 3359) 126 - (short) 0xc31f, // (12, 799) 127 - (short) 0xcb1f, // (12, 2847) 128 - (short) 0xa04f, // (10, 79) 129 - (short) 0xc71f, // (12, 1823) 130 - (short) 0x8067, // ( 8, 103) 131 - (short) 0xcf1f, // (12, 3871) 132 - (short) 0xa24f, // (10, 591) 133 - (short) 0xc09f, // (12, 159) 134 - (short) 0x80e7, // ( 8, 231) 135 - (short) 0xc89f, // (12, 2207) 136 - (short) 0xb62f, // (11, 1583) 137 - (short) 0xc49f, // (12, 1183) 138 - (short) 0x9077, // ( 9, 119) 139 - (short) 0xcc9f, // (12, 3231) 140 - (short) 0xb12f, // (11, 303) 141 - (short) 0xc29f, // (12, 671) 142 - (short) 0x9177, // ( 9, 375) 143 - (short) 0xca9f, // (12, 2719) 144 - (short) 0xc69f, // (12, 1695) 145 - (short) 0xce9f, // (12, 3743) 146 - (short) 0xa14f, // (10, 335) 147 - (short) 0xc19f, // (12, 415) 148 - (short) 0xc99f, // (12, 2463) 149 - (short) 0xc59f, // (12, 1439) 150 - (short) 0xa34f, // (10, 847) 151 - (short) 0xcd9f, // (12, 3487) 152 - (short) 0xc39f, // (12, 927) 153 - (short) 0xcb9f, // (12, 2975) 154 - (short) 0xc79f, // (12, 1951) 155 - (short) 0xcf9f, // (12, 3999) 156 - (short) 0xc05f, // (12, 95) 157 - (short) 0xc85f, // (12, 2143) 158 - (short) 0xb52f, // (11, 1327) 159 - (short) 0xc45f, // (12, 1119) 160 - (short) 0xcc5f, // (12, 3167) 161 - (short) 0xc25f, // (12, 607) 162 - (short) 0xb32f, // (11, 815) 163 - (short) 0xca5f, // (12, 2655) 164 - (short) 0xc65f, // (12, 1631) 165 - (short) 0xce5f, // (12, 3679) 166 - (short) 0xb72f, // (11, 1839) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // Six Encoding Tables for the Midrange. - - // (table 16 of 22) (midrange 0 of 6) (c/k = 0.500000000 = 3.0 / 6.0) - // entropy: 2.1627885076675394949 - // avg_length: 2.2704182849800043087; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x1000, // ( 1, 0) 0 - (short) 0x2001, // ( 2, 1) 1 - (short) 0x4003, // ( 4, 3) 2 - (short) 0x500b, // ( 5, 11) 3 - (short) 0x501b, // ( 5, 27) 4 - (short) 0x6007, // ( 6, 7) 5 - (short) 0x8057, // ( 8, 87) 6 - (short) 0x9077, // ( 9, 119) 7 - (short) 0x6027, // ( 6, 39) 8 - (short) 0x80d7, // ( 8, 215) 9 - (short) 0x9177, // ( 9, 375) 10 - (short) 0xa1f7, // (10, 503) 11 - (short) 0xa3f7, // (10, 1015) 12 - (short) 0xb08f, // (11, 143) 13 - (short) 0xc58f, // (12, 1423) 14 - (short) 0xcd8f, // (12, 3471) 15 - (short) 0x7017, // ( 7, 23) 16 - (short) 0x8037, // ( 8, 55) 17 - (short) 0xa00f, // (10, 15) 18 - (short) 0xb48f, // (11, 1167) 19 - (short) 0xb28f, // (11, 655) 20 - (short) 0xc38f, // (12, 911) 21 - (short) 0xcb8f, // (12, 2959) 22 - (short) 0xc78f, // (12, 1935) 23 - (short) 0xcf8f, // (12, 3983) 24 - (short) 0xc04f, // (12, 79) 25 - (short) 0xc84f, // (12, 2127) 26 - (short) 0xc44f, // (12, 1103) 27 - (short) 0xcc4f, // (12, 3151) 28 - (short) 0xc24f, // (12, 591) 29 - (short) 0xca4f, // (12, 2639) 30 - (short) 0xc64f, // (12, 1615) 31 - (short) 0x80b7, // ( 8, 183) 32 - (short) 0xa20f, // (10, 527) 33 - (short) 0xb68f, // (11, 1679) 34 - (short) 0xce4f, // (12, 3663) 35 - (short) 0xc14f, // (12, 335) 36 - (short) 0xc94f, // (12, 2383) 37 - (short) 0xc54f, // (12, 1359) 38 - (short) 0xcd4f, // (12, 3407) 39 - (short) 0xc34f, // (12, 847) 40 - (short) 0xcb4f, // (12, 2895) 41 - (short) 0xc74f, // (12, 1871) 42 - (short) 0xcf4f, // (12, 3919) 43 - (short) 0xc0cf, // (12, 207) 44 - (short) 0xc8cf, // (12, 2255) 45 - (short) 0xc4cf, // (12, 1231) 46 - (short) 0xcccf, // (12, 3279) 47 - (short) 0xc2cf, // (12, 719) 48 - (short) 0xcacf, // (12, 2767) 49 - (short) 0xc6cf, // (12, 1743) 50 - (short) 0xcecf, // (12, 3791) 51 - (short) 0xc1cf, // (12, 463) 52 - (short) 0xc9cf, // (12, 2511) 53 - (short) 0xc5cf, // (12, 1487) 54 - (short) 0xcdcf, // (12, 3535) 55 - (short) 0xc3cf, // (12, 975) 56 - (short) 0xcbcf, // (12, 3023) 57 - (short) 0xc7cf, // (12, 1999) 58 - (short) 0xcfcf, // (12, 4047) 59 - (short) 0xc02f, // (12, 47) 60 - (short) 0xc82f, // (12, 2095) 61 - (short) 0xc42f, // (12, 1071) 62 - (short) 0xcc2f, // (12, 3119) 63 - (short) 0x90f7, // ( 9, 247) 64 - (short) 0xa10f, // (10, 271) 65 - (short) 0xc22f, // (12, 559) 66 - (short) 0xca2f, // (12, 2607) 67 - (short) 0xc62f, // (12, 1583) 68 - (short) 0xce2f, // (12, 3631) 69 - (short) 0xc12f, // (12, 303) 70 - (short) 0xc92f, // (12, 2351) 71 - (short) 0xc52f, // (12, 1327) 72 - (short) 0xcd2f, // (12, 3375) 73 - (short) 0xc32f, // (12, 815) 74 - (short) 0xcb2f, // (12, 2863) 75 - (short) 0xc72f, // (12, 1839) 76 - (short) 0xcf2f, // (12, 3887) 77 - (short) 0xc0af, // (12, 175) 78 - (short) 0xc8af, // (12, 2223) 79 - (short) 0xc4af, // (12, 1199) 80 - (short) 0xccaf, // (12, 3247) 81 - (short) 0xc2af, // (12, 687) 82 - (short) 0xcaaf, // (12, 2735) 83 - (short) 0xc6af, // (12, 1711) 84 - (short) 0xceaf, // (12, 3759) 85 - (short) 0xc1af, // (12, 431) 86 - (short) 0xc9af, // (12, 2479) 87 - (short) 0xc5af, // (12, 1455) 88 - (short) 0xcdaf, // (12, 3503) 89 - (short) 0xc3af, // (12, 943) 90 - (short) 0xcbaf, // (12, 2991) 91 - (short) 0xc7af, // (12, 1967) 92 - (short) 0xcfaf, // (12, 4015) 93 - (short) 0xc06f, // (12, 111) 94 - (short) 0xc86f, // (12, 2159) 95 - (short) 0xc46f, // (12, 1135) 96 - (short) 0xcc6f, // (12, 3183) 97 - (short) 0xc26f, // (12, 623) 98 - (short) 0xca6f, // (12, 2671) 99 - (short) 0xc66f, // (12, 1647) 100 - (short) 0xce6f, // (12, 3695) 101 - (short) 0xc16f, // (12, 367) 102 - (short) 0xc96f, // (12, 2415) 103 - (short) 0xc56f, // (12, 1391) 104 - (short) 0xcd6f, // (12, 3439) 105 - (short) 0xc36f, // (12, 879) 106 - (short) 0xcb6f, // (12, 2927) 107 - (short) 0xc76f, // (12, 1903) 108 - (short) 0xcf6f, // (12, 3951) 109 - (short) 0xc0ef, // (12, 239) 110 - (short) 0xc8ef, // (12, 2287) 111 - (short) 0xc4ef, // (12, 1263) 112 - (short) 0xccef, // (12, 3311) 113 - (short) 0xc2ef, // (12, 751) 114 - (short) 0xcaef, // (12, 2799) 115 - (short) 0xc6ef, // (12, 1775) 116 - (short) 0xceef, // (12, 3823) 117 - (short) 0xc1ef, // (12, 495) 118 - (short) 0xc9ef, // (12, 2543) 119 - (short) 0xc5ef, // (12, 1519) 120 - (short) 0xcdef, // (12, 3567) 121 - (short) 0xc3ef, // (12, 1007) 122 - (short) 0xcbef, // (12, 3055) 123 - (short) 0xc7ef, // (12, 2031) 124 - (short) 0xcfef, // (12, 4079) 125 - (short) 0xc01f, // (12, 31) 126 - (short) 0xc81f, // (12, 2079) 127 - (short) 0xa30f, // (10, 783) 128 - (short) 0xb18f, // (11, 399) 129 - (short) 0xc41f, // (12, 1055) 130 - (short) 0xcc1f, // (12, 3103) 131 - (short) 0xc21f, // (12, 543) 132 - (short) 0xca1f, // (12, 2591) 133 - (short) 0xc61f, // (12, 1567) 134 - (short) 0xce1f, // (12, 3615) 135 - (short) 0xc11f, // (12, 287) 136 - (short) 0xc91f, // (12, 2335) 137 - (short) 0xc51f, // (12, 1311) 138 - (short) 0xcd1f, // (12, 3359) 139 - (short) 0xc31f, // (12, 799) 140 - (short) 0xcb1f, // (12, 2847) 141 - (short) 0xc71f, // (12, 1823) 142 - (short) 0xcf1f, // (12, 3871) 143 - (short) 0xc09f, // (12, 159) 144 - (short) 0xc89f, // (12, 2207) 145 - (short) 0xc49f, // (12, 1183) 146 - (short) 0xcc9f, // (12, 3231) 147 - (short) 0xc29f, // (12, 671) 148 - (short) 0xca9f, // (12, 2719) 149 - (short) 0xc69f, // (12, 1695) 150 - (short) 0xce9f, // (12, 3743) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 17 of 22) (midrange 1 of 6) (c/k = 0.833333333 = 5.0 / 6.0) - // entropy: 2.9553294756640680063 - // avg_length: 3.0766035704232641557; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x2000, // ( 2, 0) 0 - (short) 0x2002, // ( 2, 2) 1 - (short) 0x3001, // ( 3, 1) 2 - (short) 0x4005, // ( 4, 5) 3 - (short) 0x400d, // ( 4, 13) 4 - (short) 0x5003, // ( 5, 3) 5 - (short) 0x600b, // ( 6, 11) 6 - (short) 0x602b, // ( 6, 43) 7 - (short) 0x5013, // ( 5, 19) 8 - (short) 0x601b, // ( 6, 27) 9 - (short) 0x7007, // ( 7, 7) 10 - (short) 0x7047, // ( 7, 71) 11 - (short) 0x8017, // ( 8, 23) 12 - (short) 0x90b7, // ( 9, 183) 13 - (short) 0xa1f7, // (10, 503) 14 - (short) 0xa3f7, // (10, 1015) 15 - (short) 0x603b, // ( 6, 59) 16 - (short) 0x7027, // ( 7, 39) 17 - (short) 0x8097, // ( 8, 151) 18 - (short) 0x8057, // ( 8, 87) 19 - (short) 0x91b7, // ( 9, 439) 20 - (short) 0xa00f, // (10, 15) 21 - (short) 0xb18f, // (11, 399) 22 - (short) 0xb58f, // (11, 1423) 23 - (short) 0xa20f, // (10, 527) 24 - (short) 0xb38f, // (11, 911) 25 - (short) 0xc54f, // (12, 1359) 26 - (short) 0xcd4f, // (12, 3407) 27 - (short) 0xc34f, // (12, 847) 28 - (short) 0xcb4f, // (12, 2895) 29 - (short) 0xc74f, // (12, 1871) 30 - (short) 0xcf4f, // (12, 3919) 31 - (short) 0x7067, // ( 7, 103) 32 - (short) 0x80d7, // ( 8, 215) 33 - (short) 0x9077, // ( 9, 119) 34 - (short) 0xa10f, // (10, 271) 35 - (short) 0xa30f, // (10, 783) 36 - (short) 0xb78f, // (11, 1935) 37 - (short) 0xc0cf, // (12, 207) 38 - (short) 0xc8cf, // (12, 2255) 39 - (short) 0xb04f, // (11, 79) 40 - (short) 0xc4cf, // (12, 1231) 41 - (short) 0xcccf, // (12, 3279) 42 - (short) 0xc2cf, // (12, 719) 43 - (short) 0xcacf, // (12, 2767) 44 - (short) 0xc6cf, // (12, 1743) 45 - (short) 0xcecf, // (12, 3791) 46 - (short) 0xc1cf, // (12, 463) 47 - (short) 0xc9cf, // (12, 2511) 48 - (short) 0xc5cf, // (12, 1487) 49 - (short) 0xcdcf, // (12, 3535) 50 - (short) 0xc3cf, // (12, 975) 51 - (short) 0xcbcf, // (12, 3023) 52 - (short) 0xc7cf, // (12, 1999) 53 - (short) 0xcfcf, // (12, 4047) 54 - (short) 0xc02f, // (12, 47) 55 - (short) 0xc82f, // (12, 2095) 56 - (short) 0xc42f, // (12, 1071) 57 - (short) 0xcc2f, // (12, 3119) 58 - (short) 0xc22f, // (12, 559) 59 - (short) 0xca2f, // (12, 2607) 60 - (short) 0xc62f, // (12, 1583) 61 - (short) 0xce2f, // (12, 3631) 62 - (short) 0xc12f, // (12, 303) 63 - (short) 0x8037, // ( 8, 55) 64 - (short) 0x9177, // ( 9, 375) 65 - (short) 0xa08f, // (10, 143) 66 - (short) 0xb44f, // (11, 1103) 67 - (short) 0xb24f, // (11, 591) 68 - (short) 0xc92f, // (12, 2351) 69 - (short) 0xc52f, // (12, 1327) 70 - (short) 0xcd2f, // (12, 3375) 71 - (short) 0xc32f, // (12, 815) 72 - (short) 0xcb2f, // (12, 2863) 73 - (short) 0xc72f, // (12, 1839) 74 - (short) 0xcf2f, // (12, 3887) 75 - (short) 0xc0af, // (12, 175) 76 - (short) 0xc8af, // (12, 2223) 77 - (short) 0xc4af, // (12, 1199) 78 - (short) 0xccaf, // (12, 3247) 79 - (short) 0xc2af, // (12, 687) 80 - (short) 0xcaaf, // (12, 2735) 81 - (short) 0xc6af, // (12, 1711) 82 - (short) 0xceaf, // (12, 3759) 83 - (short) 0xc1af, // (12, 431) 84 - (short) 0xc9af, // (12, 2479) 85 - (short) 0xc5af, // (12, 1455) 86 - (short) 0xcdaf, // (12, 3503) 87 - (short) 0xc3af, // (12, 943) 88 - (short) 0xcbaf, // (12, 2991) 89 - (short) 0xc7af, // (12, 1967) 90 - (short) 0xcfaf, // (12, 4015) 91 - (short) 0xc06f, // (12, 111) 92 - (short) 0xc86f, // (12, 2159) 93 - (short) 0xc46f, // (12, 1135) 94 - (short) 0xcc6f, // (12, 3183) 95 - (short) 0xc26f, // (12, 623) 96 - (short) 0xca6f, // (12, 2671) 97 - (short) 0xc66f, // (12, 1647) 98 - (short) 0xce6f, // (12, 3695) 99 - (short) 0xc16f, // (12, 367) 100 - (short) 0xc96f, // (12, 2415) 101 - (short) 0xc56f, // (12, 1391) 102 - (short) 0xcd6f, // (12, 3439) 103 - (short) 0xc36f, // (12, 879) 104 - (short) 0xcb6f, // (12, 2927) 105 - (short) 0xc76f, // (12, 1903) 106 - (short) 0xcf6f, // (12, 3951) 107 - (short) 0xc0ef, // (12, 239) 108 - (short) 0xc8ef, // (12, 2287) 109 - (short) 0xc4ef, // (12, 1263) 110 - (short) 0xccef, // (12, 3311) 111 - (short) 0xc2ef, // (12, 751) 112 - (short) 0xcaef, // (12, 2799) 113 - (short) 0xc6ef, // (12, 1775) 114 - (short) 0xceef, // (12, 3823) 115 - (short) 0xc1ef, // (12, 495) 116 - (short) 0xc9ef, // (12, 2543) 117 - (short) 0xc5ef, // (12, 1519) 118 - (short) 0xcdef, // (12, 3567) 119 - (short) 0xc3ef, // (12, 1007) 120 - (short) 0xcbef, // (12, 3055) 121 - (short) 0xc7ef, // (12, 2031) 122 - (short) 0xcfef, // (12, 4079) 123 - (short) 0xc01f, // (12, 31) 124 - (short) 0xc81f, // (12, 2079) 125 - (short) 0xc41f, // (12, 1055) 126 - (short) 0xcc1f, // (12, 3103) 127 - (short) 0x90f7, // ( 9, 247) 128 - (short) 0xa28f, // (10, 655) 129 - (short) 0xb64f, // (11, 1615) 130 - (short) 0xb14f, // (11, 335) 131 - (short) 0xc21f, // (12, 543) 132 - (short) 0xca1f, // (12, 2591) 133 - (short) 0xc61f, // (12, 1567) 134 - (short) 0xce1f, // (12, 3615) 135 - (short) 0xc11f, // (12, 287) 136 - (short) 0xc91f, // (12, 2335) 137 - (short) 0xc51f, // (12, 1311) 138 - (short) 0xcd1f, // (12, 3359) 139 - (short) 0xc31f, // (12, 799) 140 - (short) 0xcb1f, // (12, 2847) 141 - (short) 0xc71f, // (12, 1823) 142 - (short) 0xcf1f, // (12, 3871) 143 - (short) 0xc09f, // (12, 159) 144 - (short) 0xc89f, // (12, 2207) 145 - (short) 0xc49f, // (12, 1183) 146 - (short) 0xcc9f, // (12, 3231) 147 - (short) 0xc29f, // (12, 671) 148 - (short) 0xca9f, // (12, 2719) 149 - (short) 0xc69f, // (12, 1695) 150 - (short) 0xce9f, // (12, 3743) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 18 of 22) (midrange 2 of 6) (c/k = 1.166666667 = 7.0 / 6.0) - // entropy: 3.5218672531711128215 - // avg_length: 3.6153551492375441967; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x2000, // ( 2, 0) 0 - (short) 0x2002, // ( 2, 2) 1 - (short) 0x4005, // ( 4, 5) 2 - (short) 0x3001, // ( 3, 1) 3 - (short) 0x5003, // ( 5, 3) 4 - (short) 0x400d, // ( 4, 13) 5 - (short) 0x600b, // ( 6, 11) 6 - (short) 0x602b, // ( 6, 43) 7 - (short) 0x601b, // ( 6, 27) 8 - (short) 0x5013, // ( 5, 19) 9 - (short) 0x703b, // ( 7, 59) 10 - (short) 0x707b, // ( 7, 123) 11 - (short) 0x8067, // ( 8, 103) 12 - (short) 0x80e7, // ( 8, 231) 13 - (short) 0x90d7, // ( 9, 215) 14 - (short) 0x91d7, // ( 9, 471) 15 - (short) 0x7007, // ( 7, 7) 16 - (short) 0x7047, // ( 7, 71) 17 - (short) 0x8017, // ( 8, 23) 18 - (short) 0x8097, // ( 8, 151) 19 - (short) 0x9037, // ( 9, 55) 20 - (short) 0x9137, // ( 9, 311) 21 - (short) 0xa1f7, // (10, 503) 22 - (short) 0xa3f7, // (10, 1015) 23 - (short) 0xa00f, // (10, 15) 24 - (short) 0xa20f, // (10, 527) 25 - (short) 0xb38f, // (11, 911) 26 - (short) 0xb78f, // (11, 1935) 27 - (short) 0xc0cf, // (12, 207) 28 - (short) 0xc8cf, // (12, 2255) 29 - (short) 0xc4cf, // (12, 1231) 30 - (short) 0xcccf, // (12, 3279) 31 - (short) 0x8057, // ( 8, 87) 32 - (short) 0x7027, // ( 7, 39) 33 - (short) 0x90b7, // ( 9, 183) 34 - (short) 0x91b7, // ( 9, 439) 35 - (short) 0xa10f, // (10, 271) 36 - (short) 0xa30f, // (10, 783) 37 - (short) 0xb04f, // (11, 79) 38 - (short) 0xb44f, // (11, 1103) 39 - (short) 0xb24f, // (11, 591) 40 - (short) 0xb64f, // (11, 1615) 41 - (short) 0xc2cf, // (12, 719) 42 - (short) 0xcacf, // (12, 2767) 43 - (short) 0xc6cf, // (12, 1743) 44 - (short) 0xcecf, // (12, 3791) 45 - (short) 0xc1cf, // (12, 463) 46 - (short) 0xc9cf, // (12, 2511) 47 - (short) 0xc5cf, // (12, 1487) 48 - (short) 0xcdcf, // (12, 3535) 49 - (short) 0xc3cf, // (12, 975) 50 - (short) 0xcbcf, // (12, 3023) 51 - (short) 0xc7cf, // (12, 1999) 52 - (short) 0xcfcf, // (12, 4047) 53 - (short) 0xc02f, // (12, 47) 54 - (short) 0xc82f, // (12, 2095) 55 - (short) 0xc42f, // (12, 1071) 56 - (short) 0xcc2f, // (12, 3119) 57 - (short) 0xc22f, // (12, 559) 58 - (short) 0xca2f, // (12, 2607) 59 - (short) 0xc62f, // (12, 1583) 60 - (short) 0xce2f, // (12, 3631) 61 - (short) 0xc12f, // (12, 303) 62 - (short) 0xc92f, // (12, 2351) 63 - (short) 0x9077, // ( 9, 119) 64 - (short) 0x9177, // ( 9, 375) 65 - (short) 0xa08f, // (10, 143) 66 - (short) 0xa28f, // (10, 655) 67 - (short) 0xb14f, // (11, 335) 68 - (short) 0xb54f, // (11, 1359) 69 - (short) 0xc52f, // (12, 1327) 70 - (short) 0xcd2f, // (12, 3375) 71 - (short) 0xc32f, // (12, 815) 72 - (short) 0xcb2f, // (12, 2863) 73 - (short) 0xc72f, // (12, 1839) 74 - (short) 0xcf2f, // (12, 3887) 75 - (short) 0xc0af, // (12, 175) 76 - (short) 0xc8af, // (12, 2223) 77 - (short) 0xc4af, // (12, 1199) 78 - (short) 0xccaf, // (12, 3247) 79 - (short) 0xc2af, // (12, 687) 80 - (short) 0xcaaf, // (12, 2735) 81 - (short) 0xc6af, // (12, 1711) 82 - (short) 0xceaf, // (12, 3759) 83 - (short) 0xc1af, // (12, 431) 84 - (short) 0xc9af, // (12, 2479) 85 - (short) 0xc5af, // (12, 1455) 86 - (short) 0xcdaf, // (12, 3503) 87 - (short) 0xc3af, // (12, 943) 88 - (short) 0xcbaf, // (12, 2991) 89 - (short) 0xc7af, // (12, 1967) 90 - (short) 0xcfaf, // (12, 4015) 91 - (short) 0xc06f, // (12, 111) 92 - (short) 0xc86f, // (12, 2159) 93 - (short) 0xc46f, // (12, 1135) 94 - (short) 0xcc6f, // (12, 3183) 95 - (short) 0xc26f, // (12, 623) 96 - (short) 0xca6f, // (12, 2671) 97 - (short) 0xc66f, // (12, 1647) 98 - (short) 0xce6f, // (12, 3695) 99 - (short) 0xc16f, // (12, 367) 100 - (short) 0xc96f, // (12, 2415) 101 - (short) 0xc56f, // (12, 1391) 102 - (short) 0xcd6f, // (12, 3439) 103 - (short) 0xc36f, // (12, 879) 104 - (short) 0xcb6f, // (12, 2927) 105 - (short) 0xc76f, // (12, 1903) 106 - (short) 0xcf6f, // (12, 3951) 107 - (short) 0xc0ef, // (12, 239) 108 - (short) 0xc8ef, // (12, 2287) 109 - (short) 0xc4ef, // (12, 1263) 110 - (short) 0xccef, // (12, 3311) 111 - (short) 0xc2ef, // (12, 751) 112 - (short) 0xcaef, // (12, 2799) 113 - (short) 0xc6ef, // (12, 1775) 114 - (short) 0xceef, // (12, 3823) 115 - (short) 0xc1ef, // (12, 495) 116 - (short) 0xc9ef, // (12, 2543) 117 - (short) 0xc5ef, // (12, 1519) 118 - (short) 0xcdef, // (12, 3567) 119 - (short) 0xc3ef, // (12, 1007) 120 - (short) 0xcbef, // (12, 3055) 121 - (short) 0xc7ef, // (12, 2031) 122 - (short) 0xcfef, // (12, 4079) 123 - (short) 0xc01f, // (12, 31) 124 - (short) 0xc81f, // (12, 2079) 125 - (short) 0xc41f, // (12, 1055) 126 - (short) 0xcc1f, // (12, 3103) 127 - (short) 0xa18f, // (10, 399) 128 - (short) 0x90f7, // ( 9, 247) 129 - (short) 0xb34f, // (11, 847) 130 - (short) 0xb74f, // (11, 1871) 131 - (short) 0xc21f, // (12, 543) 132 - (short) 0xca1f, // (12, 2591) 133 - (short) 0xc61f, // (12, 1567) 134 - (short) 0xce1f, // (12, 3615) 135 - (short) 0xc11f, // (12, 287) 136 - (short) 0xc91f, // (12, 2335) 137 - (short) 0xc51f, // (12, 1311) 138 - (short) 0xcd1f, // (12, 3359) 139 - (short) 0xc31f, // (12, 799) 140 - (short) 0xcb1f, // (12, 2847) 141 - (short) 0xc71f, // (12, 1823) 142 - (short) 0xcf1f, // (12, 3871) 143 - (short) 0xc09f, // (12, 159) 144 - (short) 0xc89f, // (12, 2207) 145 - (short) 0xc49f, // (12, 1183) 146 - (short) 0xcc9f, // (12, 3231) 147 - (short) 0xc29f, // (12, 671) 148 - (short) 0xca9f, // (12, 2719) 149 - (short) 0xc69f, // (12, 1695) 150 - (short) 0xce9f, // (12, 3743) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 19 of 22) (midrange 3 of 6) (c/k = 1.500000000 = 9.0 / 6.0) - // entropy: 3.9228873257934386842 - // avg_length: 3.9989687586992346269; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x3002, // ( 3, 2) 0 - (short) 0x2000, // ( 2, 0) 1 - (short) 0x4001, // ( 4, 1) 2 - (short) 0x3006, // ( 3, 6) 3 - (short) 0x500d, // ( 5, 13) 4 - (short) 0x4009, // ( 4, 9) 5 - (short) 0x501d, // ( 5, 29) 6 - (short) 0x4005, // ( 4, 5) 7 - (short) 0x6013, // ( 6, 19) 8 - (short) 0x5003, // ( 5, 3) 9 - (short) 0x6033, // ( 6, 51) 10 - (short) 0x600b, // ( 6, 11) 11 - (short) 0x8027, // ( 8, 39) 12 - (short) 0x701b, // ( 7, 27) 13 - (short) 0x80a7, // ( 8, 167) 14 - (short) 0x705b, // ( 7, 91) 15 - (short) 0x703b, // ( 7, 59) 16 - (short) 0x602b, // ( 6, 43) 17 - (short) 0x707b, // ( 7, 123) 18 - (short) 0x7007, // ( 7, 7) 19 - (short) 0x90d7, // ( 9, 215) 20 - (short) 0x8067, // ( 8, 103) 21 - (short) 0x91d7, // ( 9, 471) 22 - (short) 0x80e7, // ( 8, 231) 23 - (short) 0xa1f7, // (10, 503) 24 - (short) 0x9037, // ( 9, 55) 25 - (short) 0xa3f7, // (10, 1015) 26 - (short) 0xa00f, // (10, 15) 27 - (short) 0xc5cf, // (12, 1487) 28 - (short) 0xb04f, // (11, 79) 29 - (short) 0xcdcf, // (12, 3535) 30 - (short) 0xb44f, // (11, 1103) 31 - (short) 0x8017, // ( 8, 23) 32 - (short) 0x7047, // ( 7, 71) 33 - (short) 0x9137, // ( 9, 311) 34 - (short) 0x8097, // ( 8, 151) 35 - (short) 0xa20f, // (10, 527) 36 - (short) 0x90b7, // ( 9, 183) 37 - (short) 0xa10f, // (10, 271) 38 - (short) 0x91b7, // ( 9, 439) 39 - (short) 0xb24f, // (11, 591) 40 - (short) 0xa30f, // (10, 783) 41 - (short) 0xb64f, // (11, 1615) 42 - (short) 0xb14f, // (11, 335) 43 - (short) 0xc3cf, // (12, 975) 44 - (short) 0xcbcf, // (12, 3023) 45 - (short) 0xc7cf, // (12, 1999) 46 - (short) 0xcfcf, // (12, 4047) 47 - (short) 0xc02f, // (12, 47) 48 - (short) 0xb54f, // (11, 1359) 49 - (short) 0xc82f, // (12, 2095) 50 - (short) 0xc42f, // (12, 1071) 51 - (short) 0xcc2f, // (12, 3119) 52 - (short) 0xc22f, // (12, 559) 53 - (short) 0xca2f, // (12, 2607) 54 - (short) 0xc62f, // (12, 1583) 55 - (short) 0xce2f, // (12, 3631) 56 - (short) 0xc12f, // (12, 303) 57 - (short) 0xc92f, // (12, 2351) 58 - (short) 0xc52f, // (12, 1327) 59 - (short) 0xcd2f, // (12, 3375) 60 - (short) 0xc32f, // (12, 815) 61 - (short) 0xcb2f, // (12, 2863) 62 - (short) 0xc72f, // (12, 1839) 63 - (short) 0x9077, // ( 9, 119) 64 - (short) 0x8057, // ( 8, 87) 65 - (short) 0xa08f, // (10, 143) 66 - (short) 0x9177, // ( 9, 375) 67 - (short) 0xb34f, // (11, 847) 68 - (short) 0xa28f, // (10, 655) 69 - (short) 0xb74f, // (11, 1871) 70 - (short) 0xb0cf, // (11, 207) 71 - (short) 0xcf2f, // (12, 3887) 72 - (short) 0xb4cf, // (11, 1231) 73 - (short) 0xc0af, // (12, 175) 74 - (short) 0xc8af, // (12, 2223) 75 - (short) 0xc4af, // (12, 1199) 76 - (short) 0xccaf, // (12, 3247) 77 - (short) 0xc2af, // (12, 687) 78 - (short) 0xcaaf, // (12, 2735) 79 - (short) 0xc6af, // (12, 1711) 80 - (short) 0xceaf, // (12, 3759) 81 - (short) 0xc1af, // (12, 431) 82 - (short) 0xc9af, // (12, 2479) 83 - (short) 0xc5af, // (12, 1455) 84 - (short) 0xcdaf, // (12, 3503) 85 - (short) 0xc3af, // (12, 943) 86 - (short) 0xcbaf, // (12, 2991) 87 - (short) 0xc7af, // (12, 1967) 88 - (short) 0xcfaf, // (12, 4015) 89 - (short) 0xc06f, // (12, 111) 90 - (short) 0xc86f, // (12, 2159) 91 - (short) 0xc46f, // (12, 1135) 92 - (short) 0xcc6f, // (12, 3183) 93 - (short) 0xc26f, // (12, 623) 94 - (short) 0xca6f, // (12, 2671) 95 - (short) 0xc66f, // (12, 1647) 96 - (short) 0xce6f, // (12, 3695) 97 - (short) 0xc16f, // (12, 367) 98 - (short) 0xc96f, // (12, 2415) 99 - (short) 0xc56f, // (12, 1391) 100 - (short) 0xcd6f, // (12, 3439) 101 - (short) 0xc36f, // (12, 879) 102 - (short) 0xcb6f, // (12, 2927) 103 - (short) 0xc76f, // (12, 1903) 104 - (short) 0xcf6f, // (12, 3951) 105 - (short) 0xc0ef, // (12, 239) 106 - (short) 0xc8ef, // (12, 2287) 107 - (short) 0xc4ef, // (12, 1263) 108 - (short) 0xccef, // (12, 3311) 109 - (short) 0xc2ef, // (12, 751) 110 - (short) 0xcaef, // (12, 2799) 111 - (short) 0xc6ef, // (12, 1775) 112 - (short) 0xceef, // (12, 3823) 113 - (short) 0xc1ef, // (12, 495) 114 - (short) 0xc9ef, // (12, 2543) 115 - (short) 0xc5ef, // (12, 1519) 116 - (short) 0xcdef, // (12, 3567) 117 - (short) 0xc3ef, // (12, 1007) 118 - (short) 0xcbef, // (12, 3055) 119 - (short) 0xc7ef, // (12, 2031) 120 - (short) 0xcfef, // (12, 4079) 121 - (short) 0xc01f, // (12, 31) 122 - (short) 0xc81f, // (12, 2079) 123 - (short) 0xc41f, // (12, 1055) 124 - (short) 0xcc1f, // (12, 3103) 125 - (short) 0xc21f, // (12, 543) 126 - (short) 0xca1f, // (12, 2591) 127 - (short) 0xa18f, // (10, 399) 128 - (short) 0x90f7, // ( 9, 247) 129 - (short) 0xb2cf, // (11, 719) 130 - (short) 0xa38f, // (10, 911) 131 - (short) 0xc61f, // (12, 1567) 132 - (short) 0xb6cf, // (11, 1743) 133 - (short) 0xce1f, // (12, 3615) 134 - (short) 0xb1cf, // (11, 463) 135 - (short) 0xc11f, // (12, 287) 136 - (short) 0xc91f, // (12, 2335) 137 - (short) 0xc51f, // (12, 1311) 138 - (short) 0xcd1f, // (12, 3359) 139 - (short) 0xc31f, // (12, 799) 140 - (short) 0xcb1f, // (12, 2847) 141 - (short) 0xc71f, // (12, 1823) 142 - (short) 0xcf1f, // (12, 3871) 143 - (short) 0xc09f, // (12, 159) 144 - (short) 0xc89f, // (12, 2207) 145 - (short) 0xc49f, // (12, 1183) 146 - (short) 0xcc9f, // (12, 3231) 147 - (short) 0xc29f, // (12, 671) 148 - (short) 0xca9f, // (12, 2719) 149 - (short) 0xc69f, // (12, 1695) 150 - (short) 0xce9f, // (12, 3743) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 20 of 22) (midrange 4 of 6) (c/k = 1.833333333 = 11.0 / 6.0) - // entropy: 4.1937026483207340277 - // avg_length: 4.2809622975207295426; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x4006, // ( 4, 6) 0 - (short) 0x2000, // ( 2, 0) 1 - (short) 0x400e, // ( 4, 14) 2 - (short) 0x3002, // ( 3, 2) 3 - (short) 0x5005, // ( 5, 5) 4 - (short) 0x4001, // ( 4, 1) 5 - (short) 0x5015, // ( 5, 21) 6 - (short) 0x4009, // ( 4, 9) 7 - (short) 0x6003, // ( 6, 3) 8 - (short) 0x500d, // ( 5, 13) 9 - (short) 0x6023, // ( 6, 35) 10 - (short) 0x501d, // ( 5, 29) 11 - (short) 0x8047, // ( 8, 71) 12 - (short) 0x6013, // ( 6, 19) 13 - (short) 0x80c7, // ( 8, 199) 14 - (short) 0x6033, // ( 6, 51) 15 - (short) 0x701b, // ( 7, 27) 16 - (short) 0x600b, // ( 6, 11) 17 - (short) 0x8027, // ( 8, 39) 18 - (short) 0x602b, // ( 6, 43) 19 - (short) 0x90d7, // ( 9, 215) 20 - (short) 0x705b, // ( 7, 91) 21 - (short) 0x91d7, // ( 9, 471) 22 - (short) 0x703b, // ( 7, 59) 23 - (short) 0xa1f7, // (10, 503) 24 - (short) 0x80a7, // ( 8, 167) 25 - (short) 0xa3f7, // (10, 1015) 26 - (short) 0x8067, // ( 8, 103) 27 - (short) 0xb24f, // (11, 591) 28 - (short) 0xa00f, // (10, 15) 29 - (short) 0xb64f, // (11, 1615) 30 - (short) 0xa20f, // (10, 527) 31 - (short) 0x9037, // ( 9, 55) 32 - (short) 0x707b, // ( 7, 123) 33 - (short) 0x9137, // ( 9, 311) 34 - (short) 0x7007, // ( 7, 7) 35 - (short) 0xa10f, // (10, 271) 36 - (short) 0x80e7, // ( 8, 231) 37 - (short) 0xa30f, // (10, 783) 38 - (short) 0x8017, // ( 8, 23) 39 - (short) 0xb14f, // (11, 335) 40 - (short) 0x90b7, // ( 9, 183) 41 - (short) 0xb54f, // (11, 1359) 42 - (short) 0xa08f, // (10, 143) 43 - (short) 0xc02f, // (12, 47) 44 - (short) 0xb34f, // (11, 847) 45 - (short) 0xc82f, // (12, 2095) 46 - (short) 0xb74f, // (11, 1871) 47 - (short) 0xc42f, // (12, 1071) 48 - (short) 0xb0cf, // (11, 207) 49 - (short) 0xcc2f, // (12, 3119) 50 - (short) 0xb4cf, // (11, 1231) 51 - (short) 0xc22f, // (12, 559) 52 - (short) 0xca2f, // (12, 2607) 53 - (short) 0xc62f, // (12, 1583) 54 - (short) 0xce2f, // (12, 3631) 55 - (short) 0xc12f, // (12, 303) 56 - (short) 0xc92f, // (12, 2351) 57 - (short) 0xc52f, // (12, 1327) 58 - (short) 0xcd2f, // (12, 3375) 59 - (short) 0xc32f, // (12, 815) 60 - (short) 0xcb2f, // (12, 2863) 61 - (short) 0xc72f, // (12, 1839) 62 - (short) 0xcf2f, // (12, 3887) 63 - (short) 0xa28f, // (10, 655) 64 - (short) 0x8097, // ( 8, 151) 65 - (short) 0xa18f, // (10, 399) 66 - (short) 0x8057, // ( 8, 87) 67 - (short) 0xb2cf, // (11, 719) 68 - (short) 0x91b7, // ( 9, 439) 69 - (short) 0xb6cf, // (11, 1743) 70 - (short) 0x9077, // ( 9, 119) 71 - (short) 0xc0af, // (12, 175) 72 - (short) 0xb1cf, // (11, 463) 73 - (short) 0xc8af, // (12, 2223) 74 - (short) 0xb5cf, // (11, 1487) 75 - (short) 0xc4af, // (12, 1199) 76 - (short) 0xccaf, // (12, 3247) 77 - (short) 0xc2af, // (12, 687) 78 - (short) 0xcaaf, // (12, 2735) 79 - (short) 0xc6af, // (12, 1711) 80 - (short) 0xceaf, // (12, 3759) 81 - (short) 0xc1af, // (12, 431) 82 - (short) 0xc9af, // (12, 2479) 83 - (short) 0xc5af, // (12, 1455) 84 - (short) 0xcdaf, // (12, 3503) 85 - (short) 0xc3af, // (12, 943) 86 - (short) 0xcbaf, // (12, 2991) 87 - (short) 0xc7af, // (12, 1967) 88 - (short) 0xcfaf, // (12, 4015) 89 - (short) 0xc06f, // (12, 111) 90 - (short) 0xc86f, // (12, 2159) 91 - (short) 0xc46f, // (12, 1135) 92 - (short) 0xcc6f, // (12, 3183) 93 - (short) 0xc26f, // (12, 623) 94 - (short) 0xca6f, // (12, 2671) 95 - (short) 0xc66f, // (12, 1647) 96 - (short) 0xce6f, // (12, 3695) 97 - (short) 0xc16f, // (12, 367) 98 - (short) 0xc96f, // (12, 2415) 99 - (short) 0xc56f, // (12, 1391) 100 - (short) 0xcd6f, // (12, 3439) 101 - (short) 0xc36f, // (12, 879) 102 - (short) 0xcb6f, // (12, 2927) 103 - (short) 0xc76f, // (12, 1903) 104 - (short) 0xcf6f, // (12, 3951) 105 - (short) 0xc0ef, // (12, 239) 106 - (short) 0xc8ef, // (12, 2287) 107 - (short) 0xc4ef, // (12, 1263) 108 - (short) 0xccef, // (12, 3311) 109 - (short) 0xc2ef, // (12, 751) 110 - (short) 0xcaef, // (12, 2799) 111 - (short) 0xc6ef, // (12, 1775) 112 - (short) 0xceef, // (12, 3823) 113 - (short) 0xc1ef, // (12, 495) 114 - (short) 0xc9ef, // (12, 2543) 115 - (short) 0xc5ef, // (12, 1519) 116 - (short) 0xcdef, // (12, 3567) 117 - (short) 0xc3ef, // (12, 1007) 118 - (short) 0xcbef, // (12, 3055) 119 - (short) 0xc7ef, // (12, 2031) 120 - (short) 0xcfef, // (12, 4079) 121 - (short) 0xc01f, // (12, 31) 122 - (short) 0xc81f, // (12, 2079) 123 - (short) 0xc41f, // (12, 1055) 124 - (short) 0xcc1f, // (12, 3103) 125 - (short) 0xc21f, // (12, 543) 126 - (short) 0xca1f, // (12, 2591) 127 - (short) 0xb3cf, // (11, 975) 128 - (short) 0x9177, // ( 9, 375) 129 - (short) 0xb7cf, // (11, 1999) 130 - (short) 0x90f7, // ( 9, 247) 131 - (short) 0xc61f, // (12, 1567) 132 - (short) 0xa38f, // (10, 911) 133 - (short) 0xce1f, // (12, 3615) 134 - (short) 0xa04f, // (10, 79) 135 - (short) 0xc11f, // (12, 287) 136 - (short) 0xc91f, // (12, 2335) 137 - (short) 0xc51f, // (12, 1311) 138 - (short) 0xcd1f, // (12, 3359) 139 - (short) 0xc31f, // (12, 799) 140 - (short) 0xcb1f, // (12, 2847) 141 - (short) 0xc71f, // (12, 1823) 142 - (short) 0xcf1f, // (12, 3871) 143 - (short) 0xc09f, // (12, 159) 144 - (short) 0xc89f, // (12, 2207) 145 - (short) 0xc49f, // (12, 1183) 146 - (short) 0xcc9f, // (12, 3231) 147 - (short) 0xc29f, // (12, 671) 148 - (short) 0xca9f, // (12, 2719) 149 - (short) 0xc69f, // (12, 1695) 150 - (short) 0xce9f, // (12, 3743) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - }, - - // (table 21 of 22) (midrange 5 of 6) (c/k = 2.166666667 = 13.0 / 6.0) - // entropy: 4.3601926041863263706 - // avg_length: 4.4384101723259572481; max_length = 12; num_symbols = 256 - { - //table, // (4 bits, 12 bits) symbol - //entry, // (length, codeword) [byte] - (short) 0x5009, // ( 5, 9) 0 - (short) 0x3002, // ( 3, 2) 1 - (short) 0x5019, // ( 5, 25) 2 - (short) 0x2000, // ( 2, 0) 3 - (short) 0x6003, // ( 6, 3) 4 - (short) 0x4001, // ( 4, 1) 5 - (short) 0x5005, // ( 5, 5) 6 - (short) 0x3006, // ( 3, 6) 7 - (short) 0x702b, // ( 7, 43) 8 - (short) 0x5015, // ( 5, 21) 9 - (short) 0x706b, // ( 7, 107) 10 - (short) 0x500d, // ( 5, 13) 11 - (short) 0x8007, // ( 8, 7) 12 - (short) 0x6023, // ( 6, 35) 13 - (short) 0x8087, // ( 8, 135) 14 - (short) 0x501d, // ( 5, 29) 15 - (short) 0x8047, // ( 8, 71) 16 - (short) 0x6013, // ( 6, 19) 17 - (short) 0x80c7, // ( 8, 199) 18 - (short) 0x6033, // ( 6, 51) 19 - (short) 0x9097, // ( 9, 151) 20 - (short) 0x701b, // ( 7, 27) 21 - (short) 0x9197, // ( 9, 407) 22 - (short) 0x600b, // ( 6, 11) 23 - (short) 0xa0f7, // (10, 247) 24 - (short) 0x8027, // ( 8, 39) 25 - (short) 0xa2f7, // (10, 759) 26 - (short) 0x80a7, // ( 8, 167) 27 - (short) 0xb14f, // (11, 335) 28 - (short) 0x9057, // ( 9, 87) 29 - (short) 0xb54f, // (11, 1359) 30 - (short) 0x9157, // ( 9, 343) 31 - (short) 0x90d7, // ( 9, 215) 32 - (short) 0x705b, // ( 7, 91) 33 - (short) 0x91d7, // ( 9, 471) 34 - (short) 0x703b, // ( 7, 59) 35 - (short) 0xa1f7, // (10, 503) 36 - (short) 0x8067, // ( 8, 103) 37 - (short) 0xa3f7, // (10, 1015) 38 - (short) 0x707b, // ( 7, 123) 39 - (short) 0xb34f, // (11, 847) 40 - (short) 0x9037, // ( 9, 55) 41 - (short) 0xb74f, // (11, 1871) 42 - (short) 0x9137, // ( 9, 311) 43 - (short) 0xc12f, // (12, 303) 44 - (short) 0xa00f, // (10, 15) 45 - (short) 0xc92f, // (12, 2351) 46 - (short) 0xa20f, // (10, 527) 47 - (short) 0xc52f, // (12, 1327) 48 - (short) 0xa10f, // (10, 271) 49 - (short) 0xcd2f, // (12, 3375) 50 - (short) 0xa30f, // (10, 783) 51 - (short) 0xc32f, // (12, 815) 52 - (short) 0xb0cf, // (11, 207) 53 - (short) 0xcb2f, // (12, 2863) 54 - (short) 0xb4cf, // (11, 1231) 55 - (short) 0xc72f, // (12, 1839) 56 - (short) 0xcf2f, // (12, 3887) 57 - (short) 0xc0af, // (12, 175) 58 - (short) 0xc8af, // (12, 2223) 59 - (short) 0xc4af, // (12, 1199) 60 - (short) 0xccaf, // (12, 3247) 61 - (short) 0xc2af, // (12, 687) 62 - (short) 0xcaaf, // (12, 2735) 63 - (short) 0xa08f, // (10, 143) 64 - (short) 0x80e7, // ( 8, 231) 65 - (short) 0xa28f, // (10, 655) 66 - (short) 0x8017, // ( 8, 23) 67 - (short) 0xb2cf, // (11, 719) 68 - (short) 0x90b7, // ( 9, 183) 69 - (short) 0xb6cf, // (11, 1743) 70 - (short) 0x91b7, // ( 9, 439) 71 - (short) 0xc6af, // (12, 1711) 72 - (short) 0xa18f, // (10, 399) 73 - (short) 0xceaf, // (12, 3759) 74 - (short) 0xa38f, // (10, 911) 75 - (short) 0xc1af, // (12, 431) 76 - (short) 0xb1cf, // (11, 463) 77 - (short) 0xc9af, // (12, 2479) 78 - (short) 0xb5cf, // (11, 1487) 79 - (short) 0xc5af, // (12, 1455) 80 - (short) 0xb3cf, // (11, 975) 81 - (short) 0xcdaf, // (12, 3503) 82 - (short) 0xb7cf, // (11, 1999) 83 - (short) 0xc3af, // (12, 943) 84 - (short) 0xcbaf, // (12, 2991) 85 - (short) 0xc7af, // (12, 1967) 86 - (short) 0xcfaf, // (12, 4015) 87 - (short) 0xc06f, // (12, 111) 88 - (short) 0xc86f, // (12, 2159) 89 - (short) 0xc46f, // (12, 1135) 90 - (short) 0xcc6f, // (12, 3183) 91 - (short) 0xc26f, // (12, 623) 92 - (short) 0xca6f, // (12, 2671) 93 - (short) 0xc66f, // (12, 1647) 94 - (short) 0xce6f, // (12, 3695) 95 - (short) 0xc16f, // (12, 367) 96 - (short) 0xc96f, // (12, 2415) 97 - (short) 0xc56f, // (12, 1391) 98 - (short) 0xcd6f, // (12, 3439) 99 - (short) 0xc36f, // (12, 879) 100 - (short) 0xcb6f, // (12, 2927) 101 - (short) 0xc76f, // (12, 1903) 102 - (short) 0xcf6f, // (12, 3951) 103 - (short) 0xc0ef, // (12, 239) 104 - (short) 0xc8ef, // (12, 2287) 105 - (short) 0xc4ef, // (12, 1263) 106 - (short) 0xccef, // (12, 3311) 107 - (short) 0xc2ef, // (12, 751) 108 - (short) 0xcaef, // (12, 2799) 109 - (short) 0xc6ef, // (12, 1775) 110 - (short) 0xceef, // (12, 3823) 111 - (short) 0xc1ef, // (12, 495) 112 - (short) 0xc9ef, // (12, 2543) 113 - (short) 0xc5ef, // (12, 1519) 114 - (short) 0xcdef, // (12, 3567) 115 - (short) 0xc3ef, // (12, 1007) 116 - (short) 0xcbef, // (12, 3055) 117 - (short) 0xc7ef, // (12, 2031) 118 - (short) 0xcfef, // (12, 4079) 119 - (short) 0xc01f, // (12, 31) 120 - (short) 0xc81f, // (12, 2079) 121 - (short) 0xc41f, // (12, 1055) 122 - (short) 0xcc1f, // (12, 3103) 123 - (short) 0xc21f, // (12, 543) 124 - (short) 0xca1f, // (12, 2591) 125 - (short) 0xc61f, // (12, 1567) 126 - (short) 0xce1f, // (12, 3615) 127 - (short) 0xb02f, // (11, 47) 128 - (short) 0x9077, // ( 9, 119) 129 - (short) 0xb42f, // (11, 1071) 130 - (short) 0x9177, // ( 9, 375) 131 - (short) 0xc11f, // (12, 287) 132 - (short) 0xa04f, // (10, 79) 133 - (short) 0xc91f, // (12, 2335) 134 - (short) 0xa24f, // (10, 591) 135 - (short) 0xc51f, // (12, 1311) 136 - (short) 0xb22f, // (11, 559) 137 - (short) 0xcd1f, // (12, 3359) 138 - (short) 0xb62f, // (11, 1583) 139 - (short) 0xc31f, // (12, 799) 140 - (short) 0xcb1f, // (12, 2847) 141 - (short) 0xc71f, // (12, 1823) 142 - (short) 0xcf1f, // (12, 3871) 143 - (short) 0xc09f, // (12, 159) 144 - (short) 0xc89f, // (12, 2207) 145 - (short) 0xc49f, // (12, 1183) 146 - (short) 0xcc9f, // (12, 3231) 147 - (short) 0xc29f, // (12, 671) 148 - (short) 0xca9f, // (12, 2719) 149 - (short) 0xc69f, // (12, 1695) 150 - (short) 0xce9f, // (12, 3743) 151 - (short) 0xc19f, // (12, 415) 152 - (short) 0xc99f, // (12, 2463) 153 - (short) 0xc59f, // (12, 1439) 154 - (short) 0xcd9f, // (12, 3487) 155 - (short) 0xc39f, // (12, 927) 156 - (short) 0xcb9f, // (12, 2975) 157 - (short) 0xc79f, // (12, 1951) 158 - (short) 0xcf9f, // (12, 3999) 159 - (short) 0xc05f, // (12, 95) 160 - (short) 0xc85f, // (12, 2143) 161 - (short) 0xc45f, // (12, 1119) 162 - (short) 0xcc5f, // (12, 3167) 163 - (short) 0xc25f, // (12, 607) 164 - (short) 0xca5f, // (12, 2655) 165 - (short) 0xc65f, // (12, 1631) 166 - (short) 0xce5f, // (12, 3679) 167 - (short) 0xc15f, // (12, 351) 168 - (short) 0xc95f, // (12, 2399) 169 - (short) 0xc55f, // (12, 1375) 170 - (short) 0xcd5f, // (12, 3423) 171 - (short) 0xc35f, // (12, 863) 172 - (short) 0xcb5f, // (12, 2911) 173 - (short) 0xc75f, // (12, 1887) 174 - (short) 0xcf5f, // (12, 3935) 175 - (short) 0xc0df, // (12, 223) 176 - (short) 0xc8df, // (12, 2271) 177 - (short) 0xc4df, // (12, 1247) 178 - (short) 0xccdf, // (12, 3295) 179 - (short) 0xc2df, // (12, 735) 180 - (short) 0xcadf, // (12, 2783) 181 - (short) 0xc6df, // (12, 1759) 182 - (short) 0xcedf, // (12, 3807) 183 - (short) 0xc1df, // (12, 479) 184 - (short) 0xc9df, // (12, 2527) 185 - (short) 0xc5df, // (12, 1503) 186 - (short) 0xcddf, // (12, 3551) 187 - (short) 0xc3df, // (12, 991) 188 - (short) 0xcbdf, // (12, 3039) 189 - (short) 0xc7df, // (12, 2015) 190 - (short) 0xcfdf, // (12, 4063) 191 - (short) 0xc03f, // (12, 63) 192 - (short) 0xc83f, // (12, 2111) 193 - (short) 0xc43f, // (12, 1087) 194 - (short) 0xcc3f, // (12, 3135) 195 - (short) 0xc23f, // (12, 575) 196 - (short) 0xca3f, // (12, 2623) 197 - (short) 0xc63f, // (12, 1599) 198 - (short) 0xce3f, // (12, 3647) 199 - (short) 0xc13f, // (12, 319) 200 - (short) 0xc93f, // (12, 2367) 201 - (short) 0xc53f, // (12, 1343) 202 - (short) 0xcd3f, // (12, 3391) 203 - (short) 0xc33f, // (12, 831) 204 - (short) 0xcb3f, // (12, 2879) 205 - (short) 0xc73f, // (12, 1855) 206 - (short) 0xcf3f, // (12, 3903) 207 - (short) 0xc0bf, // (12, 191) 208 - (short) 0xc8bf, // (12, 2239) 209 - (short) 0xc4bf, // (12, 1215) 210 - (short) 0xccbf, // (12, 3263) 211 - (short) 0xc2bf, // (12, 703) 212 - (short) 0xcabf, // (12, 2751) 213 - (short) 0xc6bf, // (12, 1727) 214 - (short) 0xcebf, // (12, 3775) 215 - (short) 0xc1bf, // (12, 447) 216 - (short) 0xc9bf, // (12, 2495) 217 - (short) 0xc5bf, // (12, 1471) 218 - (short) 0xcdbf, // (12, 3519) 219 - (short) 0xc3bf, // (12, 959) 220 - (short) 0xcbbf, // (12, 3007) 221 - (short) 0xc7bf, // (12, 1983) 222 - (short) 0xcfbf, // (12, 4031) 223 - (short) 0xc07f, // (12, 127) 224 - (short) 0xc87f, // (12, 2175) 225 - (short) 0xc47f, // (12, 1151) 226 - (short) 0xcc7f, // (12, 3199) 227 - (short) 0xc27f, // (12, 639) 228 - (short) 0xca7f, // (12, 2687) 229 - (short) 0xc67f, // (12, 1663) 230 - (short) 0xce7f, // (12, 3711) 231 - (short) 0xc17f, // (12, 383) 232 - (short) 0xc97f, // (12, 2431) 233 - (short) 0xc57f, // (12, 1407) 234 - (short) 0xcd7f, // (12, 3455) 235 - (short) 0xc37f, // (12, 895) 236 - (short) 0xcb7f, // (12, 2943) 237 - (short) 0xc77f, // (12, 1919) 238 - (short) 0xcf7f, // (12, 3967) 239 - (short) 0xc0ff, // (12, 255) 240 - (short) 0xc8ff, // (12, 2303) 241 - (short) 0xc4ff, // (12, 1279) 242 - (short) 0xccff, // (12, 3327) 243 - (short) 0xc2ff, // (12, 767) 244 - (short) 0xcaff, // (12, 2815) 245 - (short) 0xc6ff, // (12, 1791) 246 - (short) 0xceff, // (12, 3839) 247 - (short) 0xc1ff, // (12, 511) 248 - (short) 0xc9ff, // (12, 2559) 249 - (short) 0xc5ff, // (12, 1535) 250 - (short) 0xcdff, // (12, 3583) 251 - (short) 0xc3ff, // (12, 1023) 252 - (short) 0xcbff, // (12, 3071) 253 - (short) 0xc7ff, // (12, 2047) 254 - (short) 0xcfff // (12, 4095) 255 - } - }; - - /** - * Notice that there are only 65 symbols here, which is different from our - * usual 8 to 12 coding scheme which handles 256 symbols. - */ - static short[] lengthLimitedUnaryDecodingTable65 = null; - - static short[] lengthLimitedUnaryEncodingTable65 = new short[] //[65] - { - // Length-limited "unary" code with 65 symbols. - // entropy: 2.0 - // avg_length: 2.0249023437500000000; max_length = 12; num_symbols = 65 - - //table, (4 bits, 12 bits) symbol - //entry, (length, codeword) [byte] - (short) 0x1000, // ( 1, 0) 0 - (short) 0x2001, // ( 2, 1) 1 - (short) 0x3003, // ( 3, 3) 2 - (short) 0x4007, // ( 4, 7) 3 - (short) 0x500f, // ( 5, 15) 4 - (short) 0x701f, // ( 7, 31) 5 - (short) 0x805f, // ( 8, 95) 6 - (short) 0x80df, // ( 8, 223) 7 - (short) 0xa03f, // (10, 63) 8 - (short) 0xa23f, // (10, 575) 9 - (short) 0xb13f, // (11, 319) 10 - (short) 0xc53f, // (12, 1343) 11 - (short) 0xcd3f, // (12, 3391) 12 - (short) 0xc33f, // (12, 831) 13 - (short) 0xcb3f, // (12, 2879) 14 - (short) 0xc73f, // (12, 1855) 15 - (short) 0xcf3f, // (12, 3903) 16 - (short) 0xc0bf, // (12, 191) 17 - (short) 0xc8bf, // (12, 2239) 18 - (short) 0xc4bf, // (12, 1215) 19 - (short) 0xccbf, // (12, 3263) 20 - (short) 0xc2bf, // (12, 703) 21 - (short) 0xcabf, // (12, 2751) 22 - (short) 0xc6bf, // (12, 1727) 23 - (short) 0xcebf, // (12, 3775) 24 - (short) 0xc1bf, // (12, 447) 25 - (short) 0xc9bf, // (12, 2495) 26 - (short) 0xc5bf, // (12, 1471) 27 - (short) 0xcdbf, // (12, 3519) 28 - (short) 0xc3bf, // (12, 959) 29 - (short) 0xcbbf, // (12, 3007) 30 - (short) 0xc7bf, // (12, 1983) 31 - (short) 0xcfbf, // (12, 4031) 32 - (short) 0xc07f, // (12, 127) 33 - (short) 0xc87f, // (12, 2175) 34 - (short) 0xc47f, // (12, 1151) 35 - (short) 0xcc7f, // (12, 3199) 36 - (short) 0xc27f, // (12, 639) 37 - (short) 0xca7f, // (12, 2687) 38 - (short) 0xc67f, // (12, 1663) 39 - (short) 0xce7f, // (12, 3711) 40 - (short) 0xc17f, // (12, 383) 41 - (short) 0xc97f, // (12, 2431) 42 - (short) 0xc57f, // (12, 1407) 43 - (short) 0xcd7f, // (12, 3455) 44 - (short) 0xc37f, // (12, 895) 45 - (short) 0xcb7f, // (12, 2943) 46 - (short) 0xc77f, // (12, 1919) 47 - (short) 0xcf7f, // (12, 3967) 48 - (short) 0xc0ff, // (12, 255) 49 - (short) 0xc8ff, // (12, 2303) 50 - (short) 0xc4ff, // (12, 1279) 51 - (short) 0xccff, // (12, 3327) 52 - (short) 0xc2ff, // (12, 767) 53 - (short) 0xcaff, // (12, 2815) 54 - (short) 0xc6ff, // (12, 1791) 55 - (short) 0xceff, // (12, 3839) 56 - (short) 0xc1ff, // (12, 511) 57 - (short) 0xc9ff, // (12, 2559) 58 - (short) 0xc5ff, // (12, 1535) 59 - (short) 0xcdff, // (12, 3583) 60 - (short) 0xc3ff, // (12, 1023) 61 - (short) 0xcbff, // (12, 3071) 62 - (short) 0xc7ff, // (12, 2047) 63 - (short) 0xcfff // (12, 4095) 64 - }; - - /** - * Note: these column permutations are part of the encoding scheme for sketches where - * C ≥ 3.375 * K. - * In each row, we identify the (0-based) column indices of all surprising bits - * outside of the high-entropy byte. - * - *

These indices are "rotated right" via the formula - * new = (old - (8+shift_by) + 64) mod 64 = (old + 56 - shift_by) mod 64. - * resulting in canonicalized indices between 0 and 55 inclusive. - * - *

These are then mapped through the forwards permutation specified below (and selected - * by the phase of C / K). Finally, the remapped indices are encoding with a unary code - * (with delta encoding for rows containing more than one surprising bit). - */ - static byte[][] columnPermutationsForDecoding = new byte[16][]; //[16][56] - - /** - * These permutations were created by - * the ocaml program "generatePermutationsForSLIDING.ml". - */ - static final byte[][] columnPermutationsForEncoding = new byte[][] //[16] [56] - { - // for phase = 1 / 32 - {0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 34, 14, 4}, - // for phase = 3 / 32 - {0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 35, 15, 4}, - // for phase = 5 / 32 - {0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 37, 16, 5}, - // for phase = 7 / 32 - {0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 39, 17, 5}, - // for phase = 9 / 32 - {0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, - 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 41, 18, 6}, - // for phase = 11 / 32 - {0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 43, 19, 6}, - // for phase = 13 / 32 - {1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, - 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 45, 20, 7, 0}, - // for phase = 15 / 32 - {1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 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, 48, 49, 50, 51, 52, 53, 54, 55, 47, 21, 7, 0}, - // for phase = 17 / 32 - {1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, - 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, 51, 52, 53, 54, 55, 50, 22, 8, 0}, - // for phase = 19 / 32 - {0, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, - 22, 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, 53, 54, 55, 52, 23, 9, 1}, - // for phase = 21 / 32 - {0, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 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, 25, 9, 1}, - // for phase = 23 / 32 - {0, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 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, 26, 10, 1}, - // for phase = 25 / 32 - {0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 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, 27, 11, 2}, - // for phase = 27 / 32 - {0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 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, 29, 11, 2}, - // for phase = 29 / 32 - {0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, 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, 30, 12, 3}, - // for phase = 31 / 32 - {0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 32, 13, 3} - }; - - //Initialize this class - static { - makeTheDecodingTables(); - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/CpcCompression.java b/src/main/java/org/apache/datasketches/cpc/CpcCompression.java deleted file mode 100644 index aa73b94e7..000000000 --- a/src/main/java/org/apache/datasketches/cpc/CpcCompression.java +++ /dev/null @@ -1,840 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.cpc.CompressionData.columnPermutationsForDecoding; -import static org.apache.datasketches.cpc.CompressionData.columnPermutationsForEncoding; -import static org.apache.datasketches.cpc.CompressionData.decodingTablesForHighEntropyByte; -import static org.apache.datasketches.cpc.CompressionData.encodingTablesForHighEntropyByte; -import static org.apache.datasketches.cpc.CompressionData.lengthLimitedUnaryDecodingTable65; -import static org.apache.datasketches.cpc.CompressionData.lengthLimitedUnaryEncodingTable65; -import static org.apache.datasketches.cpc.PairTable.introspectiveInsertionSort; -//import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -final class CpcCompression { - //visible for test - static final int NEXT_WORD_IDX = 0; //ptrArr[NEXT_WORD_IDX] - static final int BIT_BUF = 1; //ptrArr[BIT_BUF] - static final int BUF_BITS = 2; //ptrArr[BUF_BITS] - - //visible for test - static void writeUnary( - final int[] compressedWords, - final long[] ptrArr, - final int theValue) { - - int nextWordIndex = (int) ptrArr[NEXT_WORD_IDX]; //must be int - assert (nextWordIndex == ptrArr[NEXT_WORD_IDX]); //catch truncation error - long bitBuf = ptrArr[BIT_BUF]; //must be long - int bufBits = (int) ptrArr[BUF_BITS]; //could be byte - - assert (compressedWords != null); - assert (nextWordIndex >= 0); - assert (bitBuf >= 0); - assert ((bufBits >= 0) && (bufBits <= 31)); - - int remaining = theValue; - - while (remaining >= 16) { - remaining -= 16; - // Here we output 16 zeros, but we don't need to physically write them into bitbuf - // because it already contains zeros in that region. - bufBits += 16; // Record the fact that 16 bits of output have occurred. - //MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex); - if (bufBits >= 32) { - compressedWords[nextWordIndex++] = (int) bitBuf; - bitBuf >>>= 32; - bufBits -= 32; - } - } - - assert (remaining >= 0) && (remaining <= 15); - - final long theUnaryCode = 1L << remaining; //must be a long - bitBuf |= theUnaryCode << bufBits; - bufBits += (1 + remaining); - //MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex); - if (bufBits >= 32) { - compressedWords[nextWordIndex++] = (int) bitBuf; - bitBuf >>>= 32; - bufBits -= 32; - } - - ptrArr[NEXT_WORD_IDX] = nextWordIndex; - assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; //catch sign extension error - ptrArr[BIT_BUF] = bitBuf; - ptrArr[BUF_BITS] = bufBits; - } - - //visible for test - static long readUnary( - final int[] compressedWords, - final long[] ptrArr) { - - int nextWordIndex = (int) ptrArr[NEXT_WORD_IDX]; //must be int - assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; //catch truncation error - long bitBuf = ptrArr[BIT_BUF]; - int bufBits = (int) ptrArr[BUF_BITS]; - - assert compressedWords != null; - assert nextWordIndex >= 0; - assert bitBuf >= 0; - assert bufBits >= 0; - - long subTotal = 0; - int trailingZeros; - - //readUnaryLoop: - while (true) { - //MAYBE_FILL_BITBUF(compressedWords,nextWordIndex,8); // ensure 8 bits in bit buffer - if (bufBits < 8) { // Prepare for an 8-bit peek into the bitstream. - bitBuf |= ((compressedWords[nextWordIndex++] & 0XFFFF_FFFFL) << bufBits); - bufBits += 32; - } - - // These 8 bits include either all or part of the Unary codeword. - final int peek8 = (int) (bitBuf & 0XFFL); - trailingZeros = Math.min(8, Integer.numberOfTrailingZeros(peek8)); - - assert ((trailingZeros >= 0) && (trailingZeros <= 8)) : "TZ+ " + trailingZeros; - - if (trailingZeros == 8) { // The codeword was partial, so read some more. - subTotal += 8; - bufBits -= 8; - bitBuf >>>= 8; - continue; - } - break; - } - - bufBits -= (1 + trailingZeros); - bitBuf >>>= (1 + trailingZeros); - - ptrArr[NEXT_WORD_IDX] = nextWordIndex; - assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; //catch sign extension error - ptrArr[BIT_BUF] = bitBuf; - ptrArr[BUF_BITS] = bufBits; - return subTotal + trailingZeros; - } - - /** - * This returns the number of compressedWords that were actually used. - * @param byteArray input - * @param numBytesToEncode input - * @param encodingTable input - * @param compressedWords output - * @return the number of compressedWords that were actually used. - */ - //visible for test - //It is the caller's responsibility to ensure that the compressedWords array is long enough. - static int lowLevelCompressBytes( - final byte[] byteArray, // input - final int numBytesToEncode, // input, must be an int - final short[] encodingTable, // input - final int[] compressedWords) { // output - - int nextWordIndex = 0; - long bitBuf = 0; // bits are packed into this first, then are flushed to compressedWords - int bufBits = 0; // number of bits currently in bitbuf; must be between 0 and 31 - - for (int byteIndex = 0; byteIndex < numBytesToEncode; byteIndex++) { - final int theByte = byteArray[byteIndex] & 0XFF; - final long codeInfo = (encodingTable[theByte] & 0XFFFFL); - final long codeVal = codeInfo & 0XFFFL; - final int codeWordLength = (int) (codeInfo >>> 12); - bitBuf |= (codeVal << bufBits); - bufBits += codeWordLength; - //MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex); - if (bufBits >= 32) { - compressedWords[nextWordIndex++] = (int) bitBuf; - bitBuf >>>= 32; - bufBits -= 32; - } - } - - //Pad the bitstream with 11 zero-bits so that the decompressor's 12-bit peek - // can't overrun its input. - bufBits += 11; - //MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex); - if (bufBits >= 32) { - compressedWords[nextWordIndex++] = (int) bitBuf; - bitBuf >>>= 32; - bufBits -= 32; - } - - if (bufBits > 0) { // We are done encoding now, so we flush the bit buffer. - assert (bufBits < 32); - compressedWords[nextWordIndex++] = (int) bitBuf; - } - return nextWordIndex; - } - - //visible for test - static void lowLevelUncompressBytes( - final byte[] byteArray, // output - final int numBytesToDecode, // input (but refers to the output) - final short[] decodingTable, // input - final int[] compressedWords, // input - final long numCompressedWords) { // input - - int byteIndex = 0; - int nextWordIndex = 0; - long bitBuf = 0; - int bufBits = 0; - - assert (byteArray != null); - assert (decodingTable != null); - assert (compressedWords != null); - - for (byteIndex = 0; byteIndex < numBytesToDecode; byteIndex++) { - //MAYBE_FILL_BITBUF(compressedWords,wordIndex,12); // ensure 12 bits in bit buffer - if (bufBits < 12) { // Prepare for a 12-bit peek into the bitstream. - bitBuf |= ((compressedWords[nextWordIndex++] & 0XFFFF_FFFFL) << bufBits); - bufBits += 32; - } - - // These 12 bits will include an entire Huffman codeword. - final int peek12 = (int) (bitBuf & 0XFFFL); - final int lookup = decodingTable[peek12] & 0XFFFF; - final int codeWordLength = lookup >>> 8; - final byte decodedByte = (byte) (lookup & 0XFF); - byteArray[byteIndex] = decodedByte; - bitBuf >>>= codeWordLength; - bufBits -= codeWordLength; - } - - // Buffer over-run should be impossible unless there is a bug. - // However, we might as well check here. - assert (nextWordIndex <= numCompressedWords); - } - - /** - * Here "pairs" refers to row/column pairs that specify the positions of surprising values in - * the bit matrix. - * @param pairArray input - * @param numPairsToEncode input - * @param numBaseBits input - * @param compressedWords output - * @return the number of compressedWords actually used - */ - //visible for test - static long lowLevelCompressPairs( - final int[] pairArray, // input - final int numPairsToEncode, // input - final int numBaseBits, // input //cannot exceed 63 or 6 bits, could be byte - final int[] compressedWords) { // output - - int pairIndex = 0; - - final long[] ptrArr = new long[3]; - int nextWordIndex = 0; //must be int - long bitBuf = 0; //must be long - int bufBits = 0; //could be byte - - final long golombLoMask = (1L << numBaseBits) - 1L; - - int predictedRowIndex = 0; - int predictedColIndex = 0; - - for (pairIndex = 0; pairIndex < numPairsToEncode; pairIndex++) { - final int rowCol = pairArray[pairIndex]; - final int rowIndex = rowCol >>> 6; - final int colIndex = rowCol & 0X3F; //63 - - if (rowIndex != predictedRowIndex) { predictedColIndex = 0; } - - assert (rowIndex >= predictedRowIndex); - assert (colIndex >= predictedColIndex); - - final long yDelta = rowIndex - predictedRowIndex; //cannot exceed 2^26 - final int xDelta = colIndex - predictedColIndex; //cannot exceed 65 - - predictedRowIndex = rowIndex; - predictedColIndex = colIndex + 1; - - final long codeInfo = lengthLimitedUnaryEncodingTable65[xDelta] & 0XFFFFL; - final long codeVal = codeInfo & 0XFFFL; - final int codeLen = (int) (codeInfo >>> 12); - bitBuf |= (codeVal << bufBits); - bufBits += codeLen; - //MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex); - if (bufBits >= 32) { - compressedWords[nextWordIndex++] = (int) bitBuf; - bitBuf >>>= 32; - bufBits -= 32; - } - - final long golombLo = yDelta & golombLoMask; //long for bitBuf - final long golombHi = yDelta >>> numBaseBits; //cannot exceed 2^26 - - // Inline WriteUnary - ptrArr[NEXT_WORD_IDX] = nextWordIndex; - ptrArr[BIT_BUF] = bitBuf; - ptrArr[BUF_BITS] = bufBits; - assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; //catch sign extension error - - writeUnary(compressedWords, ptrArr, (int) golombHi); - - nextWordIndex = (int) ptrArr[NEXT_WORD_IDX]; - bitBuf = ptrArr[BIT_BUF]; - bufBits = (int) ptrArr[BUF_BITS]; - assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; //catch truncation error - //END Inline WriteUnary - - bitBuf |= golombLo << bufBits; - bufBits += numBaseBits; - //MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex); - if (bufBits >= 32) { - compressedWords[nextWordIndex++] = (int) bitBuf; - bitBuf >>>= 32; - bufBits -= 32; - } - } - - // Pad the bitstream so that the decompressor's 12-bit peek can't overrun its input. - int padding = 10 - numBaseBits; - if (padding < 0) { padding = 0; } - bufBits += padding; - //MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex); - if (bufBits >= 32) { - compressedWords[nextWordIndex++] = (int) bitBuf; - bitBuf >>>= 32; - bufBits -= 32; - } - - if (bufBits > 0) { // We are done encoding now, so we flush the bit buffer. - assert (bufBits < 32); - compressedWords[nextWordIndex++] = (int) bitBuf; - //bitBuf = 0; - //bufBits = 0; // not really necessary - } - return nextWordIndex; - } - - //visible for test - static void lowLevelUncompressPairs( - final int[] pairArray, // output - final int numPairsToDecode, // input, size of output, must be int - final int numBaseBits, // input, cannot exceed 6 bits - final int[] compressedWords, // input - final long numCompressedWords) { // input - - int pairIndex = 0; - - final long[] ptrArr = new long[3]; - int nextWordIndex = 0; - long bitBuf = 0; - int bufBits = 0; - - final long golombLoMask = (1L << numBaseBits) - 1L; - - int predictedRowIndex = 0; - int predictedColIndex = 0; - - // for each pair we need to read: - // xDelta (12-bit length-limited unary) - // yDeltaHi (unary) - // yDeltaLo (basebits) - - for (pairIndex = 0; pairIndex < numPairsToDecode; pairIndex++) { - - //MAYBE_FILL_BITBUF(compressedWords,wordIndex,12); // ensure 12 bits in bit buffer - if (bufBits < 12) { // Prepare for a 12-bit peek into the bitstream. - bitBuf |= ((compressedWords[nextWordIndex++] & 0XFFFF_FFFFL) << bufBits); - bufBits += 32; - } - - final int peek12 = (int) (bitBuf & 0XFFFL); - final int lookup = lengthLimitedUnaryDecodingTable65[peek12] & 0XFFFF; - final int codeWordLength = lookup >>> 8; - final int xDelta = lookup & 0XFF; - bitBuf >>>= codeWordLength; - bufBits -= codeWordLength; - - // Inline ReadUnary - ptrArr[NEXT_WORD_IDX] = nextWordIndex; - ptrArr[BIT_BUF] = bitBuf; - ptrArr[BUF_BITS] = bufBits; - assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; //catch sign extension error - - final long golombHi = readUnary(compressedWords, ptrArr); - - nextWordIndex = (int) ptrArr[NEXT_WORD_IDX]; - bitBuf = ptrArr[BIT_BUF]; - bufBits = (int) ptrArr[BUF_BITS]; - assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; //catch truncation error - //END Inline ReadUnary - - //MAYBE_FILL_BITBUF(compressedWords,wordIndex,numBaseBits); // ensure numBaseBits in bit buffer - if (bufBits < numBaseBits) { // Prepare for a numBaseBits peek into the bitstream. - bitBuf |= ((compressedWords[nextWordIndex++] & 0XFFFF_FFFFL) << bufBits); - bufBits += 32; - } - - final long golombLo = bitBuf & golombLoMask; - bitBuf >>>= numBaseBits; - bufBits -= numBaseBits; - final long yDelta = (golombHi << numBaseBits) | golombLo; - - // Now that we have yDelta and xDelta, we can compute the pair's row and column. - if (yDelta > 0) { predictedColIndex = 0; } - final int rowIndex = predictedRowIndex + (int) yDelta; - final int colIndex = predictedColIndex + xDelta; - final int rowCol = (rowIndex << 6) | colIndex; - pairArray[pairIndex] = rowCol; - predictedRowIndex = rowIndex; - predictedColIndex = colIndex + 1; - } - // check for buffer over-run - assert (nextWordIndex <= numCompressedWords) - : "nextWdIdx: " + nextWordIndex + ", #CompWds: " + numCompressedWords; - } - - private static int safeLengthForCompressedPairBuf( - final long k, final long numPairs, final long numBaseBits) { - assert (numPairs > 0); - // long ybits = k + numPairs; // simpler and safer UB - // The following tighter UB on ybits is based on page 198 - // of the textbook "Managing Gigabytes" by Witten, Moffat, and Bell. - // Notice that if numBaseBits == 0 it coincides with (k + numPairs). - final long ybits = (numPairs * (1L + numBaseBits)) + (k >>> numBaseBits); - final long xbits = 12 * numPairs; - long padding = 10L - numBaseBits; - if (padding < 0) { padding = 0; } - final long bits = xbits + ybits + padding; - //final long words = divideLongsRoundingUp(bits, 32); - final long words = CpcCompression.divideBy32RoundingUp(bits); - assert words < (1L << 31); - return (int) words; - } - - // Explanation of padding: we write - // 1) xdelta (huffman, provides at least 1 bit, requires 12-bit lookahead) - // 2) ydeltaGolombHi (unary, provides at least 1 bit, requires 8-bit lookahead) - // 3) ydeltaGolombLo (straight B bits). - // So the 12-bit lookahead is the tight constraint, but there are at least (2 + B) bits emitted, - // so we would be safe with max (0, 10 - B) bits of padding at the end of the bitstream. - private static int safeLengthForCompressedWindowBuf(final long k) { // measured in 32-bit words - // 11 bits of padding, due to 12-bit lookahead, with 1 bit certainly present. - final long bits = (12 * k) + 11; - //cannot exceed Integer.MAX_VALUE - //return (int) (divideLongsRoundingUp(bits, 32)); - return (int) CpcCompression.divideBy32RoundingUp(bits); - } - - private static int determinePseudoPhase(final int lgK, final long numCoupons) { - final long k = 1L << lgK; - final long c = numCoupons; - // This midrange logic produces pseudo-phases. They are used to select encoding tables. - // The thresholds were chosen by hand after looking at plots of measured compression. - if ((1000 * c) < (2375 * k)) { - if ( (4 * c) < (3 * k)) { return ( 16 + 0 ); } // midrange table - else if ( (10 * c) < (11 * k)) { return ( 16 + 1 ); } // midrange table - else if ( (100 * c) < (132 * k)) { return ( 16 + 2 ); } // midrange table - else if ( (3 * c) < (5 * k)) { return ( 16 + 3 ); } // midrange table - else if ((1000 * c) < (1965 * k)) { return ( 16 + 4 ); } // midrange table - else if ((1000 * c) < (2275 * k)) { return ( 16 + 5 ); } // midrange table - else { return 6; } // steady-state table employed before its actual phase - } - else { - // This steady-state logic produces true phases. They are used to select - // encoding tables, and also column permutations for the "Sliding" flavor. - assert lgK >= 4; - final long tmp = c >>> (lgK - 4); - final int phase = (int) (tmp & 15L); - assert (phase >= 0) && (phase < 16); - return phase; - } - } - - private static void compressTheWindow(final CompressedState target, final CpcSketch source) { - final int srcLgK = source.lgK; - final int srcK = 1 << srcLgK; - final int windowBufLen = safeLengthForCompressedWindowBuf(srcK); - final int[] windowBuf = new int[windowBufLen]; - final int pseudoPhase = determinePseudoPhase(srcLgK, source.numCoupons); - target.cwLengthInts = lowLevelCompressBytes( - source.slidingWindow, - srcK, - encodingTablesForHighEntropyByte[pseudoPhase], - windowBuf); - - // At this point we free the unused portion of the compression output buffer. - // final int[] shorterBuf = Arrays.copyOf(windowBuf, target.cwLength); - // target.compressedWindow = shorterBuf; - target.cwStream = windowBuf; //avoid extra copy - } - - private static void uncompressTheWindow(final CpcSketch target, final CompressedState source) { - final int srcLgK = source.lgK; - final int srcK = 1 << srcLgK; - final byte[] window = new byte[srcK]; - // bzero ((void *) window, (size_t) k); // zeroing not needed here (unlike the Hybrid Flavor) - assert (target.slidingWindow == null); - target.slidingWindow = window; - final int pseudoPhase = determinePseudoPhase(srcLgK, source.numCoupons); - assert (source.cwStream != null); - lowLevelUncompressBytes(target.slidingWindow, srcK, - decodingTablesForHighEntropyByte[pseudoPhase], - source.cwStream, - source.cwLengthInts); - } - - private static void compressTheSurprisingValues(final CompressedState target, final CpcSketch source, - final int[] pairs, final int numPairs) { - assert (numPairs > 0); - target.numCsv = numPairs; - final int srcK = 1 << source.lgK; - final int numBaseBits = CpcCompression.golombChooseNumberOfBaseBits(srcK + numPairs, numPairs); - final int pairBufLen = safeLengthForCompressedPairBuf(srcK, numPairs, numBaseBits); - final int[] pairBuf = new int[pairBufLen]; - - target.csvLengthInts = (int) lowLevelCompressPairs(pairs, numPairs, numBaseBits, pairBuf); - - // At this point we free the unused portion of the compression output buffer. - // final int[] shorterBuf = Arrays.copyOf(pairBuf, target.csvLength); - // target.compressedWindow = shorterBuf; - - target.csvStream = pairBuf; //avoid extra copy - } - - //allocates and returns an array of uncompressed pairs. - //the length of this array is known to the source sketch. - private static int[] uncompressTheSurprisingValues(final CompressedState source) { - final int srcK = 1 << source.lgK; - final int numPairs = source.numCsv; - assert numPairs > 0; - final int[] pairs = new int[numPairs]; - final int numBaseBits = CpcCompression.golombChooseNumberOfBaseBits(srcK + numPairs, numPairs); - lowLevelUncompressPairs(pairs, numPairs, numBaseBits, source.csvStream, source.csvLengthInts); - return pairs; - } - - private static void compressSparseFlavor(final CompressedState target, final CpcSketch source) { - assert (source.slidingWindow == null); //there is no window to compress - final PairTable srcPairTable = source.pairTable; - final int srcNumPairs = srcPairTable.getNumPairs(); - final int[] srcPairArr = PairTable.unwrappingGetItems(srcPairTable, srcNumPairs); - introspectiveInsertionSort(srcPairArr, 0, srcNumPairs - 1); - compressTheSurprisingValues(target, source, srcPairArr, srcNumPairs); - } - - private static void uncompressSparseFlavor(final CpcSketch target, final CompressedState source) { - assert (source.cwStream == null); - assert (source.csvStream != null); - final int[] srcPairArr = uncompressTheSurprisingValues(source); - final int numPairs = source.numCsv; - final PairTable table = PairTable.newInstanceFromPairsArray(srcPairArr, numPairs, source.lgK); - target.pairTable = table; - } - - //The empty space that this leaves at the beginning of the output array - // will be filled in later by the caller. - private static int[] trickyGetPairsFromWindow(final byte[] window, final int k, final int numPairsToGet, - final int emptySpace) { - final int outputLength = emptySpace + numPairsToGet; - final int[] pairs = new int[outputLength]; - int rowIndex = 0; - int pairIndex = emptySpace; - for (rowIndex = 0; rowIndex < k; rowIndex++) { - int wByte = window[rowIndex] & 0XFF; - while (wByte != 0) { - final int colIndex = Integer.numberOfTrailingZeros(wByte); - // assert (colIndex < 8); - wByte ^= (1 << colIndex); // erase the 1 - pairs[pairIndex++] = (rowIndex << 6) | colIndex; - } - } - assert (pairIndex == outputLength); - return (pairs); - } - - //This is complicated because it effectively builds a Sparse version - //of a Pinned sketch before compressing it. Hence the name Hybrid. - private static void compressHybridFlavor(final CompressedState target, final CpcSketch source) { - final int srcK = 1 << source.lgK; - final PairTable srcPairTable = source.pairTable; - final int srcNumPairs = srcPairTable.getNumPairs(); - final int[] srcPairArr = PairTable.unwrappingGetItems(srcPairTable, srcNumPairs); - introspectiveInsertionSort(srcPairArr, 0, srcNumPairs - 1); - final byte[] srcSlidingWindow = source.slidingWindow; - final int srcWindowOffset = source.windowOffset; - final long srcNumCoupons = source.numCoupons; - assert (srcSlidingWindow != null); - assert (srcWindowOffset == 0); - final long numPairs = srcNumCoupons - srcNumPairs; // because the window offset is zero - assert numPairs < Integer.MAX_VALUE; - final int numPairsFromArray = (int) numPairs; - - assert (numPairsFromArray + srcNumPairs) == srcNumCoupons; //for test - final int[] allPairs - = trickyGetPairsFromWindow(srcSlidingWindow, srcK, numPairsFromArray, srcNumPairs); - - PairTable.merge(srcPairArr, 0, srcNumPairs, - allPairs, srcNumPairs, numPairsFromArray, - allPairs, 0); // note the overlapping subarray trick - - //FOR TESTING If needed - // for (int i = 0; i < (source.numCoupons - 1); i++) { - // assert (Integer.compareUnsigned(allPairs[i], allPairs[i + 1]) < 0); } - - compressTheSurprisingValues(target, source, allPairs, (int) srcNumCoupons); - } - - private static void uncompressHybridFlavor(final CpcSketch target, final CompressedState source) { - assert (source.cwStream == null); - assert (source.csvStream != null); - final int[] pairs = uncompressTheSurprisingValues(source); //fail path 3 - final int numPairs = source.numCsv; - // In the hybrid flavor, some of these pairs actually - // belong in the window, so we will separate them out, - // moving the "true" pairs to the bottom of the array. - final int srcLgK = source.lgK; - final int k = 1 << srcLgK; - - final byte[] window = new byte[k]; - - int nextTruePair = 0; - - for (int i = 0; i < numPairs; i++) { - final int rowCol = pairs[i]; - assert (rowCol != -1); - final int col = rowCol & 63; - if (col < 8) { - final int row = rowCol >>> 6; - window[row] |= (1 << col); // set the window bit - } - else { - pairs[nextTruePair++] = rowCol; // move true pair down - } - } - - assert (source.getWindowOffset() == 0); - target.windowOffset = 0; - - final PairTable table = PairTable.newInstanceFromPairsArray(pairs, nextTruePair, srcLgK); - target.pairTable = table; - target.slidingWindow = window; - } - - private static void compressPinnedFlavor(final CompressedState target, final CpcSketch source) { - compressTheWindow(target, source); - final PairTable srcPairTable = source.pairTable; - final int numPairs = srcPairTable.getNumPairs(); - - if (numPairs > 0) { - final int[] pairs = PairTable.unwrappingGetItems(srcPairTable, numPairs); - - // Here we subtract 8 from the column indices. Because they are stored in the low 6 bits - // of each rowCol pair, and because no column index is less than 8 for a "Pinned" sketch, - // I believe we can simply subtract 8 from the pairs themselves. - - // shift the columns over by 8 positions before compressing (because of the window) - for (int i = 0; i < numPairs; i++) { - assert (pairs[i] & 63) >= 8; - pairs[i] -= 8; - } - - introspectiveInsertionSort(pairs, 0, numPairs - 1); - compressTheSurprisingValues(target, source, pairs, numPairs); - } - } - - private static void uncompressPinnedFlavor(final CpcSketch target, final CompressedState source) { - assert (source.cwStream != null); - uncompressTheWindow(target, source); - final int srcLgK = source.lgK; - final int numPairs = source.numCsv; - if (numPairs == 0) { - target.pairTable = new PairTable(2, 6 + srcLgK); - } - else { - assert numPairs > 0; - assert source.csvStream != null; - final int[] pairs = uncompressTheSurprisingValues(source); - // undo the compressor's 8-column shift - for (int i = 0; i < numPairs; i++) { - assert (pairs[i] & 63) < 56; - pairs[i] += 8; - } - final PairTable table = PairTable.newInstanceFromPairsArray(pairs, numPairs, srcLgK); - target.pairTable = table; - } - } - - //Complicated by the existence of both a left fringe and a right fringe. - private static void compressSlidingFlavor(final CompressedState target, final CpcSketch source) { - - compressTheWindow(target, source); - final PairTable srcPairTable = source.pairTable; - - final int numPairs = srcPairTable.getNumPairs(); - - if (numPairs > 0) { - final int[] pairs = PairTable.unwrappingGetItems(srcPairTable, numPairs); - - // Here we apply a complicated transformation to the column indices, which - // changes the implied ordering of the pairs, so we must do it before sorting. - - final int pseudoPhase = determinePseudoPhase(source.lgK, source.numCoupons); // NB - assert (pseudoPhase < 16); - final byte[] permutation = columnPermutationsForEncoding[pseudoPhase]; - - final int offset = source.windowOffset; - assert ((offset > 0) && (offset <= 56)); - - for (int i = 0; i < numPairs; i++) { - final int rowCol = pairs[i]; - final int row = rowCol >>> 6; - int col = (rowCol & 63); - // first rotate the columns into a canonical configuration: - // new = ((old - (offset+8)) + 64) mod 64 - col = ((col + 56) - offset) & 63; - assert (col >= 0) && (col < 56); - // then apply the permutation - col = permutation[col]; - pairs[i] = (row << 6) | col; - } - - introspectiveInsertionSort(pairs, 0, numPairs - 1); - compressTheSurprisingValues(target, source, pairs, numPairs); - } - } - - private static void uncompressSlidingFlavor(final CpcSketch target, final CompressedState source) { - assert (source.cwStream != null); - uncompressTheWindow(target, source); - final int srcLgK = source.lgK; - final int numPairs = source.numCsv; - if (numPairs == 0) { - target.pairTable = new PairTable(2, 6 + srcLgK); - } - else { - assert (numPairs > 0); - assert (source.csvStream != null); - final int[] pairs = uncompressTheSurprisingValues(source); - final int pseudoPhase = determinePseudoPhase(srcLgK, source.numCoupons); // NB - assert (pseudoPhase < 16); - final byte[] permutation = columnPermutationsForDecoding[pseudoPhase]; - - final int offset = source.getWindowOffset(); - assert (offset > 0) && (offset <= 56); - - for (int i = 0; i < numPairs; i++) { - final int rowCol = pairs[i]; - final int row = rowCol >>> 6; - int col = rowCol & 63; - // first undo the permutation - col = permutation[col]; - // then undo the rotation: old = (new + (offset+8)) mod 64 - col = (col + (offset + 8)) & 63; - pairs[i] = (row << 6) | col; - } - - final PairTable table = PairTable.newInstanceFromPairsArray(pairs, numPairs, srcLgK); - target.pairTable = table; - } - } - - static CompressedState compress(final CpcSketch source, final CompressedState target) { - - final Flavor srcFlavor = source.getFlavor(); - - switch (srcFlavor) { - case EMPTY: break; - case SPARSE: - compressSparseFlavor(target, source); - assert (target.cwStream == null); - assert (target.csvStream != null); - break; - case HYBRID: - compressHybridFlavor(target, source); - assert (target.cwStream == null); - assert (target.csvStream != null); - break; - case PINNED: - compressPinnedFlavor(target, source); - assert (target.cwStream != null); - break; - case SLIDING: - compressSlidingFlavor(target, source); - assert (target.cwStream != null); - break; - //default: not possible - } - - return target; - } - - static CpcSketch uncompress(final CompressedState source, final CpcSketch target) { - assert (target != null); - - final Flavor srcFlavor = source.getFlavor(); - switch (srcFlavor) { - case EMPTY: break; - case SPARSE: - assert (source.cwStream == null); - uncompressSparseFlavor(target, source); - break; - case HYBRID: - uncompressHybridFlavor(target, source); - break; - case PINNED: - assert (source.cwStream != null); - uncompressPinnedFlavor(target, source); - break; - case SLIDING: - uncompressSlidingFlavor(target, source); - break; - //default: not possible - } - return target; - } - - private static int golombChooseNumberOfBaseBits(final int k, final long count) { - assert k >= 1L; - assert count >= 1L; - final long quotient = (k - count) / count; // integer division - if (quotient == 0) { return 0; } - return (int) floorLog2ofLong(quotient); - } - - private static long floorLog2ofLong(final long x) { //not a good name - assert (x >= 1L); - long p = 0; - long y = 1; - while (true) { - if (y == x) { return p; } - if (y > x) { return p - 1; } - p += 1; - y <<= 1; - } - } - - private static long divideBy32RoundingUp(final long x) { - final long tmp = x >>> 5; - return ((tmp << 5) == x) ? tmp : tmp + 1; - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/CpcConfidence.java b/src/main/java/org/apache/datasketches/cpc/CpcConfidence.java deleted file mode 100644 index d948678b6..000000000 --- a/src/main/java/org/apache/datasketches/cpc/CpcConfidence.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static java.lang.Math.ceil; -import static java.lang.Math.log; -import static java.lang.Math.sqrt; -import static org.apache.datasketches.cpc.IconEstimator.getIconEstimate; - -/** - * Tables and methods for estimating upper and lower bounds. - * - *

Tables were generated from empirical measurements at N = 1000 * K using millions of trials. - * - * @author Lee Rhodes - */ -final class CpcConfidence { - private static final double iconErrorConstant = log(2.0); //0.693147180559945286 - private static final double hipErrorConstant = sqrt(log(2.0) / 2.0); //0.588705011257737332 - - static short[] iconLowSideData = { - //1, 2, 3, kappa - // lgK numtrials - 6037, 5720, 5328, // 4 1000000 - 6411, 6262, 5682, // 5 1000000 - 6724, 6403, 6127, // 6 1000000 - 6665, 6411, 6208, // 7 1000000 - 6959, 6525, 6427, // 8 1000000 - 6892, 6665, 6619, // 9 1000000 - 6792, 6752, 6690, // 10 1000000 - 6899, 6818, 6708, // 11 1000000 - 6871, 6845, 6812, // 12 1046369 - 6909, 6861, 6828, // 13 1043411 - 6919, 6897, 6842, // 14 1000297 - }; - - static short[] iconHighSideData = { - //1, 2, 3, kappa - // lgK numtrials - 8031, 8559, 9309, // 4 1000000 - 7084, 7959, 8660, // 5 1000000 - 7141, 7514, 7876, // 6 1000000 - 7458, 7430, 7572, // 7 1000000 - 6892, 7141, 7497, // 8 1000000 - 6889, 7132, 7290, // 9 1000000 - 7075, 7118, 7185, // 10 1000000 - 7040, 7047, 7085, // 11 1000000 - 6993, 7019, 7053, // 12 1046369 - 6953, 7001, 6983, // 13 1043411 - 6944, 6966, 7004, // 14 1000297 - }; - - static short[] hipLowSideData = { - //1, 2, 3, kappa - // lgK numtrials - 5871, 5247, 4826, // 4 1000000 - 5877, 5403, 5070, // 5 1000000 - 5873, 5533, 5304, // 6 1000000 - 5878, 5632, 5464, // 7 1000000 - 5874, 5690, 5564, // 8 1000000 - 5880, 5745, 5619, // 9 1000000 - 5875, 5784, 5701, // 10 1000000 - 5866, 5789, 5742, // 11 1000000 - 5869, 5827, 5784, // 12 1046369 - 5876, 5860, 5827, // 13 1043411 - 5881, 5853, 5842, // 14 1000297 - }; - - static short[] hipHighSideData = { - //1, 2, 3, kappa - // lgK numtrials - 5855, 6688, 7391, // 4 1000000 - 5886, 6444, 6923, // 5 1000000 - 5885, 6254, 6594, // 6 1000000 - 5889, 6134, 6326, // 7 1000000 - 5900, 6072, 6203, // 8 1000000 - 5875, 6005, 6089, // 9 1000000 - 5871, 5980, 6040, // 10 1000000 - 5889, 5941, 6015, // 11 1000000 - 5871, 5926, 5973, // 12 1046369 - 5866, 5901, 5915, // 13 1043411 - 5880, 5914, 5953, // 14 1000297 - }; - - static double getIconConfidenceLB(final int lgK, final long numCoupons, final int kappa) { - if (numCoupons == 0) { return 0.0; } - assert lgK >= 4; - assert (kappa >= 1) && (kappa <= 3); - double x = iconErrorConstant; - if (lgK <= 14) { x = (iconHighSideData[(3 * (lgK - 4)) + (kappa - 1)]) / 10000.0; } - final double rel = x / sqrt(1 << lgK); - final double eps = kappa * rel; - final double est = getIconEstimate(lgK, numCoupons); - double result = est / (1.0 + eps); - if (result < numCoupons) { result = numCoupons; } - return result; - } - - static double getIconConfidenceUB(final int lgK, final long numCoupons, final int kappa) { - if (numCoupons == 0) { return 0.0; } - assert lgK >= 4; - assert (kappa >= 1) && (kappa <= 3); - double x = iconErrorConstant; - if (lgK <= 14) { x = (iconLowSideData[(3 * (lgK - 4)) + (kappa - 1)]) / 10000.0; } - final double rel = x / sqrt(1 << lgK); - final double eps = kappa * rel; - final double est = getIconEstimate(lgK, numCoupons); - final double result = est / (1.0 - eps); - return ceil(result); // slight widening of interval to be conservative - } - - //mergeFlag must already be checked as false - static double getHipConfidenceLB(final int lgK, final long numCoupons, final double hipEstAccum, - final int kappa) { - if (numCoupons == 0) { return 0.0; } - assert lgK >= 4; - assert (kappa >= 1) && (kappa <= 3); - double x = hipErrorConstant; - if (lgK <= 14) { x = (hipHighSideData[(3 * (lgK - 4)) + (kappa - 1)]) / 10000.0; } - final double rel = x / sqrt(1 << lgK); - final double eps = kappa * rel; - final double est = hipEstAccum; - double result = est / (1.0 + eps); - if (result < numCoupons) { result = numCoupons; } - return result; - } - - //mergeFlag must already be checked as false - static double getHipConfidenceUB(final int lgK, final long numCoupons, final double hipEstAccum, - final int kappa) { - if (numCoupons == 0) { return 0.0; } - assert lgK >= 4; - assert (kappa >= 1) && (kappa <= 3); - double x = hipErrorConstant; - if (lgK <= 14) { x = (hipLowSideData[(3 * (lgK - 4)) + (kappa - 1)]) / 10000.0; } - final double rel = x / sqrt(1 << lgK); - final double eps = kappa * rel; - final double est = hipEstAccum; - final double result = est / (1.0 - eps); - return ceil(result); // widening for coverage - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/CpcSketch.java b/src/main/java/org/apache/datasketches/cpc/CpcSketch.java deleted file mode 100644 index d5e17388a..000000000 --- a/src/main/java/org/apache/datasketches/cpc/CpcSketch.java +++ /dev/null @@ -1,804 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static java.lang.Math.log; -import static java.lang.Math.sqrt; -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.invPow2; -import static org.apache.datasketches.common.Util.zeroPad; -import static org.apache.datasketches.cpc.CpcUtil.bitMatrixOfSketch; -import static org.apache.datasketches.cpc.CpcUtil.checkLgK; -import static org.apache.datasketches.cpc.CpcUtil.countBitsSetInMatrix; -import static org.apache.datasketches.hash.MurmurHash3.hash; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; -import java.util.Arrays; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.Util; - -/** - * This is a unique-counting sketch that implements the - * Compressed Probabilistic Counting (CPC, a.k.a FM85) algorithms developed by Kevin Lang in - * his paper - * Back to the Future: an Even More Nearly - * Optimal Cardinality Estimation Algorithm. - * - *

This sketch is extremely space-efficient when serialized. In an apples-to-apples empirical - * comparison against compressed HyperLogLog sketches, this new algorithm simultaneously wins on - * the two dimensions of the space/accuracy tradeoff and produces sketches that are - * smaller than the entropy of HLL, so no possible implementation of compressed HLL can match its - * space efficiency for a given accuracy. As described in the paper this sketch implements a newly - * developed ICON estimator algorithm that survives unioning operations, another - * well-known estimator, the - * Historical Inverse Probability (HIP) estimator - * does not. - * The update speed performance of this sketch is quite fast and is comparable to the speed of HLL. - * The unioning (merging) capability of this sketch also allows for merging of sketches with - * different configurations of K. - * - *

For additional security this sketch can be configured with a user-specified hash seed. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -public final class CpcSketch { - private static final double[] kxpByteLookup = new double[256]; - - /** - * The default Log_base2 of K - */ - public static final int DEFAULT_LG_K = 11; - final long seed; - //common variables - final int lgK; - long numCoupons; // The number of coupons collected so far. - boolean mergeFlag; // Is the sketch the result of merging? - int fiCol; // First Interesting Column. This is part of a speed optimization. - - int windowOffset; - byte[] slidingWindow; //either null or size K bytes - PairTable pairTable; //for sparse and surprising values, either null or variable size - - //The following variables are only valid in HIP variants - double kxp; //used with HIP - double hipEstAccum; //used with HIP - - /** - * Constructor with default log_base2 of k - */ - public CpcSketch() { - this(DEFAULT_LG_K, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Constructor with log_base2 of k. - * @param lgK the given log_base2 of k - */ - public CpcSketch(final int lgK) { - this(lgK, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Constructor with log_base2 of k and seed. - * @param lgK the given log_base2 of k - * @param seed the given seed - */ - public CpcSketch(final int lgK, final long seed) { - checkLgK(lgK); - this.lgK = (byte) lgK; - this.seed = seed; - kxp = 1 << lgK; - reset(); - } - - /** - * Returns a copy of this sketch - * @return a copy of this sketch - */ - CpcSketch copy() { - final CpcSketch copy = new CpcSketch(lgK, seed); - copy.numCoupons = numCoupons; - copy.mergeFlag = mergeFlag; - copy.fiCol = fiCol; - - copy.windowOffset = windowOffset; - copy.slidingWindow = (slidingWindow == null) ? null : slidingWindow.clone(); - copy.pairTable = (pairTable == null) ? null : pairTable.copy(); - - copy.kxp = kxp; - copy.hipEstAccum = hipEstAccum; - return copy; - } - - /** - * Returns the best estimate of the cardinality of the sketch. - * @return the best estimate of the cardinality of the sketch. - */ - public double getEstimate() { - if (mergeFlag) { return IconEstimator.getIconEstimate(lgK, numCoupons); } - return hipEstAccum; - } - - /** - * Return the DataSketches identifier for this CPC family of sketches. - * @return the DataSketches identifier for this CPC family of sketches. - */ - public static Family getFamily() { - return Family.CPC; - } - - /** - * Return the parameter LgK. - * @return the parameter LgK. - */ - public int getLgK() { - return lgK; - } - - /** - * Returns the best estimate of the lower bound of the confidence interval given kappa, - * the number of standard deviations from the mean. - * @param kappa the given number of standard deviations from the mean: 1, 2 or 3. - * @return the best estimate of the lower bound of the confidence interval given kappa. - */ - public double getLowerBound(final int kappa) { - if (mergeFlag) { - return CpcConfidence.getIconConfidenceLB(lgK, numCoupons, kappa); - } - return CpcConfidence.getHipConfidenceLB(lgK, numCoupons, hipEstAccum, kappa); - } - - /* - * These empirical values for the 99.9th percentile of size in bytes were measured using 100,000 - * trials. The value for each trial is the maximum of 5*16=80 measurements that were equally - * spaced over values of the quantity C/K between 3.0 and 8.0. This table does not include the - * worst-case space for the preamble, which is added by the function. - */ - private static final int empiricalSizeMaxLgK = 19; - private static final int[] empiricalMaxBytes = { - 24, // lgK = 4 - 36, // lgK = 5 - 56, // lgK = 6 - 100, // lgK = 7 - 180, // lgK = 8 - 344, // lgK = 9 - 660, // lgK = 10 - 1292, // lgK = 11 - 2540, // lgK = 12 - 5020, // lgK = 13 - 9968, // lgK = 14 - 19836, // lgK = 15 - 39532, // lgK = 16 - 78880, // lgK = 17 - 157516, // lgK = 18 - 314656 // lgK = 19 - }; - private static final double empiricalMaxSizeFactor = 0.6; // 0.6 = 4.8 / 8.0 - private static final int maxPreambleSizeBytes = 40; - - /** - * The actual size of a compressed CPC sketch has a small random variance, but the following - * empirically measured size should be large enough for at least 99.9 percent of sketches. - * - *

For small values of n the size can be much smaller. - * - * @param lgK the given value of lgK. - * @return the estimated maximum compressed serialized size of a sketch. - */ - public static int getMaxSerializedBytes(final int lgK) { - checkLgK(lgK); - if (lgK <= empiricalSizeMaxLgK) { return empiricalMaxBytes[lgK - CpcUtil.minLgK] + maxPreambleSizeBytes; } - final int k = 1 << lgK; - return (int) (empiricalMaxSizeFactor * k) + maxPreambleSizeBytes; - } - - /** - * Returns the best estimate of the upper bound of the confidence interval given kappa, - * the number of standard deviations from the mean. - * @param kappa the given number of standard deviations from the mean: 1, 2 or 3. - * @return the best estimate of the upper bound of the confidence interval given kappa. - */ - public double getUpperBound(final int kappa) { - if (mergeFlag) { - return CpcConfidence.getIconConfidenceUB(lgK, numCoupons, kappa); - } - return CpcConfidence.getHipConfidenceUB(lgK, numCoupons, hipEstAccum, kappa); - } - - /** - * Return the given MemorySegment as a CpcSketch on the Java heap using the DEFAULT_UPDATE_SEED. - * @param seg the given MemorySegment - * @return the given MemorySegment as a CpcSketch on the Java heap. - */ - public static CpcSketch heapify(final MemorySegment seg) { - return heapify(seg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Return the given byte array as a CpcSketch on the Java heap using the DEFAULT_UPDATE_SEED. - * @param byteArray the given byte array - * @return the given byte array as a CpcSketch on the Java heap. - */ - public static CpcSketch heapify(final byte[] byteArray) { - return heapify(byteArray, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Return the given MemorySegment as a CpcSketch on the Java heap. - * @param seg the given MemorySegment - * @param seed the seed used to create the original sketch from which the MemorySegment was derived. - * @return the given MemorySegment as a CpcSketch on the Java heap. - */ - public static CpcSketch heapify(final MemorySegment seg, final long seed) { - final CompressedState state = CompressedState.importFromSegment(seg); - return uncompress(state, seed); - } - - /** - * Return the given byte array as a CpcSketch on the Java heap. - * @param byteArray the given byte array - * @param seed the seed used to create the original sketch from which the byte array was derived. - * @return the given byte array as a CpcSketch on the Java heap. - */ - public static CpcSketch heapify(final byte[] byteArray, final long seed) { - final MemorySegment seg = MemorySegment.ofArray(byteArray); - return heapify(seg, seed); - } - - /** - * Return true if this sketch is empty - * @return true if this sketch is empty - */ - public boolean isEmpty() { - return numCoupons == 0; - } - - /** - * Resets this sketch to empty but retains the original LgK and Seed. - */ - public void reset() { - numCoupons = 0; - mergeFlag = false; - fiCol = 0; - - windowOffset = 0; - slidingWindow = null; - pairTable = null; - - kxp = 1 << lgK; - hipEstAccum = 0; - } - - /** - * Return this sketch as a compressed byte array. - * @return this sketch as a compressed byte array. - */ - public byte[] toByteArray() { - final CompressedState state = CompressedState.compress(this); - final long cap = state.getRequiredSerializedBytes(); - final MemorySegment wseg = MemorySegment.ofArray(new byte[(int) cap]); - state.exportToSegment(wseg); - return wseg.toArray(JAVA_BYTE); - } - - /** - * Present the given long as a potential unique item. - * - * @param datum The given long datum. - */ - public void update(final long datum) { - final long[] data = { datum }; - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); - } - - /** - * Present the given double (or float) datum as a potential unique item. - * The double will be converted to a long using Double.doubleToLongBits(datum), - * which normalizes all NaN values to a single NaN representation. - * Plus and minus zero will be normalized to plus zero. - * The special floating-point values NaN and +/- Infinity are treated as distinct. - * - * @param datum The given double datum. - */ - public void update(final double datum) { - final double d = (datum == 0.0) ? 0.0 : datum; // canonicalize -0.0, 0.0 - final long[] data = { Double.doubleToLongBits(d) };// canonicalize all NaN forms - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); - } - - /** - * Present the given String as a potential unique item. - * The string is converted to a byte array using UTF8 encoding. - * If the string is null or empty no update attempt is made and the method returns. - * - *

Note: About 2X faster performance can be obtained by first converting the String to a - * char[] and updating the sketch with that. This bypasses the complexity of the Java UTF_8 - * encoding. This, of course, will not produce the same internal hash values as updating directly - * with a String. So be consistent! Unioning two sketches, one fed with strings and the other - * fed with char[] will be meaningless. - *

- * - * @param datum The given String. - */ - public void update(final String datum) { - if ((datum == null) || datum.isEmpty()) { return; } - final byte[] data = datum.getBytes(UTF_8); - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); - } - - /** - * Present the given byte array as a potential unique item. - * If the byte array is null or empty no update attempt is made and the method returns. - * - * @param data The given byte array. - */ - public void update(final byte[] data) { - if ((data == null) || (data.length == 0)) { return; } - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); - } - - /** - * Present the given ByteBuffer as a potential unique item - * If the ByteBuffer is null or empty no update attempt is made and the method returns - * - * @param data The given ByteBuffer - */ - public void update(final ByteBuffer data) { - if ((data == null) || !data.hasRemaining()) { return; } - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); - } - - /** - * Present the given char array as a potential unique item. - * If the char array is null or empty no update attempt is made and the method returns. - * - *

Note: this will not produce the same output hash values as the {@link #update(String)} - * method but will be a little faster as it avoids the complexity of the UTF8 encoding.

- * - * @param data The given char array. - */ - public void update(final char[] data) { - if ((data == null) || (data.length == 0)) { return; } - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); - } - - /** - * Present the given integer array as a potential unique item. - * If the integer array is null or empty no update attempt is made and the method returns. - * - * @param data The given int array. - */ - public void update(final int[] data) { - if ((data == null) || (data.length == 0)) { return; } - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); - } - - /** - * Present the given long array as a potential unique item. - * If the long array is null or empty no update attempt is made and the method returns. - * - * @param data The given long array. - */ - public void update(final long[] data) { - if ((data == null) || (data.length == 0)) { return; } - final long[] arr = hash(data, seed); - hashUpdate(arr[0], arr[1]); - } - - /** - * Convience function that this Sketch is valid. This is a troubleshooting tool - * for sketches that have been heapified from serialized images. - * - *

If you are starting with a serialized image as a byte array, first heapify - * the byte array to a sketch, which performs a number of checks. Then use this - * function as one additional check on the sketch.

- * - * @return true if this sketch is validated. - */ - public boolean validate() { - final long[] bitMatrix = bitMatrixOfSketch(this); - final long matrixCoupons = countBitsSetInMatrix(bitMatrix); - return matrixCoupons == numCoupons; - } - - /** - * Returns the current Flavor of this sketch. - * @return the current Flavor of this sketch. - */ - Flavor getFlavor() { - return CpcUtil.determineFlavor(lgK, numCoupons); - } - - /** - * Returns the Format of the serialized form of this sketch. - * @return the Format of the serialized form of this sketch. - */ - Format getFormat() { - final int ordinal; - final Flavor f = getFlavor(); - if ((f == Flavor.HYBRID) || (f == Flavor.SPARSE)) { - ordinal = 2 | ( mergeFlag ? 0 : 1 ); //Hybrid is serialized as SPARSE - } else { - ordinal = ((slidingWindow != null) ? 4 : 0) - | (((pairTable != null) && (pairTable.getNumPairs() > 0)) ? 2 : 0) - | ( mergeFlag ? 0 : 1 ); - } - return Format.ordinalToFormat(ordinal); - } - - private static void promoteEmptyToSparse(final CpcSketch sketch) { - assert sketch.numCoupons == 0; - assert sketch.pairTable == null; - sketch.pairTable = new PairTable(2, 6 + sketch.lgK); - } - - //In terms of flavor, this promotes SPARSE to HYBRID. - private static void promoteSparseToWindowed(final CpcSketch sketch) { - final int lgK = sketch.lgK; - final int k = (1 << lgK); - final long c32 = sketch.numCoupons << 5; - assert ((c32 == (3 * k)) || ((lgK == 4) && (c32 > (3 * k)))); - - final byte[] window = new byte[k]; - - final PairTable newTable = new PairTable(2, 6 + lgK); - final PairTable oldTable = sketch.pairTable; - - final int[] oldSlots = oldTable.getSlotsArr(); - final int oldNumSlots = (1 << oldTable.getLgSizeInts()); - - assert (sketch.windowOffset == 0); - - for (int i = 0; i < oldNumSlots; i++) { - final int rowCol = oldSlots[i]; - if (rowCol != -1) { - final int col = rowCol & 63; - if (col < 8) { - final int row = rowCol >>> 6; - window[row] |= (1 << col); - } - else { - // cannot use Table.mustInsert(), because it doesn't provide for growth - final boolean isNovel = PairTable.maybeInsert(newTable, rowCol); - assert isNovel; - } - } - } - - assert (sketch.slidingWindow == null); - sketch.slidingWindow = window; - sketch.pairTable = newTable; - } - - /** - * The KXP register is a double with roughly 50 bits of precision, but - * it might need roughly 90 bits to track the value with perfect accuracy. - * Therefore we recalculate KXP occasionally from the sketch's full bitMatrix - * so that it will reflect changes that were previously outside the mantissa. - * @param sketch the given sketch - * @param bitMatrix the given bit Matrix - */ - //Also used in test - static void refreshKXP(final CpcSketch sketch, final long[] bitMatrix) { - final int k = (1 << sketch.lgK); - - // for improved numerical accuracy, we separately sum the bytes of the U64's - final double[] byteSums = new double[8]; - - Arrays.fill(byteSums, 0.0); - - for (int i = 0; i < k; i++) { - long row = bitMatrix[i]; - for (int j = 0; j < 8; j++) { - final int byteIdx = (int) (row & 0XFFL); - byteSums[j] += kxpByteLookup[byteIdx]; - row >>>= 8; - } - } - - double total = 0.0; - - for (int j = 7; j-- > 0; ) { // the reverse order is important - final double factor = invPow2(8 * j); // pow(256, -j) == pow(2, -8 * j); - total += factor * byteSums[j]; - } - sketch.kxp = total; - } - - /** - * This moves the sliding window - * @param sketch the given sketch - * @param newOffset the new offset, which must be oldOffset + 1 - */ - private static void modifyOffset(final CpcSketch sketch, final int newOffset) { - assert ((newOffset >= 0) && (newOffset <= 56)); - assert (newOffset == (sketch.windowOffset + 1)); - assert (newOffset == CpcUtil.determineCorrectOffset(sketch.lgK, sketch.numCoupons)); - - assert (sketch.slidingWindow != null); - assert (sketch.pairTable != null); - final int k = 1 << sketch.lgK; - - // Construct the full-sized bit matrix that corresponds to the sketch - final long[] bitMatrix = CpcUtil.bitMatrixOfSketch(sketch); - - // refresh the KXP register on every 8th window shift. - if ((newOffset & 0x7) == 0) { refreshKXP(sketch, bitMatrix); } - - sketch.pairTable.clear(); - - final PairTable table = sketch.pairTable; - final byte[] window = sketch.slidingWindow; - final long maskForClearingWindow = (0XFFL << newOffset) ^ -1L; - final long maskForFlippingEarlyZone = (1L << newOffset) - 1L; - long allSurprisesORed = 0; - - for (int i = 0; i < k; i++) { - long pattern = bitMatrix[i]; - window[i] = (byte) ((pattern >>> newOffset) & 0XFFL); - pattern &= maskForClearingWindow; - // The following line converts surprising 0's to 1's in the "early zone", - // (and vice versa, which is essential for this procedure's O(k) time cost). - pattern ^= maskForFlippingEarlyZone; - allSurprisesORed |= pattern; // a cheap way to recalculate fiCol - while (pattern != 0) { - final int col = Long.numberOfTrailingZeros(pattern); - pattern = pattern ^ (1L << col); // erase the 1. - final int rowCol = (i << 6) | col; - final boolean isNovel = PairTable.maybeInsert(table, rowCol); - assert isNovel; - } - } - sketch.windowOffset = newOffset; - sketch.fiCol = Long.numberOfTrailingZeros(allSurprisesORed); - if (sketch.fiCol > newOffset) { - sketch.fiCol = newOffset; // corner case - } - } - - /** - * Call this whenever a new coupon has been collected. - * @param sketch the given sketch - * @param rowCol the given row / column - */ - private static void updateHIP(final CpcSketch sketch, final int rowCol) { - final int k = 1 << sketch.lgK; - final int col = rowCol & 63; - final double oneOverP = k / sketch.kxp; - sketch.hipEstAccum += oneOverP; - sketch.kxp -= invPow2(col + 1); // notice the "+1" - } - - private static void updateSparse(final CpcSketch sketch, final int rowCol) { - final int k = 1 << sketch.lgK; - final long c32pre = sketch.numCoupons << 5; - assert (c32pre < (3L * k)); // C < 3K/32, in other words, flavor == SPARSE - assert (sketch.pairTable != null); - final boolean isNovel = PairTable.maybeInsert(sketch.pairTable, rowCol); - if (isNovel) { - sketch.numCoupons += 1; - updateHIP(sketch, rowCol); - final long c32post = sketch.numCoupons << 5; - if (c32post >= (3L * k)) { promoteSparseToWindowed(sketch); } // C >= 3K/32 - } - } - - /** - * The flavor is HYBRID, PINNED, or SLIDING. - * @param sketch the given sketch - * @param rowCol the given rowCol - */ - private static void updateWindowed(final CpcSketch sketch, final int rowCol) { - assert ((sketch.windowOffset >= 0) && (sketch.windowOffset <= 56)); - final int k = 1 << sketch.lgK; - final long c32pre = sketch.numCoupons << 5; - assert c32pre >= (3L * k); // C >= 3K/32, in other words flavor >= HYBRID - final long c8pre = sketch.numCoupons << 3; - final int w8pre = sketch.windowOffset << 3; - assert c8pre < ((27L + w8pre) * k); // C < (K * 27/8) + (K * windowOffset) - - boolean isNovel = false; //novel if new coupon - final int col = rowCol & 63; - - if (col < sketch.windowOffset) { // track the surprising 0's "before" the window - isNovel = PairTable.maybeDelete(sketch.pairTable, rowCol); // inverted logic - } - else if (col < (sketch.windowOffset + 8)) { // track the 8 bits inside the window - assert (col >= sketch.windowOffset); - final int row = rowCol >>> 6; - final byte oldBits = sketch.slidingWindow[row]; - final byte newBits = (byte) (oldBits | (1 << (col - sketch.windowOffset))); - if (newBits != oldBits) { - sketch.slidingWindow[row] = newBits; - isNovel = true; - } - } - else { // track the surprising 1's "after" the window - assert col >= (sketch.windowOffset + 8); - isNovel = PairTable.maybeInsert(sketch.pairTable, rowCol); // normal logic - } - - if (isNovel) { - sketch.numCoupons += 1; - updateHIP(sketch, rowCol); - final long c8post = sketch.numCoupons << 3; - if (c8post >= ((27L + w8pre) * k)) { - modifyOffset(sketch, sketch.windowOffset + 1); - assert (sketch.windowOffset >= 1) && (sketch.windowOffset <= 56); - final int w8post = sketch.windowOffset << 3; - assert c8post < ((27L + w8post) * k); // C < (K * 27/8) + (K * windowOffset) - } - } - } - - //also used in test - static CpcSketch uncompress(final CompressedState source, final long seed) { - Util.checkSeedHashes(Util.computeSeedHash(seed), source.seedHash); - final CpcSketch sketch = new CpcSketch(source.lgK, seed); - sketch.numCoupons = source.numCoupons; - sketch.windowOffset = source.getWindowOffset(); - sketch.fiCol = source.fiCol; - sketch.mergeFlag = source.mergeFlag; - sketch.kxp = source.kxp; - sketch.hipEstAccum = source.hipEstAccum; - sketch.slidingWindow = null; - sketch.pairTable = null; - CpcCompression.uncompress(source, sketch); - return sketch; - } - - //Used here and for testing - void hashUpdate(final long hash0, final long hash1) { - int col = Long.numberOfLeadingZeros(hash1); - if (col < fiCol) { return; } // important speed optimization - if (col > 63) { col = 63; } // clip so that 0 <= col <= 63 - final long c = numCoupons; - if (c == 0) { promoteEmptyToSparse(this); } - final long k = 1L << lgK; - final int row = (int) (hash0 & (k - 1L)); - int rowCol = (row << 6) | col; - - // Avoid the hash table's "empty" value which is (2^26 -1, 63) (all ones) by changing it - // to the pair (2^26 - 2, 63), which effectively merges the two cells. - // This case is *extremely* unlikely, but we might as well handle it. - // It can't happen at all if lgK (or maxLgK) < 26. - if (rowCol == -1) { rowCol ^= (1 << 6); } //set the LSB of row to 0 - - if ((c << 5) < (3L * k)) { updateSparse(this, rowCol); } - else { updateWindowed(this, rowCol); } - } - - //Used by union and in testing - void rowColUpdate(final int rowCol) { - final int col = rowCol & 63; - if (col < fiCol) { return; } // important speed optimization - final long c = numCoupons; - if (c == 0) { promoteEmptyToSparse(this); } - final long k = 1L << lgK; - if ((c << 5) < (3L * k)) { updateSparse(this, rowCol); } - else { updateWindowed(this, rowCol); } - } - - /** - * Return a human-readable string summary of this sketch - */ - @Override - public String toString() { - return toString(false); - } - - /** - * Return a human-readable string summary of this sketch - * @param detail include data detail - * @return a human-readable string summary of this sketch - */ - public String toString(final boolean detail) { - final int numPairs = (pairTable == null) ? 0 : pairTable.getNumPairs(); - final int seedHash = Short.toUnsignedInt(Util.computeSeedHash(seed)); - final double errConst = mergeFlag ? log(2) : sqrt(log(2) / 2.0); - final double rse = errConst / Math.sqrt(1 << lgK); - final StringBuilder sb = new StringBuilder(); - sb.append("### CPC SKETCH - PREAMBLE:").append(LS); - sb.append(" Flavor : ").append(getFlavor()).append(LS); - sb.append(" LgK : ").append(lgK).append(LS); - sb.append(" Merge Flag : ").append(mergeFlag).append(LS); - sb.append(" Error Const : ").append(errConst).append(LS); - sb.append(" RSE : ").append(rse).append(LS); - sb.append(" Seed Hash : ").append(Integer.toHexString(seedHash)) - .append(" | ").append(seedHash).append(LS); - sb.append(" Num Coupons : ").append(numCoupons).append(LS); - sb.append(" Num Pairs (SV) : ").append(numPairs).append(LS); - sb.append(" First Inter Col: ").append(fiCol).append(LS); - sb.append(" Valid Window : ").append(slidingWindow != null).append(LS); - sb.append(" Valid PairTable: ").append(pairTable != null).append(LS); - sb.append(" Window Offset : ").append(windowOffset).append(LS); - sb.append(" KxP : ").append(kxp).append(LS); - sb.append(" HIP Accum : ").append(hipEstAccum).append(LS); - if (detail) { - sb.append(LS).append("### CPC SKETCH - DATA").append(LS); - if (pairTable != null) { - sb.append(pairTable.toString(true)); - } - if (slidingWindow != null) { - sb.append("SlidingWindow : ").append(LS); - sb.append(" Index Bits (lsb ->)").append(LS); - for (int i = 0; i < slidingWindow.length; i++) { - - final String bits = zeroPad(Integer.toBinaryString(slidingWindow[i] & 0XFF), 8); - sb.append(String.format("%9d %8s" + LS, i, bits)); - } - } - } - sb.append("### END CPC SKETCH"); - return sb.toString(); - } - - /** - * Returns a human readable string of the preamble of a byte array image of a CpcSketch. - * @param byteArr the given byte array - * @param detail if true, a dump of the compressed window and surprising value streams will be - * included. - * @return a human readable string of the preamble of a byte array image of a CpcSketch. - */ - public static String toString(final byte[] byteArr, final boolean detail) { - return PreambleUtil.toString(byteArr, detail); - } - - /** - * Returns a human readable string of the preamble of a MemorySegment image of a CpcSketch. - * @param seg the given MemorySegment - * @param detail if true, a dump of the compressed window and surprising value streams will be - * included. - * @return a human readable string of the preamble of a MemorySegment image of a CpcSketch. - */ - public static String toString(final MemorySegment seg, final boolean detail) { - return PreambleUtil.toString(seg, detail); - } - - private static void fillKxpByteLookup() { //called from static initializer - for (int b = 0; b < 256; b++) { - double sum = 0; - for (int col = 0; col < 8; col++) { - final int bit = (b >>> col) & 1; - if (bit == 0) { // note the inverted logic - sum += invPow2(col + 1); //note the "+1" - } - } - kxpByteLookup[b] = sum; - } - } - - static { - fillKxpByteLookup(); - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/CpcUnion.java b/src/main/java/org/apache/datasketches/cpc/CpcUnion.java deleted file mode 100644 index 34ded3a9c..000000000 --- a/src/main/java/org/apache/datasketches/cpc/CpcUnion.java +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.common.Util.INVERSE_GOLDEN; -import static org.apache.datasketches.cpc.CpcUtil.countBitsSetInMatrix; -import static org.apache.datasketches.cpc.Flavor.EMPTY; -import static org.apache.datasketches.cpc.Flavor.SPARSE; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.Util; - -/* - * The merging logic is somewhat involved, so it will be summarized here. - * - *

First, we compare the K values of the union and the source sketch. - * - *

If (source.K < union.K), we reduce the union's K to match, which - * requires downsampling the union's internal sketch. - * - *

Here is how to perform the downsampling. - * - *

If the union contains a bitMatrix, downsample it by row-wise OR'ing. - * - *

If the union contains a sparse sketch, then create a new empty - * sketch, and walk the old target sketch updating the new one (with modulo). - * At the end, check whether the new target - * sketch is still in sparse mode (it might not be, because downsampling - * densifies the set of collected coupons). If it is NOT in sparse mode, - * immediately convert it to a bitmatrix. - * - *

At this point, we have source.K ≥ union.K. - * [We won't keep mentioning this, but in all of the following the - * source's row indices are used mod union.K while updating the union's sketch. - * That takes care of the situation where source.K < union.K.] - * - *

Case A: union is Sparse and source is Sparse. We walk the source sketch - * updating the union's sketch. At the end, if the union's sketch - * is no longer in sparse mode, we convert it to a bitmatrix. - * - *

Case B: union is bitmatrix and source is Sparse. We walk the source sketch, - * setting bits in the bitmatrix. - * - *

In the remaining cases, we have flavor(source) > Sparse, so we immediately convert the - * union's sketch to a bitmatrix (even if the union contains very few coupons). Then: - * - *

Case C: union is bitmatrix and source is Hybrid or Pinned. Then we OR the source's - * sliding window into the bitmatrix, and walk the source's table, setting bits in the bitmatrix. - * - *

Case D: union is bitmatrix, and source is Sliding. Then we convert the source into - * a bitmatrix, and OR it into the union's bitmatrix. [Important note; merely walking the source - * wouldn't work because of the partially inverted Logic in the Sliding flavor, where the presence of - * coupons is sometimes indicated by the ABSENCE of rowCol pairs in the surprises table.] - * - *

How does getResult work? - * - *

If the union is using its accumulator field, make a copy of that sketch. - * - *

If the union is using its bitMatrix field, then we have to convert the - * bitMatrix back into a sketch, which requires doing some extra work to - * figure out the values of numCoupons, offset, fiCol, and KxQ. - * - */ -/** - * The union (merge) operation for the CPC sketches. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -public class CpcUnion { - private final long seed; - private int lgK; - - // Note: at most one of bitMatrix and accumulator will be non-null at any given moment. - // accumulator is a sketch object that is employed until it graduates out of Sparse mode. - // At that point, it is converted into a full-sized bitMatrix, which is mathematically a sketch, - // but doesn't maintain any of the "extra" fields of our sketch objects, so some additional work - // is required when getResult is called at the end. - private long[] bitMatrix; - private CpcSketch accumulator; //can only be empty or sparse Flavor - - /** - * Construct this unioning object with the default LgK and the default update seed. - */ - public CpcUnion() { - this(CpcSketch.DEFAULT_LG_K, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Construct this unioning object with LgK and the default update seed. - * @param lgK The given log2 of K. - */ - public CpcUnion(final int lgK) { - this(lgK, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Construct this unioning object with LgK and a given seed. - * @param lgK The given log2 of K. - * @param seed The given seed. - */ - public CpcUnion(final int lgK, final long seed) { - this.seed = seed; - this.lgK = lgK; - bitMatrix = null; - // We begin with the accumulator holding an EMPTY_MERGED sketch object. - // As an optimization the accumulator could start as NULL, but that would require changes elsewhere. - accumulator = new CpcSketch(lgK, seed); - } - - /** - * Update this union with a CpcSketch. - * @param sketch the given CpcSketch. - */ - public void update(final CpcSketch sketch) { - mergeInto(this, sketch); - } - - /** - * Returns the result of union operations as a CPC sketch. - * @return the result of union operations as a CPC sketch. - */ - public CpcSketch getResult() { - return getResult(this); - } - - /** - * Returns the current value of Log_base2 of K. Note that due to merging with source sketches that - * may have a lower value of LgK, this value can be less than what the union object was configured - * with. - * - * @return the current value of Log_base2 of K. - */ - public int getLgK() { - return lgK; - } - - /** - * Return the DataSketches identifier for this CPC family of sketches. - * @return the DataSketches identifier for this CPC family of sketches. - */ - public static Family getFamily() { - return Family.CPC; - } - - //used for testing only - long getNumCoupons() { - if (bitMatrix != null) { - return countBitsSetInMatrix(bitMatrix); - } - return accumulator.numCoupons; - } - - //used for testing only - static long[] getBitMatrix(final CpcUnion union) { - checkUnionState(union); - return (union.bitMatrix != null) - ? union.bitMatrix - : CpcUtil.bitMatrixOfSketch(union.accumulator); - } - - private static void walkTableUpdatingSketch(final CpcSketch dest, final PairTable table) { - final int[] slots = table.getSlotsArr(); - final int numSlots = (1 << table.getLgSizeInts()); - assert dest.lgK <= 26; - final int destMask = (((1 << dest.lgK) - 1) << 6) | 63; //downsamples when destlgK < srcLgK - - /* Using the inverse golden ratio stride fixes the - * Snow Plow Effect. - */ - int stride = (int) (INVERSE_GOLDEN * numSlots); - assert stride >= 2; - if (stride == ((stride >>> 1) << 1)) { stride += 1; } //force the stride to be odd - assert (stride >= 3) && (stride < numSlots); - - for (int i = 0, j = 0; i < numSlots; i++, j += stride) { - j &= (numSlots - 1); - final int rowCol = slots[j]; - if (rowCol != -1) { - dest.rowColUpdate(rowCol & destMask); - } - } - } - - private static void orTableIntoMatrix(final long[] bitMatrix, final int destLgK, final PairTable table) { - final int[] slots = table.getSlotsArr(); - final int numSlots = 1 << table.getLgSizeInts(); - final int destMask = (1 << destLgK) - 1; // downsamples when destlgK < srcLgK - for (int i = 0; i < numSlots; i++) { - final int rowCol = slots[i]; - if (rowCol != -1) { - final int col = rowCol & 63; - final int row = rowCol >>> 6; - bitMatrix[row & destMask] |= (1L << col); // Set the bit. - } - } - } - - private static void orWindowIntoMatrix(final long[] destMatrix, final int destLgK, - final byte[] srcWindow, final int srcOffset, final int srcLgK) { - assert (destLgK <= srcLgK); - final int destMask = (1 << destLgK) - 1; // downsamples when destlgK < srcLgK - final int srcK = 1 << srcLgK; - for (int srcRow = 0; srcRow < srcK; srcRow++) { - destMatrix[srcRow & destMask] |= ((srcWindow[srcRow] & 0XFFL) << srcOffset); - } - } - - private static void orMatrixIntoMatrix(final long[] destMatrix, final int destLgK, - final long[] srcMatrix, final int srcLgK) { - assert (destLgK <= srcLgK); - final int destMask = (1 << destLgK) - 1; // downsamples when destlgK < srcLgK - final int srcK = 1 << srcLgK; - for (int srcRow = 0; srcRow < srcK; srcRow++) { - destMatrix[srcRow & destMask] |= srcMatrix[srcRow]; - } - } - - private static void reduceUnionK(final CpcUnion union, final int newLgK) { - assert (newLgK < union.lgK); - - if (union.bitMatrix != null) { // downsample the union's bit matrix - final int newK = 1 << newLgK; - final long[] newMatrix = new long[newK]; - - orMatrixIntoMatrix(newMatrix, newLgK, union.bitMatrix, union.lgK); - union.bitMatrix = newMatrix; - union.lgK = newLgK; - } - - else { // downsample the union's accumulator - final CpcSketch oldSketch = union.accumulator; - - if (oldSketch.numCoupons == 0) { - union.accumulator = new CpcSketch(newLgK, oldSketch.seed); - union.lgK = newLgK; - return; - } - - final CpcSketch newSketch = new CpcSketch(newLgK, oldSketch.seed); - walkTableUpdatingSketch(newSketch, oldSketch.pairTable); - - final Flavor finalNewFlavor = newSketch.getFlavor(); - assert (finalNewFlavor != EMPTY); //SV table had to have something in it - - if (finalNewFlavor == SPARSE) { - union.accumulator = newSketch; - union.lgK = newLgK; - return; - } - - // the new sketch has graduated beyond sparse, so convert to bitMatrix - union.accumulator = null; - union.bitMatrix = CpcUtil.bitMatrixOfSketch(newSketch); - union.lgK = newLgK; - } - } - - private static void mergeInto(final CpcUnion union, final CpcSketch source) { - if (source == null) { return; } - checkSeeds(union.seed, source.seed); - - final int sourceFlavorOrd = source.getFlavor().ordinal(); - if (sourceFlavorOrd == 0) { return; } //EMPTY - - //Accumulator and bitMatrix must be mutually exclusive, - //so bitMatrix != null => accumulator == null and visa versa - //if (Accumulator != null) union must be EMPTY or SPARSE, - checkUnionState(union); - - if (source.lgK < union.lgK) { reduceUnionK(union, source.lgK); } - - // if source is past SPARSE mode, make sure that union is a bitMatrix. - if ((sourceFlavorOrd > 1) && (union.accumulator != null)) { - union.bitMatrix = CpcUtil.bitMatrixOfSketch(union.accumulator); - union.accumulator = null; - } - - final int state = ((sourceFlavorOrd - 1) << 1) | ((union.bitMatrix != null) ? 1 : 0); - switch (state) { - case 0 : { //A: Sparse, bitMatrix == null, accumulator valid - if (union.accumulator == null) { - //CodeQL could not figure this out so I have to insert this. - throw new SketchesStateException("union.accumulator can never be null here."); - } - if ((union.accumulator.getFlavor() == EMPTY) - && (union.lgK == source.lgK)) { - union.accumulator = source.copy(); - break; - } - walkTableUpdatingSketch(union.accumulator, source.pairTable); - // if the accumulator has graduated beyond sparse, switch union to a bitMatrix - if (union.accumulator.getFlavor().ordinal() > 1) { - union.bitMatrix = CpcUtil.bitMatrixOfSketch(union.accumulator); - union.accumulator = null; - } - break; - } - case 1 : { //B: Sparse, bitMatrix valid, accumulator == null - orTableIntoMatrix(union.bitMatrix, union.lgK, source.pairTable); - break; - } - case 3 : //C: Hybrid, bitMatrix valid, accumulator == null - case 5 : { //C: Pinned, bitMatrix valid, accumulator == null - orWindowIntoMatrix(union.bitMatrix, union.lgK, source.slidingWindow, - source.windowOffset, source.lgK); - orTableIntoMatrix(union.bitMatrix, union.lgK, source.pairTable); - break; - } - case 7 : { //D: Sliding, bitMatrix valid, accumulator == null - // SLIDING mode involves inverted logic, so we can't just walk the source sketch. - // Instead, we convert it to a bitMatrix that can be OR'ed into the destination. - final long[] sourceMatrix = CpcUtil.bitMatrixOfSketch(source); - orMatrixIntoMatrix(union.bitMatrix, union.lgK, sourceMatrix, source.lgK); - break; - } - default: throw new SketchesStateException("Illegal Union state: " + state); - } - } - - private static CpcSketch getResult(final CpcUnion union) { - checkUnionState(union); - - if (union.accumulator != null) { // start of case where union contains a sketch - if (union.accumulator.numCoupons == 0) { - final CpcSketch result = new CpcSketch(union.lgK, union.accumulator.seed); - result.mergeFlag = true; - return (result); - } - assert (SPARSE == union.accumulator.getFlavor()); - final CpcSketch result = union.accumulator.copy(); - result.mergeFlag = true; - return (result); - } // end of case where union contains a sketch - - // start of case where union contains a bitMatrix - final long[] matrix = union.bitMatrix; - final int lgK = union.lgK; - final CpcSketch result = new CpcSketch(union.lgK, union.seed); - - final long numCoupons = countBitsSetInMatrix(matrix); - result.numCoupons = numCoupons; - - final Flavor flavor = CpcUtil.determineFlavor(lgK, numCoupons); - assert ((flavor.ordinal() > SPARSE.ordinal()) ); - - final int offset = CpcUtil.determineCorrectOffset(lgK, numCoupons); - result.windowOffset = offset; - - //Build the window and pair table - - final int k = 1 << lgK; - final byte[] window = new byte[k]; - result.slidingWindow = window; - - // LgSize = K/16; in some cases this will end up being oversized - final int newTableLgSize = Math.max(lgK - 4, 2); - final PairTable table = new PairTable(newTableLgSize, 6 + lgK); - result.pairTable = table; - - // The following works even when the offset is zero. - final long maskForClearingWindow = (0XFFL << offset) ^ -1L; - final long maskForFlippingEarlyZone = (1L << offset) - 1L; - long allSurprisesORed = 0; - - /* using a sufficiently large hash table avoids the - * Snow Plow Effect - */ - for (int i = 0; i < k; i++) { - long pattern = matrix[i]; - window[i] = (byte) ((pattern >>> offset) & 0XFFL); - pattern &= maskForClearingWindow; - pattern ^= maskForFlippingEarlyZone; // This flipping converts surprising 0's to 1's. - allSurprisesORed |= pattern; - while (pattern != 0) { - final int col = Long.numberOfTrailingZeros(pattern); - pattern = pattern ^ (1L << col); // erase the 1. - final int rowCol = (i << 6) | col; - final boolean isNovel = PairTable.maybeInsert(table, rowCol); - assert isNovel; - } - } - - // At this point we could shrink an oversize hash table, but the relative waste isn't very big. - result.fiCol = Long.numberOfTrailingZeros(allSurprisesORed); - if (result.fiCol > offset) { - result.fiCol = offset; - } // corner case - - // NB: the HIP-related fields will contain bogus values, but that is okay. - - result.mergeFlag = true; - return result; - // end of case where union contains a bitMatrix - } - - private static void checkSeeds(final long seedA, final long seedB) { - if (seedA != seedB) { - throw new SketchesArgumentException("Hash Seeds do not match."); - } - } - - private static void checkUnionState(final CpcUnion union) { - if (union == null) { - throw new SketchesStateException("union cannot be null"); - } - final CpcSketch accumulator = union.accumulator; - if ( !((accumulator != null) ^ (union.bitMatrix != null)) ) { - throw new SketchesStateException( - "accumulator and bitMatrix cannot be both valid or both null: " - + "accumValid = " + (accumulator != null) - + ", bitMatrixValid = " + (union.bitMatrix != null)); - } - if (accumulator != null) { //must be SPARSE or EMPTY - if (accumulator.numCoupons > 0) { //SPARSE - if ( !((accumulator.slidingWindow == null) && (accumulator.pairTable != null)) ) { - throw new SketchesStateException( - "Non-empty union accumulator must be SPARSE: " + accumulator.getFlavor()); - } - } //else EMPTY - if (union.lgK != accumulator.lgK) { - throw new SketchesStateException("union LgK must equal accumulator LgK"); - } - } - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/CpcUtil.java b/src/main/java/org/apache/datasketches/cpc/CpcUtil.java deleted file mode 100644 index da7cba086..000000000 --- a/src/main/java/org/apache/datasketches/cpc/CpcUtil.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -final class CpcUtil { - static final int minLgK = 4; - static final int maxLgK = 26; - - static void checkLgK(final int lgK) { - if ((lgK < minLgK) || (lgK > maxLgK)) { - throw new SketchesArgumentException("LgK must be >= 4 and <= 26: " + lgK); - } - } - - static Flavor determineFlavor(final int lgK, final long numCoupons) { - final long c = numCoupons; - final long k = 1L << lgK; - final long c2 = c << 1; - final long c8 = c << 3; - final long c32 = c << 5; - if (c == 0) { - return Flavor.EMPTY; // 0 == C < 1 - } - if (c32 < (3 * k)) { - return Flavor.SPARSE; // 1 <= C < 3K/32 - } - if (c2 < k) { - return Flavor.HYBRID; // 3K/32 <= C < K/2 - } - if (c8 < (27 * k)) { - return Flavor.PINNED; // K/2 <= C < 27K/8 - } - else { - return Flavor.SLIDING; // 27K/8 <= C - } - } - - /** - * Warning: this is called in several places, including during the - * transitional moments during which sketch invariants involving - * flavor and offset are out of whack and in fact we are re-imposing - * them. Therefore it cannot rely on determineFlavor() or - * determineCorrectOffset(). Instead it interprets the low level data - * structures "as is". - * - *

This produces a full-size k-by-64 bit matrix from any Live sketch. - * - * @param sketch the given sketch - * @return the bit matrix as an array of longs. - */ - static long[] bitMatrixOfSketch(final CpcSketch sketch) { - final int k = (1 << sketch.lgK); - final int offset = sketch.windowOffset; - assert (offset >= 0) && (offset <= 56); - - final long[] matrix = new long[k]; - - if (sketch.numCoupons == 0) { - return matrix; // Returning a matrix of zeros rather than NULL. - } - - //Fill the matrix with default rows in which the "early zone" is filled with ones. - //This is essential for the routine's O(k) time cost (as opposed to O(C)). - final long defaultRow = (1L << offset) - 1L; - Arrays.fill(matrix, defaultRow); - - final byte[] window = sketch.slidingWindow; - if (window != null) { // In other words, we are in window mode, not sparse mode. - for (int i = 0; i < k; i++) { // set the window bits, trusting the sketch's current offset. - matrix[i] |= ((window[i] & 0XFFL) << offset); - } - } - final PairTable table = sketch.pairTable; - assert (table != null); - final int[] slots = table.getSlotsArr(); - final int numSlots = 1 << table.getLgSizeInts(); - - for (int i = 0; i < numSlots; i++) { - final int rowCol = slots[i]; - if (rowCol != -1) { - final int col = rowCol & 63; - final int row = rowCol >>> 6; - // Flip the specified matrix bit from its default value. - // In the "early" zone the bit changes from 1 to 0. - // In the "late" zone the bit changes from 0 to 1. - matrix[row] ^= (1L << col); - } - } - return matrix; - } - - static long countBitsSetInMatrix(final long[] matrix) { - long count = 0; - final int len = matrix.length; - for (int i = 0; i < len; i++) { count += Long.bitCount(matrix[i]); } - return count; - } - - static int determineCorrectOffset(final int lgK, final long numCoupons) { - final long c = numCoupons; - final long k = (1L << lgK); - final long tmp = (c << 3) - (19L * k); // 8C - 19K - if (tmp < 0) { return 0; } - return (int) (tmp >>> (lgK + 3)); // tmp / 8K - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/CpcWrapper.java b/src/main/java/org/apache/datasketches/cpc/CpcWrapper.java deleted file mode 100644 index 083eeadf7..000000000 --- a/src/main/java/org/apache/datasketches/cpc/CpcWrapper.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.cpc.CpcConfidence.getHipConfidenceLB; -import static org.apache.datasketches.cpc.CpcConfidence.getHipConfidenceUB; -import static org.apache.datasketches.cpc.CpcConfidence.getIconConfidenceLB; -import static org.apache.datasketches.cpc.CpcConfidence.getIconConfidenceUB; -import static org.apache.datasketches.cpc.IconEstimator.getIconEstimate; -import static org.apache.datasketches.cpc.PreambleUtil.checkLoPreamble; -import static org.apache.datasketches.cpc.PreambleUtil.getHipAccum; -import static org.apache.datasketches.cpc.PreambleUtil.getNumCoupons; -import static org.apache.datasketches.cpc.PreambleUtil.hasHip; -import static org.apache.datasketches.cpc.PreambleUtil.isCompressed; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SuppressFBWarnings; - -/** - * This provides a read-only view of a serialized image of a CpcSketch, which can be - * on-heap or off-heap represented as a MemorySegment object, or on-heap represented as a byte array. - * @author Lee Rhodes - * @author Kevin Lang - */ -public final class CpcWrapper { - MemorySegment seg; - - /** - * Construct a read-only view of the given MemorySegment that contains a CpcSketch - * @param seg the given MemorySegment - */ - @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "This is OK here") - public CpcWrapper(final MemorySegment seg) { - this.seg = seg; - checkLoPreamble(seg); - rtAssert(isCompressed(seg)); - - } - - /** - * Construct a read-only view of the given byte array that contains a CpcSketch. - * @param byteArray the given byte array - */ - public CpcWrapper(final byte[] byteArray) { - this(MemorySegment.ofArray(byteArray)); - } - - /** - * Returns the best estimate of the cardinality of the sketch. - * @return the best estimate of the cardinality of the sketch. - */ - public double getEstimate() { - if (!hasHip(seg)) { - return getIconEstimate(PreambleUtil.getLgK(seg), getNumCoupons(seg)); - } - return getHipAccum(seg); - } - - /** - * Return the DataSketches identifier for this CPC family of sketches. - * @return the DataSketches identifier for this CPC family of sketches. - */ - public static Family getFamily() { - return Family.CPC; - } - - /** - * Returns the configured Log_base2 of K of this sketch. - * @return the configured Log_base2 of K of this sketch. - */ - public int getLgK() { - return PreambleUtil.getLgK(seg); - } - - /** - * Returns the best estimate of the lower bound of the confidence interval given kappa, - * the number of standard deviations from the mean. - * @param kappa the given number of standard deviations from the mean: 1, 2 or 3. - * @return the best estimate of the lower bound of the confidence interval given kappa. - */ - public double getLowerBound(final int kappa) { - if (!hasHip(seg)) { - return getIconConfidenceLB(PreambleUtil.getLgK(seg), getNumCoupons(seg), kappa); - } - return getHipConfidenceLB(PreambleUtil.getLgK(seg), getNumCoupons(seg), getHipAccum(seg), kappa); - } - - /** - * Returns the best estimate of the upper bound of the confidence interval given kappa, - * the number of standard deviations from the mean. - * @param kappa the given number of standard deviations from the mean: 1, 2 or 3. - * @return the best estimate of the upper bound of the confidence interval given kappa. - */ - public double getUpperBound(final int kappa) { - if (!hasHip(seg)) { - return getIconConfidenceUB(PreambleUtil.getLgK(seg), getNumCoupons(seg), kappa); - } - return getHipConfidenceUB(PreambleUtil.getLgK(seg), getNumCoupons(seg), getHipAccum(seg), kappa); - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/Flavor.java b/src/main/java/org/apache/datasketches/cpc/Flavor.java deleted file mode 100644 index 52cd66cd6..000000000 --- a/src/main/java/org/apache/datasketches/cpc/Flavor.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -/** - * Note: except for brief transitional moments, these sketches always obey the following strict - * mapping between the flavor of a sketch and the number of coupons that it has collected. - * @author Lee Rhodes - * @author Kevin Lang - */ -enum Flavor { - EMPTY, // 0 == C < 1 - SPARSE, // 1 <= C < 3K/32 - HYBRID, // 3K/32 <= C < K/2 - PINNED, // K/2 <= C < 27K/8 [NB: 27/8 = 3 + 3/8] - SLIDING; // 27K/8 <= C - - private static Flavor[] fmtArr = Flavor.class.getEnumConstants(); - - /** - * Returns the Flavor given its enum ordinal - * @param ordinal the given enum ordinal - * @return the Flavor given its enum ordinal - */ - static Flavor ordinalToFlavor(final int ordinal) { - return fmtArr[ordinal]; - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/Format.java b/src/main/java/org/apache/datasketches/cpc/Format.java deleted file mode 100644 index 200045170..000000000 --- a/src/main/java/org/apache/datasketches/cpc/Format.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -/** - * There are seven different preamble formats (8 combinations) that determine the layout of the - * HiField variables after the first 8 bytes of the preamble. - * Do not change the order. - */ -enum Format { - EMPTY_MERGED, - EMPTY_HIP, - SPARSE_HYBRID_MERGED, - SPARSE_HYBRID_HIP, - PINNED_SLIDING_MERGED_NOSV, - PINNED_SLIDING_HIP_NOSV, - PINNED_SLIDING_MERGED, - PINNED_SLIDING_HIP; - - private static Format[] fmtArr = Format.class.getEnumConstants(); - - /** - * Returns the Format given its enum ordinal - * @param ordinal the given enum ordinal - * @return the Format given its enum ordinal - */ - static Format ordinalToFormat(final int ordinal) { - return fmtArr[ordinal]; - } - -} //end enum Format diff --git a/src/main/java/org/apache/datasketches/cpc/IconEstimator.java b/src/main/java/org/apache/datasketches/cpc/IconEstimator.java deleted file mode 100644 index cc5382fdc..000000000 --- a/src/main/java/org/apache/datasketches/cpc/IconEstimator.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.cpc.CpcUtil.maxLgK; -import static org.apache.datasketches.cpc.CpcUtil.minLgK; -import static org.apache.datasketches.cpc.IconPolynomialCoefficients.iconPolynomialCoefficents; -import static org.apache.datasketches.cpc.IconPolynomialCoefficients.iconPolynomialNumCoefficients; - -/** - * The ICON estimator for CPC sketches is defined by the arXiv paper. - * - *

The current file provides exact and approximate implementations of this estimator. - * - *

The exact version works for any value of K, but is quite slow. - * - *

The much faster approximate version works for K values that are powers of two - * ranging from 2^4 to 2^32. - * - *

At a high-level, this approximation can be described as using an - * exponential approximation when C > K * (5.6 or 5.7), while smaller - * values of C are handled by a degree-19 polynomial approximation of - * a pre-conditioned version of the true ICON mapping from C to N_hat. - * - *

This file also provides a validation procedure that compares its approximate - * and exact implementations of the CPC ICON estimator. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -final class IconEstimator { - - static double evaluatePolynomial(final double[] coefficients, final int start, final int num, - final double x) { - final int end = (start + num) - 1; - double total = coefficients[end]; - for (int j = end - 1; j >= start; j--) { - total *= x; - total += coefficients[j]; - } - return total; - } - - static double iconExponentialApproximation(final double k, final double c) { - return (0.7940236163830469 * k * Math.pow(2.0, c / k)); - } - - static double getIconEstimate(final int lgK, final long c) { - assert lgK >= minLgK; - assert lgK <= maxLgK; - if (c < 2L) { return ((c == 0L) ? 0.0 : 1.0); } - final int k = 1 << lgK; - final double doubleK = k; - final double doubleC = c; - // Differing thresholds ensure that the approximated estimator is monotonically increasing. - final double thresholdFactor = ((lgK < 14) ? 5.7 : 5.6); - if (doubleC > (thresholdFactor * doubleK)) { - return (iconExponentialApproximation(doubleK, doubleC)); - } - final double factor = evaluatePolynomial(iconPolynomialCoefficents, - iconPolynomialNumCoefficients * (lgK - minLgK), - iconPolynomialNumCoefficients, - // The constant 2.0 is baked into the table iconPolynomialCoefficents[]. - // This factor, although somewhat arbitrary, is based on extensive characterization studies - // and is considered a safe conservative factor. - doubleC / (2.0 * doubleK)); - final double ratio = doubleC / doubleK; - // The constant 66.774757 is baked into the table iconPolynomialCoefficents[]. - // This factor, although somewhat arbitrary, is based on extensive characterization studies - // and is considered a safe conservative factor. - final double term = 1.0 + ((ratio * ratio * ratio) / 66.774757); - final double result = doubleC * factor * term; - return (result >= doubleC) ? result : doubleC; - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/IconPolynomialCoefficients.java b/src/main/java/org/apache/datasketches/cpc/IconPolynomialCoefficients.java deleted file mode 100644 index 6c08528f9..000000000 --- a/src/main/java/org/apache/datasketches/cpc/IconPolynomialCoefficients.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.cpc.CpcUtil.maxLgK; -import static org.apache.datasketches.cpc.CpcUtil.minLgK; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -final class IconPolynomialCoefficients { - static final int iconPolynomialDegree = 19; - static final int iconPolynomialNumCoefficients = 1 + iconPolynomialDegree; - static final int iconTableSize = iconPolynomialNumCoefficients * ((1 + maxLgK) - minLgK); - - //CHECKSTYLE.OFF: LineLength - static final double[] iconPolynomialCoefficents = new double[] { - // log K = 4 - 0.9895027971889700513, 0.3319496644645180128, 0.1242818722715769986, -0.03324149686026930256, -0.2985637298081619817, - 1.366555923595830002, -4.705499366260569971, 11.61506432505530029, -21.11254986175579873, 28.89421695078809904, - -30.1383659011730991, 24.11946778830730054, -14.83391445199539938, 6.983088767267210173, -2.48964120264876998, - 0.6593243603602499947, -0.125493534558034997, 0.01620971672896159843, -0.001271267679036929953, 4.567178653294529745e-05, - - // log K = 5 - 0.9947713741300230339, 0.3326559581620939787, 0.1250050661634889981, -0.04130073804472530336, -0.2584095537451129854, - 1.218050389433120051, -4.319106696095399656, 10.87175052045090062, -20.0184979022142997, 27.63210188163320069, - -28.97950009664030091, 23.26740804691930009, -14.33375703270860058, 6.751281271241110105, -2.406363094133439962, - 0.6367414734718820357, -0.1210468076141379967, 0.01561196698118279963, -0.001222335432128580056, 4.383502970318410206e-05, - - // log K = 6 - 0.9973904854982870161, 0.3330148852217920119, 0.125251536589509993, -0.04434075124043219962, -0.2436238890691720116, - 1.163293254754570016, -4.177758779777369647, 10.60301981340099964, -19.6274507428828997, 27.18420839597660077, - -28.56827214174580121, 22.96268674086600114, -14.15234202220280046, 6.665700662642549901, -2.375043356720739851, - 0.6280993991240929608, -0.119319019358031006, 0.01537674055733759954, -0.001202881695730769916, 4.309894633186929849e-05, - - // log K = 7 - 0.9986963310058679655, 0.3331956705633329907, 0.125337696770523005, -0.04546817338088020299, -0.2386752211125199863, - 1.145927328111949972, -4.135694445582720036, 10.52805060502839929, -19.52408322548339825, 27.06921653903929936, - -28.46207532143190022, 22.88083524357429965, -14.10057147392659971, 6.63958754983273991, -2.364865219283200037, - 0.6251341806425250169, -0.1186991327450530043, 0.0152892726403408008, -0.001195439764873199896, 4.281098416794090072e-05, - - // log K = 8 - 0.999348600452531044, 0.3332480372393080148, 0.126666900963325002, -0.06495714694254159371, -0.08376282050638980681, - 0.3760158094643630267, -1.568204791601850001, 4.483117719555970382, -9.119180124379150598, 13.65799293358900002, - -15.3100211234349004, 12.97546344654869976, -8.351661538536939489, 4.075022612435580172, -1.49387015887069996, - 0.4040976870253379927, -0.07813232681879349328, 0.01020545649538820085, -0.0008063279210812720381, 2.909334976414100078e-05, - - // log K = 9 - 0.9996743787297059924, 0.3332925779481850093, 0.1267124599259649986, -0.06550452970936600228, -0.08191738117533520214, - 0.3773034458363569987, -1.604679509609959975, 4.636761898691969641, -9.487348609558699408, 14.25164235443030059, - -15.99674955529870068, 13.56353219046370029, -8.730194904342459594, 4.259010067932120336, -1.56106689792022002, - 0.4222540912786589828, -0.08165296504921559784, 0.01066878484925220041, -0.0008433887618256910015, 3.045339724886519912e-05, - - // log K = 10 - 0.999837191783945034, 0.3333142252339619804, 0.1267759538087240012, -0.06631005632753710077, -0.07692759158286699428, - 0.3568943956395980166, -1.546598721379510044, 4.51595019978557044, -9.298431968763770428, 14.02586858080080034, - -15.78858959520439953, 13.41484931677589998, -8.647958125130809748, 4.22398017468472009, -1.549708891200570093, - 0.419507410264540026, -0.08117411611046250475, 0.01061202286184199928, -0.000839300527596772007, 3.03185874520205985e-05, - - // log K = 11 - 0.9999186020796150265, 0.3333249054574359826, 0.126791713589799987, -0.06662487271699729652, -0.07335552427910230211, - 0.3316370184815959909, -1.434143797561290068, 4.180260309967409604, -8.593906870708760692, 12.95088874800289958, - -14.56876092520539956, 12.37074367531410068, -7.969152075707960137, 3.888774396648960074, -1.424923326506990051, - 0.385084561785229984, -0.07435541911616409816, 0.009695363567476529554, -0.0007644375960047160388, 2.75156194717188011e-05, - - // log K = 12 - 0.9999592955649559967, 0.3333310560725140093, 0.1267379744020450116, -0.06524495415766619344, -0.08854031542298740343, - 0.4244320628874230228, -1.794077789033230008, 5.133875262768450298, -10.40149374917120007, 15.47808115629240078, - -17.2272296137545986, 14.5002173676463002, -9.274819801602760094, 4.500782540026570189, -1.642359389030050076, - 0.442596113445525019, -0.0853226219238850947, 0.01111969379054169975, -0.0008771614088006969611, 3.161668519459719752e-05, - - // log K = 13 - 0.9999796468102559732, 0.3333336602394039727, 0.126728089053198989, -0.06503798598282370391, -0.09050261023823169548, - 0.4350609244189960201, -1.831274835815670077, 5.223387516985289913, -10.55574395269979959, 15.67359470222429962, - -17.41263416341029924, 14.63297400889229927, -9.346752431221359458, 4.530124905188380069, -1.651245566462089975, - 0.444542549250713015, -0.08561720963336499901, 0.01114805146185449992, -0.0008786251203363140043, 3.16416341644572998e-05, - - // log K = 14 - 0.9999898187060970445, 0.3333362579300819806, 0.1266984078369459976, -0.06464561179765909715, -0.09343280886228019777, - 0.4490702549264070087, -1.878087608052450008, 5.338004322057390283, -10.76690603590630069, 15.97069195083200022, - -17.73440379943459888, 14.90212518309260048, -9.520506013770420495, 4.616238931978830173, -1.68364817877918993, - 0.4536194960681350086, -0.087448605434800597, 0.01139929991331390009, -0.0008995891451622229631, 3.244407259782900338e-05, - - // log K = 15 - 0.9999949072549390028, 0.3333376334705290267, 0.126665364358402005, -0.06411790034705669439, -0.09776009134670660128, - 0.4704691112248470253, -1.948021675295769972, 5.497760972696490001, -11.03165645315390009, 16.29703330781000048, - -18.03851029448010124, 15.11836776139680083, -9.638205179917429533, 4.665122328753120051, -1.698980686525759953, - 0.4571799506245269873, -0.08804011353783609828, 0.01146553155965330043, -0.0009040455800659569869, 3.257931866957050274e-05, - - // log K = 16 - 0.9999974544793589493, 0.3333381337614599871, 0.1266524862971120102, -0.06391676499117690535, -0.09929616211306059592, - 0.4771390820378790254, -1.965762451227349938, 5.526802350376460282, -11.05703067024660058, 16.29535848023060041, - -18.00114005075790047, 15.06214012231560062, -9.58874727382628933, 4.63537541652793017, -1.686222848555620102, - 0.4532602373715179933, -0.08719448925964939923, 0.01134365425717459921, -0.0008934965241274289835, 3.216436244471380105e-05, - - // log K = 17 - 0.9999987278278800185, 0.3333383411464330148, 0.126642761751724009, -0.06371042959073920653, -0.1013564516034080043, - 0.4891311195679299839, -2.010971712051409899, 5.644390807952309963, -11.27697253921500042, 16.59957157207080058, - -18.31808338317799922, 15.31363518393730061, -9.741451446816620674, 4.706207545519429658, -1.711102469010010063, - 0.4597587341089349744, -0.08841670767182820134, 0.01149999225097850068, -0.0009056651366963050422, 3.259910736274500059e-05, - - // log K = 18 - 0.9999993637727100371, 0.3333385511608860097, 0.1266341580529160016, -0.06353272828164230335, -0.103139962850642003, - 0.4996216017206500104, -2.05099128585287982, 5.749874086531799655, -11.47727638570349917, 16.88141587810320132, - -18.61744656177490143, 15.55634230427719977, -9.892350736128680211, 4.778033520984200422, -1.737045483861280104, - 0.4667410882683730167, -0.08977256212421590165, 0.01167940146667079994, -0.0009201381242396030127, 3.313600701586759867e-05, - - // log K = 19 - 0.9999996805376010212, 0.3333372324328989778, 0.1267104737214659882, -0.06504749929326139601, -0.0882341962464350954, - 0.4131871162041140244, -1.725190703567099915, 4.900817515593920426, -9.883452720776510603, 14.6657081190816001, - -16.29398295135089825, 13.69805011761319946, -8.753475239465899449, 4.244072374564439976, -1.547202527706629915, - 0.4164770109614310267, -0.08017596922092029565, 0.01043146101701039954, -0.00082124200571200305, 2.953319493719429935e-05, - - // log K = 20 - 0.9999998390037539986, 0.3333365859956040067, 0.1267460211029839967, -0.06569456024647769843, -0.0823070353477164951, - 0.3810826463303410017, -1.611983580241109992, 4.624520077758210057, -9.397308335633589138, 14.03184981378050011, - -15.6703191315401007, 13.22992718704790072, -8.484216393184780713, 4.125607133488029987, -1.507690650697159906, - 0.4066678517577320129, -0.07842110121777939868, 0.01021780862225150042, -0.0008054065857047439754, 2.899431830426989844e-05, - - // log K = 21 - 0.9999999207001479817, 0.3333384953015239849, 0.1266331480396669928, -0.06345750166298599892, -0.1042341210992499961, - 0.5077112908497130039, -2.087398133609810191, 5.858842546192500222, -11.70620319777190055, 17.23103975433669888, - -19.01462552846669851, 15.89674059836560005, -10.11395134034419918, 4.88760796465891989, -1.777886770904629987, - 0.4780200178339499839, -0.09200895321782050218, 0.01198029553244219989, -0.0009447283875782100165, 3.405716775824710232e-05, - - // log K = 22 - 0.9999999606908690497, 0.3333383929524300071, 0.1266456445096819927, -0.06373504294081690225, -0.1012834291081849969, - 0.4893810690172959998, -2.01391428223606983, 5.656430437473649597, -11.3067201537791, 16.64980594135310099, - -18.3792355790383013, 15.36879753115040081, -9.778831246425049528, 4.725308061988969577, -1.718423596500280093, - 0.4618308177809870019, -0.08883675060799739454, 0.01155766944804260087, -0.0009104695617243750358, 3.278237729674439666e-05, - - // log K = 23 - 0.9999999794683379628, 0.3333386441751680085, 0.1266463995182049995, -0.06376031920455070556, -0.1010799540803130059, - 0.488540137426137, -2.012048323537570127, 5.654949475342659682, -11.31023240892979942, 16.66334675284959843, - -18.40241452866079896, 15.39443572867130072, -9.798844412838670692, 4.736683907539640082, -1.723168363744929987, - 0.463270349018644001, -0.08914619066708899531, 0.01160235936257320022, -0.0009143600818183229709, 3.293669304679140117e-05, - - // log K = 24 - 0.9999999911469820146, 0.3333376076934529975, 0.1266944349940530012, -0.06470524278387919381, -0.09189342220283110152, - 0.4359182372694809793, -1.815980282951169977, 5.149474056470340066, -10.37086570678100017, 15.36962686758569951, - -17.05756384717849983, 14.32755177515199918, -9.149944050025640152, 4.434601894497260055, -1.616478926806520056, - 0.4351979157055039793, -0.08381768225272340223, 0.01091321820476520016, -0.0008600264403629039739, 3.09667800347144002e-05, - - // log K = 25 - 0.9999999968592140354, 0.3333379164881000167, 0.1266782495827009913, -0.06434163088961859789, -0.09575258124988890451, - 0.4597843575354370049, -1.911374431241559924, 5.411856661251520428, -10.88850084646090011, 16.12298941380269923, - -17.88172178487259956, 15.01301780636859995, -9.585542896142529301, 4.645811872761620442, -1.693952293156189892, - 0.4563143308861309921, -0.08795976148455289523, 0.01146560428011200033, -0.0009048442931930629528, 3.26358391497329992e-05, - - // log K = 26 - 0.9999999970700530483, 0.333338329556315982, 0.126644753076394001, -0.06372365346512399997, -0.1012760856945769949, - 0.4886852278576360176, -2.009005418394389952, 5.638119224137019714, -11.26276715335160006, 16.57640024218650154, - -18.29035093605569884, 15.28892246224570073, -9.724916375991760731, 4.6978877652334603, -1.707974125916829955, - 0.4588937864564729963, -0.08824617586088029375, 0.01147732114826570046, -0.00090384524860747295, 3.253252703695579795e-05, - }; - //CHECKSTYLE.ON: LineLength -} diff --git a/src/main/java/org/apache/datasketches/cpc/MergingValidation.java b/src/main/java/org/apache/datasketches/cpc/MergingValidation.java deleted file mode 100644 index 213e65d30..000000000 --- a/src/main/java/org/apache/datasketches/cpc/MergingValidation.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.common.Util.INVERSE_GOLDEN_U64; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.powerSeriesNextDouble; -import static org.apache.datasketches.cpc.IconEstimator.getIconEstimate; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals; - -import java.io.PrintStream; -import java.io.PrintWriter; - -import org.apache.datasketches.common.SuppressFBWarnings; - -/** - * This code is used both by unit tests, for short running tests, - * and by the characterization repository for longer running, more exhaustive testing. To be - * accessible for both, this code is part of the main hierarchy. It is not used during normal - * production runtime. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -public class MergingValidation { - private String hfmt; - private String dfmt; - private String[] hStrArr; - private long vIn = 0; - - //inputs - private int lgMinK; - private int lgMaxK; //inclusive - private int lgMulK; //multiplier of K to produce maxNa, maxNb - private int uPPO; - private int incLgK; //increment of lgK - private PrintStream printStream; - private PrintWriter printWriter; - - /** - * Constructor - * @param lgMinK lgMinK - * @param lgMaxK lgMaxK - * @param lgMulK lgMulK - * @param uPPO uPPO - * @param incLgK incLgK - * @param pS pS - * @param pW pW - */ - @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "This is OK here") - public MergingValidation(final int lgMinK, final int lgMaxK, final int lgMulK, final int uPPO, - final int incLgK, final PrintStream pS, final PrintWriter pW) { - this.lgMinK = lgMinK; - this.lgMaxK = lgMaxK; - this.lgMulK = lgMulK; - this.uPPO = Math.max(uPPO, 1); - this.incLgK = Math.max(incLgK, 1); - printStream = pS; - printWriter = pW; - assembleFormats(); - } - - /** - * Start the merging validation process - */ - public void start() { - printf(hfmt, (Object[]) hStrArr); //print header - doRangeOfLgK(); - } - - private void doRangeOfLgK() { - for (int lgK = lgMinK; lgK <= lgMaxK; lgK += incLgK) { - multiTestMerging(lgK, lgK - 1, lgK - 1); - multiTestMerging(lgK, lgK - 1, lgK + 0); - multiTestMerging(lgK, lgK - 1, lgK + 1); - - multiTestMerging(lgK, lgK + 0, lgK - 1); - multiTestMerging(lgK, lgK + 0, lgK + 0); - multiTestMerging(lgK, lgK + 0, lgK + 1); - - multiTestMerging(lgK, lgK + 1, lgK - 1); - multiTestMerging(lgK, lgK + 1, lgK + 0); - multiTestMerging(lgK, lgK + 1, lgK + 1); - } - } - - private void multiTestMerging(final int lgKm, final int lgKa, final int lgKb) { - final long limA = 1L << (lgKa + lgMulK); - final long limB = 1L << (lgKa + lgMulK); - long nA = 0; - while (nA <= limA) { - long nB = 0; - while (nB <= limB) { - testMerging(lgKm, lgKa, lgKb, nA, nB); - nB = Math.round(powerSeriesNextDouble(uPPO, nB, true, 2.0)); - } - nA = Math.round(powerSeriesNextDouble(uPPO, nA, true, 2.0)); - } - } - - private void testMerging(final int lgKm, final int lgKa, final int lgKb, final long nA, - final long nB) { - final CpcUnion ugM = new CpcUnion(lgKm); - - // int lgKd = ((nA != 0) && (lgKa < lgKm)) ? lgKa : lgKm; - // lgKd = ((nB != 0) && (lgKb < lgKd)) ? lgKb : lgKd; - int lgKd = lgKm; - if ((lgKa < lgKd) && (nA != 0)) { lgKd = lgKa; } //d = min(a,m) : m - if ((lgKb < lgKd) && (nB != 0)) { lgKd = lgKb; } //d = min(b,d) : d - - final CpcSketch skD = new CpcSketch(lgKd); // direct sketch, updated with both streams - - final CpcSketch skA = new CpcSketch(lgKa); - final CpcSketch skB = new CpcSketch(lgKb); - - for (long i = 0; i < nA; i++) { - final long in = (vIn += INVERSE_GOLDEN_U64); - skA.update(in); - skD.update(in); - } - for (long i = 0; i < nB; i++) { - final long in = (vIn += INVERSE_GOLDEN_U64); - skB.update(in); - skD.update(in); - } - - ugM.update(skA); - ugM.update(skB); - - final int finalLgKm = ugM.getLgK(); - final long[] matrixM = CpcUnion.getBitMatrix(ugM); - - final long cM = ugM.getNumCoupons();//countBitsSetInMatrix(matrixM); - final long cD = skD.numCoupons; - final Flavor flavorD = skD.getFlavor(); - final Flavor flavorA = skA.getFlavor(); - final Flavor flavorB = skB.getFlavor(); - final String dOff = Integer.toString(skD.windowOffset); - final String aOff = Integer.toString(skA.windowOffset); - final String bOff = Integer.toString(skB.windowOffset); - final String flavorDoff = flavorD + String.format("%2s",dOff); - final String flavorAoff = flavorA + String.format("%2s",aOff); - final String flavorBoff = flavorB + String.format("%2s",bOff); - final double iconEstD = getIconEstimate(lgKd, cD); - - rtAssert(finalLgKm <= lgKm); - rtAssert(cM <= (skA.numCoupons + skB.numCoupons)); - rtAssertEquals(cM, cD); - - rtAssertEquals(finalLgKm, lgKd); - final long[] matrixD = CpcUtil.bitMatrixOfSketch(skD); - rtAssertEquals(matrixM, matrixD); - - final CpcSketch skR = ugM.getResult(); - final double iconEstR = getIconEstimate(skR.lgK, skR.numCoupons); - rtAssertEquals(iconEstD, iconEstR, 0.0); - rtAssert(TestUtil.specialEquals(skD, skR, false, true)); - - printf(dfmt, lgKm, lgKa, lgKb, lgKd, nA, nB, (nA + nB), - flavorAoff, flavorBoff, flavorDoff, - skA.numCoupons, skB.numCoupons, cD, iconEstR); - } - - private void printf(final String format, final Object ... args) { - if (printStream != null) { printStream.printf(format, args); } - if (printWriter != null) { printWriter.printf(format, args); } - } - - private void assembleFormats() { - final String[][] assy = { - {"lgKm", "%4s", "%4d"}, - {"lgKa", "%4s", "%4d"}, - {"lgKb", "%4s", "%4d"}, - {"lgKfd", "%6s", "%6d"}, - {"nA", "%12s", "%12d"}, - {"nB", "%12s", "%12d"}, - {"nA+nB", "%12s", "%12d"}, - {"Flavor_a", "%11s", "%11s"}, - {"Flavor_b", "%11s", "%11s"}, - {"Flavor_fd", "%11s", "%11s"}, - {"Coupons_a", "%9s", "%9d"}, - {"Coupons_b", "%9s", "%9d"}, - {"Coupons_fd", "%9s", "%9d"}, - {"IconEst_dr", "%12s", "%,12.0f"} - }; - final int cols = assy.length; - hStrArr = new String[cols]; - final StringBuilder headerFmt = new StringBuilder(); - final StringBuilder dataFmt = new StringBuilder(); - headerFmt.append(LS + "Merging Validation" + LS); - for (int i = 0; i < cols; i++) { - hStrArr[i] = assy[i][0]; - headerFmt.append(assy[i][1]); - headerFmt.append((i < (cols - 1)) ? "\t" : LS); - dataFmt.append(assy[i][2]); - dataFmt.append((i < (cols - 1)) ? "\t" : LS); - } - hfmt = headerFmt.toString(); - dfmt = dataFmt.toString(); - } -} diff --git a/src/main/java/org/apache/datasketches/cpc/PairTable.java b/src/main/java/org/apache/datasketches/cpc/PairTable.java deleted file mode 100644 index 87258ec5c..000000000 --- a/src/main/java/org/apache/datasketches/cpc/PairTable.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals; - -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; - -/** - * Note: Definition of - * Snow Plow Effect. - * @author Lee Rhodes - * @author Kevin Lang - */ -final class PairTable { - private static final int upsizeNumer = 3; - private static final int upsizeDenom = 4; - private static final int downsizeNumer = 1; - private static final int downsizeDenom = 4; - - private int lgSizeInts; - private final int validBits; - private int numPairs; - private int[] slotsArr; - - PairTable(final int lgSizeInts, final int numValidBits) { - checkLgSizeInts(lgSizeInts); - this.lgSizeInts = lgSizeInts; - final int numSlots = 1 << lgSizeInts; - validBits = numValidBits; - numPairs = 0; - slotsArr = new int[numSlots]; - for (int i = 0; i < numSlots; i++) { slotsArr[i] = -1; } - } - - //Factory - static PairTable newInstanceFromPairsArray(final int[] pairs, final int numPairs, final int lgK) { - int lgNumSlots = 2; - while ((upsizeDenom * numPairs) > (upsizeNumer * (1 << lgNumSlots))) { - lgNumSlots++; - } - final PairTable table = new PairTable(lgNumSlots, 6 + lgK); - - /* Note: there is a possible - * Snow Plow Effect here because - * the caller is passing in a sorted pairs array. However, we are starting out with the correct - * final table size, so the problem is not likely to occur. - */ - - for (int i = 0; i < numPairs; i++) { - mustInsert(table, pairs[i]); - } - table.numPairs = numPairs; - return table; - } - - PairTable clear() { - Arrays.fill(slotsArr, -1); - numPairs = 0; - return this; - } - - PairTable copy() { - final PairTable copy = new PairTable(lgSizeInts, validBits); - copy.numPairs = numPairs; - copy.slotsArr = slotsArr.clone(); //slotsArr can never be null - return copy; - } - - int getLgSizeInts() { - return lgSizeInts; - } - - int getNumPairs() { - return numPairs; - } - - int[] getSlotsArr() { - return slotsArr; - } - - int getValidBits() { - return validBits; - } - - /** - * Rebuilds to a larger size. NumItems and validBits remain unchanged. - * @param newLgSizeInts the new size - * @return a larger PairTable - */ - PairTable rebuild(final int newLgSizeInts) { - checkLgSizeInts(newLgSizeInts); - final int newSize = 1 << newLgSizeInts; - final int oldSize = 1 << lgSizeInts; - rtAssert(newSize > numPairs); - final int[] oldSlotsArr = slotsArr; - slotsArr = new int[newSize]; - Arrays.fill(slotsArr, -1); - lgSizeInts = newLgSizeInts; - for (int i = 0; i < oldSize; i++) { - final int item = oldSlotsArr[i]; - if (item != -1) { mustInsert(this, item); } - } - return this; - } - - @Override - public String toString() { - return toString(false); - } - - private static void mustInsert(final PairTable table, final int item) { - //SHARED CODE (implemented as a macro in C and expanded here) - final int lgSizeInts = table.lgSizeInts; - final int sizeInts = 1 << lgSizeInts; - final int mask = sizeInts - 1; - final int shift = table.validBits - lgSizeInts; - rtAssert(shift > 0); - int probe = item >>> shift; //extract high tablesize bits - rtAssert((probe >= 0) && (probe <= mask)); - final int[] arr = table.slotsArr; - int fetched = arr[probe]; - while ((fetched != item) && (fetched != -1)) { - probe = (probe + 1) & mask; - fetched = arr[probe]; - } - //END SHARED CODE - if (fetched == item) { throw new SketchesStateException("PairTable mustInsert() failed"); } - else { - assert (fetched == -1); - arr[probe] = item; - // counts and resizing must be handled by the caller. - } - } - - static boolean maybeInsert(final PairTable table, final int item) { - //SHARED CODE (implemented as a macro in C and expanded here) - final int lgSizeInts = table.lgSizeInts; - final int sizeInts = 1 << lgSizeInts; - final int mask = sizeInts - 1; - final int shift = table.validBits - lgSizeInts; - rtAssert(shift > 0); - int probe = item >>> shift; - rtAssert((probe >= 0) && (probe <= mask)); - final int[] arr = table.slotsArr; - int fetched = arr[probe]; - while ((fetched != item) && (fetched != -1)) { - probe = (probe + 1) & mask; - fetched = arr[probe]; - } - //END SHARED CODE - if (fetched == item) { return false; } - else { - assert (fetched == -1); - arr[probe] = item; - table.numPairs += 1; - while ((upsizeDenom * table.numPairs) > (upsizeNumer * (1 << table.lgSizeInts))) { - table.rebuild(table.lgSizeInts + 1); - } - return true; - } - } - - static boolean maybeDelete(final PairTable table, final int item) { - //SHARED CODE (implemented as a macro in C and expanded here) - final int lgSizeInts = table.lgSizeInts; - final int sizeInts = 1 << lgSizeInts; - final int mask = sizeInts - 1; - final int shift = table.validBits - lgSizeInts; - rtAssert(shift > 0); - int probe = item >>> shift; - rtAssert((probe >= 0) && (probe <= mask)); - final int[] arr = table.slotsArr; - int fetched = arr[probe]; - while ((fetched != item) && (fetched != -1)) { - probe = (probe + 1) & mask; - fetched = arr[probe]; - } - //END SHARED CODE - if (fetched == -1) { return false; } - else { - assert (fetched == item); - // delete the item - arr[probe] = -1; - table.numPairs -= 1; assert (table.numPairs >= 0); - - // re-insert all items between the freed slot and the next empty slot - probe = (probe + 1) & mask; fetched = arr[probe]; - while (fetched != -1) { - arr[probe] = -1; - mustInsert(table, fetched); - probe = (probe + 1) & mask; fetched = arr[probe]; - } - - // shrink if necessary - while (((downsizeDenom * table.numPairs) - < (downsizeNumer * (1 << table.lgSizeInts))) && (table.lgSizeInts > 2)) { - table.rebuild(table.lgSizeInts - 1); - } - return true; - } - } - - /** - * While extracting the items from a linear probing hashtable, - * this will usually undo the wrap-around provided that the table - * isn't too full. Experiments suggest that for sufficiently large tables - * the load factor would have to be over 90 percent before this would fail frequently, - * and even then the subsequent sort would fix things up. - * @param table the given table to unwrap - * @param numPairs the number of valid pairs in the table - * @return the unwrapped table - */ - static int[] unwrappingGetItems(final PairTable table, final int numPairs) { - if (numPairs < 1) { return null; } - final int[] slotsArr = table.slotsArr; - final int tableSize = 1 << table.lgSizeInts; - final int[] result = new int[numPairs]; - int i = 0; - int l = 0; - int r = numPairs - 1; - - // Special rules for the region before the first empty slot. - final int hiBit = 1 << (table.validBits - 1); - while ((i < tableSize) && (slotsArr[i] != -1)) { - final int item = slotsArr[i++]; - if ((item & hiBit) != 0) { result[r--] = item; } // This item was probably wrapped, so move to end. - else { result[l++] = item; } - } - - // The rest of the table is processed normally. - while (i < tableSize) { - final int look = slotsArr[i++]; - if (look != -1) { result[l++] = look; } - } - assert l == (r + 1); - return result; - } - - /** - * In applications where the input array is already nearly sorted, - * insertion sort runs in linear time with a very small constant. - * This introspective version of insertion sort protects against - * the quadratic cost of sorting bad input arrays. - * It keeps track of how much work has been done, and if that exceeds a - * constant times the array length, it switches to a different sorting algorithm. - * @param a the array to sort - * @param l points AT the leftmost element, i.e., inclusive. - * @param r points AT the rightmost element, i.e., inclusive. - */ - static void introspectiveInsertionSort(final int[] a, final int l, final int r) { - final int length = (r - l) + 1; - long cost = 0; - final long costLimit = 8L * length; - for (int i = l + 1; i <= r; i++) { - int j = i; - final long v = a[i] & 0XFFFF_FFFFL; //v must be long - while ((j >= (l + 1)) && (v < ((a[j - 1]) & 0XFFFF_FFFFL))) { - a[j] = a[j - 1]; - j -= 1; - } - a[j] = (int) v; - cost += (i - j); // distance moved is a measure of work - - if (cost > costLimit) { - //we need an unsigned sort, but it is linear time and very rarely occurs - final long[] b = new long[a.length]; - for (int m = 0; m < a.length; m++) { b[m] = a[m] & 0XFFFF_FFFFL; } - Arrays.sort(b, l, r + 1); - for (int m = 0; m < a.length; m++) { a[m] = (int) b[m]; } - // The following sanity check can be used during development - //int bad = 0; - //for (int m = l; m < (r - 1); m++) { - // final long b1 = a[m] & 0XFFFF_FFFFL; - // final long b2 = a[m + 1] & 0XFFFF_FFFFL; - // if (b1 > b2) { bad++; } - //} - //assert (bad == 0); - return; - } - } - // The following sanity check can be used during development - // int bad = 0; - // for (int m = l; m < (r - 1); m++) { - // final long b1 = a[m] & 0XFFFF_FFFFL; - // final long b2 = a[m + 1] & 0XFFFF_FFFFL; - // if (b1 > b2) { bad++; } - // } - // assert (bad == 0); - } - - static void merge( - final int[] arrA, final int startA, final int lengthA, //input - final int[] arrB, final int startB, final int lengthB, //input - final int[] arrC, final int startC) { //output - - final int lengthC = lengthA + lengthB; - final int limA = startA + lengthA; - final int limB = startB + lengthB; - final int limC = startC + lengthC; - int a = startA; - int b = startB; - int c = startC; - for ( ; c < limC ; c++) { - if (b >= limB) { arrC[c] = arrA[a++]; } - else if (a >= limA) { arrC[c] = arrB[b++]; } - else { - final long aa = arrA[a] & 0XFFFF_FFFFL; - final long bb = arrB[b] & 0XFFFF_FFFFL; - if (aa < bb) { arrC[c] = arrA[a++]; } - else { arrC[c] = arrB[b++]; } - } - } - assert (a == limA); - assert (b == limB); - } - - static boolean equals(final PairTable a, final PairTable b) { - if ((a == null) && (b == null)) { return true; } - if ((a == null) || (b == null)) { - throw new SketchesArgumentException("PairTable " + ((a == null) ? "a" : "b") + " is null"); - } - //Note: lgSize array sizes may not be equal, but contents still can be equal - rtAssertEquals(a.validBits, b.validBits); - final int numPairsA = a.numPairs; - final int numPairsB = b.numPairs; - rtAssertEquals(numPairsA, numPairsB); - final int[] pairsA = PairTable.unwrappingGetItems(a, numPairsA); - final int[] pairsB = PairTable.unwrappingGetItems(b, numPairsB); - PairTable.introspectiveInsertionSort(pairsA, 0, numPairsA - 1); - PairTable.introspectiveInsertionSort(pairsB, 0, numPairsB - 1); - rtAssertEquals(pairsA, pairsB); - return true; - } - - String toString(final boolean detail) { - final StringBuilder sb = new StringBuilder(); - final int sizeInts = 1 << lgSizeInts; - sb.append("PairTable").append(LS); - sb.append(" Lg Size Ints : ").append(lgSizeInts).append(LS); - sb.append(" Size Ints : ").append(sizeInts).append(LS); - sb.append(" Valid Bits : ").append(validBits).append(LS); - sb.append(" Num Pairs : ").append(numPairs).append(LS); - if (detail) { - sb.append(" DATA (hex) : ").append(LS); - final String hdr = String.format("%9s %9s %9s %4s", "Index","Word","Row","Col"); - sb.append(hdr).append(LS); - for (int i = 0; i < sizeInts; i++) { - final int word = slotsArr[i]; - if (word == -1) { //empty - final String h = String.format("%9d %9s", i, "--"); - sb.append(h).append(LS); - } else { //data - final int row = word >>> 6; - final int col = word & 0X3F; - final String wordStr = Long.toHexString(word & 0XFFFF_FFFFL); - final String data = String.format("%9d %9s %9d %4d", i, wordStr, row, col); - sb.append(data).append(LS); - } - } - } - return sb.toString(); - } - - private static void checkLgSizeInts(final int lgSizeInts) { - if ((lgSizeInts < 2) || (lgSizeInts > 26)) { - throw new SketchesArgumentException("Illegal LgSizeInts: " + lgSizeInts); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/PreambleUtil.java b/src/main/java/org/apache/datasketches/cpc/PreambleUtil.java deleted file mode 100644 index f24c86dd1..000000000 --- a/src/main/java/org/apache/datasketches/cpc/PreambleUtil.java +++ /dev/null @@ -1,819 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.checkBounds; -import static org.apache.datasketches.common.Util.clear; -import static org.apache.datasketches.common.Util.zeroPad; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; - -//@formatter:off -/** - * All formats are illustrated as Big-Endian, LSB on the right. - * - *

- * Format = EMPTY_MERGED/EMPTY_HIP: NoWindow, NoSV, HIP or NoHIP = 00X.
- * The first 8 bytes are common for all Formats.
- * PI = 2, FIcol = 0
- * Long adr ||
- *          ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |    0   |
- *      0   ||---SEED HASH-----|-Flags--|-FIcol--|---lgK--|-FamID--|-SerVer-|---PI---|
- *
- *
- * Format = SPARSE_HYBRID_MERGED: {NoWindow, SV, NoHIP} = 2 = 010.
- * PI = 4, FIcol = 0
- * Long adr ||
- *          ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |    8   |
- *      1   ||-------------SV Length Ints--------|--------numCoupons = numSV---------|
- *
- *          ||   23   |   22   |   21   |   20   |   19   |   18   |   17   |   16   |
- *      2   ||                                   |----------Start SV bit stream------|
- *
- *
- * Format = SPARSE_HYBRID_HIP: {NoWindow, SV, HIP} = 3 = 011
- * PI = 8, FIcol = 0
- * Long adr ||
- *          ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |    8   |
- *      1   ||-------------SV Length Ints--------|--------numCoupons = numSV---------|
- *
- *          ||   23   |   22   |   21   |   20   |   19   |   18   |   17   |   16   |
- *      2   ||----------------------------------KxP----------------------------------|
- *
- *          ||   31   |   30   |   29   |   28   |   27   |   26   |   25   |   24   |
- *      3   ||-------------------------------HIP Accum-------------------------------|
- *
- *          ||   39   |   38   |   37   |   36   |   35   |   34   |   33   |   32   |
- *      4   ||                                   |----------Start of SV stream-------|
- *
- *
- * Format = PINNED_SLIDING_MERGED_NOSV: {Window, No SV, NoHIP} = 4 = 100
- * PI = 4, FIcol = valid
- * Long adr ||
- *          ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |    8   |
- *      1   ||----------Window Length Ints-------|------------numCoupons-------------|
- *
- *          ||   23   |   22   |   21   |   20   |   19   |   18   |   17   |   16   |
- *      2   ||                                   |--------Start of Window stream-----|
- *
- *
- * Format = PINNED_SLIDING_HIP_NOSV: {Window, No SV, HIP} = 5 = 101
- * PI = 8, FIcol = valid
- * Long adr ||
- *          ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |    8   |
- *      1   ||----------Window Length Ints-------|------------numCoupons-------------|
- *
- *          ||   23   |   22   |   21   |   20   |   19   |   18   |   17   |   16   |
- *      2   ||----------------------------------KxP----------------------------------|
- *
- *          ||   31   |   30   |   29   |   28   |   27   |   26   |   25   |   24   |
- *      3   ||-------------------------------HIP Accum-------------------------------|
- *
- *          ||   39   |   38   |   37   |   36   |   35   |   34   |   33   |   32   |
- *      4   ||                                   |--------Start of Window stream-----|
- *
- *
- * Format = PINNED_SLIDING_MERGED: {Window, SV, NoHIP} = 6 = 110
- * PI = 6, FIcol = valid
- * Long adr ||
- *          ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |    8   |
- *      1   ||---------------numSV---------------|------------numCoupons-------------|
- *
- *          ||   23   |   22   |   21   |   20   |   19   |   18   |   17   |   16   |
- *      2   ||----------Window Length Ints-------|-------------SV Length Ints--------|
- *
- *          ||   XX   |   XX   |   XX   |   XX   |   27   |   26   |   25   |   24   |
- *      3   ||--------Start of SV stream---------|--------Start of Window stream-----|
- *
- *
- * Format = PINNED_SLIDING_HIP: {Window, SV, HIP} = 7 = 111
- * PI = 10, FIcol = valid
- * Long adr ||
- *          ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |    8   |
- *      1   ||---------------numSV---------------|------------numCoupons-------------|
- *
- *          ||   23   |   22   |   21   |   20   |   19   |   18   |   17   |   16   |
- *      2   ||----------------------------------KxP----------------------------------|
- *
- *          ||   31   |   30   |   29   |   28   |   27   |   26   |   25   |   24   |
- *      3   ||-------------------------------HIP Accum-------------------------------|
- *
- *          ||   39   |   38   |   37   |   36   |   35   |   34   |   33   |   32   |
- *      4   ||----------Window Length Ints-------|-------------SV Length Ints--------|
- *
- *          ||   XX   |   XX   |   XX   |   XX   |   43   |   42   |   41   |   40   |
- *      5   ||--------Start of SV stream---------|--------Start of Window stream-----|
- * 
- * - * @author Lee Rhodes - * @author Kevin Lang - */ -final class PreambleUtil { - - private PreambleUtil() {} - - private static final String fmt = "%10d%10x"; - - /** - * The serialization version for the set of serialization formats defined in this class - */ - static final byte SER_VER = 1; - - //Flag bit masks, Byte 5 - static final int RESERVED_FLAG_MASK = 1; //Reserved. - static final int COMPRESSED_FLAG_MASK = 2; - static final int HIP_FLAG_MASK = 4; - static final int SUP_VAL_FLAG_MASK = 8; //num Surprising Values > 0 - static final int WINDOW_FLAG_MASK = 16;//window length > 0 - - //PREAMBLE SIZE - - /** - * This defines the preamble space required by each of the formats in units of 4-byte integers. - */ - private static final byte[] preIntDefs = { 2, 2, 4, 8, 4, 8, 6, 10 }; - - /** - * Returns the defined size of the preamble in units of integers (4 bytes) given the - * Format. - * @param format the given Format. - * @return the defined size of the preamble in units of integers (4 bytes) given the Format. - */ - static byte getDefinedPreInts(final Format format) { - return preIntDefs[format.ordinal()]; - } - - //PREAMBLE LO_FIELD DEFINITIONS, OFFSETS, AND GETS - - /** - * This defines the seven fields of the first eight bytes of the preamble. - * The ordinal of these values defines the byte offset. - * Do not change the order. - */ - enum LoField { PRE_INTS, SER_VERSION, FAMILY, LG_K, FI_COL, FLAGS, SEED_HASH } - - /** - * Returns the defined byte offset from the start of the preamble given a LoField. - * This only applies to the first 8 bytes of the preamble. - * @param loField the given LoField. - * @return the defined byte offset from the start of the preamble given a LoField. - */ - static int getLoFieldOffset(final LoField loField) { - return loField.ordinal(); - } - - static int getPreInts(final MemorySegment seg) { - return seg.get(JAVA_BYTE, getLoFieldOffset(LoField.PRE_INTS)) & 0XFF; - } - - static int getSerVer(final MemorySegment seg) { - return seg.get(JAVA_BYTE, getLoFieldOffset(LoField.SER_VERSION)) & 0XFF; - } - - static Family getFamily(final MemorySegment seg) { - final int fam = seg.get(JAVA_BYTE, getLoFieldOffset(LoField.FAMILY)) & 0XFF; - return Family.idToFamily(fam); - } - - static int getLgK(final MemorySegment seg) { - return seg.get(JAVA_BYTE, getLoFieldOffset(LoField.LG_K)) & 0XFF; - } - - static int getFiCol(final MemorySegment seg) { - return seg.get(JAVA_BYTE, getLoFieldOffset(LoField.FI_COL)) & 0XFF; - } - - static int getFlags(final MemorySegment seg) { - return seg.get(JAVA_BYTE, getLoFieldOffset(LoField.FLAGS)) & 0XFF; - } - - static short getSeedHash(final MemorySegment seg) { - return seg.get(JAVA_SHORT_UNALIGNED, getLoFieldOffset(LoField.SEED_HASH)); - } - - static int getFormatOrdinal(final MemorySegment seg) { - final int flags = getFlags(seg); - return (flags >>> 2) & 0x7; - } - - static Format getFormat(final MemorySegment seg) { - final int ordinal = getFormatOrdinal(seg); - return Format.ordinalToFormat(ordinal); - } - - static boolean hasHip(final MemorySegment seg) { - return (getFlags(seg) & HIP_FLAG_MASK) > 0; - } - - static boolean hasSv(final MemorySegment seg) { - return (getFlags(seg) & SUP_VAL_FLAG_MASK) > 0; - } - - static boolean hasWindow(final MemorySegment seg) { - return (getFlags(seg) & WINDOW_FLAG_MASK) > 0; - } - - static boolean isCompressed(final MemorySegment seg) { - return (getFlags(seg) & COMPRESSED_FLAG_MASK) > 0; - } - - //PREAMBLE HI_FIELD DEFINITIONS - - /** - * This defines the eight additional preamble fields located after the LoField. - * Do not change the order. - * - *

Note: NUM_SV has dual meanings: In sparse and hybrid flavors it is equivalent to - * numCoupons so it isn't stored separately. In pinned and sliding flavors is the - * numSV of the PairTable, which stores only surprising values.

- */ - enum HiField { NUM_COUPONS, NUM_SV, KXP, HIP_ACCUM, SV_LENGTH_INTS, W_LENGTH_INTS, SV_STREAM, - W_STREAM } - - //PREAMBLE HI_FIELD OFFSETS - - /** - * This defines the byte offset for eac of the 8 HiFields - * given the Format ordinal (1st dimension) and the HiField ordinal (2nd dimension). - */ - private static final byte[][] hiFieldOffset = //[Format][HiField] - { {0, 0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0, 0}, - {8, 0, 0, 0, 12, 0, 16, 0}, - {8, 0, 16, 24, 12, 0, 32, 0}, - {8, 0, 0, 0, 0, 12, 0, 16}, - {8, 0, 16, 24, 0, 12, 0, 32}, - {8, 12, 0, 0, 16, 20, 24, 24}, //the 2nd 24 is not used. - {8, 12, 16, 24, 32, 36, 40, 40} //the 2nd 40 is not used. - }; - - /** - * Returns the defined byte offset from the start of the preamble given the HiField - * and the Format. - * Note this can not be used to obtain the stream offsets. - * @param format the desired Format - * @param hiField the desired preamble HiField after the first eight bytes. - * @return the defined byte offset from the start of the preamble for the given HiField - * and the Format. - */ - static long getHiFieldOffset(final Format format, final HiField hiField) { - final int formatIdx = format.ordinal(); - final int hiFieldIdx = hiField.ordinal(); - final long fieldOffset = hiFieldOffset[formatIdx][hiFieldIdx] & 0xFF; //initially a byte - if (fieldOffset == 0) { - throw new SketchesStateException("Undefined preamble field given the Format: " - + "Format: " + format.toString() + ", HiField: " + hiField.toString()); - } - return fieldOffset; - } - - //PREAMBLE HI_FIELD GETS - - static int getNumCoupons(final MemorySegment seg) { - final Format format = getFormat(seg); - final HiField hiField = HiField.NUM_COUPONS; - final long offset = getHiFieldOffset(format, hiField); - return seg.get(JAVA_INT_UNALIGNED, offset); - } - - static int getNumSv(final MemorySegment seg) { - final Format format = getFormat(seg); - final HiField hiField = HiField.NUM_SV; - final long offset = getHiFieldOffset(format, hiField); - return seg.get(JAVA_INT_UNALIGNED, offset); - } - - static int getSvLengthInts(final MemorySegment seg) { - final Format format = getFormat(seg); - final HiField hiField = HiField.SV_LENGTH_INTS; - final long offset = getHiFieldOffset(format, hiField); - return seg.get(JAVA_INT_UNALIGNED, offset); - } - - static int getWLengthInts(final MemorySegment seg) { - final Format format = getFormat(seg); - final HiField hiField = HiField.W_LENGTH_INTS; - final long offset = getHiFieldOffset(format, hiField); - return seg.get(JAVA_INT_UNALIGNED, offset); - } - - static double getKxP(final MemorySegment seg) { - final Format format = getFormat(seg); - final HiField hiField = HiField.KXP; - final long offset = getHiFieldOffset(format, hiField); - return seg.get(JAVA_DOUBLE_UNALIGNED, offset); - } - - static double getHipAccum(final MemorySegment seg) { - final Format format = getFormat(seg); - final HiField hiField = HiField.HIP_ACCUM; - final long offset = getHiFieldOffset(format, hiField); - return seg.get(JAVA_DOUBLE_UNALIGNED, offset); - } - - static long getSvStreamOffset(final MemorySegment seg) { - final Format format = getFormat(seg); - final HiField svLenField = HiField.SV_LENGTH_INTS; - if (!hasSv(seg)) { - fieldError(format, svLenField); - } else { - final long svLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS)) & 0XFFFF_FFFFL; - if (svLengthInts == 0) { - throw new SketchesStateException("svLengthInts cannot be zero"); - } - } - long wLengthInts = 0; - if (hasWindow(seg)) { - wLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS)) & 0XFFFF_FFFFL; - if (wLengthInts == 0) { - throw new SketchesStateException("wLengthInts cannot be zero"); - } - } - return (getPreInts(seg) + wLengthInts) << 2; - } - - static long getWStreamOffset(final MemorySegment seg) { - final Format format = getFormat(seg); - final HiField wLenField = HiField.W_LENGTH_INTS; - if (!hasWindow(seg)) { fieldError(format, wLenField); } - final long wLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS)) & 0XFFFF_FFFFL; - if (wLengthInts == 0) { - throw new SketchesStateException("wLengthInts cannot be zero"); - } - return getPreInts(seg) << 2; - } - - static int[] getSvStream(final MemorySegment seg) { - final long offset = getSvStreamOffset(seg); - final int svLengthInts = getSvLengthInts(seg); - final int[] svStream = new int[svLengthInts]; - MemorySegment.copy(seg, JAVA_INT_UNALIGNED, offset, svStream, 0, svLengthInts); - return svStream; - } - - static int[] getWStream(final MemorySegment seg) { - final long offset = getWStreamOffset(seg); - final int wLength = getWLengthInts(seg); - final int[] wStream = new int[wLength]; - MemorySegment.copy(seg, JAVA_INT_UNALIGNED, offset, wStream, 0, wLength); - return wStream; - } - - // PUT INTO MEMORY - - static void putEmptyMerged(final MemorySegment wseg, - final int lgK, - final short seedHash) { - final Format format = Format.EMPTY_MERGED; - final byte preInts = getDefinedPreInts(format); - final byte fiCol = (byte) 0; - final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK); - checkCapacity(wseg.byteSize(), 8); - putFirst8(wseg, preInts, (byte) lgK, fiCol, flags, seedHash); - } - - static void putEmptyHip(final MemorySegment wseg, - final int lgK, - final short seedHash) { - final Format format = Format.EMPTY_HIP; - final byte preInts = getDefinedPreInts(format); - final byte fiCol = (byte) 0; - final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK); - checkCapacity(wseg.byteSize(), 8); - putFirst8(wseg, preInts, (byte) lgK, fiCol, flags, seedHash); - } - - static void putSparseHybridMerged(final MemorySegment wseg, - final int lgK, - final int numCoupons, //unsigned - final int svLengthInts, - final short seedHash, - final int[] svStream) { - final Format format = Format.SPARSE_HYBRID_MERGED; - final byte preInts = getDefinedPreInts(format); - final byte fiCol = (byte) 0; - final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK); - checkCapacity(wseg.byteSize(), 4L * (preInts + svLengthInts)); - putFirst8(wseg, preInts, (byte) lgK, fiCol, flags, seedHash); - - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS), numCoupons); - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS), svLengthInts); - MemorySegment.copy(svStream, 0, wseg, JAVA_INT_UNALIGNED, getSvStreamOffset(wseg), svLengthInts); - } - - static void putSparseHybridHip(final MemorySegment wseg, - final int lgK, - final int numCoupons, //unsigned - final int svLengthInts, - final double kxp, - final double hipAccum, - final short seedHash, - final int[] svStream) { - final Format format = Format.SPARSE_HYBRID_HIP; - final byte preInts = getDefinedPreInts(format); - final byte fiCol = (byte) 0; - final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK); - checkCapacity(wseg.byteSize(), 4L * (preInts + svLengthInts)); - putFirst8(wseg, preInts, (byte) lgK, fiCol, flags, seedHash); - - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS), numCoupons); - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS), svLengthInts); - wseg.set(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.KXP), kxp); - wseg.set(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.HIP_ACCUM), hipAccum); - MemorySegment.copy(svStream, 0, wseg, JAVA_INT_UNALIGNED, getSvStreamOffset(wseg), svLengthInts); - } - - static void putPinnedSlidingMergedNoSv(final MemorySegment wseg, - final int lgK, - final int fiCol, - final int numCoupons, //unsigned - final int wLengthInts, - final short seedHash, - final int[] wStream) { - final Format format = Format.PINNED_SLIDING_MERGED_NOSV; - final byte preInts = getDefinedPreInts(format); - final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK); - checkCapacity(wseg.byteSize(), 4L * (preInts + wLengthInts)); - putFirst8(wseg, preInts, (byte) lgK, (byte) fiCol, flags, seedHash); - - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS), numCoupons); - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS), wLengthInts); - MemorySegment.copy(wStream, 0, wseg, JAVA_INT_UNALIGNED, getWStreamOffset(wseg), wLengthInts); - } - - static void putPinnedSlidingHipNoSv(final MemorySegment wseg, - final int lgK, - final int fiCol, - final int numCoupons, //unsigned - final int wLengthInts, - final double kxp, - final double hipAccum, - final short seedHash, - final int[] wStream) { - final Format format = Format.PINNED_SLIDING_HIP_NOSV; - final byte preInts = getDefinedPreInts(format); - final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK); - checkCapacity(wseg.byteSize(), 4L * (preInts + wLengthInts)); - putFirst8(wseg, preInts, (byte) lgK, (byte) fiCol, flags, seedHash); - - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS), numCoupons); - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS), wLengthInts); - wseg.set(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.KXP), kxp); - wseg.set(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.HIP_ACCUM), hipAccum); - MemorySegment.copy(wStream, 0, wseg, JAVA_INT_UNALIGNED, getWStreamOffset(wseg), wLengthInts); - } - - static void putPinnedSlidingMerged(final MemorySegment wseg, - final int lgK, - final int fiCol, - final int numCoupons, //unsigned - final int numSv, - final int svLengthInts, - final int wLengthInts, - final short seedHash, - final int[] svStream, - final int[] wStream) { - final Format format = Format.PINNED_SLIDING_MERGED; - final byte preInts = getDefinedPreInts(format); - final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK); - checkCapacity(wseg.byteSize(), 4L * (preInts + svLengthInts + wLengthInts)); - putFirst8(wseg, preInts, (byte) lgK, (byte) fiCol, flags, seedHash); - - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS), numCoupons); - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_SV), numSv); - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS), svLengthInts); - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS), wLengthInts); - MemorySegment.copy(svStream, 0, wseg, JAVA_INT_UNALIGNED, getSvStreamOffset(wseg), svLengthInts); - MemorySegment.copy(wStream, 0, wseg, JAVA_INT_UNALIGNED, getWStreamOffset(wseg), wLengthInts); - } - - static void putPinnedSlidingHip(final MemorySegment wseg, - final int lgK, - final int fiCol, - final int numCoupons, //unsigned - final int numSv, - final double kxp, - final double hipAccum, - final int svLengthInts, - final int wLengthInts, - final short seedHash, - final int[] svStream, - final int[] wStream) { - final Format format = Format.PINNED_SLIDING_HIP; - final byte preInts = getDefinedPreInts(format); - final byte flags = (byte) ((format.ordinal() << 2) | COMPRESSED_FLAG_MASK); - checkCapacity(wseg.byteSize(), 4L * (preInts + svLengthInts + wLengthInts)); - putFirst8(wseg, preInts, (byte) lgK, (byte) fiCol, flags, seedHash); - - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS), numCoupons); - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_SV), numSv); - wseg.set(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.KXP), kxp); - wseg.set(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.HIP_ACCUM), hipAccum); - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS), svLengthInts); - wseg.set(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS), wLengthInts); - MemorySegment.copy(svStream, 0, wseg, JAVA_INT_UNALIGNED, getSvStreamOffset(wseg), svLengthInts); - MemorySegment.copy(wStream, 0, wseg, JAVA_INT_UNALIGNED, getWStreamOffset(wseg), wLengthInts); - } - - private static void putFirst8(final MemorySegment wseg, final byte preInts, final byte lgK, - final byte fiCol, final byte flags, final short seedHash) { - clear(wseg, 0L, 4L * preInts); - wseg.set(JAVA_BYTE, getLoFieldOffset(LoField.PRE_INTS), preInts); - wseg.set(JAVA_BYTE, getLoFieldOffset(LoField.SER_VERSION), SER_VER); - wseg.set(JAVA_BYTE, getLoFieldOffset(LoField.FAMILY), (byte) Family.CPC.getID()); - wseg.set(JAVA_BYTE, getLoFieldOffset(LoField.LG_K), lgK); - wseg.set(JAVA_BYTE, getLoFieldOffset(LoField.FI_COL), fiCol); - wseg.set(JAVA_BYTE, getLoFieldOffset(LoField.FLAGS), flags); - wseg.set(JAVA_SHORT_UNALIGNED, getLoFieldOffset(LoField.SEED_HASH), seedHash); - } - - //TO STRING - - static String toString(final byte[] byteArr, final boolean detail) { - final MemorySegment seg = MemorySegment.ofArray(byteArr); - return toString(seg, detail); - } - - static String toString(final MemorySegment seg, final boolean detail) { - final long capBytes = seg.byteSize(); - //Lo Fields Preamble, first 7 fields, first 8 bytes - final int preInts = seg.get(JAVA_BYTE, getLoFieldOffset(LoField.PRE_INTS)) & 0xFF; - final int serVer = seg.get(JAVA_BYTE, getLoFieldOffset(LoField.SER_VERSION)) & 0xFF; - final Family family = Family.idToFamily(seg.get(JAVA_BYTE, getLoFieldOffset(LoField.FAMILY)) & 0xFF); - final int lgK = seg.get(JAVA_BYTE, getLoFieldOffset(LoField.LG_K)) & 0xFF; - final int fiCol = seg.get(JAVA_BYTE, getLoFieldOffset(LoField.FI_COL)) & 0xFF; - final int flags = seg.get(JAVA_BYTE, getLoFieldOffset(LoField.FLAGS)) & 0XFF; - final int seedHash = seg.get(JAVA_SHORT_UNALIGNED, getLoFieldOffset(LoField.SEED_HASH)) & 0XFFFF; - final String seedHashStr = Integer.toHexString(seedHash); - - //Flags of the Flags byte - final String flagsStr = zeroPad(Integer.toBinaryString(flags), 8) + ", " + (flags); - final boolean compressed = (flags & COMPRESSED_FLAG_MASK) > 0; - final boolean hasHip = (flags & HIP_FLAG_MASK) > 0; - final boolean hasSV = (flags & SUP_VAL_FLAG_MASK) > 0; - final boolean hasWindow = (flags & WINDOW_FLAG_MASK) > 0; - - final int formatOrdinal = (flags >>> 2) & 0x7; - final Format format = Format.ordinalToFormat(formatOrdinal); - - long numCoupons = 0; - long numSv = 0; - long winOffset = 0; - long svLengthInts = 0; - long wLengthInts = 0; - double kxp = 0; - double hipAccum = 0; - long svStreamStart = 0; - long wStreamStart = 0; - long reqBytes = 0; - - final StringBuilder sb = new StringBuilder(); - sb.append(LS); - sb.append("### CPC SKETCH IMAGE - PREAMBLE:").append(LS); - sb.append("Format : ").append(format.name()).append(LS); - sb.append("Byte 0: Preamble Ints : ").append(preInts).append(LS); - sb.append("Byte 1: SerVer : ").append(serVer).append(LS); - sb.append("Byte 2: Family : ").append(family).append(LS); - sb.append("Byte 3: lgK : ").append(lgK).append(LS); - sb.append("Byte 4: First Interesting Col : ").append(fiCol).append(LS); - sb.append("Byte 5: Flags : ").append(flagsStr).append(LS); - sb.append(" Compressed : ").append(compressed).append(LS); - sb.append(" Has HIP : ").append(hasHip).append(LS); - sb.append(" Has Surprising Values : ").append(hasSV).append(LS); - sb.append(" Has Window Values : ").append(hasWindow).append(LS); - sb.append("Byte 6, 7: Seed Hash : ").append(seedHashStr).append(LS); - - final Flavor flavor; - - switch (format) { - case EMPTY_MERGED : - case EMPTY_HIP : { - flavor = CpcUtil.determineFlavor(lgK, numCoupons); - sb.append("Flavor : ").append(flavor).append(LS); - break; - } - case SPARSE_HYBRID_MERGED : { - numCoupons = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS)) & 0xFFFF_FFFFL; - - numSv = numCoupons; - svLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS)) & 0xFFFF_FFFFL; - svStreamStart = getSvStreamOffset(seg); - reqBytes = svStreamStart + (svLengthInts << 2); - flavor = CpcUtil.determineFlavor(lgK, numCoupons); - sb.append("Flavor : ").append(flavor).append(LS); - sb.append("Num Coupons : ").append(numCoupons).append(LS); - - sb.append("Num SV : ").append(numSv).append(LS); - sb.append("SV Length Ints : ").append(svLengthInts).append(LS); - sb.append("SV Stream Start : ").append(svStreamStart).append(LS); - break; - } - case SPARSE_HYBRID_HIP : { - numCoupons = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS)) & 0xFFFF_FFFFL; - - numSv = numCoupons; - svLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS)) & 0xFFFF_FFFFL; - svStreamStart = getSvStreamOffset(seg); - - kxp = seg.get(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.KXP)); - hipAccum = seg.get(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.HIP_ACCUM)); - reqBytes = svStreamStart + (svLengthInts << 2); - - flavor = CpcUtil.determineFlavor(lgK, numCoupons); - sb.append("Flavor : ").append(flavor).append(LS); - sb.append("Num Coupons : ").append(numCoupons).append(LS); - - sb.append("Num SV : ").append(numSv).append(LS); - sb.append("SV Length Ints : ").append(svLengthInts).append(LS); - sb.append("SV Stream Start : ").append(svStreamStart).append(LS); - - sb.append("KxP : ").append(kxp).append(LS); - sb.append("HipAccum : ").append(hipAccum).append(LS); - break; - } - case PINNED_SLIDING_MERGED_NOSV : { - numCoupons = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS)) & 0xFFFF_FFFFL; - - winOffset = CpcUtil.determineCorrectOffset(lgK, numCoupons); - wLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS)) & 0xFFFF_FFFFL; - wStreamStart = getWStreamOffset(seg); - reqBytes = wStreamStart + (wLengthInts << 2); - - flavor = CpcUtil.determineFlavor(lgK, numCoupons); - sb.append("Flavor : ").append(flavor).append(LS); - sb.append("Num Coupons : ").append(numCoupons).append(LS); - - sb.append("Window Offset : ").append(winOffset).append(LS); - sb.append("Window Length Ints : ").append(wLengthInts).append(LS); - sb.append("Window Stream Start : ").append(wStreamStart).append(LS); - break; - } - case PINNED_SLIDING_HIP_NOSV : { - numCoupons = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS)) & 0xFFFF_FFFFL; - - winOffset = CpcUtil.determineCorrectOffset(lgK, numCoupons); - wLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS)) & 0xFFFF_FFFFL; - wStreamStart = getWStreamOffset(seg); - - kxp = seg.get(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.KXP)); - hipAccum = seg.get(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.HIP_ACCUM)); - reqBytes = wStreamStart + (wLengthInts << 2); - - flavor = CpcUtil.determineFlavor(lgK, numCoupons); - sb.append("Flavor : ").append(flavor).append(LS); - sb.append("Num Coupons : ").append(numCoupons).append(LS); - - sb.append("Window Offset : ").append(winOffset).append(LS); - sb.append("Window Length Ints : ").append(wLengthInts).append(LS); - sb.append("Window Stream Start : ").append(wStreamStart).append(LS); - - sb.append("KxP : ").append(kxp).append(LS); - sb.append("HipAccum : ").append(hipAccum).append(LS); - break; - } - case PINNED_SLIDING_MERGED : { - numCoupons = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS) & 0xFFFF_FFFFL); - - winOffset = CpcUtil.determineCorrectOffset(lgK, numCoupons); - wLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS)) & 0xFFFF_FFFFL; - - numSv = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_SV)) & 0xFFFF_FFFFL; - svLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS)) & 0xFFFF_FFFFL; - - wStreamStart = getWStreamOffset(seg); - svStreamStart = getSvStreamOffset(seg); - reqBytes = svStreamStart + (svLengthInts << 2); - - flavor = CpcUtil.determineFlavor(lgK, numCoupons); - sb.append("Flavor : ").append(flavor).append(LS); - sb.append("Num Coupons : ").append(numCoupons).append(LS); - - sb.append("Num SV : ").append(numSv).append(LS); - sb.append("SV Length Ints : ").append(svLengthInts).append(LS); - sb.append("SV Stream Start : ").append(svStreamStart).append(LS); - - sb.append("Window Offset : ").append(winOffset).append(LS); - sb.append("Window Length Ints : ").append(wLengthInts).append(LS); - sb.append("Window Stream Start : ").append(wStreamStart).append(LS); - break; - } - case PINNED_SLIDING_HIP : { - numCoupons = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_COUPONS) & 0xFFFF_FFFFL); - - winOffset = CpcUtil.determineCorrectOffset(lgK, numCoupons); - wLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.W_LENGTH_INTS)) & 0xFFFF_FFFFL; - - numSv = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.NUM_SV)) & 0xFFFF_FFFFL; - svLengthInts = seg.get(JAVA_INT_UNALIGNED, getHiFieldOffset(format, HiField.SV_LENGTH_INTS)) & 0xFFFF_FFFFL; - wStreamStart = getWStreamOffset(seg); - svStreamStart = getSvStreamOffset(seg); - - kxp = seg.get(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.KXP)); - hipAccum = seg.get(JAVA_DOUBLE_UNALIGNED, getHiFieldOffset(format, HiField.HIP_ACCUM)); - reqBytes = svStreamStart + (svLengthInts << 2); - - flavor = CpcUtil.determineFlavor(lgK, numCoupons); - sb.append("Flavor : ").append(flavor).append(LS); - sb.append("Num Coupons : ").append(numCoupons).append(LS); - - sb.append("Num SV : ").append(numSv).append(LS); - sb.append("SV Length Ints : ").append(svLengthInts).append(LS); - sb.append("SV Stream Start : ").append(svStreamStart).append(LS); - - sb.append("Window Offset : ").append(winOffset).append(LS); - sb.append("Window Length Ints : ").append(wLengthInts).append(LS); - sb.append("Window Stream Start : ").append(wStreamStart).append(LS); - - sb.append("KxP : ").append(kxp).append(LS); - sb.append("HipAccum : ").append(hipAccum).append(LS); - break; - } - } - - sb.append("Actual Bytes : ").append(capBytes).append(LS); - sb.append("Required Bytes : ").append(reqBytes).append(LS); - - if (detail) { - sb.append(LS).append("### CPC SKETCH IMAGE - DATA").append(LS); - if (wLengthInts > 0) { - sb.append(LS).append("Window Stream:").append(LS); - listData(seg, wStreamStart, wLengthInts, sb); - } - if (svLengthInts > 0) { - sb.append(LS).append("SV Stream:").append(LS); - listData(seg, svStreamStart, svLengthInts, sb); - } - } - sb.append("### END CPC SKETCH IMAGE").append(LS); - return sb.toString(); - } //end toString(seg) - - private static void listData(final MemorySegment seg, final long offsetBytes, final long lengthInts, - final StringBuilder sb) { - final long segCap = seg.byteSize(); - final long expectedCap = offsetBytes + (4L * lengthInts); - checkCapacity(segCap, expectedCap); - for (long i = 0; i < lengthInts; i++) { - sb.append(String.format(fmt, i, seg.get(JAVA_INT_UNALIGNED, offsetBytes + (4L * i)))).append(LS); - } - } - - static void fieldError(final Format format, final HiField hiField) { - throw new SketchesArgumentException( - "Operation is illegal: Format = " + format.name() + ", HiField = " + hiField); - } - - static void checkCapacity(final long segCap, final long expectedCap) { - if (segCap < expectedCap) { - throw new SketchesArgumentException( - "Insufficient Image Bytes = " + segCap + ", Expected = " + expectedCap); - } - } - - //basic checks of SerVer, Format, preInts, Family, fiCol, lgK. - static void checkLoPreamble(final MemorySegment seg) { - Objects.requireNonNull(seg, "Source MemorySegment must not be null"); - checkBounds(0, 8, seg.byteSize()); //need min 8 bytes - rtAssertEquals(getSerVer(seg), SER_VER & 0XFF); - final Format fmat = getFormat(seg); - final int preIntsDef = getDefinedPreInts(fmat) & 0XFF; - rtAssertEquals(getPreInts(seg), preIntsDef); - final Family fam = getFamily(seg); - rtAssert(fam == Family.CPC); - final int lgK = getLgK(seg); - rtAssert((lgK >= 4) && (lgK <= 26)); - final int fiCol = getFiCol(seg); - rtAssert((fiCol <= 63) && (fiCol >= 0)); - } - -} -//@formatter:on diff --git a/src/main/java/org/apache/datasketches/cpc/QuickMergingValidation.java b/src/main/java/org/apache/datasketches/cpc/QuickMergingValidation.java deleted file mode 100644 index e2bb8605f..000000000 --- a/src/main/java/org/apache/datasketches/cpc/QuickMergingValidation.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.common.Util.INVERSE_GOLDEN_U64; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert; - -import java.io.PrintStream; -import java.io.PrintWriter; - -import org.apache.datasketches.common.SuppressFBWarnings; - -/** - * This code is used both by unit tests, for short running tests, - * and by the characterization repository for longer running, more exhaustive testing. To be - * accessible for both, this code is part of the main hierarchy. It is not used during normal - * production runtime. - * - *

This test of merging is the equal K case and is less exhaustive than TestAlltest - * but is more practical for large values of K.

- * - * @author Lee Rhodes - * @author Kevin Lang - */ -public class QuickMergingValidation { - private String hfmt; - private String dfmt; - private String[] hStrArr; - private long vIn = 0; - - //inputs - private int lgMinK; - private int lgMaxK; //inclusive - private int incLgK; //increment of lgK - private PrintStream printStream; - private PrintWriter printWriter; - - /** - * Constructor - * @param lgMinK lgMinK - * @param lgMaxK lgMaxK - * @param incLgK incLgK - * @param ps ps - * @param pw pw - */ - @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "This is OK here") - public QuickMergingValidation(final int lgMinK, final int lgMaxK, final int incLgK, - final PrintStream ps, final PrintWriter pw) { - this.lgMinK = lgMinK; - this.lgMaxK = lgMaxK; - this.incLgK = incLgK; - printStream = ps; - printWriter = pw; - assembleFormats(); - } - - /** - * Start the Quick Merging Validation process - */ - public void start() { - printf(hfmt, (Object[]) hStrArr); //print header - doRangeOfLgK(); - } - - private void doRangeOfLgK() { - for (int lgK = lgMinK; lgK <= lgMaxK; lgK += incLgK) { - multiQuickTest(lgK); - } - } - - private void multiQuickTest(final int lgK) { - final int k = 1 << lgK; - final int[] targetC = new int[] { 0, 1, ((3 * k) / 32) - 1, k / 3, k, (7 * k) / 2 }; - final int len = targetC.length; - for (int i = 0; i < len; i++) { - for (int j = 0; j < len; j++) { - quickTest(lgK, targetC[i], targetC[j]); - } - } - } - - void quickTest(final int lgK, final long cA, final long cB) { - final CpcSketch skA = new CpcSketch(lgK); - final CpcSketch skB = new CpcSketch(lgK); - final CpcSketch skD = new CpcSketch(lgK); // direct sketch - - final long t0, t1, t2, t3, t4, t5; - - t0 = System.nanoTime(); - while (skA.numCoupons < cA) { - final long in = vIn += INVERSE_GOLDEN_U64; - skA.update(in); - skD.update(in); - } - t1 = System.nanoTime(); - while (skB.numCoupons < cB) { - final long in = vIn += INVERSE_GOLDEN_U64; - skB.update(in); - skD.update(in); - } - t2 = System.nanoTime(); - - final CpcUnion ugM = new CpcUnion(lgK); - ugM.update(skA); - t3 = System.nanoTime(); - - ugM.update(skB); - t4 = System.nanoTime(); - - final CpcSketch skR = ugM.getResult(); - t5 = System.nanoTime(); - - rtAssert(TestUtil.specialEquals(skD, skR, false, true)); - final Flavor fA = skA.getFlavor(); - final Flavor fB = skB.getFlavor(); - final Flavor fR = skR.getFlavor(); - final String aOff = Integer.toString(skA.windowOffset); - final String bOff = Integer.toString(skB.windowOffset); - final String rOff = Integer.toString(skR.windowOffset); - final String fAoff = fA + String.format("%2s",aOff); - final String fBoff = fB + String.format("%2s",bOff); - final String fRoff = fR + String.format("%2s",rOff); - final double updA_mS = (t1 - t0) / 2E6; //update A,D to cA - final double updB_mS = (t2 - t1) / 2E6; //update B,D to cB - final double mrgA_mS = (t3 - t2) / 1E6; //merge A - final double mrgB_mS = (t4 - t3) / 1E6; //merge B - final double rslt_mS = (t5 - t4) / 1E6; //get Result - - printf(dfmt, lgK, cA, cB, fAoff, fBoff, fRoff, - updA_mS, updB_mS, mrgA_mS, mrgB_mS, rslt_mS); - } - - private void printf(final String format, final Object ... args) { - if (printStream != null) { printStream.printf(format, args); } - if (printWriter != null) { printWriter.printf(format, args); } - } - - private void assembleFormats() { - final String[][] assy = { - {"lgK", "%3s", "%3d"}, - {"Ca", "%10s", "%10d"}, - {"Cb", "%10s", "%10d"}, - {"Flavor_a", "%10s", "%10s"}, - {"Flavor_b", "%10s", "%10s"}, - {"Flavor_m", "%10s", "%10s"}, - {"updA_mS", "%9s", "%9.3f"}, - {"updB_mS", "%9s", "%9.3f"}, - {"mrgA_mS", "%9s", "%9.3f"}, - {"mrgB_mS", "%9s", "%9.3f"}, - {"rslt_mS", "%9s", "%9.3f"} - }; - final int cols = assy.length; - hStrArr = new String[cols]; - final StringBuilder headerFmt = new StringBuilder(); - final StringBuilder dataFmt = new StringBuilder(); - headerFmt.append(LS + "Quick Merging Validation" + LS); - for (int i = 0; i < cols; i++) { - hStrArr[i] = assy[i][0]; - headerFmt.append(assy[i][1]); - headerFmt.append((i < (cols - 1)) ? "\t" : LS); - dataFmt.append(assy[i][2]); - dataFmt.append((i < (cols - 1)) ? "\t" : LS); - } - hfmt = headerFmt.toString(); - dfmt = dataFmt.toString(); - } -} diff --git a/src/main/java/org/apache/datasketches/cpc/RuntimeAsserts.java b/src/main/java/org/apache/datasketches/cpc/RuntimeAsserts.java deleted file mode 100644 index 17e716e3a..000000000 --- a/src/main/java/org/apache/datasketches/cpc/RuntimeAsserts.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -/** - * These asserts act like the assert in C/C++. They will throw an AssertionError whether the - * JVM -ea is set or not. - * - * @author Lee Rhodes - */ -final class RuntimeAsserts { - - static void rtAssert(final boolean b) { - if (!b) { error("False, expected True."); } - } - - static void rtAssertFalse(final boolean b) { - if (b) { error("True, expected False."); } - } - - static void rtAssertEquals(final long a, final long b) { - if (a != b) { error(a + " != " + b); } - } - - static void rtAssertEquals(final double a, final double b, final double eps) { - if (Math.abs(a - b) > eps) { error("abs(" + a + " - " + b + ") > " + eps); } - } - - static void rtAssertEquals(final boolean a, final boolean b) { - if (a != b) { error(a + " != " + b); } - } - - static void rtAssertEquals(final byte[] a, final byte[] b) { - if ((a == null) && (b == null)) { return; } - if ((a != null) && (b != null)) { - final int alen = a.length; - if (alen != b.length) { error("Array lengths not equal: " + a.length + ", " + b.length); } - for (int i = 0; i < alen; i++) { - if (a[i] != b[i]) { error(a[i] + " != " + b[i] + " at index " + i); } - } - } else { error("Array " + ((a == null) ? "a" : "b") + " is null"); } - } - - static void rtAssertEquals(final short[] a, final short[] b) { - if ((a == null) && (b == null)) { return; } - if ((a != null) && (b != null)) { - final int alen = a.length; - if (alen != b.length) { error("Array lengths not equal: " + a.length + ", " + b.length); } - for (int i = 0; i < alen; i++) { - if (a[i] != b[i]) { error(a[i] + " != " + b[i] + " at index " + i); } - } - } else { error("Array " + ((a == null) ? "a" : "b") + " is null"); } - } - - static void rtAssertEquals(final int[] a, final int[] b) { - if ((a == null) && (b == null)) { return; } - if ((a != null) && (b != null)) { - final int alen = a.length; - if (alen != b.length) { error("Array lengths not equal: " + a.length + ", " + b.length); } - for (int i = 0; i < alen; i++) { - if (a[i] != b[i]) { error(a[i] + " != " + b[i] + " at index " + i); } - } - } else { error("Array " + ((a == null) ? "a" : "b") + " is null"); } - } - - static void rtAssertEquals(final long[] a, final long[] b) { - if ((a == null) && (b == null)) { return; } - if ((a != null) && (b != null)) { - final int alen = a.length; - if (alen != b.length) { error("Array lengths not equal: " + a.length + ", " + b.length); } - for (int i = 0; i < alen; i++) { - if (a[i] != b[i]) { error(a[i] + " != " + b[i] + " at index " + i); } - } - } else { error("Array " + ((a == null) ? "a" : "b") + " is null"); } - } - - static void rtAssertEquals(final float[] a, final float[] b, final float eps) { - if ((a == null) && (b == null)) { return; } - if ((a != null) && (b != null)) { - final int alen = a.length; - if (alen != b.length) { error("Array lengths not equal: " + a.length + ", " + b.length); } - for (int i = 0; i < alen; i++) { - if (Math.abs(a[i] - b[i]) > eps) { error("abs(" + a[i] + " - " + b[i] + ") > " + eps); } - } - } else { error("Array " + ((a == null) ? "a" : "b") + " is null"); } - } - - static void rtAssertEquals(final double[] a, final double[] b, final double eps) { - if ((a == null) && (b == null)) { return; } - if ((a != null) && (b != null)) { - final int alen = a.length; - if (alen != b.length) { error("Array lengths not equal: " + alen + ", " + b.length); } - for (int i = 0; i < alen; i++) { - if (Math.abs(a[i] - b[i]) > eps) { error("abs(" + a[i] + " - " + b[i] + ") > " + eps); } - } - } else { error("Array " + ((a == null) ? "a" : "b") + " is null"); } - } - - private static void error(final String message) { - throw new AssertionError(message); - } -} diff --git a/src/main/java/org/apache/datasketches/cpc/StreamingValidation.java b/src/main/java/org/apache/datasketches/cpc/StreamingValidation.java deleted file mode 100644 index aab6e5e6f..000000000 --- a/src/main/java/org/apache/datasketches/cpc/StreamingValidation.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.common.Util.INVERSE_GOLDEN_U64; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.powerSeriesNextDouble; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals; - -import java.io.PrintStream; -import java.io.PrintWriter; - -import org.apache.datasketches.common.SuppressFBWarnings; - -/** - * This code is used both by unit tests, for short running tests, - * and by the characterization repository for longer running, more exhaustive testing. To be - * accessible for both, this code is part of the main hierarchy. It is not used during normal - * production runtime. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -public class StreamingValidation { - private String hfmt; - private String dfmt; - private String[] hStrArr; - private long vIn = 0; - - //inputs - private int lgMinK; - private int lgMaxK; //inclusive - private int trials; - private int ppoN; - private PrintStream printStream; - private PrintWriter printWriter; - - //sketches - private CpcSketch sketch = null; - private BitMatrix matrix = null; - - /** - * Constructor - * @param lgMinK lgMinK - * @param lgMaxK lgMaxK - * @param trials trials - * @param ppoN ppoN - * @param pS pS - * @param pW pW - */ - @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "This is OK here") - public StreamingValidation(final int lgMinK, final int lgMaxK, final int trials, final int ppoN, - final PrintStream pS, final PrintWriter pW) { - this.lgMinK = lgMinK; - this.lgMaxK = lgMaxK; - this.trials = trials; - this.ppoN = ppoN; - printStream = pS; - printWriter = pW; - assembleStrings(); - } - - /** - * Start the streaming validation process - */ - public void start() { - printf(hfmt, (Object[]) hStrArr); - doRangeOfLgK(); - } - - private void doRangeOfLgK() { - for (int lgK = lgMinK; lgK <= lgMaxK; lgK++) { - doRangeOfNAtLgK(lgK); - } - } - - private void doRangeOfNAtLgK(final int lgK) { - long n = 1; - final long maxN = 64L * (1L << lgK); //1200 - while (n < maxN) { - doTrialsAtLgKAtN(lgK, n); - n = Math.round(powerSeriesNextDouble(ppoN, n, true, 2.0)); - } - } - - /** - * Performs the given number of trials at a lgK and at an N. - * @param lgK the configured lgK - * @param n the current value of n - */ - private void doTrialsAtLgKAtN(final int lgK, final long n) { - double sumC = 0.0; - double sumIconEst = 0.0; - double sumHipEst = 0.0; - sketch = new CpcSketch(lgK); - matrix = new BitMatrix(lgK); - - for (int t = 0; t < trials; t++) { - sketch.reset(); - matrix.reset(); - for (long i = 0; i < n; i++) { - final long in = (vIn += INVERSE_GOLDEN_U64); - sketch.update(in); - matrix.update(in); - } - sumC += sketch.numCoupons; - sumIconEst += IconEstimator.getIconEstimate(lgK, sketch.numCoupons); - sumHipEst += sketch.hipEstAccum; - rtAssertEquals(sketch.numCoupons, matrix.getNumCoupons()); - final long[] bitMatrix = CpcUtil.bitMatrixOfSketch(sketch); - rtAssertEquals(bitMatrix, matrix.getMatrix()); - } - final long finC = sketch.numCoupons; - final Flavor finFlavor = sketch.getFlavor(); - final int finOff = sketch.windowOffset; - final double avgC = sumC / trials; - final double avgIconEst = sumIconEst / trials; - final double avgHipEst = sumHipEst / trials; - printf(dfmt, lgK, trials, n, finC, finFlavor, finOff, avgC, avgIconEst, avgHipEst); - } - - private void printf(final String format, final Object ... args) { - if (printStream != null) { printStream.printf(format, args); } - if (printWriter != null) { printWriter.printf(format, args); } - } - - private void assembleStrings() { - final String[][] assy = { - {"lgK", "%3s", "%3d"}, - {"Trials", "%7s", "%7d"}, - {"n", "%8s", "%8d"}, - {"FinC", "%8s", "%8d"}, - {"FinFlavor", "%10s", "%10s"}, - {"FinOff", "%7s", "%7d"}, - {"AvgC", "%12s", "%12.3f"}, - {"AvgICON", "%12s", "%12.3f"}, - {"AvgHIP", "%12s", "%12.3f"} - }; - final int cols = assy.length; - hStrArr = new String[cols]; - final StringBuilder headerFmt = new StringBuilder(); - final StringBuilder dataFmt = new StringBuilder(); - headerFmt.append(LS + "Streaming Validation" + LS); - for (int i = 0; i < cols; i++) { - hStrArr[i] = assy[i][0]; - headerFmt.append(assy[i][1]); - headerFmt.append((i < (cols - 1)) ? "\t" : LS); - dataFmt.append(assy[i][2]); - dataFmt.append((i < (cols - 1)) ? "\t" : LS); - } - hfmt = headerFmt.toString(); - dfmt = dataFmt.toString(); - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/TestUtil.java b/src/main/java/org/apache/datasketches/cpc/TestUtil.java deleted file mode 100644 index f555dae67..000000000 --- a/src/main/java/org/apache/datasketches/cpc/TestUtil.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static java.lang.Math.pow; -import static java.lang.Math.round; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals; - -/** - * Utility methods for Test - * @author Lee Rhodes - */ -public class TestUtil { - - /** - * No argument constructor. - */ - public TestUtil() { } - - static final double pwrLaw10NextDouble(final int ppb, final double curPoint) { - final double cur = (curPoint < 1.0) ? 1.0 : curPoint; - double gi = round(Math.log10(cur) * ppb); //current generating index - double next; - do { - next = round(pow(10.0, ++gi / ppb)); - } while (next <= curPoint); - return next; - } - - static boolean specialEquals(final CpcSketch sk1, final CpcSketch sk2, - final boolean sk1wasMerged, final boolean sk2wasMerged) { - rtAssertEquals(sk1.seed, sk2.seed); - rtAssertEquals(sk1.lgK, sk2.lgK); - rtAssertEquals(sk1.numCoupons, sk2.numCoupons); - - rtAssertEquals(sk1.windowOffset, sk2.windowOffset); - rtAssertEquals(sk1.slidingWindow, sk2.slidingWindow); - PairTable.equals(sk1.pairTable, sk2.pairTable); - - // fiCol is only updated occasionally while stream processing, - // therefore, the stream sketch could be behind the merged sketch. - // So we have to recalculate the FiCol on the stream sketch. - final int ficolA = sk1.fiCol; - final int ficolB = sk2.fiCol; - - if (!sk1wasMerged && sk2wasMerged) { - rtAssert(!sk1.mergeFlag && sk2.mergeFlag); - final int fiCol1 = calculateFirstInterestingColumn(sk1); - rtAssertEquals(fiCol1, sk2.fiCol); - } else if (sk1wasMerged && !sk2wasMerged) { - rtAssert(sk1.mergeFlag && !sk2.mergeFlag); - final int fiCol2 = calculateFirstInterestingColumn(sk2); - rtAssertEquals(fiCol2,sk1.fiCol); - } else { - rtAssertEquals(sk1.mergeFlag, sk2.mergeFlag); - rtAssertEquals(ficolA, ficolB); - rtAssertEquals(sk1.kxp, sk2.kxp, .01 * sk1.kxp); //1% tolerance - rtAssertEquals(sk1.hipEstAccum, sk2.hipEstAccum, .01 * sk1.hipEstAccum); //1% tolerance - } - return true; - } - - static int calculateFirstInterestingColumn(final CpcSketch sketch) { - final int offset = sketch.windowOffset; - if (offset == 0) { - return 0; - } - final PairTable table = sketch.pairTable; - assert (table != null); - final int[] slots = table.getSlotsArr(); - final int numSlots = 1 << table.getLgSizeInts(); - int i; - int result = offset; - for (i = 0; i < numSlots; i++) { - final int rowCol = slots[i]; - if (rowCol != -1) { - final int col = rowCol & 63; - if (col < result) { result = col; } - } - } - return result; - } - -} diff --git a/src/main/java/org/apache/datasketches/cpc/package-info.java b/src/main/java/org/apache/datasketches/cpc/package-info.java deleted file mode 100644 index d946436e3..000000000 --- a/src/main/java/org/apache/datasketches/cpc/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * Compressed Probabilistic Counting sketch family - */ - -package org.apache.datasketches.cpc; diff --git a/src/main/java/org/apache/datasketches/fdt/FdtSketch.java b/src/main/java/org/apache/datasketches/fdt/FdtSketch.java deleted file mode 100644 index fb9f5c752..000000000 --- a/src/main/java/org/apache/datasketches/fdt/FdtSketch.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.fdt; - -import java.lang.foreign.MemorySegment; -import java.util.List; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.thetacommon.ThetaUtil; -import org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch; - -/** - * A Frequent Distinct Tuples sketch. - * - *

Suppose our data is a stream of pairs {IP address, User ID} and we want to identify the - * IP addresses that have the most distinct User IDs. Or conversely, we would like to identify - * the User IDs that have the most distinct IP addresses. This is a common challenge in the - * analysis of big data and the FDT sketch helps solve this problem using probabilistic techniques. - * - *

More generally, given a multiset of tuples with dimensions {d1,d2, d3, ..., dN}, - * and a primary subset of dimensions M < N, our task is to identify the combinations of - * M subset dimensions that have the most frequent number of distinct combinations of - * the N-M non-primary dimensions. - * - *

Please refer to the web page - * - * https://datasketches.apache.org/docs/Frequency/FrequentDistinctTuplesSketch.html for a more - * complete discussion about this sketch. - * - * @author Lee Rhodes - */ -public final class FdtSketch extends ArrayOfStringsTupleSketch { - - /** - * Create new instance of Frequent Distinct Tuples sketch with the given - * Log-base2 of required nominal entries. - * @param lgK Log-base2 of required nominal entries. - */ - public FdtSketch(final int lgK) { - super(lgK); - } - - /** - * Used by deserialization. - * @param seg the image of a FdtSketch - * @deprecated As of 3.0.0, heapifying an UpdatableSketch is deprecated. - * This capability will be removed in a future release. - * Heapifying a CompactSketch is not deprecated. - */ - @Deprecated - FdtSketch(final MemorySegment seg) { - super(seg); - } - - /** - * Create a new instance of Frequent Distinct Tuples sketch with a size determined by the given - * threshold and rse. - * @param threshold : the fraction, between zero and 1.0, of the total distinct stream length - * that defines a "Frequent" (or heavy) item. - * @param rse the maximum Relative Standard Error for the estimate of the distinct population of a - * reported tuple (selected with a primary key) at the threshold. - */ - public FdtSketch(final double threshold, final double rse) { - super(computeLgK(threshold, rse)); - } - - /** - * Copy Constructor - * @param sketch the sketch to copy - */ - public FdtSketch(final FdtSketch sketch) { - super(sketch); - } - - /** - * @return a deep copy of this sketch - */ - @Override - public FdtSketch copy() { - return new FdtSketch(this); - } - - /** - * Update the sketch with the given string array tuple. - * @param tuple the given string array tuple. - */ - public void update(final String[] tuple) { - super.update(tuple, tuple); - } - - /** - * Returns an ordered List of Groups of the most frequent distinct population of subset tuples - * represented by the count of entries of each group. - * @param priKeyIndices these indices define the dimensions used for the Primary Keys. - * @param limit the maximum number of groups to return. If this value is ≤ 0, all - * groups will be returned. - * @param numStdDev the number of standard deviations for the upper and lower error bounds, - * this value is an integer and must be one of 1, 2, or 3. - * See Number of Standard Deviations - * @param sep the separator character - * @return an ordered List of Groups of the most frequent distinct population of subset tuples - * represented by the count of entries of each group. - */ - public List getResult(final int[] priKeyIndices, final int limit, final int numStdDev, - final char sep) { - final PostProcessor proc = new PostProcessor(this, new Group(), sep); - return proc.getGroupList(priKeyIndices, numStdDev, limit); - } - - /** - * Returns the PostProcessor that enables multiple queries against the sketch results. - * This assumes the default Group and the default separator character '|'. - * @return the PostProcessor - */ - public PostProcessor getPostProcessor() { - return getPostProcessor(new Group(), '|'); - } - - /** - * Returns the PostProcessor that enables multiple queries against the sketch results. - * @param group the Group class to use during post processing. - * @param sep the separator character. - * @return the PostProcessor - */ - public PostProcessor getPostProcessor(final Group group, final char sep) { - return new PostProcessor(this, group, sep); - } - - // Restricted - - /** - * Computes LgK given the threshold and RSE. - * @param threshold the fraction, between zero and 1.0, of the total stream length that defines - * a "Frequent" (or heavy) tuple. - * @param rse the maximum Relative Standard Error for the estimate of the distinct population of a - * reported tuple (selected with a primary key) at the threshold. - * @return LgK - */ - static int computeLgK(final double threshold, final double rse) { - final double v = Math.ceil(1.0 / (threshold * rse * rse)); - final int lgK = (int) Math.ceil(Math.log(v) / Math.log(2)); - if (lgK > ThetaUtil.MAX_LG_NOM_LONGS) { - throw new SketchesArgumentException("Requested Sketch (LgK = " + lgK + " > 2^26), " - + "either increase the threshold, the rse or both."); - } - return lgK; - } - -} diff --git a/src/main/java/org/apache/datasketches/fdt/Group.java b/src/main/java/org/apache/datasketches/fdt/Group.java deleted file mode 100644 index e22ee2398..000000000 --- a/src/main/java/org/apache/datasketches/fdt/Group.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.fdt; - -/** - * Defines a Group from a Frequent Distinct Tuple query. This class is called internally during - * post processing and is not intended to be called by the user. - * @author Lee Rhodes - */ -public class Group implements Comparable { - private int count = 0; - private double est = 0; - private double ub = 0; - private double lb = 0; - private double fraction = 0; - private double rse = 0; - private String priKey = null; - private final static String fmt = - "%,12d" + "%,15.2f" + "%,15.2f" + "%,15.2f" + "%12.6f" + "%12.6f" + " %s"; - private final static String hfmt = - "%12s" + "%15s" + "%15s" + "%15s" + "%12s" + "%12s" + " %s"; - - /** - * Construct an empty Group - */ - public Group() { } - - /** - * Specifies the parameters to be listed as columns - * @param priKey the primary key of the FDT sketch - * @param count the number of retained rows associated with this group - * @param estimate the estimate of the original population associated with this group - * @param ub the upper bound of the estimate - * @param lb the lower bound of the estimate - * @param fraction the fraction of all retained rows of the sketch associated with this group - * @param rse the estimated Relative Standard Error for this group. - * @return return this - */ - public Group init(final String priKey, final int count, final double estimate, final double ub, - final double lb, final double fraction, final double rse) { - this.count = count; - est = estimate; - this.ub = ub; - this.lb = lb; - this.fraction = fraction; - this.rse = rse; - this.priKey = priKey; - return this; - } - - /** - * Gets the primary key of type String - * @return priKey of type String - */ - public String getPrimaryKey() { return priKey; } - - /** - * Returns the count - * @return the count - */ - public int getCount() { return count; } - - /** - * Returns the estimate - * @return the estimate - */ - public double getEstimate() { return est; } - - /** - * Returns the upper bound - * @return the upper bound - */ - public double getUpperBound() { return ub; } - - /** - * Returns the lower bound - * @return the lower bound - */ - public double getLowerBound() { return lb; } - - /** - * Returns the fraction for this group - * @return the fraction for this group - */ - public double getFraction() { return fraction; } - - /** - * Returns the RSE - * @return the RSE - */ - public double getRse() { return rse; } - - /** - * Returns the descriptive header - * @return the descriptive header - */ - public String getHeader() { - return String.format(hfmt,"Count", "Est", "UB", "LB", "Fraction", "RSE", "PriKey"); - } - - @Override - public String toString() { - return String.format(fmt, count, est, ub, lb, fraction, rse, priKey); - } - - @Override - public int compareTo(final Group that) { - return that.count - count; //decreasing - } - - @Override - public boolean equals(final Object that) { - if (this == that) { return true; } - if (!(that instanceof Group)) { return false; } - return ((Group)that).count == count; - } - - @Override - public int hashCode() { - return Integer.MAX_VALUE - count; //MAX_VALUE is a Double Mersenne Prime = 2^31 - 1 = M_M_5 - } - -} diff --git a/src/main/java/org/apache/datasketches/fdt/PostProcessor.java b/src/main/java/org/apache/datasketches/fdt/PostProcessor.java deleted file mode 100644 index 4d4df39a2..000000000 --- a/src/main/java/org/apache/datasketches/fdt/PostProcessor.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.fdt; - -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.thetacommon.HashOperations.hashSearchOrInsert; -import static org.apache.datasketches.tuple.Util.stringHash; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -import org.apache.datasketches.tuple.TupleSketchIterator; -import org.apache.datasketches.tuple.strings.ArrayOfStringsSummary; - -/** - * This processes the contents of a FDT sketch to extract the - * primary keys with the most frequent unique combinations of the non-primary dimensions. - * The source sketch is not modified. - * - * @author Lee Rhodes - */ -public class PostProcessor { - private final FdtSketch sketch; - private final char sep; - private int groupCount; - @SuppressWarnings("unused") - private Group group; //uninitialized - - //simple hash-map - private boolean mapValid; - private final int mapArrSize; - private final long[] hashArr; - private final String[] priKeyArr; - private final int[] counterArr; - - /** - * Construct with a populated FdtSketch - * @param sketch the given sketch to query. - * @param group the Group - * @param sep the separator character - */ - public PostProcessor(final FdtSketch sketch, final Group group, final char sep) { - Objects.requireNonNull(sketch, "sketch must be non-null"); - Objects.requireNonNull(group, "group must be non-null"); - this.sketch = sketch.copy(); - this.sep = sep; - final int numEntries = sketch.getRetainedEntries(); - mapArrSize = ceilingPowerOf2((int)(numEntries / 0.75)); - hashArr = new long[mapArrSize]; - priKeyArr = new String[mapArrSize]; - counterArr = new int[mapArrSize]; - mapValid = false; - this.group = group; - } - - /** - * Returns the number of groups in the final sketch. - * @return the number of groups in the final sketch. - */ - public int getGroupCount() { - return groupCount; - } - - /** - * Return the most frequent Groups associated with Primary Keys based on the size of the groups. - * @param priKeyIndices the indices of the primary dimensions - * @param numStdDev the number of standard deviations for the error bounds, this value is an - * integer and must be one of 1, 2, or 3. - * See Number of Standard Deviations - * @param limit the maximum number of rows to return. If ≤ 0, all rows will be returned. - * @return the most frequent Groups associated with Primary Keys based on the size of the groups. - */ - public List getGroupList(final int[] priKeyIndices, final int numStdDev, - final int limit) { - //allows subsequent queries with different priKeyIndices without rebuilding the map - if (!mapValid) { populateMap(priKeyIndices); } - return populateList(numStdDev, limit); - } - - /** - * Scan each entry in the sketch. Count the number of duplicate occurrences of each - * primary key in a hash map. - * @param priKeyIndices identifies the primary key indices - */ - private void populateMap(final int[] priKeyIndices) { - final TupleSketchIterator it = sketch.iterator(); - Arrays.fill(hashArr, 0L); - Arrays.fill(priKeyArr, null); - Arrays.fill(counterArr, 0); - groupCount = 0; - final int lgMapArrSize = Integer.numberOfTrailingZeros(mapArrSize); - - while (it.next()) { - //getSummary() is not a copy, but getValue() is - final String[] arr = it.getSummary().getValue(); - final String priKey = getPrimaryKey(arr, priKeyIndices, sep); - final long hash = stringHash(priKey); - final int index = hashSearchOrInsert(hashArr, lgMapArrSize, hash); - if (index < 0) { //was empty, hash inserted - final int idx = -(index + 1); //actual index - counterArr[idx] = 1; - groupCount++; - priKeyArr[idx] = priKey; - } else { //found, duplicate - counterArr[index]++; //increment - } - } - mapValid = true; - } - - /** - * Create the list of groups along with the error statistics - * @param numStdDev number of standard deviations - * @param limit the maximum size of the list to return - * @return the list of groups along with the error statistics - */ - private List populateList(final int numStdDev, final int limit) { - final List list = new ArrayList<>(); - for (int i = 0; i < mapArrSize; i++) { - if (hashArr[i] != 0) { - final String priKey = priKeyArr[i]; - final int count = counterArr[i]; - final double est = sketch.getEstimate(count); - final double ub = sketch.getUpperBound(numStdDev, count); - final double lb = sketch.getLowerBound(numStdDev, count); - final double thresh = (double) count / sketch.getRetainedEntries(); - final double rse = (sketch.getUpperBound(1, count) / est) - 1.0; - final Group gp = new Group(); - gp.init(priKey, count, est, ub, lb, thresh, rse); - list.add(gp); - } - } - list.sort(null); //Comparable implemented in Group - final int totLen = list.size(); - - final List returnList; - if ((limit > 0) && (limit < totLen)) { - returnList = list.subList(0, limit); - } else { - returnList = list; - } - return returnList; - } - - /** - * Extract simple string Primary Key defined by the priKeyIndices from the given tuple. - * @param tuple the given tuple containing the Primary Key - * @param priKeyIndices the indices indicating the ordering and selection of dimensions defining - * the Primary Key - * @param sep the separator character - * @return a simple string Primary Key defined by the priKeyIndices from the given tuple. - */ - //also used by test - private static String getPrimaryKey(final String[] tuple, final int[] priKeyIndices, - final char sep) { - assert priKeyIndices.length < tuple.length; - final StringBuilder sb = new StringBuilder(); - final int keys = priKeyIndices.length; - for (int i = 0; i < keys; i++) { - final int idx = priKeyIndices[i]; - sb.append(tuple[idx]); - if ((i + 1) < keys) { sb.append(sep); } - } - return sb.toString(); - } - -} diff --git a/src/main/java/org/apache/datasketches/fdt/package-info.java b/src/main/java/org/apache/datasketches/fdt/package-info.java deleted file mode 100644 index 7853c8626..000000000 --- a/src/main/java/org/apache/datasketches/fdt/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * Frequent Distinct Tuples Sketch - */ -package org.apache.datasketches.fdt; diff --git a/src/main/java/org/apache/datasketches/filters/bloomfilter/BitArray.java b/src/main/java/org/apache/datasketches/filters/bloomfilter/BitArray.java deleted file mode 100644 index 91f85499c..000000000 --- a/src/main/java/org/apache/datasketches/filters/bloomfilter/BitArray.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.filters.bloomfilter; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.ceilingMultiple2expK; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.positional.PositionalSegment; - -/** - * This class holds an array of bits suitable for use in a Bloom Filter - * - *

Rounds the number of bits up to the smallest multiple of 64 (one long) - * that is not smaller than the specified number. - */ -abstract class BitArray implements MemorySegmentStatus { - // MAX_BITS using longs, based on array indices being capped at Integer.MAX_VALUE - protected static final long MAX_BITS = Integer.MAX_VALUE * (long) Long.SIZE; - - protected BitArray() {} - - //The position of the PositionalSegment must be the start of the bit array - static BitArray heapify(final PositionalSegment posSeg, final boolean isEmpty) { - return HeapBitArray.heapify(posSeg, isEmpty); - } - - static BitArray wrap(final MemorySegment seg, final boolean isEmpty) { - return DirectBitArrayR.wrap(seg, isEmpty); - } - - static BitArray writableWrap(final MemorySegment wseg, final boolean isEmpty) { - return DirectBitArray.writableWrap(wseg, isEmpty); - } - - boolean isEmpty() { - return !isDirty() && (getNumBitsSet() == 0); - } - - @Override - public abstract boolean hasMemorySegment(); - - @Override - public abstract boolean isOffHeap(); - - abstract boolean isReadOnly(); - - @Override - public abstract boolean isSameResource(MemorySegment that); - - abstract boolean getBit(final long index); - - abstract boolean getAndSetBit(final long index); - - abstract void setBit(final long index); - - abstract long getNumBitsSet(); - - abstract void reset(); - - abstract long getCapacity(); - - abstract int getArrayLength(); - - abstract void union(final BitArray other); - - abstract void intersect(final BitArray other); - - abstract void invert(); - - // prints the raw BitArray as 0s and 1s, one long per row - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < getArrayLength(); ++i) { - sb.append(i + ": ") - .append(printLong(getLong(i))) - .append(LS); - } - return sb.toString(); - } - - long getSerializedSizeBytes() { - // We only really need an int for array length but this will keep everything - // aligned to 8 bytes. - // Always write array length, but write numBitsSet only if empty - return Long.BYTES * (isEmpty() ? 1L : (2L + getArrayLength())); - } - - // returns the number of bytes needed for a non-empty BitArray of the requested size - static long getSerializedSizeBytes(final long numBits) { - if (numBits <= 0) { - throw new SketchesArgumentException("Requested number of bits must be strictly positive"); - } - if (numBits > MAX_BITS) { - throw new SketchesArgumentException("Requested number of bits exceeds maximum allowed. " - + "Requested: " + numBits + ", maximum: " + MAX_BITS); - } - final int numLongs = (int) ceilingMultiple2expK(numBits, 6);//Math.ceil(numBits / 64.0) - return Long.BYTES * (numLongs + 2L); - } - - abstract protected boolean isDirty(); - - // used to get a long from the array regardless of underlying storage - // NOT used to query individual bits - abstract protected long getLong(final int arrayIndex); - - // used to set a long in the array regardless of underlying storage - // NOT used to set individual bits - abstract protected void setLong(final int arrayIndex, final long value); - - // prints a long as a series of 0s and 1s as little endian - protected static String printLong(final long val) { - final StringBuilder sb = new StringBuilder(); - for (int j = 0; j < Long.SIZE; ++j) { - sb.append((val & (1L << j)) != 0 ? "1" : "0"); - if ((j % 8) == 7) { sb.append(" "); } - } - return sb.toString(); - } - -} diff --git a/src/main/java/org/apache/datasketches/filters/bloomfilter/BloomFilter.java b/src/main/java/org/apache/datasketches/filters/bloomfilter/BloomFilter.java deleted file mode 100644 index d21335c85..000000000 --- a/src/main/java/org/apache/datasketches/filters/bloomfilter/BloomFilter.java +++ /dev/null @@ -1,860 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.filters.bloomfilter; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; - -import java.lang.foreign.MemorySegment; -import java.nio.charset.StandardCharsets; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.positional.PositionalSegment; -import org.apache.datasketches.hash.XxHash; -import org.apache.datasketches.hash.XxHash64; - -/** - * A Bloom filter is a data structure that can be used for probabilistic - * set membership. - * - *

When querying a Bloom filter, there are no false positives. Specifically: - * When querying an item that has already been inserted to the filter, the filter will - * always indicate that the item is present. There is a chance of false positives, where - * querying an item that has never been presented to the filter will indicate that the - * item has already been seen. Consequently, any query should be interpreted as - * "might have seen."

- * - *

A standard Bloom filter is unlike typical sketches in that it is not sub-linear - * in size and does not resize itself. A Bloom filter will work up to a target number of - * distinct items, beyond which it will saturate and the false positive rate will start to - * increase. The size of a Bloom filter will be linear in the expected number of - * distinct items.

- * - *

See the BloomFilterBuilder class for methods to create a filter, especially - * one sized correctly for a target number of distinct elements and a target - * false positive probability.

- * - *

This implementation uses xxHash64 and follows the approach in Kirsch and Mitzenmacher, - * "Less Hashing, Same Performance: Building a Better Bloom Filter," Wiley Interscience, 2008, pp. 187-218.

- */ -public final class BloomFilter implements MemorySegmentStatus { - /** - * The maximum size of a bloom filter in bits. - */ - public static final long MAX_SIZE_BITS = (Integer.MAX_VALUE - Family.BLOOMFILTER.getMaxPreLongs()) * (long) Long.SIZE; - private static final int SER_VER = 1; - private static final int EMPTY_FLAG_MASK = 4; - private static final long BIT_ARRAY_OFFSET = 16; - private static final int FLAGS_BYTE = 3; - - private final long seed_; // hash seed - private final short numHashes_; // number of hash values - private final BitArray bitArray_; // the actual data bits - private final MemorySegment wseg_; // used only for direct mode BitArray - - /** - * Creates a BloomFilter with given number of bits and number of hash functions, - * and a user-specified seed. - * - * @param numBits The size of the BloomFilter, in bits - * @param numHashes The number of hash functions to apply to items - * @param seed The base hash seed - */ - BloomFilter(final long numBits, final int numHashes, final long seed) { - seed_ = seed; - numHashes_ = (short) numHashes; - bitArray_ = new HeapBitArray(numBits); - wseg_ = null; - } - - /** - * Creates a BloomFilter with given number of bits and number of hash functions, - * and a user-specified seed in the provided MemorySegment - * - * @param numBits The size of the BloomFilter, in bits - * @param numHashes The number of hash functions to apply to items - * @param seed The base hash seed - * @param wseg A MemorySegment that will be initialized to hold the filter - */ - BloomFilter(final long numBits, final int numHashes, final long seed, final MemorySegment wseg) { - if (wseg.byteSize() < Family.BLOOMFILTER.getMaxPreLongs()) { - throw new SketchesArgumentException("Provided MemorySegment capacity insufficient to initialize BloomFilter"); - } - - // we don't resize so initialize with non-empty preLongs value - // and no empty flag - final PositionalSegment posSeg = PositionalSegment.wrap(wseg); - posSeg.setByte((byte) Family.BLOOMFILTER.getMaxPreLongs()); - posSeg.setByte((byte) SER_VER); - posSeg.setByte((byte) Family.BLOOMFILTER.getID()); - posSeg.setByte((byte) 0); // instead of (bitArray_.isEmpty() ? EMPTY_FLAG_MASK : 0); - posSeg.setShort((short) numHashes); - posSeg.setShort((short) 0); // unused - posSeg.setLong(seed); - - seed_ = seed; - numHashes_ = (short) numHashes; - bitArray_ = DirectBitArray.initialize(numBits, wseg.asSlice(BIT_ARRAY_OFFSET, wseg.byteSize() - BIT_ARRAY_OFFSET)); - wseg_ = wseg; - } - - // Constructor used with internalHeapifyOrWrap() - BloomFilter(final short numHashes, final long seed, final BitArray bitArray, final MemorySegment wseg) { - seed_ = seed; - numHashes_ = numHashes; - bitArray_ = bitArray; - wseg_ = wseg; - } - - /** - * Reads a serialized image of a BloomFilter from the provided MemorySegment - * @param seg MemorySegment containing a previously serialized BloomFilter - * @return a BloomFilter object - */ - public static BloomFilter heapify(final MemorySegment seg) { - // casting to writable, but heapify so only reading - return internalHeapifyOrWrap(seg, false, false); - } - - /** - * Wraps the given MemorySegment into this filter class. The class itself only contains a few metadata items and holds - * a reference to the MemorySegment object, which contains all the data. - * @param seg the given MemorySegment object - * @return the wrapping BloomFilter class. - */ - public static BloomFilter wrap(final MemorySegment seg) { - // casting to writable, but tracking that the object is read-only - return internalHeapifyOrWrap(seg, true, false); - } - - /** - * Wraps the given MemorySegment into this filter class. The class itself only contains a few metadata items and holds - * a reference to the MemorySegment object, which contains all the data. - * @param wseg the given MemorySegment object - * @return the wrapping BloomFilter class. - */ - public static BloomFilter writableWrap(final MemorySegment wseg) { - return internalHeapifyOrWrap(wseg, true, true); - } - - private static BloomFilter internalHeapifyOrWrap(final MemorySegment wseg, final boolean isWrap, final boolean isWritable) { - final PositionalSegment posSeg = PositionalSegment.wrap(wseg); - final int preLongs = posSeg.getByte(); - final int serVer = posSeg.getByte(); - final int familyID = posSeg.getByte(); - final int flags = posSeg.getByte(); - - checkArgument((preLongs < Family.BLOOMFILTER.getMinPreLongs()) || (preLongs > Family.BLOOMFILTER.getMaxPreLongs()), - "Possible corruption: Incorrect number of preamble bytes specified in header"); - checkArgument(serVer != SER_VER, "Possible corruption: Unrecognized serialization version: " + serVer); - checkArgument(familyID != Family.BLOOMFILTER.getID(), "Possible corruption: Incorrect FamilyID for bloom filter. Found: " + familyID); - - final short numHashes = posSeg.getShort(); - posSeg.getShort(); // unused - checkArgument(numHashes < 1, "Possible corruption: Need strictly positive number of hash functions. Found: " + numHashes); - - final long seed = posSeg.getLong(); - - final boolean isEmpty = (flags & EMPTY_FLAG_MASK) != 0; - - final BitArray bitArray; - if (isWrap) { - if (isWritable) { - bitArray = BitArray.writableWrap(wseg.asSlice(BIT_ARRAY_OFFSET, wseg.byteSize() - BIT_ARRAY_OFFSET), isEmpty); - } else { - bitArray = BitArray.wrap(wseg.asSlice(BIT_ARRAY_OFFSET, wseg.byteSize() - BIT_ARRAY_OFFSET), isEmpty); - } - return new BloomFilter(numHashes, seed, bitArray, wseg); - } else { // if heapify - bitArray = BitArray.heapify(posSeg, isEmpty); - return new BloomFilter(numHashes, seed, bitArray, null); - } - } - - /** - * Resets the BloomFilter to an empty state - */ - public void reset() { - bitArray_.reset(); - } - - /** - * Checks if the BloomFilter has processed any items - * @return True if the BloomFilter is empty, otherwise False - */ - public boolean isEmpty() { return bitArray_.isEmpty(); } - - /** - * Returns the number of bits in the BloomFilter that are set to 1. - * @return The number of bits in use in this filter - */ - public long getBitsUsed() { return bitArray_.getNumBitsSet(); } - - /** - * Returns the total number of bits in the BloomFilter. - * @return The total size of the BloomFilter - */ - public long getCapacity() { return bitArray_.getCapacity(); } - - /** - * Returns the configured number of hash functions for this BloomFilter - * @return The number of hash functions to apply to inputs - */ - public short getNumHashes() { return numHashes_; } - - /** - * Returns the hash seed for this BloomFilter. - * @return The hash seed for this filter - */ - public long getSeed() { return seed_; } - - @Override - public boolean hasMemorySegment() { return wseg_ != null; } - - /** - * Returns whether the filter is in read-only mode. That is possible - * only if there is a backing MemorySegment in read-only mode. - * @return true if read-only, otherwise false - */ - public boolean isReadOnly() { - return (wseg_ != null) && bitArray_.isReadOnly(); - } - - @Override - public boolean isOffHeap() { - return hasMemorySegment() && bitArray_.isOffHeap(); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return MemorySegmentStatus.isSameResource(wseg_, that); - } - - /** - * Returns the percentage of all bits in the BloomFilter set to 1. - * @return the percentage of bits in the filter set to 1 - */ - public double getFillPercentage() { - return (double) bitArray_.getNumBitsSet() / bitArray_.getCapacity(); - } - - // UPDATE METHODS - /** - * Updates the filter with the provided long value. - * @param item an item with which to update the filter - */ - public void update(final long item) { - final long h0 = XxHash.hashLong(item, seed_); - final long h1 = XxHash.hashLong(item, h0); - updateInternal(h0, h1); - } - - /** - * Updates the filter with the provided double value. The value is - * canonicalized (NaN and infinities) prior to updating. - * @param item an item with which to update the filter - */ - public void update(final double item) { - // canonicalize all NaN & +/- infinity forms - final long[] data = { Double.doubleToLongBits(item) }; - final long h0 = XxHash.hashLongArr(data, 0, 1, seed_); - final long h1 = XxHash.hashLongArr(data, 0, 1, h0); - updateInternal(h0, h1); - } - - /** - * Updates the filter with the provided String. - * The string is converted to a byte array using UTF8 encoding. - * - *

Note: this will not produce the same output hash values as the {@link #update(char[])} - * method and will generally be a little slower depending on the complexity of the UTF8 encoding. - *

- * - * @param item an item with which to update the filter - */ - public void update(final String item) { - if ((item == null) || item.isEmpty()) { return; } - final byte[] strBytes = item.getBytes(StandardCharsets.UTF_8); - final long h0 = XxHash.hashByteArr(strBytes, 0, strBytes.length, seed_); - final long h1 = XxHash.hashByteArr(strBytes, 0, strBytes.length, h0); - updateInternal(h0, h1); - } - - /** - * Updates the filter with the provided byte[]. - * @param data an array with which to update the filter - */ - public void update(final byte[] data) { - if (data == null) { return; } - final long h0 = XxHash.hashByteArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashByteArr(data, 0, data.length, h0); - updateInternal(h0, h1); - } - - /** - * Updates the filter with the provided char[]. - * @param data an array with which to update the filter - */ - public void update(final char[] data) { - if (data == null) { return; } - final long h0 = XxHash.hashCharArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashCharArr(data, 0, data.length, h0); - updateInternal(h0, h1); - } - - /** - * Updates the filter with the provided short[]. - * @param data an array with which to update the filter - */ - public void update(final short[] data) { - if (data == null) { return; } - final long h0 = XxHash.hashShortArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashShortArr(data, 0, data.length, h0); - updateInternal(h0, h1); - } - - /** - * Updates the filter with the provided int[]. - * @param data an array with which to update the filter - */ - public void update(final int[] data) { - if (data == null) { return; } - final long h0 = XxHash.hashIntArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashIntArr(data, 0, data.length, h0); - updateInternal(h0, h1); - } - - /** - * Updates the filter with the provided long[]. - * @param data an array with which to update the filter - */ - public void update(final long[] data) { - if (data == null) { return; } - final long h0 = XxHash.hashLongArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashLongArr(data, 0, data.length, h0); - updateInternal(h0, h1); - } - - /** - * Updates the filter with the data in the provided MemorySegment. - * @param seg a MemorySegment object with which to update the filter - */ - public void update(final MemorySegment seg) { - if (seg == null) { return; } - final long h0 = XxHash64.hash(seg, 0, seg.byteSize(), seed_); - final long h1 = XxHash64.hash(seg, 0, seg.byteSize(), h0); - updateInternal(h0, h1); - } - - // Internal method to apply updates given pre-computed hashes - private void updateInternal(final long h0, final long h1) { - final long numBits = bitArray_.getCapacity(); - for (int i = 1; i <= numHashes_; ++i) { - // right-shift to ensure non-negative value - final long hashIndex = ((h0 + (i * h1)) >>> 1) % numBits; - bitArray_.setBit(hashIndex); - } - } - - // QUERY-AND-UPDATE METHODS - - /** - * Updates the filter with the provided long and - * returns the result from querying that value prior to the update. - * @param item an item with which to update the filter - * @return The query result prior to applying the update - */ - public boolean queryAndUpdate(final long item) { - final long h0 = XxHash.hashLong(item, seed_); - final long h1 = XxHash.hashLong(item, h0); - return queryAndUpdateInternal(h0, h1); - } - - /** - * Updates the filter with the provided double and - * returns the result from querying that value prior to the update. - * The double is canonicalized (NaN and +/- infinity) in the call. - * @param item an item with which to update the filter - * @return The query result prior to applying the update - */ - public boolean queryAndUpdate(final double item) { - // canonicalize all NaN & +/- infinity forms - final long[] data = { Double.doubleToLongBits(item) }; - final long h0 = XxHash.hashLongArr(data, 0, 1, seed_); - final long h1 = XxHash.hashLongArr(data, 0, 1, h0); - return queryAndUpdateInternal(h0, h1); - } - - /** - * Updates the filter with the provided String and - * returns the result from querying that value prior to the update. - * The string is converted to a byte array using UTF8 encoding. - * - *

Note: this will not produce the same output hash values as the {@link #queryAndUpdate(char[])} - * method and will generally be a little slower depending on the complexity of the UTF8 encoding. - *

- * - * @param item an item with which to update the filter - * @return The query result prior to applying the update, or false if item is null - */ - public boolean queryAndUpdate(final String item) { - if ((item == null) || item.isEmpty()) { return false; } - final byte[] strBytes = item.getBytes(StandardCharsets.UTF_8); - final long h0 = XxHash.hashByteArr(strBytes, 0, strBytes.length, seed_); - final long h1 = XxHash.hashByteArr(strBytes, 0, strBytes.length, h0); - return queryAndUpdateInternal(h0, h1); - } - - /** - * Updates the filter with the provided byte[] and - * returns the result from querying that array prior to the update. - * @param data an array with which to update the filter - * @return The query result prior to applying the update, or false if data is null - */ - public boolean queryAndUpdate(final byte[] data) { - final long h0 = XxHash.hashByteArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashByteArr(data, 0, data.length, h0); - return queryAndUpdateInternal(h0, h1); - } - - /** - * Updates the filter with the provided char[] and - * returns the result from querying that array prior to the update. - * @param data an array with which to update the filter - * @return The query result prior to applying the update, or false if data is null - */ - public boolean queryAndUpdate(final char[] data) { - if (data == null) { return false; } - final long h0 = XxHash.hashCharArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashCharArr(data, 0, data.length, h0); - return queryAndUpdateInternal(h0, h1); - } - - /** - * Updates the filter with the provided short[] and - * returns the result from querying that array prior to the update. - * @param data an array with which to update the filter - * @return The query result prior to applying the update, or false if data is null - */ - public boolean queryAndUpdate(final short[] data) { - if (data == null) { return false; } - final long h0 = XxHash.hashShortArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashShortArr(data, 0, data.length, h0); - return queryAndUpdateInternal(h0, h1); - } - - /** - * Updates the filter with the provided int[] and - * returns the result from querying that array prior to the update. - * @param data an array with which to update the filter - * @return The query result prior to applying the update, or false if data is null - */ - public boolean queryAndUpdate(final int[] data) { - if (data == null) { return false; } - final long h0 = XxHash.hashIntArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashIntArr(data, 0, data.length, h0); - return queryAndUpdateInternal(h0, h1); - } - - /** - * Updates the filter with the provided long[] and - * returns the result from querying that array prior to the update. - * @param data an array with which to update the filter - * @return The query result prior to applying the update, or false if data is null - */ - public boolean queryAndUpdate(final long[] data) { - if (data == null) { return false; } - final long h0 = XxHash.hashLongArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashLongArr(data, 0, data.length, h0); - return queryAndUpdateInternal(h0, h1); - } - - /** - * Updates the filter with the provided MemorySegment and - * returns the result from querying that MemorySegment prior to the update. - * @param seg an array with which to update the filter - * @return The query result prior to applying the update, or false if MemorySegment is null - */ - public boolean queryAndUpdate(final MemorySegment seg) { - if (seg == null) { return false; } - final long h0 = XxHash64.hash(seg, 0, seg.byteSize(), seed_); - final long h1 = XxHash64.hash(seg, 0, seg.byteSize(), h0); - return queryAndUpdateInternal(h0, h1); - } - - // Internal query-and-update method given pre-computed hashes - private boolean queryAndUpdateInternal(final long h0, final long h1) { - final long numBits = bitArray_.getCapacity(); - boolean valueAlreadyExists = true; - for (int i = 1; i <= numHashes_; ++i) { - final long hashIndex = ((h0 + (i * h1)) >>> 1) % numBits; - // returns old value of bit - valueAlreadyExists &= bitArray_.getAndSetBit(hashIndex); - } - return valueAlreadyExists; - } - - // QUERY METHODS - /** - * Queries the filter with the provided long and returns whether the - * value might have been seen previously. The filter's expected - * False Positive Probability determines the chances of a true result being - * a false positive. False negatives are never possible. - * @param item an item with which to query the filter - * @return The result of querying the filter with the given item - */ - public boolean query(final long item) { - final long h0 = XxHash.hashLong(item, seed_); - final long h1 = XxHash.hashLong(item, h0); - return queryInternal(h0, h1); - } - - /** - * Queries the filter with the provided double and returns whether the - * value might have been seen previously. The filter's expected - * False Positive Probability determines the chances of a true result being - * a false positive. False negatives are never possible. Double values are - * canonicalized (NaN and +/- infinity) before querying. - * @param item an item with which to query the filter - * @return The result of querying the filter with the given item - */ - public boolean query(final double item) { - // canonicalize all NaN & +/- infinity forms - final long[] data = { Double.doubleToLongBits(item) }; - final long h0 = XxHash.hashLongArr(data, 0, 1, seed_); - final long h1 = XxHash.hashLongArr(data, 0, 1, h0); - return queryInternal(h0, h1); - } - - /** - * Queries the filter with the provided double and returns whether the - * value might have been seen previously. The filter's expected - * False Positive Probability determines the chances of a true result being - * a false positive. False negatives are never possible. - * The string is converted to a byte array using UTF8 encoding. - * - *

Note: this will not produce the same output hash values as the {@link #update(char[])} - * method and will generally be a little slower depending on the complexity of the UTF8 encoding. - *

- * - * @param item an item with which to query the filter - * @return The result of querying the filter with the given item, or false if item is null - */ - public boolean query(final String item) { - if ((item == null) || item.isEmpty()) { return false; } - final byte[] strBytes = item.getBytes(StandardCharsets.UTF_8); - final long h0 = XxHash.hashByteArr(strBytes, 0, strBytes.length, seed_); - final long h1 = XxHash.hashByteArr(strBytes, 0, strBytes.length, h0); - return queryInternal(h0, h1); - } - - /** - * Queries the filter with the provided byte[] and returns whether the - * array might have been seen previously. The filter's expected - * False Positive Probability determines the chances of a true result being - * a false positive. False negatives are never possible. - * @param data an array with which to query the filter - * @return The result of querying the filter with the given data, or false if data is null - */ - public boolean query(final byte[] data) { - if (data == null) { return false; } - final long h0 = XxHash.hashByteArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashByteArr(data, 0, data.length, h0); - return queryInternal(h0, h1); - } - - /** - * Queries the filter with the provided char[] and returns whether the - * array might have been seen previously. The filter's expected - * False Positive Probability determines the chances of a true result being - * a false positive. False negatives are never possible. - * @param data an array with which to query the filter - * @return The result of querying the filter with the given data, or false if data is null - */ - public boolean query(final char[] data) { - if (data == null) { return false; } - final long h0 = XxHash.hashCharArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashCharArr(data, 0, data.length, h0); - return queryInternal(h0, h1); - } - - /** - * Queries the filter with the provided short[] and returns whether the - * array might have been seen previously. The filter's expected - * False Positive Probability determines the chances of a true result being - * a false positive. False negatives are never possible. - * @param data an array with which to query the filter - * @return The result of querying the filter with the given data, or false if data is null - */ - public boolean query(final short[] data) { - if (data == null) { return false; } - final long h0 = XxHash.hashShortArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashShortArr(data, 0, data.length, h0); - return queryInternal(h0, h1); - } - - /** - * Queries the filter with the provided int[] and returns whether the - * array might have been seen previously. The filter's expected - * False Positive Probability determines the chances of a true result being - * a false positive. False negatives are never possible. - * @param data an array with which to query the filter - * @return The result of querying the filter with the given data, or false if data is null - */ - public boolean query(final int[] data) { - if (data == null) { return false; } - final long h0 = XxHash.hashIntArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashIntArr(data, 0, data.length, h0); - return queryInternal(h0, h1); - } - - /** - * Queries the filter with the provided long[] and returns whether the - * array might have been seen previously. The filter's expected - * False Positive Probability determines the chances of a true result being - * a false positive. False negatives are never possible. - * @param data an array with which to query the filter - * @return The result of querying the filter with the given data, or false if data is null - */ - public boolean query(final long[] data) { - if (data == null) { return false; } - final long h0 = XxHash.hashLongArr(data, 0, data.length, seed_); - final long h1 = XxHash.hashLongArr(data, 0, data.length, h0); - return queryInternal(h0, h1); - } - - /** - * Queries the filter with the provided MemorySegment and returns whether the - * data might have been seen previously. The filter's expected - * False Positive Probability determines the chances of a true result being - * a false positive. False negatives are never possible. - * @param seg a MemorySegment array with which to query the filter - * @return The result of querying the filter with the given MemorySegment, or false if data is null - */ - public boolean query(final MemorySegment seg) { - if (seg == null) { return false; } - final long h0 = XxHash64.hash(seg, 0, seg.byteSize(), seed_); - final long h1 = XxHash64.hash(seg, 0, seg.byteSize(), h0); - return queryInternal(h0, h1); - } - - // Internal method to query the filter given pre-computed hashes - private boolean queryInternal(final long h0, final long h1) { - final long numBits = bitArray_.getCapacity(); - for (int i = 1; i <= numHashes_; ++i) { - final long hashIndex = ((h0 + (i * h1)) >>> 1) % numBits; - // returns old value of bit - if (!bitArray_.getBit(hashIndex)) { - return false; - } - } - return true; - } - - // OTHER OPERATIONS - /** - * Unions two BloomFilters by applying a logical OR. The result will recognized - * any values seen by either filter (as well as false positives). - * @param other A BloomFilter to union with this one - */ - public void union(final BloomFilter other) { - if (other == null) { return; } - if (!isCompatible(other)) { - throw new SketchesArgumentException("Cannot union sketches with different seeds, hash functions, or sizes"); - } - - bitArray_.union(other.bitArray_); - } - - /** - * Intersects two BloomFilters by applying a logical AND. The result will recognize - * only values seen by both filters (as well as false positives). - * @param other A BloomFilter to union with this one - */ - public void intersect(final BloomFilter other) { - if (other == null) { return; } - if (!isCompatible(other)) { - throw new SketchesArgumentException("Cannot union sketches with different seeds, hash functions, or sizes"); - } - - bitArray_.intersect(other.bitArray_); - } - - /** - * Inverts all the bits of the BloomFilter. Approximately inverts the notion of set-membership. - */ - public void invert() { - bitArray_.invert(); - } - - /** - * Helps identify if two BloomFilters may be unioned or intersected. - * @param other A BloomFilter to check for compatibility with this one - * @return True if the filters are compatible, otherwise false - */ - public boolean isCompatible(final BloomFilter other) { - if ((other == null) - || (seed_ != other.seed_) - || (numHashes_ != other.numHashes_) - || (bitArray_.getArrayLength() != other.bitArray_.getArrayLength())) { - return false; - } - return true; - } - - /** - * Returns the length of this BloomFilter when serialized, in bytes - * @return The length of this BloomFilter when serialized, in bytes - */ - public long getSerializedSizeBytes() { - long sizeBytes = 2L * Long.BYTES; // basic sketch info + baseSeed - sizeBytes += bitArray_.getSerializedSizeBytes(); - return sizeBytes; - } - - /** - * Returns the serialized length of a non-empty BloomFilter of the given size, in bytes - * @param numBits The number of bits of to use for size computation - * @return The serialized length of a non-empty BloomFilter of the given size, in bytes - */ - public static long getSerializedSize(final long numBits) { - return (2L * Long.BYTES) + BitArray.getSerializedSizeBytes(numBits); - } - -/* - * A Bloom Filter's serialized image always uses 3 longs of preamble when empty, - * otherwise 4 longs: - * - *
- * Long || Start Byte Adr:
- * Adr:
- *      ||       0        |    1   |    2   |    3   |    4   |    5   |    6   |    7   |
- *  0   || Preamble_Longs | SerVer | FamID  |  Flags |----Num Hashes---|-----Unused------|
- *
- *      ||       8        |    9   |   10   |   11   |   12   |   13   |   14   |   15   |
- *  1   ||---------------------------------Hash Seed-------------------------------------|
- *
- *      ||      16        |   17   |   18   |   19   |   20   |   21   |   22   |   23   |
- *  2   ||-------BitArray Length (in longs)----------|-----------Unused------------------|
- *
- *      ||      24        |   25   |   26   |   27   |   28   |   29   |   30   |   31   |
- *  3   ||---------------------------------NumBitsSet------------------------------------|
- *  
- * - * The raw BitArray bits, if non-empty, start at byte 32. - */ - - /** - * Serializes the current BloomFilter to an array of bytes. - * - *

Note: Method throws if the serialized size exceeds Integer.MAX_VALUE.

- * @return A serialized image of the current BloomFilter as byte[] - */ - public byte[] toByteArray() { - final long sizeBytes = getSerializedSizeBytes(); - if (sizeBytes > Integer.MAX_VALUE) { - throw new SketchesStateException("Cannot serialize a BloomFilter of this size using toByteArray(); use toLongArray() instead."); - } - - final byte[] bytes = new byte[(int) sizeBytes]; - - if (wseg_ == null) { - final MemorySegment seg = MemorySegment.ofArray(bytes); - final PositionalSegment posSeg = PositionalSegment.wrap(seg); - - final int numPreLongs = isEmpty() ? Family.BLOOMFILTER.getMinPreLongs() : Family.BLOOMFILTER.getMaxPreLongs(); - posSeg.setByte((byte) numPreLongs); - posSeg.setByte((byte) SER_VER); - posSeg.setByte((byte) Family.BLOOMFILTER.getID()); - posSeg.setByte((byte) (bitArray_.isEmpty() ? EMPTY_FLAG_MASK : 0)); - posSeg.setShort(numHashes_); - posSeg.setShort((short) 0); // unused - posSeg.setLong(seed_); - - ((HeapBitArray) bitArray_).writeToSegmentAsStream(posSeg); //option: posSeg.asSlice() - } else { - MemorySegment.copy(wseg_, JAVA_BYTE, 0, bytes, 0, (int)sizeBytes); - - if (isEmpty()) { - bytes[FLAGS_BYTE] |= EMPTY_FLAG_MASK; - } - } - return bytes; - } - - /** - * Serializes the current BloomFilter to an array of longs. Unlike {@link #toByteArray()}, - * this method can handle any size filter. - * - * @return A serialized image of the current BloomFilter as long[] - */ - public long[] toLongArray() { - final long sizeBytes = getSerializedSizeBytes(); - - final long[] longs = new long[(int) (sizeBytes >> 3)]; - if (wseg_ == null) { - final MemorySegment wseg = MemorySegment.ofArray(longs); - final PositionalSegment posSeg = PositionalSegment.wrap(wseg); - - final int numPreLongs = isEmpty() ? Family.BLOOMFILTER.getMinPreLongs() : Family.BLOOMFILTER.getMaxPreLongs(); - posSeg.setByte((byte) numPreLongs); - posSeg.setByte((byte) SER_VER); // to do: add constant - posSeg.setByte((byte) Family.BLOOMFILTER.getID()); - posSeg.setByte((byte) (bitArray_.isEmpty() ? EMPTY_FLAG_MASK : 0)); - posSeg.setShort(numHashes_); - posSeg.setShort((short) 0); // unused - posSeg.setLong(seed_); - - ((HeapBitArray) bitArray_).writeToSegmentAsStream(posSeg); //option: posSeg.asSlice() - } else { - MemorySegment.copy(wseg_, JAVA_LONG_UNALIGNED, 0, longs, 0, (int) (sizeBytes >>> 3)); - if (isEmpty()) { - longs[0] |= (EMPTY_FLAG_MASK << (FLAGS_BYTE << 3)); - } - } - return longs; - } - - // Throws an exception with the provided message if the given condition is true - private static void checkArgument(final boolean condition, final String message) { - if (condition) { throw new SketchesArgumentException(message); } - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - - sb.append(LS); - final String thisSimpleName = this.getClass().getSimpleName(); - sb.append("### ").append(thisSimpleName).append(" SUMMARY: ").append(LS); - sb.append(" numBits : ").append(bitArray_.getCapacity()).append(LS); - sb.append(" numHashes : ").append(numHashes_).append(LS); - sb.append(" seed : ").append(seed_).append(LS); - sb.append(" bitsUsed : ").append(bitArray_.getNumBitsSet()).append(LS); - sb.append(" fill % : ").append(getFillPercentage()).append(LS); - sb.append("### END SKETCH SUMMARY").append(LS); - - return sb.toString(); - } -} diff --git a/src/main/java/org/apache/datasketches/filters/bloomfilter/BloomFilterBuilder.java b/src/main/java/org/apache/datasketches/filters/bloomfilter/BloomFilterBuilder.java deleted file mode 100644 index 78098878f..000000000 --- a/src/main/java/org/apache/datasketches/filters/bloomfilter/BloomFilterBuilder.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.filters.bloomfilter; - -import java.lang.foreign.MemorySegment; -import java.util.concurrent.ThreadLocalRandom; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This class provides methods to help estimate the correct parameters when - * creating a Bloom filter, and methods to create the filter using those values. - * - *

The underlying math is described in the - * - * Wikipedia article on Bloom filters.

- */ -public final class BloomFilterBuilder { - - /** - * No argument constructor. - */ - public BloomFilterBuilder() { } - - /** - * Returns the optimal number of hash functions to given target numbers of distinct items - * and the BloomFilter size in bits. This function will provide a result even if the input - * values exceed the capacity of a single BloomFilter. - * @param maxDistinctItems The maximum expected number of distinct items to add to the filter - * @param numFilterBits The intended size of the Bloom Filter in bits - * @return The suggested number of hash functions to use with the filter - */ - public static short suggestNumHashes(final long maxDistinctItems, final long numFilterBits) { - if ((maxDistinctItems < 1) || (numFilterBits < 1)) { - throw new SketchesArgumentException("maxDistinctItems and numFilterBits must be strictly positive"); - } - // ceil to ensure we never average worse than the target - return (short) Math.max(1, (int) Math.ceil(((double) numFilterBits / maxDistinctItems) * Math.log(2.0))); - } - - /** - * Returns the optimal number of hash functions to achieve a target false positive probability. - * @param targetFalsePositiveProb A desired false positive probability per item - * @return The suggested number of hash functions to use with the filter. - */ - public static short suggestNumHashes(final double targetFalsePositiveProb) { - if ((targetFalsePositiveProb <= 0.0) || (targetFalsePositiveProb > 1.0)) { - throw new SketchesArgumentException("targetFalsePositiveProb must be a valid probability and strictly greater than 0"); - } - // ceil to ensure we never average worse than the target - return (short) Math.ceil((- Math.log(targetFalsePositiveProb) / Math.log(2))); - } - - /** - * Returns the optimal number of bits to use in a Bloom Filter given a target number of distinct - * items and a target false positive probability. - * @param maxDistinctItems The maximum expected number of distinct items to add to the filter - * @param targetFalsePositiveProb A desired false positive probability per item - * @return The suggested number of bits to use with the filter - */ - public static long suggestNumFilterBits(final long maxDistinctItems, final double targetFalsePositiveProb) { - validateAccuracyInputs(maxDistinctItems, targetFalsePositiveProb); - return (long) Math.ceil((-maxDistinctItems * Math.log(targetFalsePositiveProb)) / (Math.log(2) * Math.log(2))); - } - - /** - * Returns the minimum MemorySegment size, in bytes, needed for a serialized BloomFilter with an optimal number of bits - * and hash functions for the given inputs. This is also the minimum size of a MemorySegment for - * in-place filter initialization. - * @param maxDistinctItems The maximum expected number of distinct items to add to the filter - * @param targetFalsePositiveProb A desired false positive probability per item - * @return The size, in bytes, required to hold the specified BloomFilter when serialized - */ - public static long getSerializedFilterSizeByAccuracy(final long maxDistinctItems, final double targetFalsePositiveProb) { - validateAccuracyInputs(maxDistinctItems, targetFalsePositiveProb); - return BloomFilter.getSerializedSize(suggestNumFilterBits(maxDistinctItems, targetFalsePositiveProb)); - } - - /** - * Returns the minimum MemorySegment size, in bytes, needed for a serialized BloomFilter with the given number of bits. - * This is also the minimum size of a MemorySegment for in-place filter initialization. - * @param numBits The number of bits in the target BloomFilter's bit array. - * @return The size, in bytes, required to hold the specified BloomFilter when serialized - */ - public static long getSerializedFilterSize(final long numBits) { - validateSizeInputs(numBits, 1); // dummy numHashes value - return BloomFilter.getSerializedSize(numBits); - } - - /** - * Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, - * using a random base seed for the hash function. - * @param maxDistinctItems The maximum expected number of distinct items to add to the filter - * @param targetFalsePositiveProb A desired false positive probability per item - * @return A new BloomFilter configured for the given input parameters - */ - public static BloomFilter createByAccuracy(final long maxDistinctItems, final double targetFalsePositiveProb) { - validateAccuracyInputs(maxDistinctItems, targetFalsePositiveProb); - return createByAccuracy(maxDistinctItems, targetFalsePositiveProb, ThreadLocalRandom.current().nextLong()); - } - - /** - * Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, - * using the provided base seed for the hash function. - * @param maxDistinctItems The maximum expected number of distinct items to add to the filter - * @param targetFalsePositiveProb A desired false positive probability per item - * @param seed A base hash seed - * @return A new BloomFilter configured for the given input parameters - */ - public static BloomFilter createByAccuracy(final long maxDistinctItems, final double targetFalsePositiveProb, final long seed) { - validateAccuracyInputs(maxDistinctItems, targetFalsePositiveProb); - final long numBits = suggestNumFilterBits(maxDistinctItems, targetFalsePositiveProb); - final short numHashes = suggestNumHashes(maxDistinctItems, numBits); - return new BloomFilter(numBits, numHashes, seed); - } - - /** - * Creates a BloomFilter with given number of bits and number of hash functions, - * using a random base seed for the hash function. - * - * @param numBits The size of the BloomFilter, in bits - * @param numHashes The number of hash functions to apply to items - * @return A new BloomFilter configured for the given input parameters - */ - public static BloomFilter createBySize(final long numBits, final int numHashes) { - return createBySize(numBits, numHashes, ThreadLocalRandom.current().nextLong()); - } - - /** - * Creates a BloomFilter with given number of bits and number of hash functions, - * using the provided base seed for the hash function. - * - * @param numBits The size of the BloomFilter, in bits - * @param numHashes The number of hash functions to apply to items - * @param seed A base hash seed - * @return A new BloomFilter configured for the given input parameters - */ - public static BloomFilter createBySize(final long numBits, final int numHashes, final long seed) { - validateSizeInputs(numBits, numHashes); - return new BloomFilter(numBits, numHashes, seed); - } - - /** - * Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, - * using a random base seed for the hash function and writing into the provided MemorySegment. - * @param maxDistinctItems The maximum expected number of distinct items to add to the filter - * @param targetFalsePositiveProb A desired false positive probability per item - * @param dstSeg A MemorySegment to hold the initialized filter - * @return A new BloomFilter configured for the given input parameters - */ - public static BloomFilter initializeByAccuracy( - final long maxDistinctItems, final double targetFalsePositiveProb, final MemorySegment dstSeg) { - return initializeByAccuracy(maxDistinctItems, targetFalsePositiveProb, ThreadLocalRandom.current().nextLong(), dstSeg); - } - - /** - * Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, - * using the provided base seed for the hash function and writing into the provided MemorySegment. - * @param maxDistinctItems The maximum expected number of distinct items to add to the filter - * @param targetFalsePositiveProb A desired false positive probability per item - * @param seed A base hash seed - * @param dstSeg A MemorySegment to hold the initialized filter - * @return A new BloomFilter configured for the given input parameters - */ - public static BloomFilter initializeByAccuracy( - final long maxDistinctItems, final double targetFalsePositiveProb, final long seed, final MemorySegment dstSeg) { - validateAccuracyInputs(maxDistinctItems, targetFalsePositiveProb); - final long numBits = suggestNumFilterBits(maxDistinctItems, targetFalsePositiveProb); - final short numHashes = suggestNumHashes(maxDistinctItems, numBits); - - if (dstSeg.byteSize() < BloomFilter.getSerializedSize(numBits)) { - throw new SketchesArgumentException("Provided MemorySegment is insufficient to hold requested filter"); - } - - return new BloomFilter(numBits, numHashes, seed, dstSeg); - } - - /** - * Initializes a BloomFilter with given number of bits and number of hash functions, - * using a random base seed for the hash function and writing into the provided MemorySegment. - * - * @param numBits The size of the BloomFilter, in bits - * @param numHashes The number of hash functions to apply to items - * @param dstSeg A MemorySegment to hold the initialized filter - * @return A new BloomFilter configured for the given input parameters - */ - public static BloomFilter initializeBySize(final long numBits, final int numHashes, final MemorySegment dstSeg) { - return initializeBySize(numBits, numHashes, ThreadLocalRandom.current().nextLong(), dstSeg); - } - - /** - * Initializes a BloomFilter with given number of bits and number of hash functions, - * using the provided base seed for the hash function and writing into the provided MemorySegment. - * - * @param numBits The size of the BloomFilter, in bits - * @param numHashes The number of hash functions to apply to items - * @param seed A base hash seed - * @param dstSeg A MemorySegment to hold the initialized filter - * @return A new BloomFilter configured for the given input parameters - */ - public static BloomFilter initializeBySize(final long numBits, final int numHashes, final long seed, final MemorySegment dstSeg) { - validateSizeInputs(numBits, numHashes); - - if (dstSeg.byteSize() < BloomFilter.getSerializedSize(numBits)) { - throw new SketchesArgumentException("Provided MemorySegment is insufficient to hold requested filter"); - } - - return new BloomFilter(numBits, numHashes, seed, dstSeg); - } - - private static void validateAccuracyInputs(final long maxDistinctItems, final double targetFalsePositiveProb) { - if (maxDistinctItems <= 0) { - throw new SketchesArgumentException("maxDistinctItems must be strictly positive"); - } - if ((targetFalsePositiveProb <= 0.0) || (targetFalsePositiveProb > 1.0)) { - throw new SketchesArgumentException("targetFalsePositiveProb must be a valid probability and strictly greater than 0"); - } - } - - private static void validateSizeInputs(final long numBits, final int numHashes) { - if (numBits <= 0) { - throw new SketchesArgumentException("Size of BloomFilter must be strictly positive. " - + "Requested: " + numBits); - } - if (numBits > BloomFilter.MAX_SIZE_BITS) { - throw new SketchesArgumentException("Size of BloomFilter must be <= " - + BloomFilter.MAX_SIZE_BITS + ". Requested: " + numBits); - } - if (numHashes < 1) { - throw new SketchesArgumentException("Must specify a strictly positive number of hash functions. " - + "Requested: " + numHashes); - } - if (numHashes > Short.MAX_VALUE) { - throw new SketchesArgumentException("Number of hashes cannot exceed " + Short.MAX_VALUE - + ". Requested: " + numHashes); - } - } -} diff --git a/src/main/java/org/apache/datasketches/filters/bloomfilter/DirectBitArray.java b/src/main/java/org/apache/datasketches/filters/bloomfilter/DirectBitArray.java deleted file mode 100644 index 9314614aa..000000000 --- a/src/main/java/org/apache/datasketches/filters/bloomfilter/DirectBitArray.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.filters.bloomfilter; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.Util.ceilingMultiple2expK; -import static org.apache.datasketches.common.Util.clear; -import static org.apache.datasketches.common.Util.setBits; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; - -final class DirectBitArray extends DirectBitArrayR { - - DirectBitArray(final int dataLength, final long storedNumBitsSet, final MemorySegment wseg) { - super(dataLength, 0, wseg); // we'll set numBitsSet_ ourselves so pass 0 - - // can recompute later if needed - numBitsSet_ = storedNumBitsSet; - } - - DirectBitArray(final int dataLength, final MemorySegment wseg) { - super(dataLength, 0, wseg); - - wseg_.set(JAVA_INT_UNALIGNED, 0, dataLength_); - setNumBitsSet(0); - clear(wseg_, DATA_OFFSET, (long) dataLength_ * Long.BYTES); - } - - static DirectBitArray initialize(final long numBits, final MemorySegment wseg) { - if (numBits <= 0) { - throw new SketchesArgumentException("Number of bits must be strictly positive. Found: " + numBits); - } - if (numBits > MAX_BITS) { - throw new SketchesArgumentException("Maximum size of a single filter is " + MAX_BITS + " + bits. " - + "Requested: " + numBits); - } - // we know it'll fit in an int based on above checks - final int arrayLength = (int) ceilingMultiple2expK(numBits, 6);//Math.ceil(numBits / 64.0); - final long requiredBytes = (2L + arrayLength) * Long.BYTES; - if (wseg.byteSize() < requiredBytes) { - throw new SketchesArgumentException("Provided MemorySegment too small for requested array length. " - + "Required: " + requiredBytes + ", provided capacity: " + wseg.byteSize()); - } - - return new DirectBitArray(arrayLength, wseg); - } - - static DirectBitArray writableWrap(final MemorySegment seg, final boolean isEmpty) { - final int arrayLength = seg.get(JAVA_INT_UNALIGNED, 0); - final long storedNumBitsSet = isEmpty ? 0L : seg.get(JAVA_LONG_UNALIGNED, NUM_BITS_OFFSET); - - if ((arrayLength * (long) Long.SIZE) > MAX_BITS) { - throw new SketchesArgumentException("Possible corruption: Serialized image indicates array beyond maximum filter capacity"); - } - - // if empty cannot wrap as writable - if (isEmpty) { - throw new SketchesArgumentException("Cannot wrap an empty filter for writing as there is no backing data array"); - } - - // required capacity is arrayLength plus room for - // arrayLength (in longs) and numBitsSet - if ((storedNumBitsSet != 0) && (seg.byteSize() < (arrayLength + 2))) { - throw new SketchesArgumentException("MemorySegment capacity is insufficient for Bloom Filter. Needs: " - + (arrayLength + 2) + " , found: " + seg.byteSize()); - } - return new DirectBitArray(arrayLength, storedNumBitsSet, seg); - } - - @Override - long getNumBitsSet() { - // update numBitsSet and store in array - if (isDirty()) { - numBitsSet_ = 0; - for (int i = 0; i < dataLength_; ++i) { - numBitsSet_ += Long.bitCount(getLong(i)); - } - wseg_.set(JAVA_LONG_UNALIGNED, NUM_BITS_OFFSET, numBitsSet_); - } - - return numBitsSet_; - } - - @Override - protected boolean isDirty() { - return numBitsSet_ == -1; - } - - @Override - boolean getBit(final long index) { //index a bit in an array of bytes - return (wseg_.get(JAVA_BYTE, DATA_OFFSET + ((int) index >>> 3)) & (1 << (index & 0x7))) != 0; - } - - @Override - protected long getLong(final int arrayIndex) { - return wseg_.get(JAVA_LONG_UNALIGNED, DATA_OFFSET + (arrayIndex << 3)); - } - - @Override - public boolean isReadOnly() { - return false; - } - - @Override - void reset() { - setNumBitsSet(0); - clear(wseg_, DATA_OFFSET, (long) dataLength_ * Long.BYTES); - } - - @Override - void setBit(final long index) { //index a bit in an array of bytes - final long segmentOffset = DATA_OFFSET + ((int) index >>> 3); - final byte val = wseg_.get(JAVA_BYTE, segmentOffset); - setBits(wseg_, segmentOffset, (byte) (val | (1 << (index & 0x07)))); - setNumBitsSet(-1); // mark dirty - } - - @Override - boolean getAndSetBit(final long index) { //index a bit in an array of bytes - final long segmentOffset = DATA_OFFSET + ((int) index >>> 3); - final byte mask = (byte) (1 << (index & 0x07)); - final byte val = wseg_.get(JAVA_BYTE, segmentOffset); - if ((val & mask) != 0) { - return true; // already seen - } else { - setBits(wseg_, segmentOffset, (byte) (val | mask)); - if (!isDirty()) { setNumBitsSet(numBitsSet_ + 1); } - return false; // new set - } - } - - @Override - void intersect(final BitArray other) { - if (getCapacity() != other.getCapacity()) { - throw new SketchesArgumentException("Cannot intersect bit arrays with unequal lengths"); - } - - numBitsSet_ = 0; - for (int i = 0; i < dataLength_; ++i) { - final long val = getLong(i) & other.getLong(i); - numBitsSet_ += Long.bitCount(val); - setLong(i, val); - } - wseg_.set(JAVA_LONG_UNALIGNED, NUM_BITS_OFFSET, numBitsSet_); - } - - @Override - void union(final BitArray other) { - if (getCapacity() != other.getCapacity()) { - throw new SketchesArgumentException("Cannot intersect bit arrays with unequal lengths"); - } - - numBitsSet_ = 0; - for (int i = 0; i < dataLength_; ++i) { - final long val = getLong(i) | other.getLong(i); - numBitsSet_ += Long.bitCount(val); - setLong(i, val); - } - wseg_.set(JAVA_LONG_UNALIGNED, NUM_BITS_OFFSET, numBitsSet_); - } - - @Override - void invert() { - if (isDirty()) { - numBitsSet_ = 0; - for (int i = 0; i < dataLength_; ++i) { - final long val = ~getLong(i); - setLong(i, val); - numBitsSet_ += Long.bitCount(val); - } - } else { - for (int i = 0; i < dataLength_; ++i) { - setLong(i, ~getLong(i)); - } - numBitsSet_ = getCapacity() - numBitsSet_; - } - wseg_.set(JAVA_LONG_UNALIGNED, NUM_BITS_OFFSET, numBitsSet_); - } - - @Override - protected void setLong(final int arrayIndex, final long value) { - wseg_.set(JAVA_LONG_UNALIGNED, DATA_OFFSET + (arrayIndex << 3), value); - } - - private void setNumBitsSet(final long numBitsSet) { - numBitsSet_ = numBitsSet; - wseg_.set(JAVA_LONG_UNALIGNED, NUM_BITS_OFFSET, numBitsSet); - } -} diff --git a/src/main/java/org/apache/datasketches/filters/bloomfilter/DirectBitArrayR.java b/src/main/java/org/apache/datasketches/filters/bloomfilter/DirectBitArrayR.java deleted file mode 100644 index 78e2bf348..000000000 --- a/src/main/java/org/apache/datasketches/filters/bloomfilter/DirectBitArrayR.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.filters.bloomfilter; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesReadOnlyException; - -/** - * This class can maintain the BitArray object off-heap. - */ -public class DirectBitArrayR extends BitArray { - final static protected long NUM_BITS_OFFSET = Long.BYTES; - final static protected long DATA_OFFSET = 2L * Long.BYTES; - - final protected int dataLength_; - final protected MemorySegment wseg_; // for inheritance; we won't write to it - protected long numBitsSet_; // could be final here but DirectBitArray will update it - - protected DirectBitArrayR(final int dataLength, final long storedNumBitsSet, final MemorySegment seg) { - dataLength_ = dataLength; - wseg_ = seg; - - if (storedNumBitsSet == -1) { - numBitsSet_ = 0; - for (int i = 0; i < dataLength_; ++i) { - numBitsSet_ += Long.bitCount(wseg_.get(JAVA_LONG_UNALIGNED, DATA_OFFSET + (i << 3))); - } - } else { - numBitsSet_ = storedNumBitsSet; - } - } - - // assumes we have a slice with only the portion of the MemorySegment the BitArray cares about - static DirectBitArrayR wrap(final MemorySegment seg, final boolean isEmpty) { - final int arrayLength = seg.get(JAVA_INT_UNALIGNED, 0L); - final long storedNumBitsSet = isEmpty ? 0L : seg.get(JAVA_LONG_UNALIGNED, NUM_BITS_OFFSET); - - if (arrayLength < 0) { - throw new SketchesArgumentException("Possible corruption: Serialized image indicates non-positive array length"); - } - - // required capacity is arrayLength plus room for - // arrayLength (in longs) and numBitsSet - if ((storedNumBitsSet != 0) && (seg.byteSize() < (arrayLength + 2))) { - throw new SketchesArgumentException("MemorySegment capacity is insufficient for Bloom Filter. Needs: " - + (arrayLength + 2) + " , found: " + seg.byteSize()); - } - return new DirectBitArrayR(arrayLength, storedNumBitsSet, seg); - } - - @Override - long getCapacity() { - return (long) dataLength_ * Long.SIZE; - } - - @Override - long getNumBitsSet() { - return numBitsSet_; - } - - @Override - protected boolean isDirty() { - // read-only so necessarily false - return false; - } - - @Override - int getArrayLength() { - return dataLength_; - } - - @Override - boolean getBit(final long index) { //index into an array of bytes - if (isEmpty()) { return false; } - return (wseg_.get(JAVA_BYTE, DATA_OFFSET + ((int) index >>> 3)) & (1 << (index & 0x7))) != 0; - } - - @Override - protected long getLong(final int arrayIndex) { - if (isEmpty()) { return 0L; } - return wseg_.get(JAVA_LONG_UNALIGNED, DATA_OFFSET + (arrayIndex << 3)); - } - - @Override - public boolean hasMemorySegment() { - return (wseg_ != null); - } - - @Override - public boolean isOffHeap() { - return hasMemorySegment() && wseg_.isNative(); - } - - @Override - public boolean isReadOnly() { - return true; - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return MemorySegmentStatus.isSameResource(wseg_, that); - } - - @Override - void reset() { - throw new SketchesReadOnlyException("Attempt to call reset() on read-only MemorySegment"); - } - - @Override - void setBit(final long index) { - throw new SketchesReadOnlyException("Attempt to call setBit() on read-only MemorySegment"); - } - - @Override - boolean getAndSetBit(final long index) { - throw new SketchesReadOnlyException("Attempt to call getAndSetBit() on read-only MemorySegment"); - } - - @Override - void intersect(final BitArray other) { - throw new SketchesReadOnlyException("Attempt to call intersect() on read-only MemorySegment"); - } - - @Override - void union(final BitArray other) { - throw new SketchesReadOnlyException("Attempt to call union() on read-only MemorySegment"); - } - - @Override - void invert() { - throw new SketchesReadOnlyException("Attempt to call invert() on read-only MemorySegment"); - } - - @Override - protected void setLong(final int arrayIndex, final long value) { - throw new SketchesReadOnlyException("Attempt to call setLong() on read-only MemorySegment"); - } -} diff --git a/src/main/java/org/apache/datasketches/filters/bloomfilter/HeapBitArray.java b/src/main/java/org/apache/datasketches/filters/bloomfilter/HeapBitArray.java deleted file mode 100644 index ada7add57..000000000 --- a/src/main/java/org/apache/datasketches/filters/bloomfilter/HeapBitArray.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.filters.bloomfilter; - -import static org.apache.datasketches.common.Util.ceilingMultiple2expK; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.positional.PositionalSegment; - -/** - * This class holds an array of bits suitable for use in a Bloom Filter - * - *

Rounds the number of bits up to the smallest multiple of 64 (one long) - * that is not smaller than the specified number. - */ -final class HeapBitArray extends BitArray { - private long numBitsSet_; // if -1, need to recompute value - private boolean isDirty_; - final private long[] data_; - - // creates an array of a given size - HeapBitArray(final long numBits) { - if (numBits <= 0) { - throw new SketchesArgumentException("Number of bits must be strictly positive. Found: " + numBits); - } - if (numBits > MAX_BITS) { - throw new SketchesArgumentException("Number of bits may not exceed " + MAX_BITS + ". Found: " + numBits); - } - - final int numLongs = (int) ceilingMultiple2expK(numBits, 6);//Math.ceil(numBits / 64.0) - numBitsSet_ = 0; - isDirty_ = false; - data_ = new long[numLongs]; - } - - // uses the provided array - HeapBitArray(final long numBitsSet, final long[] data) { - data_ = data; - isDirty_ = numBitsSet < 0; - numBitsSet_ = numBitsSet; - } - - // reads a serialized image, but the BitArray is not fully self-describing so requires - // a flag to indicate whether the array is empty - // The PositionslSegment's position must be set to the start of the bit array. - static HeapBitArray heapify(final PositionalSegment posSeg, final boolean isEmpty) { - final int numLongs = posSeg.getInt(); - if (numLongs < 0) { - throw new SketchesArgumentException("Possible corruption: Must have non-negative array size. Found: " + numLongs); - } - - if (isEmpty) { - return new HeapBitArray((long) numLongs * Long.SIZE); - } - - posSeg.getInt(); // unused - - // will be -1 if dirty - final long numBitsSet = posSeg.getLong(); - - final long[] data = new long[numLongs]; - posSeg.getLongArray(data, 0, numLongs); - return new HeapBitArray(numBitsSet, data); - } - - @Override - protected boolean isDirty() { - return isDirty_; - } - - @Override - public boolean hasMemorySegment() { - return false; - } - - @Override - public boolean isOffHeap() { - return false; - } - - @Override - boolean isReadOnly() { return false; } - - @Override - public boolean isSameResource(final MemorySegment that) { return false; } - - // queries a single bit in the array of longs - @Override - boolean getBit(final long index) { - return ((data_[(int) index >>> 6] & (1L << index)) != 0); - } - - // sets a single bit in the array of longs without querying, meaning the method - // cannot properly track the number of bits set, so set isDirty = true - @Override - void setBit(final long index) { - data_[(int) index >>> 6] |= 1L << index; - isDirty_ = true; - } - - // returns existing value of bit in an array of longs - @Override - boolean getAndSetBit(final long index) { - final int offset = (int) index >>> 6; - final long mask = 1L << index; - if ((data_[offset] & mask) != 0) { - return true; // already seen - } else { - data_[offset] |= mask; - ++numBitsSet_; // increment regardless of isDirty_ - return false; // new set - } - } - - // may need to recompute value: - // O(1) if only getAndSetBit() has been used - // O(data_.length) if setBit() has ever been used - @Override - long getNumBitsSet() { - if (isDirty_) { - numBitsSet_ = 0; - for (final long val : data_) { - numBitsSet_ += Long.bitCount(val); - } - } - return numBitsSet_; - } - - @Override - long getCapacity() { return (long) data_.length * Long.SIZE; } - - @Override - int getArrayLength() { return data_.length; } - - // applies logical OR - @Override - void union(final BitArray other) { - if (getCapacity() != other.getCapacity()) { - throw new SketchesArgumentException("Cannot union bit arrays with unequal lengths"); - } - - numBitsSet_ = 0; - for (int i = 0; i < data_.length; ++i) { - final long val = data_[i] | other.getLong(i); - numBitsSet_ += Long.bitCount(val); - data_[i] = val; - } - isDirty_ = false; - } - - // applies logical AND - @Override - void intersect(final BitArray other) { - if (getCapacity() != other.getCapacity()) { - throw new SketchesArgumentException("Cannot intersect bit arrays with unequal lengths"); - } - - numBitsSet_ = 0; - for (int i = 0; i < data_.length; ++i) { - final long val = data_[i] & other.getLong(i); - numBitsSet_ += Long.bitCount(val); - data_[i] = val; - } - isDirty_ = false; - } - - // applies bitwise inversion - @Override - void invert() { - if (isDirty_) { - numBitsSet_ = 0; - for (int i = 0; i < data_.length; ++i) { - data_[i] = ~data_[i]; - numBitsSet_ += Long.bitCount(data_[i]); - } - isDirty_ = false; - } else { - for (int i = 0; i < data_.length; ++i) { - data_[i] = ~data_[i]; - } - numBitsSet_ = getCapacity() - numBitsSet_; - } - } - - void writeToSegmentAsStream(final PositionalSegment posSeg) { //position = 16 - posSeg.setInt(data_.length); - posSeg.setInt(0); // unused - - if (!isEmpty()) { - posSeg.setLong(isDirty_ ? -1 : numBitsSet_); - posSeg.setLongArray(data_, 0, data_.length); - } - } - - @Override - protected long getLong(final int arrayIndex) { - return data_[arrayIndex]; - } - - @Override - protected void setLong(final int arrayIndex, final long value) { - data_[arrayIndex] = value; - } - - // clears the array - @Override - void reset() { - Arrays.fill(data_, 0); - numBitsSet_ = 0; - isDirty_ = false; - } -} diff --git a/src/main/java/org/apache/datasketches/filters/bloomfilter/package-info.java b/src/main/java/org/apache/datasketches/filters/bloomfilter/package-info.java deleted file mode 100644 index 4823fcca7..000000000 --- a/src/main/java/org/apache/datasketches/filters/bloomfilter/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * BloomFilter package - */ -package org.apache.datasketches.filters.bloomfilter; diff --git a/src/main/java/org/apache/datasketches/filters/package-info.java b/src/main/java/org/apache/datasketches/filters/package-info.java deleted file mode 100644 index 93410e1c5..000000000 --- a/src/main/java/org/apache/datasketches/filters/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * The filters package contains data structures used to determine - * approximate set-membership. Classes in this package may not follow - * the standard sub-linear properties of other offerings in this - * library, but they fit with the spirit of DataSketches by providing - * fast and approximate answers to complex problems. - */ -package org.apache.datasketches.filters; diff --git a/src/main/java/org/apache/datasketches/frequencies/ErrorType.java b/src/main/java/org/apache/datasketches/frequencies/ErrorType.java deleted file mode 100644 index 050462acd..000000000 --- a/src/main/java/org/apache/datasketches/frequencies/ErrorType.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -/** - * Specifies one of two types of error regions of the statistical classification Confusion Matrix - * that can be excluded from a returned sample of Frequent Items. - */ -public enum ErrorType { - - /** - * No Type I error samples will be included in the sample set, - * which means all Truly Negative samples will be excluded from the sample set. - * However, there may be Type II error samples (False Negatives) - * that should have been included that were not. - * This is a subset of the NO_FALSE_NEGATIVES ErrorType. - */ - NO_FALSE_POSITIVES, - - /** - * No Type II error samples will be excluded from the sample set, - * which means all Truly Positive samples will be included in the sample set. - * However, there may be Type I error samples (False Positives) - * that were included that should not have been. - */ - NO_FALSE_NEGATIVES -} diff --git a/src/main/java/org/apache/datasketches/frequencies/FrequentItemsSketch.java b/src/main/java/org/apache/datasketches/frequencies/FrequentItemsSketch.java deleted file mode 100644 index 857d8e1f6..000000000 --- a/src/main/java/org/apache/datasketches/frequencies/FrequentItemsSketch.java +++ /dev/null @@ -1,751 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.checkBounds; -import static org.apache.datasketches.common.Util.exactLog2OfInt; -import static org.apache.datasketches.common.Util.isPowerOf2; -import static org.apache.datasketches.frequencies.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.frequencies.PreambleUtil.SER_VER; -import static org.apache.datasketches.frequencies.PreambleUtil.extractActiveItems; -import static org.apache.datasketches.frequencies.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.frequencies.PreambleUtil.extractFlags; -import static org.apache.datasketches.frequencies.PreambleUtil.extractLgCurMapSize; -import static org.apache.datasketches.frequencies.PreambleUtil.extractLgMaxMapSize; -import static org.apache.datasketches.frequencies.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.frequencies.PreambleUtil.extractSerVer; -import static org.apache.datasketches.frequencies.PreambleUtil.insertActiveItems; -import static org.apache.datasketches.frequencies.PreambleUtil.insertFamilyID; -import static org.apache.datasketches.frequencies.PreambleUtil.insertFlags; -import static org.apache.datasketches.frequencies.PreambleUtil.insertLgCurMapSize; -import static org.apache.datasketches.frequencies.PreambleUtil.insertLgMaxMapSize; -import static org.apache.datasketches.frequencies.PreambleUtil.insertPreLongs; -import static org.apache.datasketches.frequencies.PreambleUtil.insertSerVer; -import static org.apache.datasketches.frequencies.Util.LG_MIN_MAP_SIZE; -import static org.apache.datasketches.frequencies.Util.SAMPLE_SIZE; - -import java.lang.foreign.MemorySegment; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Objects; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; - -/** - * This sketch is based on the paper https://arxiv.org/abs/1705.07001 - * ("A High-Performance Algorithm for Identifying Frequent Items in Data Streams" - * by Daniel Anderson, Pryce Bevan, Kevin Lang, Edo Liberty, Lee Rhodes, and Justin Thaler) - * and is useful for tracking approximate frequencies of items of type <T> - * with optional associated counts (<T> item, long count) that are members of a - * multiset of such items. The true frequency of an item is defined to be the sum of associated - * counts. - * - *

This implementation provides the following capabilities:

- *
    - *
  • Estimate the frequency of an item.
  • - *
  • Return upper and lower bounds of any item, such that the true frequency is always - * between the upper and lower bounds.
  • - *
  • Return a global maximum error that holds for all items in the stream.
  • - *
  • Return an array of frequent items that qualify either a NO_FALSE_POSITIVES or a - * NO_FALSE_NEGATIVES error type.
  • - *
  • Merge itself with another sketch object created from this class.
  • - *
  • Serialize/Deserialize to/from a byte array.
  • - *
- * - *

Space Usage

- * - *

The sketch is initialized with a maxMapSize that specifies the maximum physical - * length of the internal hash map of the form (<T> item, long count). - * The maxMapSize must be a power of 2.

- * - *

The hash map starts at a very small size (8 entries), and grows as needed up to the - * specified maxMapSize.

- * - *

Excluding external space required for the item objects, the internal memory space usage of - * this sketch is 18 * mapSize bytes (assuming 8 bytes for each Java reference), plus a small - * constant number of additional bytes. The internal memory space usage of this sketch will never - * exceed 18 * maxMapSize bytes, plus a small constant number of additional bytes.

- * - *

Maximum Capacity of the Sketch

- * - *

The LOAD_FACTOR for the hash map is internally set at 75%, - * which means at any time the map capacity of (item, count) pairs is mapCap = 0.75 * - * mapSize. - * The maximum capacity of (item, count) pairs of the sketch is maxMapCap = 0.75 * - * maxMapSize.

- * - *

Updating the sketch with (item, count) pairs

- * - *

If the item is found in the hash map, the mapped count field (the "counter") is - * incremented by the incoming count, otherwise, a new counter "(item, count) pair" is - * created. If the number of tracked counters reaches the maximum capacity of the hash map - * the sketch decrements all of the counters (by an approximately computed median), and - * removes any non-positive counters.

- * - *

Accuracy

- * - *

If fewer than 0.75 * maxMapSize different items are inserted into the sketch the - * estimated frequencies returned by the sketch will be exact.

- * - *

The logic of the frequent items sketch is such that the stored counts and true counts are - * never too different. - * More specifically, for any item, the sketch can return an estimate of the - * true frequency of item, along with upper and lower bounds on the frequency - * (that hold deterministically).

- * - *

For this implementation and for a specific active item, it is guaranteed that - * the true frequency will be between the Upper Bound (UB) and the Lower Bound (LB) computed for - * that item. Specifically, (UB- LB) ≤ W * epsilon, where W denotes the - * sum of all item counts, and epsilon = 3.5/M, where M is the maxMapSize.

- * - *

This is a worst case guarantee that applies to arbitrary inputs.1 - * For inputs typically seen in practice (UB-LB) is usually much smaller. - *

- * - *

Background

- * - *

This code implements a variant of what is commonly known as the "Misra-Gries - * algorithm". Variants of it were discovered and rediscovered and redesigned several times - * over the years:

- *
  • "Finding repeated elements", Misra, Gries, 1982
  • - *
  • "Frequency estimation of Internet packet streams with limited space" Demaine, - * Lopez-Ortiz, Munro, 2002
  • - *
  • "A simple algorithm for finding frequent elements in streams and bags" Karp, Shenker, - * Papadimitriou, 2003
  • - *
  • "Efficient Computation of Frequent and Top-k Elements in Data Streams" Metwally, - * Agrawal, Abbadi, 2006
  • - *
- * - * 1 For speed we do employ some randomization that introduces a small probability that - * our proof of the worst-case bound might not apply to a given run. However, we have ensured - * that this probability is extremely small. For example, if the stream causes one table purge - * (rebuild), our proof of the worst case bound applies with probability at least 1 - 1E-14. - * If the stream causes 1E9 purges, our proof applies with probability at least 1 - 1E-5. - * - * @param The type of item to be tracked by this sketch - * - * @author Justin Thaler - * @author Alexander Saydakov - */ -public class FrequentItemsSketch { - - /** - * Log2 Maximum length of the arrays internal to the hash map supported by the data - * structure. - */ - private int lgMaxMapSize; - - /** - * The current number of counters supported by the hash map. - */ - private int curMapCap; //the threshold to purge - - /** - * Tracks the total of decremented counts. - */ - private long offset; - - /** - * The sum of all frequencies of the stream so far. - */ - private long streamWeight = 0; - - /** - * The maximum number of samples used to compute approximate median of counters when doing - * decrement - */ - private int sampleSize; - - /** - * Hash map mapping stored items to approximate counts - */ - private ReversePurgeItemHashMap hashMap; - - /** - * Construct this sketch with the parameter maxMapSize and the default initialMapSize (8). - * - * @param maxMapSize Determines the physical size of the internal hash map managed by this - * sketch and must be a power of 2. The maximum capacity of this internal hash map is - * 0.75 times * maxMapSize. Both the ultimate accuracy and size of this sketch are - * functions of maxMapSize. - */ - public FrequentItemsSketch(final int maxMapSize) { - this(exactLog2OfInt(maxMapSize, "maxMapSize"), LG_MIN_MAP_SIZE); - } - - /** - * Construct this sketch with parameter lgMaxMapSize and lgCurMapSize. This internal - * constructor is used when deserializing the sketch. - * - * @param lgMaxMapSize Log2 of the physical size of the internal hash map managed by this - * sketch. The maximum capacity of this internal hash map is 0.75 times 2^lgMaxMapSize. - * Both the ultimate accuracy and size of this sketch are functions of lgMaxMapSize. - * - * @param lgCurMapSize Log2 of the starting (current) physical size of the internal hash - * map managed by this sketch. - */ - FrequentItemsSketch(final int lgMaxMapSize, final int lgCurMapSize) { - //set initial size of hash map - this.lgMaxMapSize = Math.max(lgMaxMapSize, LG_MIN_MAP_SIZE); - final int lgCurMapSz = Math.max(lgCurMapSize, LG_MIN_MAP_SIZE); - hashMap = new ReversePurgeItemHashMap<>(1 << lgCurMapSz); - curMapCap = hashMap.getCapacity(); - final int maxMapCap = - (int) ((1 << lgMaxMapSize) * ReversePurgeItemHashMap.getLoadFactor()); - offset = 0; - sampleSize = Math.min(SAMPLE_SIZE, maxMapCap); - } - - /** - * Returns a sketch instance of this class from the given srcSeg, - * which must be a MemorySegment representation of this sketch class. - * - * @param The type of item that this sketch will track - * @param srcSeg a MemorySegment representation of a sketch of this class. - * @param serDe an instance of ArrayOfItemsSerDe - * @return a sketch instance of this class. - */ - public static FrequentItemsSketch getInstance(final MemorySegment srcSeg, - final ArrayOfItemsSerDe serDe) { - Objects.requireNonNull(srcSeg, "srcSeg must not be null."); - Objects.requireNonNull(serDe, "serDe must not be null."); - - final long pre0 = PreambleUtil.checkPreambleSize(srcSeg); //make sure preamble will fit - final int maxPreLongs = Family.FREQUENCY.getMaxPreLongs(); - - final int preLongs = extractPreLongs(pre0); //Byte 0 - final int serVer = extractSerVer(pre0); //Byte 1 - final int familyID = extractFamilyID(pre0); //Byte 2 - final int lgMaxMapSize = extractLgMaxMapSize(pre0); //Byte 3 - final int lgCurMapSize = extractLgCurMapSize(pre0); //Byte 4 - final boolean empty = (extractFlags(pre0) & EMPTY_FLAG_MASK) != 0; //Byte 5 - - // Checks - final boolean preLongsEq1 = (preLongs == 1); //Byte 0 - final boolean preLongsEqMax = (preLongs == maxPreLongs); - if (!preLongsEq1 && !preLongsEqMax) { - throw new SketchesArgumentException( - "Possible Corruption: PreLongs must be 1 or " + maxPreLongs + ": " + preLongs); - } - if (serVer != SER_VER) { //Byte 1 - throw new SketchesArgumentException( - "Possible Corruption: Ser Ver must be " + SER_VER + ": " + serVer); - } - final int actFamID = Family.FREQUENCY.getID(); //Byte 2 - if (familyID != actFamID) { - throw new SketchesArgumentException( - "Possible Corruption: FamilyID must be " + actFamID + ": " + familyID); - } - if (empty ^ preLongsEq1) { //Byte 5 and Byte 0 - throw new SketchesArgumentException( - "Possible Corruption: (PreLongs == 1) ^ Empty == True."); - } - - if (empty) { - return new FrequentItemsSketch<>(lgMaxMapSize, LG_MIN_MAP_SIZE); - } - //get full preamble - final long[] preArr = new long[preLongs]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, 0, preArr, 0, preLongs); - - final FrequentItemsSketch fis = new FrequentItemsSketch<>(lgMaxMapSize, lgCurMapSize); - fis.streamWeight = 0; //update after - fis.offset = preArr[3]; - - final int preBytes = preLongs << 3; - final int activeItems = extractActiveItems(preArr[1]); - - //Get countArray - final long[] countArray = new long[activeItems]; - final long reqBytes = (preBytes + ((long)activeItems * Long.BYTES)); //count Arr only - checkBounds(0, reqBytes, srcSeg.byteSize()); //check MemorySegment capacity - - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, preBytes, countArray, 0, activeItems); - - //Get itemArray - final int itemsOffset = preBytes + (Long.BYTES * activeItems); - final T[] itemArray = serDe.deserializeFromMemorySegment(srcSeg.asSlice(itemsOffset), 0, activeItems); - //update the sketch - for (int i = 0; i < activeItems; i++) { - fis.update(itemArray[i], countArray[i]); - } - fis.streamWeight = preArr[2]; //override streamWeight due to updating - return fis; - } - - /** - * Returns the estimated a priori error given the maxMapSize for the sketch and the - * estimatedTotalStreamWeight. - * @param maxMapSize the planned map size to be used when constructing this sketch. - * @param estimatedTotalStreamWeight the estimated total stream weight. - * @return the estimated a priori error. - */ - public static double getAprioriError(final int maxMapSize, final long estimatedTotalStreamWeight) { - return getEpsilon(maxMapSize) * estimatedTotalStreamWeight; - } - - /** - * Returns the current number of counters the sketch is configured to support. - * - * @return the current number of counters the sketch is configured to support. - */ - public int getCurrentMapCapacity() { - return curMapCap; - } - - /** - * Returns epsilon used to compute a priori error. - * This is just the value 3.5 / maxMapSize. - * @param maxMapSize the planned map size to be used when constructing this sketch. - * @return epsilon used to compute a priori error. - */ - public static double getEpsilon(final int maxMapSize) { - if (!isPowerOf2(maxMapSize)) { - throw new SketchesArgumentException("maxMapSize is not a power of 2."); - } - return 3.5 / maxMapSize; - } - - /** - * Gets the estimate of the frequency of the given item. - * Note: The true frequency of a item would be the sum of the counts as a result of the - * two update functions. - * - * @param item the given item - * @return the estimate of the frequency of the given item - */ - public long getEstimate(final T item) { - // If item is tracked: - // Estimate = itemCount + offset; Otherwise it is 0. - final long itemCount = hashMap.get(item); - return (itemCount > 0) ? itemCount + offset : 0; - } - - /** - * Gets the guaranteed lower bound frequency of the given item, which can never be - * negative. - * - * @param item the given item. - * @return the guaranteed lower bound frequency of the given item. That is, a number which - * is guaranteed to be no larger than the real frequency. - */ - public long getLowerBound(final T item) { - //LB = itemCount or 0 - return hashMap.get(item); - } - - /** - * Returns an array of Rows that include frequent items, estimates, upper and lower bounds - * given a threshold and an ErrorCondition. If the threshold is lower than getMaximumError(), - * then getMaximumError() will be used instead. - * - *

The method first examines all active items in the sketch (items that have a counter). - * - *

If ErrorType = NO_FALSE_NEGATIVES, this will include an item in the result - * list if getUpperBound(item) > threshold. - * There will be no false negatives, i.e., no Type II error. - * There may be items in the set with true frequencies less than the threshold - * (false positives).

- * - *

If ErrorType = NO_FALSE_POSITIVES, this will include an item in the result - * list if getLowerBound(item) > threshold. - * There will be no false positives, i.e., no Type I error. - * There may be items omitted from the set with true frequencies greater than the - * threshold (false negatives).

- * - * @param threshold to include items in the result list - * @param errorType determines whether no false positives or no false negatives are - * desired. - * @return an array of frequent items - */ - public Row[] getFrequentItems(final long threshold, final ErrorType errorType) { - return sortItems(threshold > getMaximumError() ? threshold : getMaximumError(), errorType); - } - - /** - * Returns an array of Rows that include frequent items, estimates, upper and lower bounds - * given an ErrorCondition and the default threshold. - * This is the same as getFrequentItems(getMaximumError(), errorType) - * - * @param errorType determines whether no false positives or no false negatives are - * desired. - * @return an array of frequent items - */ - public Row[] getFrequentItems(final ErrorType errorType) { - return sortItems(getMaximumError(), errorType); - } - - /** - * Returns an upper bound on the maximum error of getEstimate(item) for any item. - * @return An upper bound on the maximum error of getEstimate(item) for any item. - * This is equivalent to the maximum distance between the upper bound and the lower bound - * for any item. - */ - public long getMaximumError() { - return offset; - } - - /** - * Returns the maximum number of counters the sketch is configured to support. - * - * @return the maximum number of counters the sketch is configured to support. - */ - public int getMaximumMapCapacity() { - return (int) ((1 << lgMaxMapSize) * ReversePurgeLongHashMap.getLoadFactor()); - } - - /** - * Returns the number of active items in the sketch. - * @return the number of active items in the sketch. - */ - public int getNumActiveItems() { - return hashMap.getNumActive(); - } - - /** - * Returns the sum of the frequencies in the stream seen so far by the sketch - * - * @return the sum of the frequencies in the stream seen so far by the sketch - */ - public long getStreamLength() { - return streamWeight; - } - - /** - * Gets the guaranteed upper bound frequency of the given item. - * - * @param item the given item - * @return the guaranteed upper bound frequency of the given item. That is, a number which - * is guaranteed to be no smaller than the real frequency. - */ - public long getUpperBound(final T item) { - // UB = itemCount + offset - return hashMap.get(item) + offset; - } - - /** - * Returns true if this sketch is empty - * - * @return true if this sketch is empty - */ - public boolean isEmpty() { - return getNumActiveItems() == 0; - } - - /** - * This function merges the other sketch into this one. - * The other sketch may be of a different size. - * - * @param other sketch of this class - * @return a sketch whose estimates are within the guarantees of the - * largest error tolerance of the two merged sketches. - */ - public FrequentItemsSketch merge(final FrequentItemsSketch other) { - if ((other == null) || other.isEmpty()) { return this; } - - final long streamLen = streamWeight + other.streamWeight; //capture before merge - - final ReversePurgeItemHashMap.Iterator iter = other.hashMap.iterator(); - while (iter.next()) { //this may add to offset during rebuilds - this.update(iter.getKey(), iter.getValue()); - } - offset += other.offset; - streamWeight = streamLen; //corrected streamWeight - return this; - } - - /** - * Resets this sketch to a virgin state. - */ - public void reset() { - hashMap = new ReversePurgeItemHashMap<>(1 << LG_MIN_MAP_SIZE); - curMapCap = hashMap.getCapacity(); - offset = 0; - streamWeight = 0; - } - - //Serialization - - /** - * Returns a byte array representation of this sketch - * @param serDe an instance of ArrayOfItemsSerDe - * @return a byte array representation of this sketch - */ - public byte[] toByteArray(final ArrayOfItemsSerDe serDe) { - final int preLongs; - final int outBytes; - final boolean empty = isEmpty(); - final int activeItems = getNumActiveItems(); - byte[] bytes = null; - if (empty) { - preLongs = 1; - outBytes = 8; - } else { - preLongs = Family.FREQUENCY.getMaxPreLongs(); - bytes = serDe.serializeToByteArray(hashMap.getActiveKeys()); - outBytes = ((preLongs + activeItems) << 3) + bytes.length; - } - final byte[] outArr = new byte[outBytes]; - final MemorySegment seg = MemorySegment.ofArray(outArr); - - // build first preLong empty or not - long pre0 = 0L; - pre0 = insertPreLongs(preLongs, pre0); //Byte 0 - pre0 = insertSerVer(SER_VER, pre0); //Byte 1 - pre0 = insertFamilyID(Family.FREQUENCY.getID(), pre0); //Byte 2 - pre0 = insertLgMaxMapSize(lgMaxMapSize, pre0); //Byte 3 - pre0 = insertLgCurMapSize(hashMap.getLgLength(), pre0); //Byte 4 - pre0 = empty ? insertFlags(EMPTY_FLAG_MASK, pre0) : insertFlags(0, pre0); //Byte 5 - - if (empty) { - seg.set(JAVA_LONG_UNALIGNED, 0, pre0); - } else { - final long pre = 0; - final long[] preArr = new long[preLongs]; - preArr[0] = pre0; - preArr[1] = insertActiveItems(activeItems, pre); - preArr[2] = streamWeight; - preArr[3] = offset; - MemorySegment.copy(preArr, 0, seg, JAVA_LONG_UNALIGNED, 0, preLongs); - - final int preBytes = preLongs << 3; - MemorySegment.copy(hashMap.getActiveValues(), 0, seg, JAVA_LONG_UNALIGNED, preBytes, activeItems); - MemorySegment.copy(bytes, 0, seg, JAVA_BYTE, preBytes + (activeItems << 3), bytes.length); - } - return outArr; - } - - /** - * Returns a human readable summary of this sketch. - * @return a human readable summary of this sketch. - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("FrequentItemsSketch:").append(LS); - sb.append(" Stream Length : " + streamWeight).append(LS); - sb.append(" Max Error Offset : " + offset).append(LS); - sb.append(hashMap.toString()); - return sb.toString(); - } - - /** - * Returns a human readable string of the preamble of a byte array image of a FrequentItemsSketch. - * @param byteArr the given byte array - * @return a human readable string of the preamble of a byte array image of a FrequentItemsSketch. - */ - public static String toString(final byte[] byteArr) { - return toString(MemorySegment.ofArray(byteArr)); - } - - /** - * Returns a human readable string of the preamble of a MemorySegment image of a FrequentItemsSketch. - * @param seg the given MemorySegment object - * @return a human readable string of the preamble of a MemorySegment image of a FrequentItemsSketch. - */ - public static String toString(final MemorySegment seg) { - return PreambleUtil.preambleToString(seg); - } - - /** - * Update this sketch with an item and a frequency count of one. - * @param item for which the frequency should be increased. - */ - public void update(final T item) { - update(item, 1); - } - - /** - * Update this sketch with an item and a positive frequency count. - * @param item for which the frequency should be increased. The sketch uses - * hashCode() and equals() methods of the type T. - * @param count the amount by which the frequency of the item should be increased. - * A count of zero is a no-op, and a negative count will throw an exception. - */ - public void update(final T item, final long count) { - if ((item == null) || (count == 0)) { - return; - } - if (count < 0) { - throw new SketchesArgumentException("Count may not be negative"); - } - streamWeight += count; - hashMap.adjustOrPutValue(item, count); - - if (getNumActiveItems() > curMapCap) { //over the threshold, we need to do something - if (hashMap.getLgLength() < lgMaxMapSize) { //below tgt size, we can grow - hashMap.resize(2 * hashMap.getLength()); - curMapCap = hashMap.getCapacity(); - } else { //At tgt size, must purge - offset += hashMap.purge(sampleSize); - if (getNumActiveItems() > getMaximumMapCapacity()) { - throw new SketchesStateException("Purge did not reduce active items."); - } - } - } - } - - /** - * Row class that defines the return values from a getFrequentItems query. - * @param type of item - */ - public static class Row implements Comparable> { - final T item; - final long est; - final long ub; - final long lb; - private static final String FMT = " %12d%12d%12d %s"; - private static final String HFMT = " %12s%12s%12s %s"; - - Row(final T item, final long estimate, final long ub, final long lb) { - this.item = item; - est = estimate; - this.ub = ub; - this.lb = lb; - } - - /** - * Returns an item of type T - * @return item of type T - */ - public T getItem() { return item; } - - /** - * Returns the estimate - * @return the estimate - */ - public long getEstimate() { return est; } - - /** - * Returns the upper bound - * @return the upper bound - */ - public long getUpperBound() { return ub; } - - /** - * Returns the lower bound - * @return return the lower bound - */ - public long getLowerBound() { return lb; } - - /** - * Returns the descriptive row header - * @return the descriptive row header - */ - public static String getRowHeader() { - return String.format(HFMT,"Est", "UB", "LB", "Item"); - } - - @Override - public String toString() { - return String.format(FMT, est, ub, lb, item.toString()); - } - - /** - * This compareTo is strictly limited to the Row.getEstimate() value and does not imply any - * ordering whatsoever to the other elements of the row: item and upper and lower bounds. - * Defined this way, this compareTo will be consistent with hashCode() and equals(Object). - * @param that the other row to compare to. - * @return a negative integer, zero, or a positive integer as this.getEstimate() is less than, - * equal to, or greater than that.getEstimate(). - */ - @Override - public int compareTo(final Row that) { - return (est < that.est) ? -1 : (est > that.est) ? 1 : 0; - } - - /** - * This hashCode is computed only from the Row.getEstimate() value. - * Defined this way, this hashCode will be consistent with equals(Object):
- * If (x.equals(y)) implies: x.hashCode() == y.hashCode().
- * If (!x.equals(y)) does NOT imply: x.hashCode() != y.hashCode(). - * @return the hashCode computed from getEstimate(). - */ - @Override - public int hashCode() { - final int prime = 31; - final int result = 1; - return (prime * result) + (int) (est ^ (est >>> 32)); - } - - /** - * This equals is computed only from the Row.getEstimate() value and does not imply equality - * of the other items within the row: item and upper and lower bounds. - * Defined this way, this equals will be consistent with compareTo(Row). - * @param obj the other row to determine equality with. - * @return true if this.getEstimate() equals ((Row<T>)obj).getEstimate(). - */ - @SuppressWarnings("unchecked") - @Override - public boolean equals(final Object obj) { - if (this == obj) { return true; } - if ( (obj == null) || !(obj instanceof Row)) { return false; } - final Row that = (Row) obj; - if (est != that.est) { return false; } - return true; - } - - } //End of class Row - - @SuppressWarnings("unchecked") - Row[] sortItems(final long threshold, final ErrorType errorType) { - final ArrayList> rowList = new ArrayList<>(); - final ReversePurgeItemHashMap.Iterator iter = hashMap.iterator(); - if (errorType == ErrorType.NO_FALSE_NEGATIVES) { - while (iter.next()) { - final long est = getEstimate(iter.getKey()); - final long ub = getUpperBound(iter.getKey()); - final long lb = getLowerBound(iter.getKey()); - if (ub >= threshold) { - final Row row = new Row<>(iter.getKey(), est, ub, lb); - rowList.add(row); - } - } - } else { //NO_FALSE_POSITIVES - while (iter.next()) { - final long est = getEstimate(iter.getKey()); - final long ub = getUpperBound(iter.getKey()); - final long lb = getLowerBound(iter.getKey()); - if (lb >= threshold) { - final Row row = new Row<>(iter.getKey(), est, ub, lb); - rowList.add(row); - } - } - } - - // descending order - rowList.sort(new Comparator>() { - @Override - public int compare(final Row r1, final Row r2) { - return r2.compareTo(r1); - } - }); - - return rowList.toArray((Row[]) Array.newInstance(Row.class, rowList.size())); - } - -} diff --git a/src/main/java/org/apache/datasketches/frequencies/FrequentLongsSketch.java b/src/main/java/org/apache/datasketches/frequencies/FrequentLongsSketch.java deleted file mode 100644 index f20e97352..000000000 --- a/src/main/java/org/apache/datasketches/frequencies/FrequentLongsSketch.java +++ /dev/null @@ -1,835 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.checkBounds; -import static org.apache.datasketches.common.Util.exactLog2OfInt; -import static org.apache.datasketches.common.Util.isPowerOf2; -import static org.apache.datasketches.frequencies.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.frequencies.PreambleUtil.SER_VER; -import static org.apache.datasketches.frequencies.PreambleUtil.extractActiveItems; -import static org.apache.datasketches.frequencies.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.frequencies.PreambleUtil.extractFlags; -import static org.apache.datasketches.frequencies.PreambleUtil.extractLgCurMapSize; -import static org.apache.datasketches.frequencies.PreambleUtil.extractLgMaxMapSize; -import static org.apache.datasketches.frequencies.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.frequencies.PreambleUtil.extractSerVer; -import static org.apache.datasketches.frequencies.PreambleUtil.insertActiveItems; -import static org.apache.datasketches.frequencies.PreambleUtil.insertFamilyID; -import static org.apache.datasketches.frequencies.PreambleUtil.insertFlags; -import static org.apache.datasketches.frequencies.PreambleUtil.insertLgCurMapSize; -import static org.apache.datasketches.frequencies.PreambleUtil.insertLgMaxMapSize; -import static org.apache.datasketches.frequencies.PreambleUtil.insertPreLongs; -import static org.apache.datasketches.frequencies.PreambleUtil.insertSerVer; -import static org.apache.datasketches.frequencies.Util.LG_MIN_MAP_SIZE; -import static org.apache.datasketches.frequencies.Util.SAMPLE_SIZE; - -import java.lang.foreign.MemorySegment; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Objects; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.SuppressFBWarnings; - -/** - * This sketch is based on the paper https://arxiv.org/abs/1705.07001 - * ("A High-Performance Algorithm for Identifying Frequent Items in Data Streams" - * by Daniel Anderson, Pryce Bevan, Kevin Lang, Edo Liberty, Lee Rhodes, and Justin Thaler) - * and is useful for tracking approximate frequencies of long items with optional - * associated counts (long item, long count) that are members of a multiset of - * such items. The true frequency of an item is defined to be the sum of associated counts. - * - *

This implementation provides the following capabilities:

- *
    - *
  • Estimate the frequency of an item.
  • - *
  • Return upper and lower bounds of any item, such that the true frequency is always - * between the upper and lower bounds.
  • - *
  • Return a global maximum error that holds for all items in the stream.
  • - *
  • Return an array of frequent items that qualify either a NO_FALSE_POSITIVES or a - * NO_FALSE_NEGATIVES error type.
  • - *
  • Merge itself with another sketch object created from this class.
  • - *
  • Serialize/Deserialize to/from a String or byte array.
  • - *
- * - *

Space Usage

- * - *

The sketch is initialized with a maxMapSize that specifies the maximum physical - * length of the internal hash map of the form (long item, long count). - * The maxMapSize must be a power of 2.

- * - *

The hash map starts at a very small size (8 entries), and grows as needed up to the - * specified maxMapSize.

- * - *

At any moment the internal memory space usage of this sketch is 18 * mapSize bytes, - * plus a small constant number of additional bytes. The maximum internal memory space usage of - * this sketch will never exceed 18 * maxMapSize bytes, plus a small constant number of - * additional bytes.

- * - *

Maximum Capacity of the Sketch

- * - *

The LOAD_FACTOR for the hash map is internally set at 75%, - * which means at any time the map capacity of (item, count) pairs is mapCap = - * 0.75 * mapSize. - * The maximum capacity of (item, count) pairs of the sketch is maxMapCap = - * 0.75 * maxMapSize.

- * - *

Updating the sketch with (item, count) pairs

- * - *

If the item is found in the hash map, the mapped count field (the "counter") is - * incremented by the incoming count, otherwise, a new counter "(item, count) pair" is - * created. If the number of tracked counters reaches the maximum capacity of the hash map - * the sketch decrements all of the counters (by an approximately computed median), and - * removes any non-positive counters.

- * - *

Accuracy

- * - *

If fewer than 0.75 * maxMapSize different items are inserted into the sketch the - * estimated frequencies returned by the sketch will be exact.

- * - *

The logic of the frequent items sketch is such that the stored counts and true counts are - * never too different. - * More specifically, for any item, the sketch can return an estimate of the - * true frequency of item, along with upper and lower bounds on the frequency - * (that hold deterministically).

- * - *

For this implementation and for a specific active item, it is guaranteed that - * the true frequency will be between the Upper Bound (UB) and the Lower Bound (LB) computed for - * that item. Specifically, (UB- LB) ≤ W * epsilon, where W denotes the - * sum of all item counts, and epsilon = 3.5/M, where M is the maxMapSize.

- * - *

This is a worst case guarantee that applies to arbitrary inputs.1 - * For inputs typically seen in practice (UB-LB) is usually much smaller. - *

- * - *

Background

- * - *

This code implements a variant of what is commonly known as the "Misra-Gries - * algorithm". Variants of it were discovered and rediscovered and redesigned several times - * over the years:

- *
  • "Finding repeated elements", Misra, Gries, 1982
  • - *
  • "Frequency estimation of Internet packet streams with limited space" Demaine, - * Lopez-Ortiz, Munro, 2002
  • - *
  • "A simple algorithm for finding frequent elements in streams and bags" Karp, Shenker, - * Papadimitriou, 2003
  • - *
  • "Efficient Computation of Frequent and Top-k Elements in Data Streams" Metwally, - * Agrawal, Abbadi, 2006
  • - *
- * - * 1 For speed we do employ some randomization that introduces a small probability that - * our proof of the worst-case bound might not apply to a given run. However, we have ensured - * that this probability is extremely small. For example, if the stream causes one table purge - * (rebuild), our proof of the worst case bound applies with probability at least 1 - 1E-14. - * If the stream causes 1E9 purges, our proof applies with probability at least 1 - 1E-5. - * - * @author Justin Thaler - * @author Lee Rhodes - */ -@SuppressFBWarnings(value = "SIC_INNER_SHOULD_BE_STATIC_ANON", justification = "Harmless, fix later") -public class FrequentLongsSketch { - - private static final int STR_PREAMBLE_TOKENS = 6; - - /** - * Log2 Maximum length of the arrays internal to the hash map supported by the data - * structure. - */ - private final int lgMaxMapSize; - - /** - * The current number of counters supported by the hash map. - */ - private int curMapCap; //the threshold to purge - - /** - * Tracks the total of decremented counts. - */ - private long offset; - - /** - * The sum of all frequencies of the stream so far. - */ - private long streamWeight = 0; - - /** - * The maximum number of samples used to compute approximate median of counters when doing - * decrement - */ - private final int sampleSize; - - /** - * Hash map mapping stored items to approximate counts - */ - private ReversePurgeLongHashMap hashMap; - - /** - * Construct this sketch with the parameter maxMapSize and the default initialMapSize (8). - * - * @param maxMapSize Determines the physical size of the internal hash map managed by this - * sketch and must be a power of 2. The maximum capacity of this internal hash map is - * 0.75 times * maxMapSize. Both the ultimate accuracy and size of this sketch are a - * function of maxMapSize. - */ - public FrequentLongsSketch(final int maxMapSize) { - this(exactLog2OfInt(maxMapSize, "maxMapSize"), LG_MIN_MAP_SIZE); - } - - /** - * Construct this sketch with parameter lgMapMapSize and lgCurMapSize. This internal - * constructor is used when deserializing the sketch. - * - * @param lgMaxMapSize Log2 of the physical size of the internal hash map managed by this - * sketch. The maximum capacity of this internal hash map is 0.75 times 2^lgMaxMapSize. - * Both the ultimate accuracy and size of this sketch are a function of lgMaxMapSize. - * - * @param lgCurMapSize Log2 of the starting (current) physical size of the internal hash - * map managed by this sketch. - */ - FrequentLongsSketch(final int lgMaxMapSize, final int lgCurMapSize) { - //set initial size of hash map - this.lgMaxMapSize = Math.max(lgMaxMapSize, LG_MIN_MAP_SIZE); - final int lgCurMapSz = Math.max(lgCurMapSize, LG_MIN_MAP_SIZE); - hashMap = new ReversePurgeLongHashMap(1 << lgCurMapSz); - curMapCap = hashMap.getCapacity(); - final int maxMapCap = - (int) ((1 << lgMaxMapSize) * ReversePurgeLongHashMap.getLoadFactor()); - offset = 0; - sampleSize = Math.min(SAMPLE_SIZE, maxMapCap); - } - - /** - * Returns a sketch instance of this class from the given srcSeg, - * which must be a MemorySegment representation of this sketch class. - * - * @param srcSeg a MemorySegment representation of a sketch of this class. - * @return a sketch instance of this class. - */ - public static FrequentLongsSketch getInstance(final MemorySegment srcSeg) { - Objects.requireNonNull(srcSeg, "Source MemorySegment must not be null."); - final long pre0 = PreambleUtil.checkPreambleSize(srcSeg); //check MemorySegment capacity - final int maxPreLongs = Family.FREQUENCY.getMaxPreLongs(); - - final int preLongs = extractPreLongs(pre0); //Byte 0 - final int serVer = extractSerVer(pre0); //Byte 1 - final int familyID = extractFamilyID(pre0); //Byte 2 - final int lgMaxMapSize = extractLgMaxMapSize(pre0); //Byte 3 - final int lgCurMapSize = extractLgCurMapSize(pre0); //Byte 4 - final boolean empty = (extractFlags(pre0) & EMPTY_FLAG_MASK) != 0; //Byte 5 - - // Checks - final boolean preLongsEq1 = (preLongs == 1); //Byte 0 - final boolean preLongsEqMax = (preLongs == maxPreLongs); - if (!preLongsEq1 && !preLongsEqMax) { - throw new SketchesArgumentException( - "Possible Corruption: PreLongs must be 1 or " + maxPreLongs + ": " + preLongs); - } - if (serVer != SER_VER) { //Byte 1 - throw new SketchesArgumentException( - "Possible Corruption: Ser Ver must be " + SER_VER + ": " + serVer); - } - final int actFamID = Family.FREQUENCY.getID(); //Byte 2 - if (familyID != actFamID) { - throw new SketchesArgumentException( - "Possible Corruption: FamilyID must be " + actFamID + ": " + familyID); - } - if (empty ^ preLongsEq1) { //Byte 5 and Byte 0 - throw new SketchesArgumentException( - "Possible Corruption: (PreLongs == 1) ^ Empty == True."); - } - - if (empty) { - return new FrequentLongsSketch(lgMaxMapSize, LG_MIN_MAP_SIZE); - } - //get full preamble - final long[] preArr = new long[preLongs]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, 0, preArr, 0, preLongs); - - final FrequentLongsSketch fls = new FrequentLongsSketch(lgMaxMapSize, lgCurMapSize); - fls.streamWeight = 0; //update after - fls.offset = preArr[3]; - - final int preBytes = preLongs << 3; - final int activeItems = extractActiveItems(preArr[1]); - - //Get countArray - final long[] countArray = new long[activeItems]; - final int reqBytes = preBytes + (2 * activeItems * Long.BYTES); //count Arr + Items Arr - checkBounds(0, reqBytes, srcSeg.byteSize()); //check MemorySegment capacity - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, preBytes, countArray, 0, activeItems); - - //Get itemArray - final int itemsOffset = preBytes + (Long.BYTES * activeItems); - final long[] itemArray = new long[activeItems]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, itemsOffset, itemArray, 0, activeItems); - //update the sketch - for (int i = 0; i < activeItems; i++) { - fls.update(itemArray[i], countArray[i]); - } - fls.streamWeight = preArr[2]; //override streamWeight due to updating - return fls; - } - - /** - * Returns a sketch instance of this class from the given String, - * which must be a String representation of this sketch class. - * - * @param string a String representation of a sketch of this class. - * @return a sketch instance of this class. - */ - public static FrequentLongsSketch getInstance(final String string) { - Objects.requireNonNull(string, "string must not be null."); - final String[] tokens = string.split(","); - if (tokens.length < (STR_PREAMBLE_TOKENS + 2)) { - throw new SketchesArgumentException( - "String not long enough: " + tokens.length); - } - final int serVer = Integer.parseInt(tokens[0]); - final int famID = Integer.parseInt(tokens[1]); - final int lgMax = Integer.parseInt(tokens[2]); - final int flags = Integer.parseInt(tokens[3]); - final long streamWt = Long.parseLong(tokens[4]); - final long offset = Long.parseLong(tokens[5]); //error offset - //should always get at least the next 2 from the map - final int numActive = Integer.parseInt(tokens[6]); - final int lgCur = Integer.numberOfTrailingZeros(Integer.parseInt(tokens[7])); - - //checks - if (serVer != SER_VER) { - throw new SketchesArgumentException("Possible Corruption: Bad SerVer: " + serVer); - } - Family.FREQUENCY.checkFamilyID(famID); - final boolean empty = flags > 0; - if (!empty && (numActive == 0)) { - throw new SketchesArgumentException( - "Possible Corruption: !Empty && NumActive=0; strLen: " + numActive); - } - final int numTokens = tokens.length; - if ((2 * numActive) != (numTokens - STR_PREAMBLE_TOKENS - 2)) { - throw new SketchesArgumentException( - "Possible Corruption: Incorrect # of tokens: " + numTokens - + ", numActive: " + numActive); - } - - final FrequentLongsSketch sketch = new FrequentLongsSketch(lgMax, lgCur); - sketch.streamWeight = streamWt; - sketch.offset = offset; - sketch.hashMap = deserializeFromStringArray(tokens); - return sketch; - } - - /** - * Returns the estimated a priori error given the maxMapSize for the sketch and the - * estimatedTotalStreamWeight. - * @param maxMapSize the planned map size to be used when constructing this sketch. - * @param estimatedTotalStreamWeight the estimated total stream weight. - * @return the estimated a priori error. - */ - public static double getAprioriError(final int maxMapSize, final long estimatedTotalStreamWeight) { - return getEpsilon(maxMapSize) * estimatedTotalStreamWeight; - } - - /** - * Returns the current number of counters the sketch is configured to support. - * - * @return the current number of counters the sketch is configured to support. - */ - public int getCurrentMapCapacity() { - return curMapCap; - } - - /** - * Returns epsilon used to compute a priori error. - * This is just the value 3.5 / maxMapSize. - * @param maxMapSize the planned map size to be used when constructing this sketch. - * @return epsilon used to compute a priori error. - */ - public static double getEpsilon(final int maxMapSize) { - if (!isPowerOf2(maxMapSize)) { - throw new SketchesArgumentException("maxMapSize is not a power of 2."); - } - return 3.5 / maxMapSize; - } - - /** - * Gets the estimate of the frequency of the given item. - * Note: The true frequency of a item would be the sum of the counts as a result of the - * two update functions. - * - * @param item the given item - * @return the estimate of the frequency of the given item - */ - public long getEstimate(final long item) { - // If item is tracked: - // Estimate = itemCount + offset; Otherwise it is 0. - final long itemCount = hashMap.get(item); - return (itemCount > 0) ? itemCount + offset : 0; - } - - /** - * Gets the guaranteed lower bound frequency of the given item, which can never be - * negative. - * - * @param item the given item. - * @return the guaranteed lower bound frequency of the given item. That is, a number which - * is guaranteed to be no larger than the real frequency. - */ - public long getLowerBound(final long item) { - //LB = itemCount or 0 - return hashMap.get(item); - } - - /** - * Returns an array of Rows that include frequent items, estimates, upper and lower bounds - * given a threshold and an ErrorCondition. If the threshold is lower than getMaximumError(), - * then getMaximumError() will be used instead. - * - *

The method first examines all active items in the sketch (items that have a counter). - * - *

If ErrorType = NO_FALSE_NEGATIVES, this will include an item in the result - * list if getUpperBound(item) > threshold. - * There will be no false negatives, i.e., no Type II error. - * There may be items in the set with true frequencies less than the threshold - * (false positives).

- * - *

If ErrorType = NO_FALSE_POSITIVES, this will include an item in the result - * list if getLowerBound(item) > threshold. - * There will be no false positives, i.e., no Type I error. - * There may be items omitted from the set with true frequencies greater than the - * threshold (false negatives). This is a subset of the NO_FALSE_NEGATIVES case.

- * - * @param threshold to include items in the result list - * @param errorType determines whether no false positives or no false negatives are - * desired. - * @return an array of frequent items - */ - public Row[] getFrequentItems(final long threshold, final ErrorType errorType) { - return sortItems(threshold > getMaximumError() ? threshold : getMaximumError(), errorType); - } - - /** - * Returns an array of Rows that include frequent items, estimates, upper and lower bounds - * given an ErrorCondition and the default threshold. - * This is the same as getFrequentItems(getMaximumError(), errorType) - * - * @param errorType determines whether no false positives or no false negatives are - * desired. - * @return an array of frequent items - */ - public Row[] getFrequentItems(final ErrorType errorType) { - return sortItems(getMaximumError(), errorType); - } - - /** - * Returns an upper bound on the maximum error of getEstimate(item) for any item. - * @return An upper bound on the maximum error of getEstimate(item) for any item. - * This is equivalent to the maximum distance between the upper bound and the lower bound - * for any item. - */ - public long getMaximumError() { - return offset; - } - - /** - * Returns the maximum number of counters the sketch is configured to support. - * - * @return the maximum number of counters the sketch is configured to support. - */ - public int getMaximumMapCapacity() { - return (int) ((1 << lgMaxMapSize) * ReversePurgeLongHashMap.getLoadFactor()); - } - - /** - * Returns the number of active items in the sketch. - * @return the number of active items in the sketch. - */ - public int getNumActiveItems() { - return hashMap.getNumActive(); - } - - /** - * Returns the number of bytes required to store this sketch as an array of bytes. - * - * @return the number of bytes required to store this sketch as an array of bytes. - */ - public int getStorageBytes() { - if (isEmpty()) { return 8; } - return (4 * 8) + (16 * getNumActiveItems()); - } - - /** - * Returns the sum of the frequencies (weights or counts) in the stream seen so far by the sketch - * - * @return the sum of the frequencies in the stream seen so far by the sketch - */ - public long getStreamLength() { - return streamWeight; - } - - /** - * Gets the guaranteed upper bound frequency of the given item. - * - * @param item the given item - * @return the guaranteed upper bound frequency of the given item. That is, a number which - * is guaranteed to be no smaller than the real frequency. - */ - public long getUpperBound(final long item) { - // UB = itemCount + offset - return hashMap.get(item) + offset; - } - - /** - * Returns true if this sketch is empty - * - * @return true if this sketch is empty - */ - public boolean isEmpty() { - return getNumActiveItems() == 0; - } - - /** - * This function merges the other sketch into this one. - * The other sketch may be of a different size. - * - * @param other sketch of this class - * @return a sketch whose estimates are within the guarantees of the - * largest error tolerance of the two merged sketches. - */ - public FrequentLongsSketch merge(final FrequentLongsSketch other) { - if ((other == null) || other.isEmpty()) { return this; } - - final long streamWt = streamWeight + other.streamWeight; //capture before merge - - final ReversePurgeLongHashMap.Iterator iter = other.hashMap.iterator(); - while (iter.next()) { //this may add to offset during rebuilds - this.update(iter.getKey(), iter.getValue()); - } - offset += other.offset; - streamWeight = streamWt; //corrected streamWeight - return this; - } - - /** - * Resets this sketch to a virgin state. - */ - public void reset() { - hashMap = new ReversePurgeLongHashMap(1 << LG_MIN_MAP_SIZE); - curMapCap = hashMap.getCapacity(); - offset = 0; - streamWeight = 0; - } - - //Serialization - - /** - * Returns a String representation of this sketch - * - * @return a String representation of this sketch - */ - public String serializeToString() { - final StringBuilder sb = new StringBuilder(); - //start the string with parameters of the sketch - final int serVer = SER_VER; //0 - final int famID = Family.FREQUENCY.getID(); //1 - final int lgMaxMapSz = lgMaxMapSize; //2 - final int flags = (hashMap.getNumActive() == 0) ? EMPTY_FLAG_MASK : 0; //3 - final String fmt = "%d,%d,%d,%d,%d,%d,"; - final String s = - String.format(fmt, serVer, famID, lgMaxMapSz, flags, streamWeight, offset); - sb.append(s); - sb.append(hashMap.serializeToString()); //numActive, curMaplen, key[i], value[i], ... - // maxMapCap, sample size are deterministic functions of maxMapSize, - // so we don't need them in the serialization - return sb.toString(); - } - - /** - * Returns a byte array representation of this sketch - * @return a byte array representation of this sketch - */ - public byte[] toByteArray() { - final int preLongs, outBytes; - final boolean empty = isEmpty(); - final int activeItems = getNumActiveItems(); - if (empty) { - preLongs = 1; - outBytes = 8; - } else { - preLongs = Family.FREQUENCY.getMaxPreLongs(); //4 - outBytes = (preLongs + (2 * activeItems)) << 3; //2 because both keys and values are longs - } - final byte[] outArr = new byte[outBytes]; - final MemorySegment seg = MemorySegment.ofArray(outArr); - - // build first preLong empty or not - long pre0 = 0L; - pre0 = insertPreLongs(preLongs, pre0); //Byte 0 - pre0 = insertSerVer(SER_VER, pre0); //Byte 1 - pre0 = insertFamilyID(Family.FREQUENCY.getID(), pre0); //Byte 2 - pre0 = insertLgMaxMapSize(lgMaxMapSize, pre0); //Byte 3 - pre0 = insertLgCurMapSize(hashMap.getLgLength(), pre0); //Byte 4 - pre0 = (empty) ? insertFlags(EMPTY_FLAG_MASK, pre0) : insertFlags(0, pre0); //Byte 5 - - if (empty) { - seg.set(JAVA_LONG_UNALIGNED, 0, pre0); - } else { - final long pre = 0; - final long[] preArr = new long[preLongs]; - preArr[0] = pre0; - preArr[1] = insertActiveItems(activeItems, pre); - preArr[2] = streamWeight; - preArr[3] = offset; - MemorySegment.copy(preArr, 0, seg, JAVA_LONG_UNALIGNED, 0, preLongs); - - final int preBytes = preLongs << 3; - MemorySegment.copy(hashMap.getActiveValues(), 0, seg, JAVA_LONG_UNALIGNED, preBytes, activeItems); - MemorySegment.copy(hashMap.getActiveKeys(), 0, seg, JAVA_LONG_UNALIGNED, preBytes + (activeItems << 3), activeItems); - } - return outArr; - } - - /** - * Returns a human readable summary of this sketch. - * @return a human readable summary of this sketch. - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("FrequentLongsSketch:").append(LS); - sb.append(" Stream Length : " + streamWeight).append(LS); - sb.append(" Max Error Offset : " + offset).append(LS); - sb.append(hashMap.toString()); - return sb.toString(); - } - - /** - * Returns a human readable string of the preamble of a byte array image of a FrequentLongsSketch. - * @param byteArr the given byte array - * @return a human readable string of the preamble of a byte array image of a FrequentLongsSketch. - */ - public static String toString(final byte[] byteArr) { - return toString(MemorySegment.ofArray(byteArr)); - } - - /** - * Returns a human readable string of the preamble of a MemorySegment image of a FrequentLongsSketch. - * @param seg the given MemorySegment object - * @return a human readable string of the preamble of a MemorySegment image of a FrequentLongsSketch. - */ - public static String toString(final MemorySegment seg) { - return PreambleUtil.preambleToString(seg); - } - - /** - * Update this sketch with an item and a frequency count of one. - * @param item for which the frequency should be increased. - */ - public void update(final long item) { - update(item, 1); - } - - /** - * Update this sketch with a item and a positive frequency count (or weight). - * @param item for which the frequency should be increased. The item can be any long value - * and is only used by the sketch to determine uniqueness. - * @param count the amount by which the frequency of the item should be increased. - * An count of zero is a no-op, and a negative count will throw an exception. - */ - public void update(final long item, final long count) { - if (count == 0) { return; } - if (count < 0) { - throw new SketchesArgumentException("Count may not be negative"); - } - streamWeight += count; - hashMap.adjustOrPutValue(item, count); - - if (getNumActiveItems() > curMapCap) { //over the threshold, we need to do something - if (hashMap.getLgLength() < lgMaxMapSize) { //below tgt size, we can grow - hashMap.resize(2 * hashMap.getLength()); - curMapCap = hashMap.getCapacity(); - } else { //At tgt size, must purge - offset += hashMap.purge(sampleSize); - if (getNumActiveItems() > getMaximumMapCapacity()) { - throw new SketchesStateException("Purge did not reduce active items."); - } - } - } - } - - /** - * Row class that defines the return values from a getFrequentItems query. - */ - public static class Row implements Comparable { - final long item; - final long est; - final long ub; - final long lb; - private static final String fmt = (" %20d%20d%20d %d"); - private static final String hfmt = (" %20s%20s%20s %s"); - - Row(final long item, final long estimate, final long ub, final long lb) { - this.item = item; - est = estimate; - this.ub = ub; - this.lb = lb; - } - - /** - * Returns item of type long - * @return item of type long - */ - public long getItem() { return item; } - - /** - * Returns the estimate - * @return the estimate - */ - public long getEstimate() { return est; } - - /** - * Returns the upper bound - * @return the upper bound - */ - public long getUpperBound() { return ub; } - - /** - * Returns the lower bound - * @return return the lower bound - */ - public long getLowerBound() { return lb; } - - /** - * Returns the descriptive row header - * @return the descriptive row header - */ - public static String getRowHeader() { - return String.format(hfmt,"Est", "UB", "LB", "Item"); - } - - @Override - public String toString() { - return String.format(fmt, est, ub, lb, item); - } - - /** - * This compareTo is strictly limited to the Row.getEstimate() value and does not imply any - * ordering whatsoever to the other elements of the row: item and upper and lower bounds. - * Defined this way, this compareTo will be consistent with hashCode() and equals(Object). - * @param that the other row to compare to. - * @return a negative integer, zero, or a positive integer as this.getEstimate() is less than, - * equal to, or greater than that.getEstimate(). - */ - @Override - public int compareTo(final Row that) { - return (est < that.est) ? -1 : (est > that.est) ? 1 : 0; - } - - /** - * This hashCode is computed only from the Row.getEstimate() value. - * Defined this way, this hashCode will be consistent with equals(Object):
- * If (x.equals(y)) implies: x.hashCode() == y.hashCode().
- * If (!x.equals(y)) does NOT imply: x.hashCode() != y.hashCode(). - * @return the hashCode computed from getEstimate(). - */ - @Override - public int hashCode() { - final int prime = 31; - final int result = 1; - return (prime * result) + (int) (est ^ (est >>> 32)); - } - - /** - * This equals is computed only from the Row.getEstimate() value and does not imply equality - * of the other items within the row: item and upper and lower bounds. - * Defined this way, this equals will be consistent with compareTo(Row). - * @param obj the other row to determine equality with. - * @return true if this.getEstimate() equals ((Row)obj).getEstimate(). - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { return true; } - if ( (obj == null) || !(obj instanceof Row)) { return false; } - final Row that = (Row) obj; - if (est != that.est) { return false; } - return true; - } - - } // End of class Row - - Row[] sortItems(final long threshold, final ErrorType errorType) { - final ArrayList rowList = new ArrayList<>(); - final ReversePurgeLongHashMap.Iterator iter = hashMap.iterator(); - if (errorType == ErrorType.NO_FALSE_NEGATIVES) { - while (iter.next()) { - final long est = getEstimate(iter.getKey()); - final long ub = getUpperBound(iter.getKey()); - final long lb = getLowerBound(iter.getKey()); - if (ub >= threshold) { - final Row row = new Row(iter.getKey(), est, ub, lb); - rowList.add(row); - } - } - } else { //NO_FALSE_POSITIVES - while (iter.next()) { - final long est = getEstimate(iter.getKey()); - final long ub = getUpperBound(iter.getKey()); - final long lb = getLowerBound(iter.getKey()); - if (lb >= threshold) { - final Row row = new Row(iter.getKey(), est, ub, lb); - rowList.add(row); - } - } - } - - // descending order - rowList.sort(new Comparator() { - @Override - public int compare(final Row r1, final Row r2) { - return r2.compareTo(r1); - } - }); - - return rowList.toArray(new Row[rowList.size()]); - } - - /** - * Deserializes an array of String tokens into a hash map object of this class. - * - * @param tokens the given array of Strings tokens. - * @return a hash map object of this class - */ - static ReversePurgeLongHashMap deserializeFromStringArray(final String[] tokens) { - final int ignore = STR_PREAMBLE_TOKENS; - final int numActive = Integer.parseInt(tokens[ignore]); - final int length = Integer.parseInt(tokens[ignore + 1]); - final ReversePurgeLongHashMap hashMap = new ReversePurgeLongHashMap(length); - int j = 2 + ignore; - for (int i = 0; i < numActive; i++) { - final long key = Long.parseLong(tokens[j++]); - final long value = Long.parseLong(tokens[j++]); - hashMap.adjustOrPutValue(key, value); - } - return hashMap; - } - -} diff --git a/src/main/java/org/apache/datasketches/frequencies/PreambleUtil.java b/src/main/java/org/apache/datasketches/frequencies/PreambleUtil.java deleted file mode 100644 index 490e89391..000000000 --- a/src/main/java/org/apache/datasketches/frequencies/PreambleUtil.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.zeroPad; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; - -// @formatter:off - -/** - * This class defines the preamble data structure and provides basic utilities for some of the key - * fields. - * - *

The intent of the design of this class was to isolate the detailed knowledge of the bit and byte - * layout of the serialized form of the sketches derived from the Sketch class into one place. This - * allows the possibility of the introduction of different serialization schemes with minimal impact - * on the rest of the library.

- * - *

MAP: Low significance bytes of this long data structure are on the right. However, the - * multi-byte integers (int and long) are stored in native byte order. The byte - * values are treated as unsigned.

- * - *

An empty FrequentItems only requires 8 bytes. All others require 32 bytes of preamble.

- * - *
- *  * Long || Start Byte Adr:
- * Adr:
- *      ||    7     |    6   |    5   |    4   |    3   |    2   |    1   |     0          |
- *  0   ||------ unused -----|-Flags--|-LgCur--| LgMax  | FamID  | SerVer | PreambleLongs  |
- *      ||    15    |   14   |   13   |   12   |   11   |   10   |    9   |     8          |
- *  1   ||------------(unused)-----------------|--------ActiveItems------------------------|
- *      ||    23    |   22   |   21   |   20   |   19   |   18   |   17   |    16          |
- *  2   ||-----------------------------------streamLength----------------------------------|
- *      ||    31    |   30   |   29   |   28   |   27   |   26   |   25   |    24          |
- *  3   ||---------------------------------offset------------------------------------------|
- *      ||    39    |   38   |   37   |   36   |   35   |   34   |   33   |    32          |
- *  5   ||----------start of values buffer, followed by keys buffer------------------------|
- * 
- * - * @author Lee Rhodes - */ -final class PreambleUtil { - - private PreambleUtil() {} - - // ###### DO NOT MESS WITH THIS FROM HERE ... - // Preamble byte Addresses - static final int PREAMBLE_LONGS_BYTE = 0; // either 1 or 4 - static final int SER_VER_BYTE = 1; - static final int FAMILY_BYTE = 2; - static final int LG_MAX_MAP_SIZE_BYTE = 3; - static final int LG_CUR_MAP_SIZE_BYTE = 4; - static final int FLAGS_BYTE = 5; - static final int SER_DE_ID_SHORT = 6; // to 7 - static final int ACTIVE_ITEMS_INT = 8; // to 11 : 0 to 4 in pre1 - static final int STREAMLENGTH_LONG = 16; // to 23 : pre2 - static final int OFFSET_LONG = 24; // to 31 : pre3 - - // flag bit masks - // due to a mistake different bits were used in C++ and Java to indicate empty sketch - // therefore both are set and checked for compatibility with historical binary format - static final int EMPTY_FLAG_MASK = 5; - - // Specific values for this implementation - static final int SER_VER = 1; - - /** - * Returns a human readable string summary of the preamble state of the given MemorySegment. - * Note: other than making sure that the given MemorySegment size is large - * enough for just the preamble, this does not do much value checking of the contents of the - * preamble as this is primarily a tool for debugging the preamble visually. - * - * @param srcSeg the given MemorySegment - * @return the summary preamble string. - */ - public static String preambleToString(final MemorySegment srcSeg) { - final long pre0 = checkPreambleSize(srcSeg); //make sure we can get the assumed preamble - final int preLongs = extractPreLongs(pre0); //byte 0 - final int serVer = extractSerVer(pre0); //byte 1 - final Family family = Family.idToFamily(extractFamilyID(pre0)); //byte 2 - final int lgMaxMapSize = extractLgMaxMapSize(pre0); //byte 3 - final int lgCurMapSize = extractLgCurMapSize(pre0); //byte 4 - final int flags = extractFlags(pre0); //byte 5 - - final String flagsStr = zeroPad(Integer.toBinaryString(flags), 8) + ", " + (flags); - final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; - final int maxMapSize = 1 << lgMaxMapSize; - final int curMapSize = 1 << lgCurMapSize; - final int maxPreLongs = Family.FREQUENCY.getMaxPreLongs(); - - //Assumed if preLongs == 1 - int activeItems = 0; - long streamLength = 0; - long offset = 0; - - //Assumed if preLongs == maxPreLongs - - if (preLongs == maxPreLongs) { - //get full preamble - final long[] preArr = new long[preLongs]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, 0, preArr, 0, preLongs); - activeItems = extractActiveItems(preArr[1]); - streamLength = preArr[2]; - offset = preArr[3]; - } - - final StringBuilder sb = new StringBuilder(); - sb.append(LS) - .append("### FREQUENCY SKETCH PREAMBLE SUMMARY:").append(LS) - .append("Byte 0: Preamble Longs : ").append(preLongs).append(LS) - .append("Byte 1: Serialization Version: ").append(serVer).append(LS) - .append("Byte 2: Family : ").append(family.toString()).append(LS) - .append("Byte 3: MaxMapSize : ").append(maxMapSize).append(LS) - .append("Byte 4: CurMapSize : ").append(curMapSize).append(LS) - .append("Byte 5: Flags Field : ").append(flagsStr).append(LS) - .append(" EMPTY : ").append(empty).append(LS); - - if (preLongs == 1) { - sb.append(" --ABSENT, ASSUMED:").append(LS); - } else { //preLongs == maxPreLongs - sb.append("Bytes 8-11 : ActiveItems : ").append(activeItems).append(LS); - sb.append("Bytes 16-23: StreamLength : ").append(streamLength).append(LS) - .append("Bytes 24-31: Offset : ").append(offset).append(LS); - } - - sb.append( "Preamble Bytes : ").append(preLongs * 8).append(LS); - sb.append( "TOTAL Sketch Bytes : ").append((preLongs + (activeItems * 2)) << 3) - .append(LS) - .append("### END FREQUENCY SKETCH PREAMBLE SUMMARY").append(LS); - return sb.toString(); - } - - // @formatter:on - - static int extractPreLongs(final long pre0) { //Byte 0 - final long mask = 0X3FL; //Lower 6 bits - return (int) (pre0 & mask); - } - - static int extractSerVer(final long pre0) { //Byte 1 - final int shift = SER_VER_BYTE << 3; - final long mask = 0XFFL; - return (int) ((pre0 >>> shift) & mask); - } - - static int extractFamilyID(final long pre0) { //Byte 2 - final int shift = FAMILY_BYTE << 3; - final long mask = 0XFFL; - return (int) ((pre0 >>> shift) & mask); - } - - static int extractLgMaxMapSize(final long pre0) { //Byte 3 - final int shift = LG_MAX_MAP_SIZE_BYTE << 3; - final long mask = 0XFFL; - return (int) ((pre0 >>> shift) & mask); - } - - static int extractLgCurMapSize(final long pre0) { //Byte 4 - final int shift = LG_CUR_MAP_SIZE_BYTE << 3; - final long mask = 0XFFL; - return (int) ((pre0 >>> shift) & mask); - } - - static int extractFlags(final long pre0) { //Byte 5 - final int shift = FLAGS_BYTE << 3; - final long mask = 0XFFL; - return (int) ((pre0 >>> shift) & mask); - } - - static int extractActiveItems(final long pre1) { //Bytes 8 to 11 - final long mask = 0XFFFFFFFFL; - return (int) (pre1 & mask) ; - } - - static long insertPreLongs(final int preLongs, final long pre0) { //Byte 0 - final long mask = 0X3FL; //Lower 6 bits - return (preLongs & mask) | (~mask & pre0); - } - - static long insertSerVer(final int serVer, final long pre0) { //Byte 1 - final int shift = SER_VER_BYTE << 3; - final long mask = 0XFFL; - return ((serVer & mask) << shift) | (~(mask << shift) & pre0); - } - - static long insertFamilyID(final int familyID, final long pre0) { //Byte 2 - final int shift = FAMILY_BYTE << 3; - final long mask = 0XFFL; - return ((familyID & mask) << shift) | (~(mask << shift) & pre0); - } - - static long insertLgMaxMapSize(final int lgMaxMapSize, final long pre0) { //Byte 3 - final int shift = LG_MAX_MAP_SIZE_BYTE << 3; - final long mask = 0XFFL; - return ((lgMaxMapSize & mask) << shift) | (~(mask << shift) & pre0); - } - - static long insertLgCurMapSize(final int lgCurMapSize, final long pre0) { //Byte 4 - final int shift = LG_CUR_MAP_SIZE_BYTE << 3; - final long mask = 0XFFL; - return ((lgCurMapSize & mask) << shift) | (~(mask << shift) & pre0); - } - - static long insertFlags(final int flags, final long pre0) { //Byte 5 - final int shift = FLAGS_BYTE << 3; - final long mask = 0XFFL; - return ((flags & mask) << shift) | (~(mask << shift) & pre0); - } - - static long insertActiveItems(final int activeItems, final long pre1) { //Bytes 8 to 11 - final long mask = 0XFFFFFFFFL; - return (activeItems & mask) | (~mask & pre1); - } - - /** - * Checks MemorySegment for capacity to hold the preamble and returns the first 8 bytes. - * @param seg the given MemorySegment - * @return the first 8 bytes of preamble as a long. - */ - static long checkPreambleSize(final MemorySegment seg) { - final long cap = seg.byteSize(); - if (cap < 8) { throwNotBigEnough(cap, 8); } - final long pre0 = seg.get(JAVA_LONG_UNALIGNED, 0); - final int preLongs = (int) (pre0 & 0X3FL); //lower 6 bits - final int required = Math.max(preLongs << 3, 8); - if (cap < required) { throwNotBigEnough(cap, required); } - return pre0; - } - - private static void throwNotBigEnough(final long cap, final int required) { - throw new SketchesArgumentException( - "Possible Corruption: " - + "Size of byte array or MemorySegment not large enough for Preamble: Size: " + cap - + ", Required: " + required); - } - -} diff --git a/src/main/java/org/apache/datasketches/frequencies/ReversePurgeItemHashMap.java b/src/main/java/org/apache/datasketches/frequencies/ReversePurgeItemHashMap.java deleted file mode 100644 index 7f998f505..000000000 --- a/src/main/java/org/apache/datasketches/frequencies/ReversePurgeItemHashMap.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.exactLog2OfInt; -import static org.apache.datasketches.frequencies.Util.hash; - -import java.lang.reflect.Array; - -import org.apache.datasketches.common.QuickSelect; - -/** - * Implements a linear-probing based hash map of (key, value) pairs and is distinguished by a - * "reverse" purge operation that removes all keys in the map whose associated values are ≤ 0 - * and is performed in reverse, starting at the "back" of the array and moving toward the front. - * - * @param The type of item to be tracked by this sketch - * - * @author Edo Liberty - * @author Justin Thaler - * @author Alexander Saydakov - */ -class ReversePurgeItemHashMap { - private static final double LOAD_FACTOR = 0.75; - private static final int DRIFT_LIMIT = 1024; //used only in stress testing - private int lgLength; - protected int loadThreshold; - protected Object[] keys; - protected long[] values; - protected short[] states; - protected int numActive = 0; - - /** - * Constructor will create arrays of length mapSize, which must be a power of two. - * This restriction was made to ensure fast hashing. - * The protected variable this.loadThreshold is then set to the largest value that - * will not overload the hash table. - * - * @param mapSize This determines the number of cells in the arrays underlying the - * HashMap implementation and must be a power of 2. - * The hash table will be expected to store LOAD_FACTOR * mapSize (key, value) pairs. - */ - ReversePurgeItemHashMap(final int mapSize) { - lgLength = exactLog2OfInt(mapSize, "mapSize"); - loadThreshold = (int) (mapSize * LOAD_FACTOR); - keys = new Object[mapSize]; - values = new long[mapSize]; - states = new short[mapSize]; - } - - /** - * @param probe location in the hash table array - * @return true if the cell in the array contains an active key - */ - boolean isActive(final int probe) { - return states[probe] > 0; - } - - /** - * Gets the current value with the given key - * @param key the given key - * @return the positive value the key corresponds to or zero if the key is not found in the - * hash map. - */ - long get(final T key) { - if (key == null) { return 0; } - final int probe = hashProbe(key); - if (states[probe] > 0) { - assert keys[probe].equals(key); - return values[probe]; - } - return 0; - } - - /** - * Increments the value mapped to the key if the key is present in the map. Otherwise, - * the key is inserted with the adjustAmount. - * - * @param key the key of the value to increment - * @param adjustAmount the amount by which to increment the value - */ - void adjustOrPutValue(final T key, final long adjustAmount) { - final int arrayMask = keys.length - 1; - int probe = (int) hash(key.hashCode()) & arrayMask; - int drift = 1; - while ((states[probe] != 0) && !keys[probe].equals(key)) { - probe = (probe + 1) & arrayMask; - drift++; - //only used for theoretical analysis - assert drift < DRIFT_LIMIT : "drift: " + drift + " >= DRIFT_LIMIT"; - } - - if (states[probe] == 0) { - // adding the key to the table the value - assert numActive <= loadThreshold - : "numActive: " + numActive + " > loadThreshold: " + loadThreshold; - keys[probe] = key; - values[probe] = adjustAmount; - states[probe] = (short) drift; - numActive++; - } else { - // adjusting the value of an existing key - assert keys[probe].equals(key); - values[probe] += adjustAmount; - } - } - - /** - * Processes the map arrays and retains only keys with positive counts. - */ - void keepOnlyPositiveCounts() { - // Starting from the back, find the first empty cell, - // which establishes the high end of a cluster. - int firstProbe = states.length - 1; - while (states[firstProbe] > 0) { - firstProbe--; - } - // firstProbe keeps track of this point. - // When we find the next non-empty cell, we know we are at the high end of a cluster - // Work towards the front; delete any non-positive entries. - for (int probe = firstProbe; probe-- > 0;) { - if ((states[probe] > 0) && (values[probe] <= 0)) { - hashDelete(probe); //does the work of deletion and moving higher items towards the front. - numActive--; - } - } - //now work on the first cluster that was skipped. - for (int probe = states.length; probe-- > firstProbe;) { - if ((states[probe] > 0) && (values[probe] <= 0)) { - hashDelete(probe); - numActive--; - } - } - } - - /** - * @param adjustAmount value by which to shift all values. Only keys corresponding to positive - * values are retained. - */ - void adjustAllValuesBy(final long adjustAmount) { - for (int i = values.length; i-- > 0;) { - values[i] += adjustAmount; - } - } - - /** - * @return an array containing the active keys in the hash map. - */ - @SuppressWarnings("unchecked") - T[] getActiveKeys() { - if (numActive == 0) { return null; } - T[] returnedKeys = null; - int j = 0; - for (int i = 0; i < keys.length; i++) { - if (isActive(i)) { - if (returnedKeys == null) { - returnedKeys = (T[]) Array.newInstance(keys[i].getClass(), numActive); - } - returnedKeys[j] = (T) keys[i]; - j++; - } - } - assert j == numActive : "j: " + j + " != numActive: " + numActive; - return returnedKeys; - } - - /** - * @return an array containing the values corresponding to the active keys in the hash - */ - long[] getActiveValues() { - if (numActive == 0) { return null; } - final long[] returnedValues = new long[numActive]; - int j = 0; - for (int i = 0; i < values.length; i++) { - if (isActive(i)) { - returnedValues[j] = values[i]; - j++; - } - } - assert j == numActive; - return returnedValues; - } - - // assume newSize is power of 2 - @SuppressWarnings("unchecked") - void resize(final int newSize) { - final Object[] oldKeys = keys; - final long[] oldValues = values; - final short[] oldStates = states; - keys = new Object[newSize]; - values = new long[newSize]; - states = new short[newSize]; - loadThreshold = (int) (newSize * LOAD_FACTOR); - lgLength = Integer.numberOfTrailingZeros(newSize); - numActive = 0; - for (int i = 0; i < oldKeys.length; i++) { - if (oldStates[i] > 0) { - adjustOrPutValue((T) oldKeys[i], oldValues[i]); - } - } - } - - /** - * @return length of hash table internal arrays - */ - int getLength() { - return keys.length; - } - - int getLgLength() { - return lgLength; - } - - /** - * @return capacity of hash table internal arrays (i.e., max number of keys that can be stored) - */ - int getCapacity() { - return loadThreshold; - } - - /** - * @return number of populated keys - */ - int getNumActive() { - return numActive; - } - - /** - * Returns the hash table as a human readable string. - */ - @Override - public String toString() { - final String fmt = " %12d:%11d%12d %s"; - final String hfmt = " %12s:%11s%12s %s"; - final StringBuilder sb = new StringBuilder(); - sb.append("ReversePurgeItemHashMap").append(LS); - sb.append(String.format(hfmt, "Index","States","Values","Keys")).append(LS); - - for (int i = 0; i < keys.length; i++) { - if (states[i] <= 0) { continue; } - sb.append(String.format(fmt, i, states[i], values[i], keys[i].toString())); - sb.append(LS); - } - return sb.toString(); - } - - /** - * @return the load factor of the hash table, i.e, the ratio between the capacity and the array - * length - */ - static double getLoadFactor() { - return LOAD_FACTOR; - } - - /** - * This function is called when a key is processed that is not currently assigned a counter, and - * all the counters are in use. This function estimates the median of the counters in the sketch - * via sampling, decrements all counts by this estimate, throws out all counters that are no - * longer positive, and increments offset accordingly. - * @param sampleSize number of samples - * @return the median value - */ - long purge(final int sampleSize) { - final int limit = Math.min(sampleSize, getNumActive()); - - int numSamples = 0; - int i = 0; - final long[] samples = new long[limit]; - - while (numSamples < limit) { - if (isActive(i)) { - samples[numSamples] = values[i]; - numSamples++; - } - i++; - } - - final long val = QuickSelect.select(samples, 0, numSamples - 1, limit / 2); - adjustAllValuesBy(-1 * val); - keepOnlyPositiveCounts(); - return val; - } - - private void hashDelete(int deleteProbe) { - // Looks ahead in the table to search for another - // item to move to this location - // if none are found, the status is changed - states[deleteProbe] = 0; //mark as empty - int drift = 1; - final int arrayMask = keys.length - 1; - int probe = (deleteProbe + drift) & arrayMask; //map length must be a power of 2 - // advance until you find a free location replacing locations as needed - while (states[probe] != 0) { - if (states[probe] > drift) { - // move current element - keys[deleteProbe] = keys[probe]; - values[deleteProbe] = values[probe]; - states[deleteProbe] = (short) (states[probe] - drift); - // marking this location as deleted - states[probe] = 0; - drift = 0; - deleteProbe = probe; - } - probe = (probe + 1) & arrayMask; - drift++; - //only used for theoretical analysis - assert drift < DRIFT_LIMIT : "drift: " + drift + " >= DRIFT_LIMIT"; - } - } - - private int hashProbe(final T key) { - final int arrayMask = keys.length - 1; - int probe = (int) hash(key.hashCode()) & arrayMask; - while ((states[probe] > 0) && !keys[probe].equals(key)) { - probe = (probe + 1) & arrayMask; - } - return probe; - } - - Iterator iterator() { - return new Iterator<>(keys, values, states, numActive); - } - - // This iterator uses strides based on golden ratio to avoid clustering during merge - static class Iterator { - private static final double GOLDEN_RATIO_RECIPROCAL = (Math.sqrt(5) - 1) / 2; - - private final Object[] keys_; - private final long[] values_; - private final short[] states_; - private final int numActive_; - private final int stride_; - private final int mask_; - private int i_; - private int count_; - - Iterator(final Object[] keys, final long[] values, final short[] states, final int numActive) { - keys_ = keys; - values_ = values; - states_ = states; - numActive_ = numActive; - stride_ = (int) (keys.length * GOLDEN_RATIO_RECIPROCAL) | 1; - mask_ = keys.length - 1; - i_ = -stride_; - count_ = 0; - } - - boolean next() { - i_ = (i_ + stride_) & mask_; - while (count_ < numActive_) { - if (states_[i_] > 0) { - count_++; - return true; - } - i_ = (i_ + stride_) & mask_; - } - return false; - } - - @SuppressWarnings("unchecked") - T getKey() { - return (T) keys_[i_]; - } - - long getValue() { - return values_[i_]; - } - } - -} diff --git a/src/main/java/org/apache/datasketches/frequencies/ReversePurgeLongHashMap.java b/src/main/java/org/apache/datasketches/frequencies/ReversePurgeLongHashMap.java deleted file mode 100644 index 269ca8706..000000000 --- a/src/main/java/org/apache/datasketches/frequencies/ReversePurgeLongHashMap.java +++ /dev/null @@ -1,418 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.exactLog2OfInt; -import static org.apache.datasketches.frequencies.Util.hash; -import static org.apache.datasketches.common.Util.INVERSE_GOLDEN; - -import org.apache.datasketches.common.QuickSelect; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Implements a linear-probing based hash map of (key, value) pairs and is distinguished by a - * "reverse" purge operation that removes all keys in the map whose associated values are ≤ 0 - * and is performed in reverse, starting at the "back" of the array and moving toward the front. - * - * @author Edo Liberty - * @author Justin Thaler - * @author Lee Rhodes - */ -class ReversePurgeLongHashMap { - private static final double LOAD_FACTOR = 0.75; - private static final int DRIFT_LIMIT = 1024; //used only in stress testing - private int lgLength; - private int loadThreshold; - private long[] keys; - private long[] values; - private short[] states; - private int numActive = 0; - - /** - * Constructor will create arrays of length mapSize, which must be a power of two. - * This restriction was made to ensure fast hashing. - * The protected variable this.loadThreshold is then set to the largest value that - * will not overload the hash table. - * - * @param mapSize This determines the number of cells in the arrays underlying the - * HashMap implementation and must be a power of 2. - * The hash table will be expected to store LOAD_FACTOR * mapSize (key, value) pairs. - */ - ReversePurgeLongHashMap(final int mapSize) { - lgLength = exactLog2OfInt(mapSize, "mapSize"); - loadThreshold = (int) (mapSize * LOAD_FACTOR); - keys = new long[mapSize]; - values = new long[mapSize]; - states = new short[mapSize]; - } - - /** - * Returns an instance of this class from the given String, - * which must be a String representation of this class. - * - * @param string a String representation of this class. - * @return an instance of this class. - */ - static ReversePurgeLongHashMap getInstance(final String string) { - final String[] tokens = string.split(","); - if (tokens.length < 2) { - throw new SketchesArgumentException( - "String not long enough to specify length and capacity."); - } - final int numActive = Integer.parseInt(tokens[0]); - final int length = Integer.parseInt(tokens[1]); - final ReversePurgeLongHashMap table = new ReversePurgeLongHashMap(length); - int j = 2; - for (int i = 0; i < numActive; i++) { - final long key = Long.parseLong(tokens[j++]); - final long value = Long.parseLong(tokens[j++]); - table.adjustOrPutValue(key, value); - } - return table; - } - - //Serialization - - /** - * Returns a String representation of this hash map. - * - * @return a String representation of this hash map. - */ - String serializeToString() { - final StringBuilder sb = new StringBuilder(); - sb.append(String.format("%d,%d,", numActive, keys.length)); - - for (int i = 0; i < keys.length; i++) { - if (states[i] != 0) { - sb.append(String.format("%d,%d,", keys[i], values[i])); - } - } - return sb.toString(); - } - - /** - * @param probe location in the hash table array - * @return true if the cell in the array contains an active key - */ - boolean isActive(final int probe) { - return (states[probe] > 0); - } - - /** - * Gets the current value with the given key - * @param key the given key - * @return the positive value the key corresponds to or zero if the key is not found in the - * hash map. - */ - long get(final long key) { - final int probe = hashProbe(key); - if (states[probe] > 0) { - assert (keys[probe] == key); - return values[probe]; - } - return 0; - } - - /** - * Increments the value mapped to the key if the key is present in the map. Otherwise, - * the key is inserted with the putAmount. - * - * @param key the key of the value to increment - * @param adjustAmount the amount by which to increment the value - */ - void adjustOrPutValue(final long key, final long adjustAmount) { - final int arrayMask = keys.length - 1; - int probe = (int) hash(key) & arrayMask; - int drift = 1; - while ((states[probe] != 0) && (keys[probe] != key)) { - probe = (probe + 1) & arrayMask; - drift++; - //only used for theoretical analysis - assert (drift < DRIFT_LIMIT) : "drift: " + drift + " >= DRIFT_LIMIT"; - } - //found either an empty slot or the key - if (states[probe] == 0) { //found empty slot - // adding the key and value to the table - assert (numActive <= loadThreshold) - : "numActive: " + numActive + " > loadThreshold : " + loadThreshold; - keys[probe] = key; - values[probe] = adjustAmount; - states[probe] = (short) drift; //how far off we are - numActive++; - } else { //found the key, adjust the value - assert (keys[probe] == key); - values[probe] += adjustAmount; - } - } - - /** - * Processes the map arrays and retains only keys with positive counts. - */ - void keepOnlyPositiveCounts() { - // Starting from the back, find the first empty cell, which marks a boundary between clusters. - int firstProbe = keys.length - 1; - while (states[firstProbe] > 0) { - firstProbe--; - } - - //Work towards the front; delete any non-positive entries. - for (int probe = firstProbe; probe-- > 0; ) { - // When we find the next non-empty cell, we know we are at the high end of a cluster, - // which is tracked by firstProbe. - if ((states[probe] > 0) && (values[probe] <= 0)) { - hashDelete(probe); //does the work of deletion and moving higher items towards the front. - numActive--; - } - } - //now work on the first cluster that was skipped. - for (int probe = keys.length; probe-- > firstProbe;) { - if ((states[probe] > 0) && (values[probe] <= 0)) { - hashDelete(probe); - numActive--; - } - } - } - - /** - * @param adjustAmount value by which to shift all values. Only keys corresponding to positive - * values are retained. - */ - void adjustAllValuesBy(final long adjustAmount) { - for (int i = keys.length; i-- > 0; ) { - values[i] += adjustAmount; - } - } - - /** - * @return an array containing the active keys in the hash map. - */ - long[] getActiveKeys() { - if (numActive == 0) { return null; } - final long[] returnedKeys = new long[numActive]; - int j = 0; - for (int i = 0; i < keys.length; i++) { - if (isActive(i)) { - returnedKeys[j] = keys[i]; - j++; - } - } - assert (j == numActive) : "j: " + j + " != numActive: " + numActive; - return returnedKeys; - } - - /** - * @return an array containing the values corresponding. to the active keys in the hash - */ - long[] getActiveValues() { - if (numActive == 0) { return null; } - final long[] returnedValues = new long[numActive]; - int j = 0; - for (int i = 0; i < values.length; i++) { - if (isActive(i)) { - returnedValues[j] = values[i]; - j++; - } - } - assert (j == numActive); - return returnedValues; - } - - // assume newSize is power of 2 - void resize(final int newSize) { - final long[] oldKeys = keys; - final long[] oldValues = values; - final short[] oldStates = states; - keys = new long[newSize]; - values = new long[newSize]; - states = new short[newSize]; - loadThreshold = (int) (newSize * LOAD_FACTOR); - lgLength = Integer.numberOfTrailingZeros(newSize); - numActive = 0; - for (int i = 0; i < oldKeys.length; i++) { - if (oldStates[i] > 0) { - adjustOrPutValue(oldKeys[i], oldValues[i]); - } - } - } - - /** - * @return length of hash table internal arrays - */ - int getLength() { - return keys.length; - } - - int getLgLength() { - return lgLength; - } - - /** - * @return capacity of hash table internal arrays (i.e., max number of keys that can be stored) - */ - int getCapacity() { - return loadThreshold; - } - - /** - * @return number of populated keys - */ - int getNumActive() { - return numActive; - } - - /** - * Returns the hash table as a human readable string. - */ - @Override - public String toString() { - final String fmt = " %12d:%11d%20d %d"; - final String hfmt = " %12s:%11s%20s %s"; - final StringBuilder sb = new StringBuilder(); - sb.append("ReversePurgeLongHashMap:").append(LS); - sb.append(String.format(hfmt, "Index","States","Values","Keys")).append(LS); - - for (int i = 0; i < keys.length; i++) { - if (states[i] <= 0) { continue; } - sb.append(String.format(fmt, i, states[i], values[i], keys[i])).append(LS); - } - return sb.toString(); - } - - /** - * @return the load factor of the hash table, i.e, the ratio between the capacity and the array - * length - */ - static double getLoadFactor() { - return LOAD_FACTOR; - } - - /** - * This function is called when a key is processed that is not currently assigned a counter, and - * all the counters are in use. This function estimates the median of the counters in the sketch - * via sampling, decrements all counts by this estimate, throws out all counters that are no - * longer positive, and increments offset accordingly. - * @param sampleSize number of samples - * @return the median value - */ - long purge(final int sampleSize) { - final int limit = Math.min(sampleSize, getNumActive()); - - int numSamples = 0; - int i = 0; - final long[] samples = new long[limit]; - - while (numSamples < limit) { - if (isActive(i)) { - samples[numSamples] = values[i]; - numSamples++; - } - i++; - } - - final long val = QuickSelect.select(samples, 0, numSamples - 1, limit / 2); - adjustAllValuesBy(-1 * val); - keepOnlyPositiveCounts(); - return val; - } - - private void hashDelete(int deleteProbe) { - // Looks ahead in the table to search for another item to move to this location. - // If none are found, the status is changed - states[deleteProbe] = 0; //mark as empty - int drift = 1; - final int arrayMask = keys.length - 1; - int probe = (deleteProbe + drift) & arrayMask; //map length must be a power of 2 - // advance until you find a free location replacing locations as needed - while (states[probe] != 0) { - if (states[probe] > drift) { - // move current element - keys[deleteProbe] = keys[probe]; - values[deleteProbe] = values[probe]; - states[deleteProbe] = (short) (states[probe] - drift); - // marking the current probe location as deleted - states[probe] = 0; - drift = 0; - deleteProbe = probe; - } - probe = (probe + 1) & arrayMask; - drift++; - //only used for theoretical analysis - assert (drift < DRIFT_LIMIT) : "drift: " + drift + " >= DRIFT_LIMIT"; - } - } - - private int hashProbe(final long key) { - final int arrayMask = keys.length - 1; - int probe = (int) hash(key) & arrayMask; - while ((states[probe] > 0) && (keys[probe] != key)) { - probe = (probe + 1) & arrayMask; - } - return probe; - } - - Iterator iterator() { - return new Iterator(keys, values, states, numActive); - } - - // This iterator uses strides based on golden ratio to avoid clustering during merge - static class Iterator { - private final long[] keys_; - private final long[] values_; - private final short[] states_; - private final int numActive_; - private final int stride_; - private final int mask_; - private int i_; - private int count_; - - Iterator(final long[] keys, final long[] values, final short[] states, final int numActive) { - keys_ = keys; - values_ = values; - states_ = states; - numActive_ = numActive; - stride_ = (int) (keys.length * INVERSE_GOLDEN) | 1; - mask_ = keys.length - 1; - i_ = -stride_; - count_ = 0; - } - - boolean next() { - i_ = (i_ + stride_) & mask_; - while (count_ < numActive_) { - if (states_[i_] > 0) { - count_++; - return true; - } - i_ = (i_ + stride_) & mask_; - } - return false; - } - - long getKey() { - return keys_[i_]; - } - - long getValue() { - return values_[i_]; - } - } - -} diff --git a/src/main/java/org/apache/datasketches/frequencies/Util.java b/src/main/java/org/apache/datasketches/frequencies/Util.java deleted file mode 100644 index 743389068..000000000 --- a/src/main/java/org/apache/datasketches/frequencies/Util.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -final class Util { - - private Util() {} - - /** - * The following constant controls the size of the initial data structure for the - * frequencies sketches and its value is somewhat arbitrary. - */ - static final int LG_MIN_MAP_SIZE = 3; - - /** - * This constant is large enough so that computing the median of SAMPLE_SIZE - * randomly selected entries from a list of numbers and outputting - * the empirical median will give a constant-factor approximation to the - * true median with high probability. - */ - static final int SAMPLE_SIZE = 1024; - - /** - * @param key to be hashed - * @return an index into the hash table This hash function is taken from the internals of - * Austin Appleby's MurmurHash3 algorithm. It is also used by the Trove for Java libraries. - */ - static long hash(long key) { - key ^= key >>> 33; - key *= 0xff51afd7ed558ccdL; - key ^= key >>> 33; - key *= 0xc4ceb9fe1a85ec53L; - key ^= key >>> 33; - return key; - } - -} diff --git a/src/main/java/org/apache/datasketches/frequencies/package-info.java b/src/main/java/org/apache/datasketches/frequencies/package-info.java deleted file mode 100644 index d7ab9b7ac..000000000 --- a/src/main/java/org/apache/datasketches/frequencies/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package contains the implementations of the paper https://arxiv.org/abs/1705.07001. - */ -package org.apache.datasketches.frequencies; diff --git a/src/main/java/org/apache/datasketches/hash/MurmurHash3.java b/src/main/java/org/apache/datasketches/hash/MurmurHash3.java deleted file mode 100644 index d0a46db92..000000000 --- a/src/main/java/org/apache/datasketches/hash/MurmurHash3.java +++ /dev/null @@ -1,546 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hash; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; - -import java.lang.foreign.MemorySegment; -import java.io.Serializable; -import java.nio.ByteBuffer; -import java.util.Objects; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; - -/** - * The MurmurHash3 is a fast, non-cryptographic, 128-bit hash function that has - * excellent avalanche and 2-way bit independence properties. - * - *

- * Austin Appleby's C++ - * - * MurmurHash3_x64_128(...), final revision 150, - * which is in the Public Domain, was the inspiration for this implementation in Java. - *

- * - *

- * This java implementation pays close attention to the C++ algorithms in order to - * maintain bit-wise compatibility, but the design is quite different. This implementation has also - * been extended to include processing of arrays of longs, char or ints, which was not part of the - * original C++ implementation. This implementation produces the same exact output hash bits as - * the above C++ method given the same input.

- * - *

In addition, with this implementation, the hash of byte[], char[], int[], or long[] will - * produce the same hash result if, and only if, all the arrays have the same exact length in - * bytes, and if the contents of the values in the arrays have the same byte endianness and - * overall order. There is a unit test for this class that demonstrates this.

- * - *

- * The structure of this implementation also reflects a separation of code that is dependent on the - * input structure (in this case byte[], int[] or long[]) from code that is independent of the input - * structure. This also makes the code more readable and suitable for future extensions. - *

- * - *

Note that even though this hash function produces 128 bits, the entropy of the resulting hash cannot - * be greater than the entropy of the input. For example, if the input is only a single long of 64 bits, - * the entropy of the resulting 128 bit hash is no greater than 64 bits. - * - * @author Lee Rhodes - */ -public final class MurmurHash3 implements Serializable { - private static final long serialVersionUID = 0L; - - private MurmurHash3() {} - - //--Hash of long--------------------------------------------------------- - /** - * Hash the given long. - * - * @param key The input long. - * @param seed A long valued seed. - * @return a 128-bit hash of the input as a long array of size 2. - */ - public static long[] hash(final long key, final long seed) { - final HashState hashState = new HashState(seed, seed); - return hashState.finalMix128(key, 0, Long.BYTES); - } - - //--Hash of long[]------------------------------------------------------- - /** - * Hash the given long[] array. - * - * @param key The input long[] array. It must be non-null and non-empty. - * @param seed A long valued seed. - * @return a 128-bit hash of the input as a long array of size 2. - */ - public static long[] hash(final long[] key, final long seed) { - return hash(key, 0, key.length, seed); - } - - /** - * Hash a portion of the given long[] array. - * - * @param key The input long[] array. It must be non-null and non-empty. - * @param offsetLongs the starting offset in longs. - * @param lengthLongs the length in longs of the portion of the array to be hashed. - * @param seed A long valued seed. - * @return a 128-bit hash of the input as a long array of size 2 - */ - public static long[] hash(final long[] key, final int offsetLongs, final int lengthLongs, final long seed) { - Objects.requireNonNull(key); - final int arrLen = key.length; - checkPositive(arrLen); - Util.checkBounds(offsetLongs, lengthLongs, arrLen); - final HashState hashState = new HashState(seed, seed); - - // Number of full 128-bit blocks of 2 longs (the body). - // Possible exclusion of a remainder of 1 long. - final int nblocks = lengthLongs >>> 1; //longs / 2 - - // Process the 128-bit blocks (the body) into the hash - for (int i = 0; i < nblocks; i++ ) { - final long k1 = key[offsetLongs + (i << 1)]; //offsetLongs + 0, 2, 4, ... - final long k2 = key[offsetLongs + (i << 1) + 1]; //offsetLongs + 1, 3, 5, ... - hashState.blockMix128(k1, k2); - } - - // Get the tail index wrt hashed portion, remainder length - final int tail = nblocks << 1; // 2 longs / block - final int rem = lengthLongs - tail; // remainder longs: 0,1 - - // Get the tail - final long k1 = rem == 0 ? 0 : key[offsetLongs + tail]; //k2 -> 0 - // Mix the tail into the hash and return - return hashState.finalMix128(k1, 0, lengthLongs << 3); //convert to bytes - } - - //--Hash of int[]-------------------------------------------------------- - /** - * Hash the given int[] array. - * - * @param key The input int[] array. It must be non-null and non-empty. - * @param seed A long valued seed. - * @return a 128-bit hash of the input as a long array of size 2. - */ - public static long[] hash(final int[] key, final long seed) { - return hash(key, 0, key.length, seed); - } - - /** - * Hash a portion of the given int[] array. - * - * @param key The input int[] array. It must be non-null and non-empty. - * @param offsetInts the starting offset in ints. - * @param lengthInts the length in ints of the portion of the array to be hashed. - * @param seed A long valued seed. - * @return a 128-bit hash of the input as a long array of size 2. - */ - public static long[] hash(final int[] key, final int offsetInts, final int lengthInts, final long seed) { - Objects.requireNonNull(key); - final int arrLen = key.length; - checkPositive(arrLen); - Util.checkBounds(offsetInts, lengthInts, arrLen); - final HashState hashState = new HashState(seed, seed); - - // Number of full 128-bit blocks of 4 ints. - // Possible exclusion of a remainder of up to 3 ints. - final int nblocks = lengthInts >>> 2; //ints / 4 - - // Process the 128-bit blocks (the body) into the hash - for (int i = 0; i < nblocks; i++ ) { //4 ints per block - final long k1 = getLong(key, offsetInts + (i << 2), 2); //offsetInts + 0, 4, 8, ... - final long k2 = getLong(key, offsetInts + (i << 2) + 2, 2); //offsetInts + 2, 6, 10, ... - hashState.blockMix128(k1, k2); - } - - // Get the tail index wrt hashed portion, remainder length - final int tail = nblocks << 2; // 4 ints per block - final int rem = lengthInts - tail; // remainder ints: 0,1,2,3 - - // Get the tail - final long k1; - final long k2; - if (rem > 2) { //k1 -> whole; k2 -> partial - k1 = getLong(key, offsetInts + tail, 2); - k2 = getLong(key, offsetInts + tail + 2, rem - 2); - } - else { //k1 -> whole(2), partial(1) or 0; k2 == 0 - k1 = rem == 0 ? 0 : getLong(key, offsetInts + tail, rem); - k2 = 0; - } - // Mix the tail into the hash and return - return hashState.finalMix128(k1, k2, lengthInts << 2); //convert to bytes - } - - //--Hash of char[]------------------------------------------------------- - /** - * Hash the given char[] array. - * - * @param key The input char[] array. It must be non-null and non-empty. - * @param seed A long valued seed. - * @return a 128-bit hash of the input as a long array of size 2 - */ - public static long[] hash(final char[] key, final long seed) { - return hash(key, 0, key.length, seed); - } - - /** - * Hash a portion of the given char[] array. - * - * @param key The input char[] array. It must be non-null and non-empty. - * @param offsetChars the starting offset in chars. - * @param lengthChars the length in chars of the portion of the array to be hashed. - * @param seed A long valued seed. - * @return a 128-bit hash of the input as a long array of size 2 - */ - public static long[] hash(final char[] key, final int offsetChars, final int lengthChars, final long seed) { - Objects.requireNonNull(key); - final int arrLen = key.length; - checkPositive(arrLen); - Util.checkBounds(offsetChars, lengthChars, arrLen); - final HashState hashState = new HashState(seed, seed); - - // Number of full 128-bit blocks of 8 chars. - // Possible exclusion of a remainder of up to 7 chars. - final int nblocks = lengthChars >>> 3; //chars / 8 - - // Process the 128-bit blocks (the body) into the hash - for (int i = 0; i < nblocks; i++ ) { //8 chars per block - final long k1 = getLong(key, offsetChars + (i << 3), 4); //offsetChars + 0, 8, 16, ... - final long k2 = getLong(key, offsetChars + (i << 3) + 4, 4); //offsetChars + 4, 12, 20, ... - hashState.blockMix128(k1, k2); - } - - // Get the tail index wrt hashed portion, remainder length - final int tail = nblocks << 3; // 8 chars per block - final int rem = lengthChars - tail; // remainder chars: 0,1,2,3,4,5,6,7 - - // Get the tail - final long k1; - final long k2; - if (rem > 4) { //k1 -> whole; k2 -> partial - k1 = getLong(key, offsetChars + tail, 4); - k2 = getLong(key, offsetChars + tail + 4, rem - 4); - } - else { //k1 -> whole, partial or 0; k2 == 0 - k1 = rem == 0 ? 0 : getLong(key, offsetChars + tail, rem); - k2 = 0; - } - // Mix the tail into the hash and return - return hashState.finalMix128(k1, k2, lengthChars << 1); //convert to bytes - } - - //--Hash of byte[]------------------------------------------------------- - /** - * Hash the given byte[] array. - * - * @param key The input byte[] array. It must be non-null and non-empty. - * @param seed A long valued seed. - * @return a 128-bit hash of the input as a long array of size 2. - */ - public static long[] hash(final byte[] key, final long seed) { - return hash(key, 0, key.length, seed); - } - - /** - * Hash a portion of the given byte[] array. - * - * @param key The input byte[] array. It must be non-null and non-empty. - * @param offsetBytes the starting offset in bytes. - * @param lengthBytes the length in bytes of the portion of the array to be hashed. - * @param seed A long valued seed. - * @return a 128-bit hash of the input as a long array of size 2. - */ - public static long[] hash(final byte[] key, final int offsetBytes, final int lengthBytes, final long seed) { - Objects.requireNonNull(key); - final int arrLen = key.length; - checkPositive(arrLen); - Util.checkBounds(offsetBytes, lengthBytes, arrLen); - final HashState hashState = new HashState(seed, seed); - - // Number of full 128-bit blocks of 16 bytes. - // Possible exclusion of a remainder of up to 15 bytes. - final int nblocks = lengthBytes >>> 4; //bytes / 16 - - // Process the 128-bit blocks (the body) into the hash - for (int i = 0; i < nblocks; i++ ) { //16 bytes per block - final long k1 = getLong(key, offsetBytes + (i << 4), 8); //offsetBytes + 0, 16, 32, ... - final long k2 = getLong(key, offsetBytes + (i << 4) + 8, 8); //offsetBytes + 8, 24, 40, ... - hashState.blockMix128(k1, k2); - } - - // Get the tail index wrt hashed portion, remainder length - final int tail = nblocks << 4; //16 bytes per block - final int rem = lengthBytes - tail; // remainder bytes: 0,1,...,15 - - // Get the tail - final long k1; - final long k2; - if (rem > 8) { //k1 -> whole; k2 -> partial - k1 = getLong(key, offsetBytes + tail, 8); - k2 = getLong(key, offsetBytes + tail + 8, rem - 8); - } - else { //k1 -> whole, partial or 0; k2 == 0 - k1 = rem == 0 ? 0 : getLong(key, offsetBytes + tail, rem); - k2 = 0; - } - // Mix the tail into the hash and return - return hashState.finalMix128(k1, k2, lengthBytes); - } - - //--Hash of ByteBuffer--------------------------------------------------- - /** - * Hash the remaining bytes of the given ByteBuffer starting at position() ending at limit (exclusive). - * - * @param buf The input ByteBuffer. It must be non-null and non-empty. - * @param seed A long valued seed. - * @return a 128-bit hash of the input as a long array of size 2. - */ - public static long[] hash(final ByteBuffer buf, final long seed) { - Objects.requireNonNull(buf); - final MemorySegment bbSeg = MemorySegment.ofBuffer(buf); - return hash(bbSeg, seed); - } - - //--Hash of MemorySegment------------------------------------------------------- - /** - * Hash the given MemorySegment. - * - *

Note: if you want to hash only a portion of MemorySegment, convert it to the - * appropriate Slice first. - * - * @param seg The input MemorySegment. It must be non-null and non-empty. - * @param seed A long valued seed. - * @return a 128-bit hash of the input as a long array of size 2. - */ - public static long[] hash(final MemorySegment seg, final long seed) { - Objects.requireNonNull(seg); - final long lengthBytes = seg.byteSize(); - checkPositive(lengthBytes); - - final HashState hashState = new HashState(seed, seed); - - // Number of full 128-bit blocks of 16 bytes. - // Possible exclusion of a remainder of up to 15 bytes. - final long nblocks = lengthBytes >>> 4; //bytes / 16 - - // Process the 128-bit blocks (the body) into the hash - for (long i = 0; i < nblocks; i++ ) { //16 bytes per block - final long k1 = seg.get(JAVA_LONG_UNALIGNED, i << 4); //0, 16, 32, ... - final long k2 = seg.get(JAVA_LONG_UNALIGNED, (i << 4) + 8); //8, 24, 40, ... - hashState.blockMix128(k1, k2); - } - - // Get the tail index wrt hashed portion, remainder length - final long tail = nblocks << 4; //16 bytes per block - final int rem = (int)(lengthBytes - tail); // remainder bytes: 0,1,...,15 - - // Get the tail - final long k1; - final long k2; - if (rem > 8) { //k1 -> whole; k2 -> partial - k1 = seg.get(JAVA_LONG_UNALIGNED, tail); - k2 = getLong(seg, tail + 8, rem - 8); - } - else { //k1 -> whole, partial or 0; k2 == 0 - k1 = rem == 0 ? 0 : getLong(seg, tail, rem); - k2 = 0; - } - // Mix the tail into the hash and return - return hashState.finalMix128(k1, k2, lengthBytes); - } - - //--HashState class------------------------------------------------------ - /** - * Common processing of the 128-bit hash state independent of input type. - */ - private static final class HashState { - private static final long C1 = 0x87c37b91114253d5L; - private static final long C2 = 0x4cf5ad432745937fL; - private long h1; - private long h2; - - HashState(final long h1, final long h2) { - this.h1 = h1; - this.h2 = h2; - } - - /** - * Block mix (128-bit block) of input key to internal hash state. - * - * @param k1 intermediate mix value - * @param k2 intermediate mix value - */ - void blockMix128(final long k1, final long k2) { - h1 ^= mixK1(k1); - h1 = Long.rotateLeft(h1, 27); - h1 += h2; - h1 = (h1 * 5) + 0x52dce729; - - h2 ^= mixK2(k2); - h2 = Long.rotateLeft(h2, 31); - h2 += h1; - h2 = (h2 * 5) + 0x38495ab5; - } - - long[] finalMix128(final long k1, final long k2, final long inputLengthBytes) { - h1 ^= mixK1(k1); - h2 ^= mixK2(k2); - h1 ^= inputLengthBytes; - h2 ^= inputLengthBytes; - h1 += h2; - h2 += h1; - h1 = finalMix64(h1); - h2 = finalMix64(h2); - h1 += h2; - h2 += h1; - return new long[] { h1, h2 }; - } - - /** - * Final self mix of h*. - * - * @param h input to final mix - * @return mix - */ - private static long finalMix64(long h) { - h ^= h >>> 33; - h *= 0xff51afd7ed558ccdL; - h ^= h >>> 33; - h *= 0xc4ceb9fe1a85ec53L; - h ^= h >>> 33; - return h; - } - - /** - * Self mix of k1 - * - * @param k1 input argument - * @return mix - */ - private static long mixK1(long k1) { - k1 *= C1; - k1 = Long.rotateLeft(k1, 31); - k1 *= C2; - return k1; - } - - /** - * Self mix of k2 - * - * @param k2 input argument - * @return mix - */ - private static long mixK2(long k2) { - k2 *= C2; - k2 = Long.rotateLeft(k2, 33); - k2 *= C1; - return k2; - } - } - - //--Helper methods------------------------------------------------------- - - /** - * Gets a long from the given int array starting at the given int array index and continuing for - * remainder (rem) integers. The integers are extracted in little-endian order. There is no limit - * checking. - * - * @param intArr The given input int array. - * @param index Zero-based index from the start of the int array. - * @param rem Remainder integers. An integer in the range [1,2]. - * @return long - */ - private static long getLong(final int[] intArr, final int index, final int rem) { - long out = 0L; - for (int i = rem; i-- > 0;) { //i= 1,0 - final int v = intArr[index + i]; - out ^= (v & 0xFFFFFFFFL) << (i * 32); //equivalent to |= - } - return out; - } - - /** - * Gets a long from the given char array starting at the given char array index and continuing for - * remainder (rem) chars. The chars are extracted in little-endian order. There is no limit - * checking. - * - * @param charArr The given input char array. - * @param index Zero-based index from the start of the char array. - * @param rem Remainder chars. An integer in the range [1,4]. - * @return a long - */ - private static long getLong(final char[] charArr, final int index, final int rem) { - long out = 0L; - for (int i = rem; i-- > 0;) { //i= 3,2,1,0 - final char c = charArr[index + i]; - out ^= (c & 0xFFFFL) << (i * 16); //equivalent to |= - } - return out; - } - - /** - * Gets a long from the given byte array starting at the given byte array index and continuing for - * remainder (rem) bytes. The bytes are extracted in little-endian order. There is no limit - * checking. - * - * @param bArr The given input byte array. - * @param index Zero-based index from the start of the byte array. - * @param rem Remainder bytes. An integer in the range [1,8]. - * @return a long - */ - private static long getLong(final byte[] bArr, final int index, final int rem) { - long out = 0L; - for (int i = rem; i-- > 0;) { //i= 7,6,5,4,3,2,1,0 - final byte b = bArr[index + i]; - out ^= (b & 0xFFL) << (i * 8); //equivalent to |= - } - return out; - } - - /** - * Gets a long from the given MemorySegment starting at the given offsetBytes and continuing for - * remainder (rem) bytes. The bytes are extracted in little-endian order. There is no limit - * checking. - * - * @param seg The given input MemorySegment. - * @param offsetBytes Zero-based offset in bytes from the start of the MemorySegment. - * @param rem Remainder bytes. An integer in the range [1,8]. - * @return a long - */ - private static long getLong(final MemorySegment seg, final long offsetBytes, final int rem) { - long out = 0L; - if (rem == 8) { - return seg.get(JAVA_LONG_UNALIGNED, offsetBytes); - } - for (int i = rem; i-- > 0; ) { //i= 7,6,5,4,3,2,1,0 - final byte b = seg.get(JAVA_BYTE, offsetBytes + i); - out ^= (b & 0xFFL) << (i << 3); //equivalent to |= - } - return out; - } - - private static void checkPositive(final long size) { - if (size <= 0) { - throw new SketchesArgumentException("Array size must not be negative or zero: " + size); - } - } -} diff --git a/src/main/java/org/apache/datasketches/hash/MurmurHash3FFM.java b/src/main/java/org/apache/datasketches/hash/MurmurHash3FFM.java deleted file mode 100644 index 722aba8bb..000000000 --- a/src/main/java/org/apache/datasketches/hash/MurmurHash3FFM.java +++ /dev/null @@ -1,373 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hash; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static java.nio.charset.StandardCharsets.UTF_8; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -/** - * The MurmurHash3 is a fast, non-cryptographic, 128-bit hash function that has - * excellent avalanche and 2-way bit independence properties. - * - *

Austin Appleby's C++ - * - * MurmurHash3_x64_128(...), final revision 150, - * which is in the Public Domain, was the inspiration for this implementation in Java.

- * - *

This implementation of the MurmurHash3 allows hashing of a block of on-heap MemorySegment defined by an offset - * and length. The calling API also allows the user to supply the small output array of two longs, - * so that the entire hash function is static and free of object allocations.

- * - *

This implementation produces exactly the same hash result as the - * MurmurHash3 function in datasketches-java given compatible inputs.

- * - *

This FFM version of the implementation leverages the java.lang.foreign package (FFM) of JDK-25 in place of - * the Unsafe class. - * - * @author Lee Rhodes - */ -public final class MurmurHash3FFM { - private static final long C1 = 0x87c37b91114253d5L; - private static final long C2 = 0x4cf5ad432745937fL; - - private MurmurHash3FFM() { } - - /** - * Returns a 128-bit hash of the input. - * Provided for compatibility with older version of MurmurHash3, - * but empty or null input now throws IllegalArgumentException. - * @param in long array - * @param seed A long valued seed. - * @return the hash - * @throws IllegalArgumentException if input is empty or null - */ - public static long[] hash(final long[] in, final long seed) { - if ((in == null) || (in.length == 0)) { - throw new IllegalArgumentException("Input in is empty or null."); - } - return hash(MemorySegment.ofArray(in), 0L, in.length << 3, seed, new long[2]); - } - - /** - * Returns a 128-bit hash of the input. - * Provided for compatibility with older version of MurmurHash3, - * but empty or null input now throws IllegalArgumentException. - * @param in int array - * @param seed A long valued seed. - * @return the hash - * @throws IllegalArgumentException if input is empty or null - */ - public static long[] hash(final int[] in, final long seed) { - if ((in == null) || (in.length == 0)) { - throw new IllegalArgumentException("Input in is empty or null."); - } - return hash(MemorySegment.ofArray(in), 0L, in.length << 2, seed, new long[2]); - } - - /** - * Returns a 128-bit hash of the input. - * Provided for compatibility with older version of MurmurHash3, - * but empty or null input now throws IllegalArgumentException. - * @param in char array - * @param seed A long valued seed. - * @return the hash - * @throws IllegalArgumentException if input is empty or null - */ - public static long[] hash(final char[] in, final long seed) { - if ((in == null) || (in.length == 0)) { - throw new IllegalArgumentException("Input in is empty or null."); - } - return hash(MemorySegment.ofArray(in), 0L, in.length << 1, seed, new long[2]); - } - - /** - * Returns a 128-bit hash of the input. - * Provided for compatibility with older version of MurmurHash3, - * but empty or null input now throws IllegalArgumentException. - * @param in byte array - * @param seed A long valued seed. - * @return the hash - * @throws IllegalArgumentException if input is empty or null - */ - public static long[] hash(final byte[] in, final long seed) { - if ((in == null) || (in.length == 0)) { - throw new IllegalArgumentException("Input in is empty or null."); - } - return hash(MemorySegment.ofArray(in), 0L, in.length, seed, new long[2]); - } - - //Single primitive inputs - - /** - * Returns a 128-bit hash of the input. - * Note the entropy of the resulting hash cannot be more than 64 bits. - * @param in a long - * @param seed A long valued seed. - * @param hashOut A long array of size 2 - * @return the hash - */ - public static long[] hash(final long in, final long seed, final long[] hashOut) { - final long h1 = seed ^ mixK1(in); - final long h2 = seed; - return finalMix128(h1, h2, 8, hashOut); - } - - /** - * Returns a 128-bit hash of the input. - * Note the entropy of the resulting hash cannot be more than 64 bits. - * @param in a double - * @param seed A long valued seed. - * @param hashOut A long array of size 2 - * @return the hash - */ - public static long[] hash(final double in, final long seed, final long[] hashOut) { - final double d = (in == 0.0) ? 0.0 : in; // canonicalize -0.0, 0.0 - final long k1 = Double.doubleToLongBits(d); // canonicalize all NaN forms - final long h1 = seed ^ mixK1(k1); - final long h2 = seed; - return finalMix128(h1, h2, 8, hashOut); - } - - /** - * Returns a 128-bit hash of the input. - * An empty or null input throws IllegalArgumentException. - * @param in a String - * @param seed A long valued seed. - * @param hashOut A long array of size 2 - * @return the hash - * @throws IllegalArgumentException if input is empty or null - */ - public static long[] hash(final String in, final long seed, final long[] hashOut) { - if ((in == null) || (in.length() == 0)) { - throw new IllegalArgumentException("Input in is empty or null."); - } - final byte[] byteArr = in.getBytes(UTF_8); - return hash(MemorySegment.ofArray(byteArr), 0L, byteArr.length, seed, hashOut); - } - - //The worker method - - /** - * Returns a 128-bit hash of the input as a long array of size 2. - * - * @param seg The input MemorySegment. Must be non-null and non-empty, - * otherwise throws IllegalArgumentException. - * @param offsetBytes the starting point within MemorySegment. - * @param lengthBytes the total number of bytes to be hashed. - * @param seed A long valued seed. - * @param hashOut the size 2 long array for the resulting 128-bit hash - * @return the hash. - * @throws IllegalArgumentException if input MemorySegment is empty - */ - public static long[] hash(final MemorySegment seg, final long offsetBytes, final long lengthBytes, - final long seed, final long[] hashOut) { - Objects.requireNonNull(seg, "Input MemorySegment must not be null"); - final long segCap = seg.byteSize(); - if (segCap == 0L) { throw new IllegalArgumentException("Input MemorySegment must not be empty."); } - - long cumOff = offsetBytes; - long rem = lengthBytes; - - long h1 = seed; - long h2 = seed; - - // Process the 128-bit blocks (the body) into the hash - while (rem >= 16L) { - final long k1 = seg.get(JAVA_LONG_UNALIGNED, cumOff); //0, 16, 32, ... - final long k2 = seg.get(JAVA_LONG_UNALIGNED, cumOff + 8); //8, 24, 40, ... - - synchronized (MurmurHash3FFM.class) { - cumOff += 16L; - rem -= 16L; - } - - h1 ^= mixK1(k1); - h1 = Long.rotateLeft(h1, 27); - h1 += h2; - h1 = (h1 * 5) + 0x52dce729L; - - h2 ^= mixK2(k2); - h2 = Long.rotateLeft(h2, 31); - h2 += h1; - h2 = (h2 * 5) + 0x38495ab5L; - } - - // Get the tail (if any): 1 to 15 bytes - if (rem > 0L) { - long k1 = 0; - long k2 = 0; - switch ((int) rem) { - case 15: { - k2 ^= (seg.get(JAVA_BYTE, cumOff + 14) & 0xFFL) << 48; - } - //$FALL-THROUGH$ - case 14: { - k2 ^= (seg.get(JAVA_SHORT_UNALIGNED, cumOff + 12) & 0xFFFFL) << 32; - k2 ^= seg.get(JAVA_INT_UNALIGNED, cumOff + 8) & 0xFFFFFFFFL; - k1 = seg.get(JAVA_LONG_UNALIGNED, cumOff); - break; - } - - case 13: { - k2 ^= (seg.get(JAVA_BYTE, cumOff + 12) & 0xFFL) << 32; - } - //$FALL-THROUGH$ - case 12: { - k2 ^= seg.get(JAVA_INT_UNALIGNED, cumOff + 8) & 0xFFFFFFFFL; - k1 = seg.get(JAVA_LONG_UNALIGNED, cumOff); - break; - } - - case 11: { - k2 ^= (seg.get(JAVA_BYTE, cumOff + 10) & 0xFFL) << 16; - } - //$FALL-THROUGH$ - case 10: { - k2 ^= seg.get(JAVA_SHORT_UNALIGNED, cumOff + 8) & 0xFFFFL; - k1 = seg.get(JAVA_LONG_UNALIGNED, cumOff); - break; - } - - case 9: { - k2 ^= seg.get(JAVA_BYTE, cumOff + 8) & 0xFFL; - } - //$FALL-THROUGH$ - case 8: { - k1 = seg.get(JAVA_LONG_UNALIGNED, cumOff); - break; - } - - case 7: { - k1 ^= (seg.get(JAVA_BYTE, cumOff + 6) & 0xFFL) << 48; - } - //$FALL-THROUGH$ - case 6: { - k1 ^= (seg.get(JAVA_SHORT_UNALIGNED, cumOff + 4) & 0xFFFFL) << 32; - k1 ^= seg.get(JAVA_INT_UNALIGNED, cumOff) & 0xFFFFFFFFL; - break; - } - - case 5: { - k1 ^= (seg.get(JAVA_BYTE, cumOff + 4) & 0xFFL) << 32; - } - //$FALL-THROUGH$ - case 4: { - k1 ^= seg.get(JAVA_INT_UNALIGNED, cumOff) & 0xFFFFFFFFL; - break; - } - - case 3: { - k1 ^= (seg.get(JAVA_BYTE, cumOff + 2) & 0xFFL) << 16; - } - //$FALL-THROUGH$ - case 2: { - k1 ^= seg.get(JAVA_SHORT_UNALIGNED, cumOff) & 0xFFFFL; - break; - } - - case 1: { - k1 ^= seg.get(JAVA_BYTE, cumOff) & 0xFFL; - break; - } - default: break; //can't happen - } - - h1 ^= mixK1(k1); - h2 ^= mixK2(k2); - } - return finalMix128(h1, h2, lengthBytes, hashOut); - } - - //--Helper methods---------------------------------------------------- - - /** - * Self mix of k1 - * - * @param k1 input argument - * @return mix - */ - private static long mixK1(long k1) { - k1 *= C1; - k1 = Long.rotateLeft(k1, 31); - k1 *= C2; - return k1; - } - - /** - * Self mix of k2 - * - * @param k2 input argument - * @return mix - */ - private static long mixK2(long k2) { - k2 *= C2; - k2 = Long.rotateLeft(k2, 33); - k2 *= C1; - return k2; - } - - /** - * Final self mix of h*. - * - * @param h input to final mix - * @return mix - */ - private static long finalMix64(long h) { - h ^= h >>> 33; - h *= 0xff51afd7ed558ccdL; - h ^= h >>> 33; - h *= 0xc4ceb9fe1a85ec53L; - h ^= h >>> 33; - return h; - } - - /** - * Finalization: Add the length into the hash and mix - * @param h1 intermediate hash - * @param h2 intermediate hash - * @param lengthBytes the length in bytes - * @param hashOut the output array of 2 longs - * @return hashOut - */ - private static long[] finalMix128(long h1, long h2, final long lengthBytes, final long[] hashOut) { - h1 ^= lengthBytes; - h2 ^= lengthBytes; - - h1 += h2; - h2 += h1; - - h1 = finalMix64(h1); - h2 = finalMix64(h2); - - h1 += h2; - h2 += h1; - - hashOut[0] = h1; - hashOut[1] = h2; - return hashOut; - } - -} diff --git a/src/main/java/org/apache/datasketches/hash/XxHash.java b/src/main/java/org/apache/datasketches/hash/XxHash.java deleted file mode 100644 index cb3f6e0df..000000000 --- a/src/main/java/org/apache/datasketches/hash/XxHash.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hash; - -import static org.apache.datasketches.hash.XxHash64.hash; -import static org.apache.datasketches.hash.XxHash64.hashBytes; -import static org.apache.datasketches.hash.XxHash64.hashChars; -import static org.apache.datasketches.hash.XxHash64.hashDoubles; -import static org.apache.datasketches.hash.XxHash64.hashFloats; -import static org.apache.datasketches.hash.XxHash64.hashInts; -import static org.apache.datasketches.hash.XxHash64.hashLongs; -import static org.apache.datasketches.hash.XxHash64.hashShorts; - -/** - * The XxHash is a fast, non-cryptographic, 64-bit hash function that has - * excellent avalanche and 2-way bit independence properties. - * This java version adapted the C++ version and the OpenHFT/Zero-Allocation-Hashing implementation - * referenced below as inspiration. - * - *

The C++ source repository: - * - * https://github.com/Cyan4973/xxHash. It has a BSD 2-Clause License: - * - * http://www.opensource.org/licenses/bsd-license.php. See LICENSE. - * - *

Portions of this code were adapted from - * - * OpenHFT/Zero-Allocation-Hashing, which has an Apache 2 license as does this site. See LICENSE. - * - * @author Lee Rhodes - */ -public final class XxHash { - - private XxHash() { /* singleton */ } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetBytes starting at this offset - * @param lengthBytes continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashByteArr( - final byte[] arr, - final int offsetBytes, - final int lengthBytes, - final long seed) { - return hashBytes(arr, offsetBytes, lengthBytes, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetShorts starting at this offset - * @param lengthShorts continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashShortArr( - final short[] arr, - final int offsetShorts, - final int lengthShorts, - final long seed) { - return hashShorts(arr, offsetShorts, lengthShorts, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetChars starting at this offset - * @param lengthChars continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashCharArr( - final char[] arr, - final int offsetChars, - final int lengthChars, - final long seed) { - return hashChars(arr, offsetChars, lengthChars, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetInts starting at this offset - * @param lengthInts continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashIntArr( - final int[] arr, - final int offsetInts, - final int lengthInts, - final long seed) { - return hashInts(arr, offsetInts, lengthInts, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetLongs starting at this offset - * @param lengthLongs continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashLongArr( - final long[] arr, - final int offsetLongs, - final int lengthLongs, - final long seed) { - return hashLongs(arr, offsetLongs, lengthLongs, seed); - } - - /** - * Returns a 64-bit hash from a single long. This method has been optimized for speed when only - * a single hash of a long is required. - * @param in A long. - * @param seed A long valued seed. - * @return the hash. - */ - public static long hashLong( - final long in, - final long seed) { - return hash(in, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetFloats starting at this offset - * @param lengthFloats continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashFloatArr( - final float[] arr, - final int offsetFloats, - final int lengthFloats, - final long seed) { - return hashFloats(arr, offsetFloats, lengthFloats, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetDoubles starting at this offset - * @param lengthDoubles continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashDoubleArr( - final double[] arr, - final int offsetDoubles, - final int lengthDoubles, - final long seed) { - return hashDoubles(arr, offsetDoubles, lengthDoubles, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param str the given string - * @param offsetChars starting at this offset - * @param lengthChars continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashString( - final String str, - final int offsetChars, - final int lengthChars, - final long seed) { - return XxHash64.hashString(str, offsetChars, lengthChars, seed); - } - -} diff --git a/src/main/java/org/apache/datasketches/hash/XxHash64.java b/src/main/java/org/apache/datasketches/hash/XxHash64.java deleted file mode 100644 index a908b6aaf..000000000 --- a/src/main/java/org/apache/datasketches/hash/XxHash64.java +++ /dev/null @@ -1,314 +0,0 @@ - /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hash; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -/** - * The XxHash is a fast, non-cryptographic, 64-bit hash function that has - * excellent avalanche and 2-way bit independence properties. - * This java version adapted from the C++ version and the OpenHFT/Zero-Allocation-Hashing implementation - * referenced below as inspiration. - * - *

The C++ source repository: - * - * https://github.com/Cyan4973/xxHash. It has a BSD 2-Clause License: - * - * http://www.opensource.org/licenses/bsd-license.php. See LICENSE. - * - *

Portions of this code were adapted from - * - * OpenHFT/Zero-Allocation-Hashing, which has an Apache 2 license as does this site. See LICENSE. - * - * @author Lee Rhodes - */ -public final class XxHash64 { - // Unsigned, 64-bit primes - private static final long P1 = -7046029288634856825L; - private static final long P2 = -4417276706812531889L; - private static final long P3 = 1609587929392839161L; - private static final long P4 = -8796714831421723037L; - private static final long P5 = 2870177450012600261L; - //shift constants - private static final byte SHORT_SHIFT = 1; - private static final byte CHAR_SHIFT = 1; - private static final byte INT_SHIFT = 2; - private static final byte LONG_SHIFT = 3; - private static final byte FLOAT_SHIFT = 2; - private static final byte DOUBLE_SHIFT = 3; - - private XxHash64() { } - - /** - * Returns the 64-bit hash of the sequence of bytes in the given MemorySegment - * - * @param seg A reference to the relevant MemorySegment. - * @param offsetBytes offset in bytes in the given segment. - * @param lengthBytes the length in bytes to be hashed - * @param seed a given seed - * @return the 64-bit hash of the sequence of bytes. - */ - public static long hash(final MemorySegment seg, long offsetBytes, final long lengthBytes, final long seed) { - long hash; - long remaining = lengthBytes; - - if (remaining >= 32) { - long v1 = seed + P1 + P2; - long v2 = seed + P2; - long v3 = seed; - long v4 = seed - P1; - - do { - v1 += seg.get(JAVA_LONG_UNALIGNED, offsetBytes) * P2; - v1 = Long.rotateLeft(v1, 31); - v1 *= P1; - - v2 += seg.get(JAVA_LONG_UNALIGNED, offsetBytes + 8L) * P2; - v2 = Long.rotateLeft(v2, 31); - v2 *= P1; - - v3 += seg.get(JAVA_LONG_UNALIGNED, offsetBytes + 16L) * P2; - v3 = Long.rotateLeft(v3, 31); - v3 *= P1; - - v4 += seg.get(JAVA_LONG_UNALIGNED, offsetBytes + 24L) * P2; - v4 = Long.rotateLeft(v4, 31); - v4 *= P1; - - offsetBytes += 32; - remaining -= 32; - } while (remaining >= 32); - - hash = Long.rotateLeft(v1, 1) - + Long.rotateLeft(v2, 7) - + Long.rotateLeft(v3, 12) - + Long.rotateLeft(v4, 18); - - v1 *= P2; - v1 = Long.rotateLeft(v1, 31); - v1 *= P1; - hash ^= v1; - hash = (hash * P1) + P4; - - v2 *= P2; - v2 = Long.rotateLeft(v2, 31); - v2 *= P1; - hash ^= v2; - hash = (hash * P1) + P4; - - v3 *= P2; - v3 = Long.rotateLeft(v3, 31); - v3 *= P1; - hash ^= v3; - hash = (hash * P1) + P4; - - v4 *= P2; - v4 = Long.rotateLeft(v4, 31); - v4 *= P1; - hash ^= v4; - hash = (hash * P1) + P4; - } //end remaining >= 32 - else { - hash = seed + P5; - } - - hash += lengthBytes; - - while (remaining >= 8) { - long k1 = seg.get(JAVA_LONG_UNALIGNED, offsetBytes); - k1 *= P2; - k1 = Long.rotateLeft(k1, 31); - k1 *= P1; - hash ^= k1; - hash = (Long.rotateLeft(hash, 27) * P1) + P4; - offsetBytes += 8; - remaining -= 8; - } - - if (remaining >= 4) { //treat as unsigned ints - hash ^= (seg.get(JAVA_INT_UNALIGNED, offsetBytes) & 0XFFFF_FFFFL) * P1; - hash = (Long.rotateLeft(hash, 23) * P2) + P3; - offsetBytes += 4; - remaining -= 4; - } - - while (remaining != 0) { //treat as unsigned bytes - hash ^= (seg.get(JAVA_BYTE, offsetBytes) & 0XFFL) * P5; - hash = Long.rotateLeft(hash, 11) * P1; - --remaining; - ++offsetBytes; - } - - return finalize(hash); - } - - /** - * Returns a 64-bit hash from a single long. This method has been optimized for speed when only - * a single hash of a long is required. - * @param in A long. - * @param seed A long valued seed. - * @return the hash. - */ - public static long hash(final long in, final long seed) { - long hash = seed + P5; - hash += 8; - long k1 = in; - k1 *= P2; - k1 = Long.rotateLeft(k1, 31); - k1 *= P1; - hash ^= k1; - hash = (Long.rotateLeft(hash, 27) * P1) + P4; - return finalize(hash); - } - - private static long finalize(long hash) { - hash ^= hash >>> 33; - hash *= P2; - hash ^= hash >>> 29; - hash *= P3; - hash ^= hash >>> 32; - return hash; - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetBytes starting at this offset - * @param lengthBytes continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashBytes(final byte[] arr, final int offsetBytes, - final int lengthBytes, final long seed) { - final MemorySegment seg = MemorySegment.ofArray(arr); - return hash(seg, offsetBytes, lengthBytes, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetShorts starting at this offset - * @param lengthShorts continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashShorts(final short[] arr, final int offsetShorts, - final int lengthShorts, final long seed) { - final MemorySegment seg = MemorySegment.ofArray(arr); - return hash(seg, (offsetShorts << SHORT_SHIFT), lengthShorts << SHORT_SHIFT, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetChars starting at this offset - * @param lengthChars continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashChars(final char[] arr, final int offsetChars, - final int lengthChars, final long seed) { - final MemorySegment seg = MemorySegment.ofArray(arr); - return hash(seg, offsetChars << CHAR_SHIFT, lengthChars << CHAR_SHIFT, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetInts starting at this offset - * @param lengthInts continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashInts(final int[] arr, final int offsetInts, - final int lengthInts, final long seed) { - final MemorySegment seg = MemorySegment.ofArray(arr); - return hash(seg, offsetInts << INT_SHIFT, lengthInts << INT_SHIFT, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetLongs starting at this offset - * @param lengthLongs continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashLongs(final long[] arr, final int offsetLongs, - final int lengthLongs, final long seed) { - final MemorySegment seg = MemorySegment.ofArray(arr); - return hash(seg, offsetLongs << LONG_SHIFT, lengthLongs << LONG_SHIFT, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetFloats starting at this offset - * @param lengthFloats continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashFloats(final float[] arr, final int offsetFloats, - final int lengthFloats, final long seed) { - final MemorySegment seg = MemorySegment.ofArray(arr); - return hash(seg, offsetFloats << FLOAT_SHIFT, lengthFloats << FLOAT_SHIFT, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param arr the given array - * @param offsetDoubles starting at this offset - * @param lengthDoubles continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashDoubles(final double[] arr, final int offsetDoubles, - final int lengthDoubles, final long seed) { - final MemorySegment seg = MemorySegment.ofArray(arr); - return hash(seg, offsetDoubles << DOUBLE_SHIFT, lengthDoubles << DOUBLE_SHIFT, seed); - } - - /** - * Hash the given arr starting at the given offset and continuing for the given length using the - * given seed. - * @param str the given string - * @param offsetChars starting at this offset - * @param lengthChars continuing for this length - * @param seed the given seed - * @return the hash - */ - public static long hashString(final String str, final int offsetChars, - final int lengthChars, final long seed) { - final MemorySegment seg = MemorySegment.ofArray(str.toCharArray()); - return hash(seg, offsetChars << CHAR_SHIFT, lengthChars << CHAR_SHIFT, seed); - } - -} diff --git a/src/main/java/org/apache/datasketches/hash/package-info.java b/src/main/java/org/apache/datasketches/hash/package-info.java deleted file mode 100644 index 5744b2776..000000000 --- a/src/main/java/org/apache/datasketches/hash/package-info.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * The hash package contains a high-performing and extended Java implementations - * of Austin Appleby's 128-bit MurmurHash3 hash function originally coded in C. - * This core MurmurHash3.java class is used throughout many of the sketch classes for consistency - * and as long as the user specifies the same seed will result in coordinated hash operations. - * This package also contains an adaptor class that extends the basic class with more functions - * commonly associated with hashing. - */ -package org.apache.datasketches.hash; diff --git a/src/main/java/org/apache/datasketches/hll/AbstractCoupons.java b/src/main/java/org/apache/datasketches/hll/AbstractCoupons.java deleted file mode 100644 index 62727ebed..000000000 --- a/src/main/java/org/apache/datasketches/hll/AbstractCoupons.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.Math.max; -import static org.apache.datasketches.hll.HllUtil.COUPON_RSE; -import static org.apache.datasketches.hll.HllUtil.EMPTY; -import static org.apache.datasketches.hll.HllUtil.KEY_MASK_26; -import static org.apache.datasketches.hll.ToByteArrayImpl.toCouponByteArray; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * @author Lee Rhodes - */ -abstract class AbstractCoupons extends HllSketchImpl { - - AbstractCoupons(final int lgConfigK, final TgtHllType tgtHllType, final CurMode curMode) { - super(lgConfigK, tgtHllType, curMode); - } - - @Override - double getCompositeEstimate() { - return getEstimate(); - } - - abstract int getCouponCount(); - - abstract int[] getCouponIntArr(); - - /** - * This is the estimator for the Coupon List mode and Coupon Hash Set mode. - * - *

Note: This is an approximation to the true mapping from numCoupons to N, - * which has a range of validity roughly from 0 to 6 million coupons.

- * - *

The k of the implied coupon sketch, which must not be confused with the k of the HLL - * sketch. In this application k is always 2^26, which is the number of address bits of the - * 32-bit coupon.

- * @return the unique count estimate. - */ - @Override - double getEstimate() { - final int couponCount = getCouponCount(); - final double est = CubicInterpolation.usingXAndYTables(CouponMapping.xArr, - CouponMapping.yArr, couponCount); - return max(est, couponCount); - } - - @Override - double getHipEstimate() { - return getEstimate(); - } - - abstract int getLgCouponArrInts(); - - @Override - double getLowerBound(final int numStdDev) { - HllUtil.checkNumStdDev(numStdDev); - final int couponCount = getCouponCount(); - final double est = CubicInterpolation.usingXAndYTables(CouponMapping.xArr, - CouponMapping.yArr, couponCount); - final double tmp = est / (1.0 + (numStdDev * COUPON_RSE)); - return max(tmp, couponCount); - } - - @Override - double getUpperBound(final int numStdDev) { - HllUtil.checkNumStdDev(numStdDev); - final int couponCount = getCouponCount(); - final double est = CubicInterpolation.usingXAndYTables(CouponMapping.xArr, - CouponMapping.yArr, couponCount); - final double tmp = est / (1.0 - (numStdDev * COUPON_RSE)); - return max(tmp, couponCount); - } - - @Override - int getUpdatableSerializationBytes() { - return getSegDataStart() + (4 << getLgCouponArrInts()); - } - - @Override - boolean isEmpty() { - return getCouponCount() == 0; - } - - @Override - boolean isOutOfOrder() { - return false; - } - - @Override - boolean isRebuildCurMinNumKxQFlag() { - return false; - } - - @Override - void putEmptyFlag(final boolean empty) { /*no-op for coupons */ } - - @Override - void putOutOfOrder(final boolean outOfOrder) { /*no-op for coupons */ } - - @Override - void putRebuildCurMinNumKxQFlag(final boolean rebuild) { /*no-op for coupons */ } - - @Override - byte[] toCompactByteArray() { - return toCouponByteArray(this, true); - } - - @Override - byte[] toUpdatableByteArray() { - return toCouponByteArray(this, false); - } - - //FIND for Heap and Direct - //Searches the Coupon hash table for an empty slot or a duplicate depending on the context. - //If entire entry is empty, returns one's complement of index = found empty. - //If entry equals given coupon, returns its index = found duplicate coupon - //Continues searching - //If the probe comes back to original index, throws an exception. - //Called by CouponHashSet.couponUpdate() - //Called by CouponHashSet.growHashSet() - //Called by DirectCouponHashSet.growHashSet() - static final int find(final int[] array, final int lgArrInts, final int coupon) { - final int arrMask = array.length - 1; - int probe = coupon & arrMask; - final int loopIndex = probe; - do { - final int couponAtIdx = array[probe]; - if (couponAtIdx == EMPTY) { - return ~probe; //empty - } - else if (coupon == couponAtIdx) { - return probe; //duplicate - } - final int stride = ((coupon & KEY_MASK_26) >>> lgArrInts) | 1; - probe = (probe + stride) & arrMask; - } while (probe != loopIndex); - throw new SketchesArgumentException("Key not found and no empty slots!"); - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/AbstractHllArray.java b/src/main/java/org/apache/datasketches/hll/AbstractHllArray.java deleted file mode 100644 index 1a152e7ee..000000000 --- a/src/main/java/org/apache/datasketches/hll/AbstractHllArray.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.common.Util.invPow2; -import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.HLL_PREINTS; -import static org.apache.datasketches.hll.TgtHllType.HLL_4; -import static org.apache.datasketches.hll.TgtHllType.HLL_6; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * @author Lee Rhodes - */ -abstract class AbstractHllArray extends HllSketchImpl { - AuxHashMap auxHashMap = null; //used for both heap and direct HLL4 - final int auxStart; //used for direct HLL4 - - AbstractHllArray(final int lgConfigK, final TgtHllType tgtHllType, final CurMode curMode) { - super(lgConfigK, tgtHllType, curMode); - auxStart = HLL_BYTE_ARR_START + hll4ArrBytes(lgConfigK); - } - - abstract void addToHipAccum(double delta); - - @Override - HllArray copyAs(final TgtHllType tgtHllType) { - if (tgtHllType == getTgtHllType()) { - return (HllArray) copy(); - } - if (tgtHllType == HLL_4) { - return Conversions.convertToHll4(this); - } - if (tgtHllType == HLL_6) { - return Conversions.convertToHll6(this); - } - return Conversions.convertToHll8(this); - } - - abstract void decNumAtCurMin(); - - AuxHashMap getAuxHashMap() { - return auxHashMap; - } - - PairIterator getAuxIterator() { - return (auxHashMap == null) ? null : auxHashMap.getIterator(); - } - - @Override - int getCompactSerializationBytes() { - final AuxHashMap auxHashMap = getAuxHashMap(); - final int auxCountBytes = (auxHashMap == null) ? 0 : auxHashMap.getAuxCount() << 2; - return HLL_BYTE_ARR_START + getHllByteArrBytes() + auxCountBytes; - } - - /** - * This is the (non-HIP) estimator. - * It is called "composite" because multiple estimators are pasted together. - * @return the composite estimate - */ - //In C: again-two-registers.c hhb_get_composite_estimate L1489 - @Override - double getCompositeEstimate() { - return HllEstimators.hllCompositeEstimate(this); - } - - abstract int getCurMin(); - - @Override - double getEstimate() { - if (isOutOfOrder()) { - return getCompositeEstimate(); - } - return getHipAccum(); - } - - /** - * For each actual update of the sketch, where the state of the sketch is changed, this register - * tracks the Historical Inverse Probability or HIP. Before the update is recorded this register - * is incremented by adding the inverse probability 1/Q (defined below). Since KxQ is scaled by K, - * the actual increment is K/KxQ as can be seen in the hipAndKxQIncrementalUpdate(...) method - * below. - * @return the HIP Accumulator - */ - abstract double getHipAccum(); - - @Override - double getHipEstimate() { - return getHipAccum(); - } - - abstract int getHllByteArrBytes(); - - /** - * Q = KxQ/K is the probability that an incoming event can modify the state of the sketch. - * KxQ is literally K times Q. The HIP estimator is based on tracking this probability as the - * sketch gets populated. It is tracked in the hipAccum register. - * - *

The KxQ registers serve dual purposes: They are used in the HIP estimator and in - * the "raw" HLL estimator defined in the Flajolet, et al, 2007 HLL paper. In order to do this, - * the way the KxQ registers are computed here differ from how they are defined in the paper.

- * - *

The paper Fig 2 defines

- *
Z := ( sum[j=1,m](2^(-M[j])) )^(-1).
- * But the HIP estimator requires a computation of the probability defined above. - * We accomplish both by redefining Z as - *
Z := ( m + sum[j=1,m](2^(-M[j] - 1)) )^(-1).
- * They are mathematically equivalent since: - *
m + sum[j=1,m](2^(-M[j] - 1)) == m + sum[j=1,m](2^(-M[j])) - m == sum[j=1,m](2^(-M[j])).
- * - * @return KxQ0 - */ - abstract double getKxQ0(); - - /** - * This second KxQ register is shifted by 32 bits to give us more than 90 bits of mantissa - * precision, which produces more accurate results for very large counts. - * @return KxQ1 - */ - abstract double getKxQ1(); - - @Override - double getLowerBound(final int numStdDev) { - HllUtil.checkNumStdDev(numStdDev); - return HllEstimators.hllLowerBound(this, numStdDev); - } - - @Override - int getSegDataStart() { - return HLL_BYTE_ARR_START; - } - - abstract AuxHashMap getNewAuxHashMap(); - - /** - * Returns the number of slots that have the value CurMin. - * If CurMin is 0, then it returns the number of zeros in the array. - * @return the number of slots that have the value CurMin. - */ - abstract int getNumAtCurMin(); - - @Override - int getPreInts() { - return HLL_PREINTS; - } - - //overridden by Hll4Array and DirectHll4Array - abstract int getNibble(int slotNo); - - abstract int getSlotValue(int slotNo); - - @Override //used by HLL6 and HLL8, Overridden by HLL4 - int getUpdatableSerializationBytes() { - return HLL_BYTE_ARR_START + getHllByteArrBytes(); - } - - @Override - double getUpperBound(final int numStdDev) { - HllUtil.checkNumStdDev(numStdDev); - return HllEstimators.hllUpperBound(this, numStdDev); - } - - @Override - abstract PairIterator iterator(); - - @Override - void mergeTo(final HllSketch that) { - throw new SketchesStateException("Possible Corruption, improper access."); - } - - abstract void putAuxHashMap(AuxHashMap auxHashMap, boolean compact); - - abstract void putCurMin(int curMin); - - abstract void putHipAccum(double hipAccum); - - abstract void putKxQ0(double kxq0); - - abstract void putKxQ1(double kxq1); - - //overridden by Hll4Array and DirectHll4Array - abstract void putNibble(int slotNo, int nibValue); - - abstract void putNumAtCurMin(int numAtCurMin); - - abstract void updateSlotWithKxQ(final int slotNo, final int value); - - abstract void updateSlotNoKxQ(final int slotNo, final int value); - - //Compute HLL byte array lengths, used by both heap and direct. - - static final int hll4ArrBytes(final int lgConfigK) { - return 1 << (lgConfigK - 1); - } - - static final int hll6ArrBytes(final int lgConfigK) { - final int numSlots = 1 << lgConfigK; - return ((numSlots * 3) >>> 2) + 1; - } - - static final int hll8ArrBytes(final int lgConfigK) { - return 1 << lgConfigK; - } - - /** - * Common HIP and KxQ incremental update for all heap and direct Hll. - * This is used when incrementally updating an existing array with non-zero values. - * @param host the origin implementation - * @param oldValue old value - * @param newValue new value - */ - //Called here and by Heap and Direct 6 and 8 bit implementations - //In C: again-two-registers.c Lines 851 to 871 - static final void hipAndKxQIncrementalUpdate(final AbstractHllArray host, - final int oldValue, final int newValue) { - assert newValue > oldValue; - final double kxq0 = host.getKxQ0(); - final double kxq1 = host.getKxQ1(); - //update hipAccum BEFORE updating kxq0 and kxq1 - host.addToHipAccum((1 << host.getLgConfigK()) / (kxq0 + kxq1)); - incrementalUpdateKxQ(host, oldValue, newValue, kxq0, kxq1); - } - - //separate KxQ updates - static final void incrementalUpdateKxQ(final AbstractHllArray host, - final int oldValue, final int newValue, double kxq0, double kxq1) { - //update kxq0 and kxq1; subtract first, then add. - if (oldValue < 32) { host.putKxQ0(kxq0 -= invPow2(oldValue)); } - else { host.putKxQ1(kxq1 -= invPow2(oldValue)); } - if (newValue < 32) { host.putKxQ0(kxq0 + invPow2(newValue)); } - else { host.putKxQ1(kxq1 + invPow2(newValue)); } - } -} diff --git a/src/main/java/org/apache/datasketches/hll/AuxHashMap.java b/src/main/java/org/apache/datasketches/hll/AuxHashMap.java deleted file mode 100644 index f255b0fd6..000000000 --- a/src/main/java/org/apache/datasketches/hll/AuxHashMap.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.MemorySegmentStatus; - -/** - * @author Lee Rhodes - */ -interface AuxHashMap extends MemorySegmentStatus { - - AuxHashMap copy(); - - int getAuxCount(); - - int[] getAuxIntArr(); - - int getCompactSizeBytes(); - - PairIterator getIterator(); - - int getLgAuxArrInts(); - - int getUpdatableSizeBytes(); - - @Override - boolean hasMemorySegment(); - - @Override - boolean isOffHeap(); - - @Override - boolean isSameResource(MemorySegment seg); - - /** - * Adds the slotNo and value to the aux array. - * @param slotNo the index from the HLL array - * @param value the HLL value at the slotNo. - * @throws SketchesStateException if this slotNo already exists in the aux array. - */ - void mustAdd(int slotNo, int value); - - /** - * Returns value given slotNo. If this fails an exception is thrown. - * @param slotNo the index from the HLL array - * @return value the HLL value at the slotNo - * @throws SketchesStateException if valid slotNo and value is not found. - */ - int mustFindValueFor(int slotNo); - - /** - * Replaces the entry at slotNo with the given value. - * @param slotNo the index from the HLL array - * @param value the HLL value at the slotNo - * @throws SketchesStateException if a valid slotNo, value is not found. - */ - void mustReplace(int slotNo, int value); - -} diff --git a/src/main/java/org/apache/datasketches/hll/BaseHllSketch.java b/src/main/java/org/apache/datasketches/hll/BaseHllSketch.java deleted file mode 100644 index 99107220e..000000000 --- a/src/main/java/org/apache/datasketches/hll/BaseHllSketch.java +++ /dev/null @@ -1,416 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.datasketches.hash.MurmurHash3.hash; -import static org.apache.datasketches.hll.HllUtil.HLL_HIP_RSE_FACTOR; -import static org.apache.datasketches.hll.HllUtil.HLL_NON_HIP_RSE_FACTOR; -import static org.apache.datasketches.hll.HllUtil.KEY_BITS_26; -import static org.apache.datasketches.hll.HllUtil.KEY_MASK_26; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; - -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.Util; - -/** - * Although this class is package-private, it provides a single place to define and document - * the common public API for both HllSketch and HllUnion. - * @author Lee Rhodes - * @author Kevin Lang - */ -abstract class BaseHllSketch implements MemorySegmentStatus { - - abstract void couponUpdate(int coupon); - - /** - * Gets the size in bytes of the current sketch when serialized using - * toCompactByteArray(). - * @return the size in bytes of the current sketch when serialized using - * toCompactByteArray(). - */ - public abstract int getCompactSerializationBytes(); - - /** - * This is less accurate than the getEstimate() method and is automatically used - * when the sketch has gone through union operations where the more accurate HIP estimator - * cannot be used. - * This is made public only for error characterization software that exists in separate - * packages and is not intended for normal use. - * @return the composite estimate - */ - public abstract double getCompositeEstimate(); - - /** - * Returns the current mode of the sketch: LIST, SET, HLL - * @return the current mode of the sketch: LIST, SET, HLL - */ - abstract CurMode getCurMode(); - - /** - * Return the cardinality estimate - * @return the cardinality estimate - */ - public abstract double getEstimate(); - - /** - * Gets the {@link TgtHllType} - * @return the TgtHllType enum value - */ - public abstract TgtHllType getTgtHllType(); - - /** - * Gets the lgConfigK. - * @return the lgConfigK. - */ - public abstract int getLgConfigK(); - - /** - * Gets the approximate lower error bound given the specified number of Standard Deviations. - * - * @param numStdDev This must be an integer between 1 and 3, inclusive. - * See Number of Standard Deviations - * @return the lower bound. - */ - public abstract double getLowerBound(int numStdDev); - - /** - * Returns the current serialization version. - * @return the current serialization version. - */ - public static final int getSerializationVersion() { - return PreambleUtil.SER_VER; - } - - /** - * Returns the current serialization version of the given MemorySegment. - * @param seg the given MemorySegment containing a serialized HllSketch image. - * @return the current serialization version. - */ - public static final int getSerializationVersion(final MemorySegment seg) { - return seg.get(JAVA_BYTE, PreambleUtil.SER_VER_BYTE) & 0XFF; - } - - /** - * Gets the current (approximate) Relative Error (RE) asymptotic values given several - * parameters. This is used primarily for testing. - * @param upperBound return the RE for the Upper Bound, otherwise for the Lower Bound. - * @param oooFlag set true if the sketch is the result of a non qualifying HllUnion operation. - * @param lgConfigK the configured value for the sketch. - * @param numStdDev the given number of Standard Deviations. This must be an integer between - * 1 and 3, inclusive. - * Number of Standard Deviations - * @return the current (approximate) RelativeError - */ - public static double getRelErr(final boolean upperBound, final boolean oooFlag, - final int lgConfigK, final int numStdDev) { - HllUtil.checkLgK(lgConfigK); - if (lgConfigK > 12) { - final double rseFactor = oooFlag ? HLL_NON_HIP_RSE_FACTOR : HLL_HIP_RSE_FACTOR; - final int configK = 1 << lgConfigK; - return (numStdDev * rseFactor) / Math.sqrt(configK); - } - return Math.abs(RelativeErrorTables.getRelErr(upperBound, oooFlag, lgConfigK, numStdDev)); - } - - /** - * Gets the size in bytes of the current sketch when serialized using - * toUpdatableByteArray(). - * @return the size in bytes of the current sketch when serialized using - * toUpdatableByteArray(). - */ - public abstract int getUpdatableSerializationBytes(); - - /** - * Gets the approximate upper error bound given the specified number of Standard Deviations. - * - * @param numStdDev This must be an integer between 1 and 3, inclusive. - * Number of Standard Deviations - * @return the upper bound. - */ - public abstract double getUpperBound(int numStdDev); - - /** - * Returns true if empty - * @return true if empty - */ - public abstract boolean isEmpty(); - - /** - * Returns true if the backing MemorySegment of this sketch is in compact form. - * @return true if the backing MemorySegment of this sketch is in compact form. - */ - public abstract boolean isCompact(); - - /** - * This HLL family of sketches and operators is always estimating, even for very small values. - * @return true - */ - public boolean isEstimationMode() { - return true; - } - - /** - * Returns true if this sketch was created using MemorySegment. - * @return true if this sketch was created using MemorySegment. - */ - @Override - public abstract boolean hasMemorySegment(); - - /** - * Returns true if the backing MemorySegment for this sketch is off-heap. - * @return true if the backing MemorySegment for this sketch is off-heap. - */ - @Override - public abstract boolean isOffHeap(); - - /** - * Gets the Out-of-order flag. - * @return true if the current estimator is the non-HIP estimator, which is slightly less - * accurate than the HIP estimator. - */ - abstract boolean isOutOfOrder(); - - /** - * Returns true if the given MemorySegment refers to the same underlying resource as this sketch. - * The capacities must be the same. If this is a region, - * the region offset must also be the same. - * - *

This is only relevant for HLL_4 sketches that have been configured for off-heap - * using MemorySegment. For on-heap sketches or unions this will return false. - * - *

It is rare, but possible, the the off-heap MemorySegment that has been allocated to an HLL_4 - * sketch may not be large enough. If this should happen, the sketch makes a request for more - * space from the owner of the resource and then moves itself to this new location. This all - * happens transparently to the user. This method provides a means for the user to - * inquire of the sketch if it has, in fact, moved itself. - * - * @param seg the given MemorySegment - * @return true if the given MemorySegment refers to the same underlying resource as this HllSketch or - * HllUnion. - */ - @Override - public abstract boolean isSameResource(MemorySegment seg); - - /** - * Resets to empty, but does not change the configured values of lgConfigK and tgtHllType. - */ - public abstract void reset(); - - /** - * Serializes this sketch as a byte array in compact form. The compact form is smaller in size - * than the updatable form and read-only. It can be used in HllUnion operations as follows: - *

{@code
-   *     HllUnion union; HllSketch sk, sk2;
-   *     int lgK = 12;
-   *     sk = new HllSketch(lgK, TgtHllType.HLL_4); //can be 4, 6, or 8
-   *     for (int i = 0; i < (2 << lgK); i++) { sk.update(i); }
-   *     byte[] arr = HllSketch.toCompactByteArray();
-   *     //...
-   *     union = HllUnion.heapify(arr); //initializes the HllUnion using data from the array.
-   *     //OR, if used in an off-heap environment:
-   *     union = HllUnion.heapify(MemorySegment.ofArray(arr)); //same as above, except from MemorySegment object.
-   *
-   *     //To recover an updatable heap sketch:
-   *     sk2 = HllSketch.heapify(arr);
-   *     //OR, if used in an off-heap environment:
-   *     sk2 = HllSketch.heapify(MemorySegment.ofArray(arr));
-   * }
- * - *

The sketch "wrapping" operation skips actual deserialization thus is quite fast. However, - * any attempt to update the derived HllSketch will result in a Read-only exception.

- * - *

Note that in some cases, based on the state of the sketch, the compact form is - * indistiguishable from the updatable form. In these cases the updatable form is returned - * and the compact flag bit will not be set.

- * @return this sketch as a compact byte array. - */ - public abstract byte[] toCompactByteArray(); - - /** - * Serializes this sketch as a byte array in an updatable form. The updatable form is larger than - * the compact form. The use of this form is primarily in environments that support updating - * sketches in off-heap MemorySegment. If the sketch is constructed using HLL_8, HllSketch updating and - * HllUnion updating operations can actually occur in MemorySegment, which can be off-heap: - *
{@code
-   *     HllUnion union; HllSketch sk;
-   *     int lgK = 12;
-   *     sk = new HllSketch(lgK, TgtHllType.HLL_8) //must be 8
-   *     for (int i = 0; i < (2 << lgK); i++) { sk.update(i); }
-   *     byte[] arr = sk.toUpdatableByteArray();
-   *     MemorySegment wseg = MemorySegment.wrap(arr);
-   *     //...
-   *     union = HllUnion.writableWrap(wseg); //no deserialization!
-   * }
- * @return this sketch as an updatable byte array. - */ - public abstract byte[] toUpdatableByteArray(); - - /** - * Human readable summary as a string. - * @return Human readable summary as a string. - */ - @Override - public String toString() { - return toString(true, false, false, false); - } - - /** - * Human readable summary with optional detail. Does not list empty entries. - * @param summary if true, output the sketch summary - * @param detail if true, output the internal data array - * @param auxDetail if true, output the internal Aux array, if it exists. - * @return human readable string with optional detail. - */ - public String toString(final boolean summary, final boolean detail, final boolean auxDetail) { - return toString(summary, detail, auxDetail, false); - } - - /** - * Human readable summary with optional detail - * @param summary if true, output the sketch summary - * @param detail if true, output the internal data array - * @param auxDetail if true, output the internal Aux array, if it exists. - * @param all if true, outputs all entries including empty ones - * @return human readable string with optional detail. - */ - public abstract String toString(boolean summary, boolean detail, boolean auxDetail, - boolean all); - - /** - * Present the given long as a potential unique item. - * - * @param datum The given long datum. - */ - public void update(final long datum) { - final long[] data = { datum }; - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); - } - - /** - * Present the given double (or float) datum as a potential unique item. - * The double will be converted to a long using Double.doubleToLongBits(datum), - * which normalizes all NaN values to a single NaN representation. - * Plus and minus zero will be normalized to plus zero. - * The special floating-point values NaN and +/- Infinity are treated as distinct. - * - * @param datum The given double datum. - */ - public void update(final double datum) { - final double d = (datum == 0.0) ? 0.0 : datum; // canonicalize -0.0, 0.0 - final long[] data = { Double.doubleToLongBits(d) };// canonicalize all NaN & +/- infinity forms - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); - } - - /** - * Present the given String as a potential unique item. - * The string is converted to a byte array using UTF8 encoding. - * If the string is null or empty no update attempt is made and the method returns. - * - *

Note: About 2X faster performance can be obtained by first converting the String to a - * char[] and updating the sketch with that. This bypasses the complexity of the Java UTF_8 - * encoding. This, of course, will not produce the same internal hash values as updating directly - * with a String. So be consistent! Unioning two sketches, one fed with strings and the other - * fed with char[] will be meaningless. - *

- * - * @param datum The given String. - */ - public void update(final String datum) { - if ((datum == null) || datum.isEmpty()) { return; } - final byte[] data = datum.getBytes(UTF_8); - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); - } - - /** - * Present the given byte buffer as a potential unique item. - * Bytes are read from the current position of the buffer until its limit. - * If the byte buffer is null or has no bytes remaining, no update attempt is made and the method returns. - * - *

This method will not modify the position, mark, limit, or byte order of the buffer.

- * - *

Little-endian order is preferred, but not required. This method may perform better if the provided byte - * buffer is in little-endian order.

- * - * @param data The given byte buffer. - */ - public void update(final ByteBuffer data) { - if ((data == null) || (data.remaining() == 0)) { return; } - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); - } - - /** - * Present the given byte array as a potential unique item. - * If the byte array is null or empty no update attempt is made and the method returns. - * - * @param data The given byte array. - */ - public void update(final byte[] data) { - if ((data == null) || (data.length == 0)) { return; } - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); - } - - /** - * Present the given char array as a potential unique item. - * If the char array is null or empty no update attempt is made and the method returns. - * - *

Note: this will not produce the same output hash values as the update(String) - * method but will be a little faster as it avoids the complexity of the UTF8 encoding.

- * - * @param data The given char array. - */ - public void update(final char[] data) { - if ((data == null) || (data.length == 0)) { return; } - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); - } - - /** - * Present the given integer array as a potential unique item. - * If the integer array is null or empty no update attempt is made and the method returns. - * - * @param data The given int array. - */ - public void update(final int[] data) { - if ((data == null) || (data.length == 0)) { return; } - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); - } - - /** - * Present the given long array as a potential unique item. - * If the long array is null or empty no update attempt is made and the method returns. - * - * @param data The given long array. - */ - public void update(final long[] data) { - if ((data == null) || (data.length == 0)) { return; } - couponUpdate(coupon(hash(data, Util.DEFAULT_UPDATE_SEED))); - } - - private static final int coupon(final long[] hash) { - final int addr26 = (int) ((hash[0] & KEY_MASK_26)); - final int lz = Long.numberOfLeadingZeros(hash[1]); - final int value = ((lz > 62 ? 62 : lz) + 1); - return (value << KEY_BITS_26) | addr26; - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/CompositeInterpolationXTable.java b/src/main/java/org/apache/datasketches/hll/CompositeInterpolationXTable.java deleted file mode 100644 index 030a3cf94..000000000 --- a/src/main/java/org/apache/datasketches/hll/CompositeInterpolationXTable.java +++ /dev/null @@ -1,782 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -final class CompositeInterpolationXTable { - - //CHECKSTYLE.OFF: LineLength - /** - * 18 Values, index 0 is LgK = 4, index 17 is LgK = 21. - */ - static final int[] yStrides = - {1, 2, 3, 5, 10, 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 20480, 40960, 81920 }; - - static final double xArrs[][] = { - // log K = 4 - { - 10.767999803534, 11.237701481774, 11.722738717438, 12.223246391222, - 12.739366773787, 13.271184824495, 13.818759686650, 14.382159835785, - 14.961390904922, 15.556414447178, 16.167227058768, 16.793705840034, - 17.435831011559, 18.093368824077, 18.766214022468, 19.454114555153, - 20.156877376380, 20.874309118151, 21.606085061388, 22.351926834624, - 23.111406651437, 23.884222842419, 24.669953053285, 25.468324695415, - 26.278740385032, 27.100807701976, 27.934264623663, 28.778498012717, - 29.633064579479, 30.497559091830, 31.371415928956, 32.254248998304, - 33.145649456017, 34.045084140394, 34.952069032314, 35.866210502243, - 36.787128772113, 37.714316067007, 38.647432342061, 39.586020708848, - 40.529738186256, 41.478377527525, 42.431435504179, 43.388619067416, - 44.349650659292, 45.314111448463, 46.281805382722, 47.252472240229, - 48.225969481651, 49.202042512440, 50.180350422249, 51.160761480664, - 52.143032445587, 53.127233235412, 54.112986437616, 55.100182392694, - 56.088558030701, 57.078156023607, 58.068788167275, 59.060493030644, - 60.053033784417, 61.046284072738, 62.040286486621, 63.034929032992, - 64.030027371399, 65.025588917110, 66.021614945599, 67.018177418440, - 68.015186786528, 69.012467972526, 70.010014322660, 71.007638150468, - 72.005472777573, 73.003558069130, 74.001925061314, 75.000323809106, - 75.998875046818, 76.997735309722, 77.996356820987, 78.995236661037, - 79.994185446564, 80.993179953574, 81.991936172868, 82.991277726952, - 83.990564675011, 84.990016215330, 85.989354175963, 86.988664031183, - 87.988038383374, 88.987487931153, 89.987011275632, 90.986376635228, - 91.985802667485, 92.985125933965, 93.984894049744, 94.984597185523, - 95.984374633793, 96.983987641198, 97.983728001025, 98.983151114601, - 99.982917278162, 100.982752268263, 101.982610588914, 102.982425129077, - 103.982425883214, 104.982193814993, 105.982188025268, 106.982005912713, - 107.981949640254, 108.981777381902, 109.981767708570, 110.981785341504, - 111.981686149156, 112.981635012054, 113.981557303839, 114.981412817204, - 115.981636136290, 116.981451847734, 117.981619278961, 118.981656205677, - 119.981462628717, 120.981648197593, 121.981672839888, 122.981536601882, - 123.981424780957, 124.981245233627, 125.981297203177, 126.981469882453, - 127.981420558510, 128.981470958251, 129.981803124940, 130.981454077005, - 131.981307772677, 132.981136552712, 133.981060440468, 134.980764897921, - 135.980250123519, 136.979947889981, 137.979778713731, 138.979651075854, - 139.979521006237, 140.979619490143, 141.979418214464, 142.979378742690, - 143.979006714929, 144.978789085341, 145.978940618746, 146.978699584620, - 147.978509489139, 148.978375065557, 149.978382007245, 150.978320879037, - 151.978431501891, 152.978357310224, 153.978079953131, 154.977867908315, - 155.977897282267, 156.977732141540, 157.977285841428, 158.977381755450, - 159.977107808858, 160.976898092463, 161.976945065052, 162.976415653211, - 163.976063254486, 164.976168718176, 165.976009634854, 166.975746910144, - 167.975365498336, 168.975302031315, 169.975145815395, 170.975048401084, - 171.974904933990, 172.974962856090, 173.974307743427, 174.974505556696, - 175.974404122880, 176.974154794798, 177.973936891006, 178.973909768514, - 179.973629325330, 180.973396428571, 181.973041798012, 182.972922327014, - 183.972453839631, 184.972389341638, 185.971978290400, 186.971721489488, - 187.971610992921, 188.971432541974, 189.970886522529, 190.970636748690, - 191.970543849249, 192.970222044828, 193.969945219163, 194.969816174441, - 195.969660267113, 196.969306217626, 197.969283141670, 198.968952697752, - 199.968650726389, 200.968771498143, 201.969063388798, 202.968624157712, - 203.968385122471, 204.968459873029, 205.968253426841, 206.968128284823, - 207.968002441937, 208.967981887571, 209.967853843352, 210.967653026858, - 211.967601511385, 212.967479077297, 213.967293002672, 214.967265475369, - 215.967098197208, 216.966915139758, 217.966680984700, 218.966156974161, - 219.965788928685, 220.965578199561, 221.965550145047, 222.965055562297, - 223.965041228123, 224.965088576052, 225.964951649635, 226.964837079061, - 227.964949815142, 228.964753278386, 229.964358666956, 230.964158288467, - 231.964118659643, 232.964105599719, 233.964013041408, 234.963810178150, - 235.963847138572, 236.963634735645, 237.963596910032, 238.963659218725, - 239.963498440155, 240.963445597658, 241.963141291971, 242.962684055746, - 243.962664757583, 244.962762174588, 245.962862664373, 246.962595237647, - 247.962493432533, 248.962292518484, 249.962622934132, 250.962187495200, - 251.962038306920, 252.961926735684, 253.961867248643, 254.961699581530, - 255.961371028199 - }, - // log K = 5 - { - 22.304000309384, 23.261989079230, 24.249656493833, 25.267226901899, - 26.314781734430, 27.392414068382, 28.500177845081, 29.638044883897, - 30.805888087516, 32.003714838418, 33.231360682863, 34.488477823483, - 35.774924122967, 37.090293268866, 38.434292452116, 39.806594197334, - 41.206691028159, 42.634002763091, 44.088065403269, 45.568286128520, - 47.074066947685, 48.604745105475, 50.159729872619, 51.738339282229, - 53.339805618020, 54.963435280656, 56.608464119077, 58.274038434156, - 59.959403900602, 61.663926660982, 63.386737477574, 65.127093833107, - 66.884091606686, 68.656959698762, 70.445052178435, 72.247581860591, - 74.063607663774, 75.892531705810, 77.733879994604, 79.586788509372, - 81.450593478752, 83.324645303244, 85.208482496209, 87.101116685537, - 89.002152917959, 90.911090999940, 92.827275073114, 94.750224301260, - 96.679773715696, 98.615214511699, 100.556211548644, 102.502148428334, - 104.452899214344, 106.407767504404, 108.366625832228, 110.329564692634, - 112.295481742874, 114.264715056639, 116.236769512562, 118.211214593179, - 120.188376370012, 122.167746134232, 124.148833002551, 126.131612799989, - 128.116072530208, 130.102155735854, 132.089449244974, 134.077816832908, - 136.067404409248, 138.057703527432, 140.049350564796, 142.041756984355, - 144.034780624078, 146.028584459531, 148.022894428003, 150.017952482368, - 152.013358245376, 154.009157360372, 156.005076955043, 158.001501688538, - 159.998043891849, 161.995141096448, 163.992507770330, 165.990019741406, - 167.987379363144, 169.985323168231, 171.983371903769, 173.981134136378, - 175.979306888599, 177.977458741010, 179.975994045101, 181.974478508488, - 183.973329438036, 185.972061903815, 187.971014174496, 189.969582278901, - 191.968450510061, 193.967607022497, 195.966726931677, 197.965915341472, - 199.964910588293, 201.964427852336, 203.964308576556, 205.963778587196, - 207.963244179225, 209.962423156859, 211.961859295409, 213.961171237132, - 215.960624048009, 217.959980906604, 219.959156277574, 221.958692298143, - 223.958335010302, 225.958329061602, 227.957722024027, 229.957134954397, - 231.956897929205, 233.956901572571, 235.956650770311, 237.956593290745, - 239.956700470895, 241.956192761863, 243.956003327600, 245.955794901574, - 247.955501305446, 249.954960233132, 251.954510187803, 253.954252376340, - 255.954011943050, 257.953388008439, 259.953139524693, 261.952918466928, - 263.952432910213, 265.952485387126, 267.952763908808, 269.952510701682, - 271.952383356830, 273.951921008979, 275.951766755515, 277.951697578478, - 279.951700548755, 281.951805228218, 283.951934023417, 285.952140722678, - 287.952063941231, 289.951717207670, 291.951294241955, 293.950937111819, - 295.950900506385, 297.950320403388, 299.949546547128, 301.949474819234, - 303.949155377395, 305.948725010033, 307.948408553357, 309.948120512731, - 311.947897212148, 313.947738181662, 315.947255247579, 317.946631669691, - 319.946302193308, 321.945855881155, 323.945603079048, 325.944930145876, - 327.945048538923, 329.944795565500, 331.944227346318, 333.943705422222, - 335.943231918970, 337.942333069602, 339.942354997227, 341.941890952026, - 343.941346276351, 345.940653575739, 347.940019001109, 349.940026817951, - 351.938944534275, 353.938172407151, 355.937584534690, 357.937041224148, - 359.936673631279, 361.936179855216, 363.936105840596, 365.935367434940, - 367.935295315770, 369.934793960370, 371.934314961518, 373.933949277377, - 375.933420587284, 377.933148188654, 379.932379363314, 381.931900192237, - 383.930951130857, 385.930667541762, 387.930025971711, 389.929529183966, - 391.929116798157, 393.928361940635, 395.927673611921, 397.927111110912, - 399.926483516685, 401.925799510661, 403.924918492428, 405.924540208915, - 407.924014467935, 409.923779779206, 411.922979548363, 413.922515268061, - 415.922148908645, 417.921643066153, 419.921126587639, 421.920766647684, - 423.920642824255, 425.920411492484, 427.920603679205, 429.920445437023, - 431.920286509746, 433.919789058392, 435.919408587813, 437.918873200300, - 439.918417416574, 441.918192491069, 443.918376503567, 445.917692006023, - 447.917132642691, 449.917217997363, 451.916924115487, 453.916662151474, - 455.916485288107, 457.915879851633, 459.915842501592, 461.915547354915, - 463.914995141359, 465.914585759187, 467.914144928428, 469.913956069337, - 471.913046082896, 473.912468624617, 475.912322983182, 477.912118100240, - 479.911923664773, 481.911518944025, 483.911023761757, 485.910386539830, - 487.910092345284, 489.910153786770, 491.909575245360, 493.908973823502, - 495.908577061168, 497.908550221055, 499.908127020659, 501.907710605296, - 503.907806972566, 505.907336571662, 507.907081330259, 509.906648846180, - 511.906201574892 - }, - // log K = 6 - { - 45.375999854524, 46.820948326168, 48.298703712049, 49.809402685314, - 51.353165756275, 52.929933710602, 54.539893242468, 56.183033892089, - 57.859217068495, 59.568519998303, 61.310801009963, 63.085886926328, - 64.893798324934, 66.734230191052, 68.607173306372, 70.512210309984, - 72.449265953981, 74.418007054647, 76.417910710559, 78.448929349152, - 80.510585932256, 82.602514696500, 84.724061528721, 86.875166381330, - 89.055217833675, 91.263852803721, 93.500342620773, 95.764451518395, - 98.055566319691, 100.373234086043, 102.716794393386, 105.085599217566, - 107.479363461004, 109.897282858060, 112.338907676111, 114.803401103124, - 117.290259931022, 119.799265623507, 122.329323908482, 124.879681624600, - 127.450299022993, 130.040239267142, 132.648756733593, 135.275366525219, - 137.919720233989, 140.580778017562, 143.258128898839, 145.951552244700, - 148.660145472460, 151.383257444852, 154.120434694643, 156.871202914301, - 159.634634288797, 162.410377522877, 165.198249005575, 167.997420145534, - 170.807579918337, 173.628020587905, 176.458633641294, 179.298282098581, - 182.147449731726, 185.005094444186, 187.870899328937, 190.744709255561, - 193.625572419776, 196.513740460772, 199.408599560293, 202.309940032246, - 205.217132295894, 208.129828601313, 211.047995735211, 213.970919426104, - 216.899109829571, 219.832024990852, 222.769136305806, 225.710258431247, - 228.655217514772, 231.603984417526, 234.555642012353, 237.510635882749, - 240.468820458907, 243.429903849174, 246.393192036307, 249.359251612075, - 252.327416912482, 255.297598046767, 258.269777722144, 261.244337060733, - 264.219958654591, 267.197643910088, 270.177202282129, 273.157339433786, - 276.139287129066, 279.122276848731, 282.107226383752, 285.092136000673, - 288.078230550129, 291.065256815999, 294.053160971001, 297.042401030971, - 300.031784889467, 303.022502412860, 306.013581138287, 309.005124942334, - 311.996910583050, 314.989635544162, 317.982189300799, 320.975762085573, - 323.969719809182, 326.963672522149, 329.958419674913, 332.953046205989, - 335.948338966110, 338.943201657934, 341.938798787180, 344.935321901459, - 347.931089897905, 350.927355153871, 353.923731760523, 356.920383399325, - 359.916863372939, 362.914245241722, 365.911216314347, 368.908636150615, - 371.905028432797, 374.901981729273, 377.899718967915, 380.897391911925, - 383.894945428721, 386.892974193389, 389.890517424427, 392.889050804732, - 395.886893560179, 398.884852345719, 401.883235933616, 404.881805247652, - 407.880049402262, 410.878410789472, 413.876755787854, 416.875140105536, - 419.873758096660, 422.872739431833, 425.871627898739, 428.870663138631, - 431.869475472357, 434.868378059774, 437.867537661532, 440.866274620049, - 443.865086570094, 446.864282236320, 449.863630871851, 452.862772062678, - 455.861877807413, 458.860680461949, 461.859728874700, 464.858478829514, - 467.857314559298, 470.856707830759, 473.855641079729, 476.854880576501, - 479.853812351976, 482.852666825246, 485.851471230749, 488.850997731659, - 491.850420535006, 494.849118717584, 497.848645341646, 500.848230362352, - 503.847546143645, 506.847285358235, 509.846275998715, 512.845599444922, - 515.845441684852, 518.844522015985, 521.843923976006, 524.843281639782, - 527.842399994830, 530.841152548296, 533.840788827465, 536.840058715879, - 539.839578267778, 542.839076801367, 545.838441853502, 548.837925005355, - 551.837456112430, 554.837041819817, 557.836916936797, 560.836116071833, - 563.834832988710, 566.834107840572, 569.832763471368, 572.831700689757, - 575.832050680783, 578.831190216307, 581.831249402778, 584.830325442080, - 587.828993643112, 590.827962761832, 593.827454067745, 596.825833598259, - 599.824193205007, 602.822806340644, 605.822276069352, 608.821423024191, - 611.820006110523, 614.819016304854, 617.818220240160, 620.817311827644, - 623.816286470744, 626.815211383752, 629.815077535810, 632.813925717940, - 635.813392704099, 638.812424935595, 641.811289306882, 644.809932622788, - 647.808609610738, 650.807771758015, 653.806851303878, 656.805452367508, - 659.804133900742, 662.803103749985, 665.801910649522, 668.800969589926, - 671.798796938405, 674.798110719805, 677.797843657187, 680.797711918663, - 683.796449689643, 686.794998006462, 689.794205385109, 692.792836542916, - 695.792195299304, 698.790778974184, 701.790704644168, 704.790168225574, - 707.789261680438, 710.788674453657, 713.787207421297, 716.786043303658, - 719.784740017888, 722.783523691482, 725.782739693893, 728.781695938105, - 731.780295310459, 734.778719103047, 737.778056368816, 740.777014963309, - 743.776470087777, 746.774710218241, 749.773897180146, 752.772555359445, - 755.771799417720, 758.770328749569, 761.768940347768, 764.768630836408, - 767.767399121425 - }, - // log K = 7 - { - 91.554623, 93.970317, 96.431113, 98.937264, 101.488909, 104.086010, 106.728780, 109.417062, - 112.150914, 114.930279, 117.755065, 120.625143, 123.540431, 126.500927, 129.506371, 132.556551, - 135.651450, 138.790477, 141.973357, 145.200176, 148.470504, 151.783478, 155.139376, 158.537455, - 161.977357, 165.458477, 168.980630, 172.543258, 176.145951, 179.788203, 183.469266, 187.188166, - 190.945533, 194.739618, 198.570460, 202.437447, 206.339379, 210.276276, 214.247092, 218.251243, - 222.288169, 226.357728, 230.458810, 234.590263, 238.751826, 242.942859, 247.162518, 251.410098, - 255.685517, 259.987202, 264.314569, 268.667458, 273.044873, 277.445418, 281.869296, 286.316796, - 290.785471, 295.276055, 299.788143, 304.319743, 308.869691, 313.438842, 318.026761, 322.632499, - 327.254588, 331.892954, 336.547483, 341.217702, 345.901880, 350.601214, 355.313731, 360.038868, - 364.777348, 369.526476, 374.288795, 379.061811, 383.846122, 388.640850, 393.446218, 398.260691, - 403.084626, 407.916053, 412.755659, 417.604951, 422.461448, 427.324128, 432.195028, 437.072269, - 441.956190, 446.846167, 451.741463, 456.641868, 461.549478, 466.461280, 471.377098, 476.297446, - 481.222717, 486.151860, 491.085033, 496.022133, 500.962856, 505.906586, 510.853868, 515.802981, - 520.755460, 525.711123, 530.668833, 535.629910, 540.592334, 545.557764, 550.525455, 555.494082, - 560.463996, 565.436164, 570.410847, 575.385933, 580.361996, 585.339352, 590.318151, 595.300216, - 600.281543, 605.264482, 610.250114, 615.236608, 620.222025, 625.208433, 630.195367, 635.183997, - 640.172271, 645.162589, 650.153647, 655.144276, 660.133923, 665.123818, 670.115789, 675.109169, - 680.103270, 685.097349, 690.091960, 695.086028, 700.080326, 705.075670, 710.069697, 715.065265, - 720.062426, 725.058529, 730.054916, 735.050560, 740.048508, 745.044790, 750.041067, 755.037833, - 760.035090, 765.033371, 770.029865, 775.025946, 780.022408, 785.021534, 790.018699, 795.016742, - 800.013947, 805.012680, 810.009483, 815.007921, 820.008589, 825.007658, 830.007411, 835.006892, - 840.006917, 845.006362, 850.004606, 855.003367, 860.001219, 864.999491, 869.999131, 874.998190, - 879.998460, 884.997482, 889.995952, 894.995130, 899.994555, 904.993474, 909.991434, 914.990519, - 919.991564, 924.992234, 929.993901, 934.992310, 939.992013, 944.993341, 949.993576, 954.992981, - 959.993548, 964.993781, 969.993129, 974.994050, 979.994706, 984.994372, 989.994395, 994.995339, - 999.995544, 1004.995498, 1009.996864, 1014.997829, 1019.996531, 1024.996724, 1029.997574, 1034.998591, - 1039.997807, 1044.998954, 1050.000113, 1055.000633, 1060.000845, 1065.000760, 1070.000907, 1075.001248, - 1080.001187, 1084.999775, 1089.999105, 1094.999647, 1100.001983, 1105.003468, 1110.004542, 1115.005170, - 1120.006517, 1125.006493, 1130.006837, 1135.008369, 1140.006966, 1145.009225, 1150.008497, 1155.009589, - 1160.009558, 1165.011395, 1170.009739, 1175.011131, 1180.013303, 1185.012525, 1190.014190, 1195.016399, - 1200.016087, 1205.016715, 1210.018008, 1215.018108, 1220.019677, 1225.020269, 1230.019468, 1235.020515, - 1240.021850, 1245.020961, 1250.019785, 1255.020253, 1260.020623, 1265.020156, 1270.020625, 1275.019028, - 1280.019972 - }, - // log K = 8 - { - 183.877784, 188.720097, 193.652407, 198.675131, 203.788397, 208.992238, 214.286620, 219.671580, - 225.147277, 230.713559, 236.370208, 242.117078, 247.953569, 253.880078, 259.895869, 266.000405, - 272.193694, 278.474457, 284.843102, 291.298228, 297.839692, 304.466434, 311.177471, 317.972674, - 324.850719, 331.811076, 338.852902, 345.974709, 353.175880, 360.455237, 367.811613, 375.244484, - 382.752472, 390.334218, 397.988777, 405.714596, 413.510671, 421.376147, 429.308973, 437.308197, - 445.372302, 453.500121, 461.690796, 469.942249, 478.253652, 486.623402, 495.049662, 503.532193, - 512.068670, 520.658371, 529.299186, 537.990886, 546.732097, 555.520093, 564.355935, 573.235689, - 582.159345, 591.126063, 600.133321, 609.181348, 618.267848, 627.392384, 636.552822, 645.748152, - 654.977601, 664.239902, 673.534497, 682.859448, 692.213983, 701.598606, 711.009376, 720.446781, - 729.910995, 739.397888, 748.908546, 758.443812, 768.000572, 777.577584, 787.174815, 796.791250, - 806.427107, 816.079660, 825.748493, 835.435992, 845.136828, 854.854141, 864.583886, 874.328396, - 884.085720, 893.855568, 903.637568, 913.431080, 923.234553, 933.049830, 942.873895, 952.707793, - 962.551743, 972.402421, 982.263001, 992.131464, 1002.006941, 1011.888460, 1021.777462, 1031.671376, - 1041.569600, 1051.476632, 1061.386996, 1071.302834, 1081.224251, 1091.148847, 1101.080297, 1111.013589, - 1120.951962, 1130.893360, 1140.838011, 1150.786112, 1160.737100, 1170.689817, 1180.646908, 1190.604979, - 1200.565150, 1210.527894, 1220.492169, 1230.460128, 1240.429764, 1250.401749, 1260.373274, 1270.349608, - 1280.325544, 1290.302087, 1300.279074, 1310.257850, 1320.238948, 1330.221273, 1340.203554, 1350.186669, - 1360.171345, 1370.156233, 1380.142561, 1390.129535, 1400.119177, 1410.107938, 1420.097171, 1430.087586, - 1440.077831, 1450.067996, 1460.060299, 1470.050059, 1480.042995, 1490.035101, 1500.026878, 1510.021128, - 1520.014262, 1530.008487, 1540.002895, 1549.996342, 1559.991075, 1569.986665, 1579.981202, 1589.976021, - 1599.969512, 1609.964051, 1619.959210, 1629.957092, 1639.953516, 1649.948113, 1659.946715, 1669.945253, - 1679.941736, 1689.938651, 1699.937600, 1709.936396, 1719.933608, 1729.931040, 1739.930316, 1749.927141, - 1759.922600, 1769.920847, 1779.918614, 1789.915707, 1799.913000, 1809.910958, 1819.908532, 1829.906905, - 1839.903410, 1849.904217, 1859.901705, 1869.898815, 1879.898869, 1889.899032, 1899.899113, 1909.896164, - 1919.893199, 1929.894515, 1939.894965, 1949.893184, 1959.892164, 1969.890794, 1979.889035, 1989.888005, - 1999.888538, 2009.888252, 2019.888976, 2029.890242, 2039.890655, 2049.891065, 2059.891068, 2069.889204, - 2079.891120, 2089.892462, 2099.892479, 2109.891814, 2119.893049, 2129.893705, 2139.893471, 2149.894162, - 2159.894213, 2169.895041, 2179.895987, 2189.894721, 2199.894028, 2209.896005, 2219.898683, 2229.898673, - 2239.898012, 2249.898018, 2259.898215, 2269.899380, 2279.902590, 2289.903144, 2299.902047, 2309.904214, - 2319.903812, 2329.904180, 2339.902528, 2349.903057, 2359.903089, 2369.904512, 2379.902563, 2389.905522, - 2399.903653, 2409.902313, 2419.904452, 2429.905949, 2439.905059, 2449.904954, 2459.904977, 2469.905111, - 2479.904049, 2489.903762, 2499.902022, 2509.904352, 2519.903272, 2529.901643, 2539.900789, 2549.903045, - 2559.904334 - }, - // log K = 9 - { - 368.528954, 378.224619, 388.100156, 398.155846, 408.391912, 418.808631, 429.406377, 440.185048, - 451.144613, 462.284693, 473.604932, 485.105306, 496.784844, 508.643147, 520.679581, 532.893098, - 545.282616, 557.848295, 570.587645, 583.500268, 596.584345, 609.838697, 623.261582, 636.851681, - 650.607666, 664.527320, 678.608336, 692.849674, 707.248088, 721.803089, 736.511331, 751.372034, - 766.381798, 781.538178, 796.839808, 812.283881, 827.867995, 843.588520, 859.444318, 875.432109, - 891.550599, 907.795630, 924.165943, 940.657393, 957.268601, 973.995685, 990.837235, 1007.789667, - 1024.850025, 1042.016602, 1059.286426, 1076.658199, 1094.126523, 1111.689346, 1129.345589, 1147.092119, - 1164.926795, 1182.844471, 1200.846880, 1218.929006, 1237.088281, 1255.322930, 1273.630393, 1292.007269, - 1310.452948, 1328.963430, 1347.538768, 1366.176566, 1384.871299, 1403.626249, 1422.434094, 1441.295238, - 1460.208340, 1479.169853, 1498.179265, 1517.234855, 1536.335403, 1555.477305, 1574.659180, 1593.881592, - 1613.139378, 1632.433516, 1651.764587, 1671.127255, 1690.519577, 1709.942250, 1729.393153, 1748.871689, - 1768.377142, 1787.907209, 1807.464755, 1827.043146, 1846.641976, 1866.263022, 1885.903553, 1905.564908, - 1925.240581, 1944.936723, 1964.648221, 1984.375489, 2004.117246, 2023.875053, 2043.644075, 2063.423514, - 2083.218689, 2103.026148, 2122.840475, 2142.669046, 2162.505619, 2182.351758, 2202.205963, 2222.068658, - 2241.939010, 2261.814547, 2281.701803, 2301.591894, 2321.490728, 2341.393208, 2361.298412, 2381.211528, - 2401.132345, 2421.057721, 2440.985510, 2460.916691, 2480.851468, 2500.792645, 2520.738446, 2540.683395, - 2560.634603, 2580.586307, 2600.540530, 2620.497170, 2640.458137, 2660.421783, 2680.386186, 2700.352664, - 2720.321411, 2740.291944, 2760.264068, 2780.238910, 2800.212546, 2820.185829, 2840.163952, 2860.142145, - 2880.120568, 2900.102466, 2920.081981, 2940.062964, 2960.046262, 2980.029101, 3000.012591, 3019.998424, - 3039.983637, 3059.969573, 3079.955927, 3099.942114, 3119.930348, 3139.919614, 3159.909130, 3179.899816, - 3199.892231, 3219.885316, 3239.878917, 3259.871675, 3279.865195, 3299.856210, 3319.848871, 3339.840385, - 3359.834158, 3379.830660, 3399.826361, 3419.822855, 3439.814714, 3459.813765, 3479.808673, 3499.804339, - 3519.797785, 3539.791012, 3559.789885, 3579.785152, 3599.780237, 3619.775480, 3639.772724, 3659.768920, - 3679.765735, 3699.766361, 3719.765048, 3739.762845, 3759.761526, 3779.757598, 3799.755719, 3819.751149, - 3839.750182, 3859.749673, 3879.749344, 3899.749939, 3919.749060, 3939.748385, 3959.750520, 3979.750055, - 3999.750104, 4019.749963, 4039.748453, 4059.746737, 4079.744522, 4099.744430, 4119.741804, 4139.740704, - 4159.742056, 4179.740063, 4199.739155, 4219.741718, 4239.743433, 4259.743115, 4279.743265, 4299.745518, - 4319.746682, 4339.750491, 4359.748549, 4379.747226, 4399.750319, 4419.750379, 4439.752339, 4459.750561, - 4479.750612, 4499.747862, 4519.750693, 4539.747476, 4559.749051, 4579.750603, 4599.750089, 4619.754781, - 4639.755536, 4659.758879, 4679.762145, 4699.762199, 4719.763886, 4739.765081, 4759.765681, 4779.765427, - 4799.767582, 4819.769915, 4839.770107, 4859.769398, 4879.768976, 4899.768288, 4919.768786, 4939.768607, - 4959.772822, 4979.772833, 4999.775808, 5019.773468, 5039.776181, 5059.770860, 5079.773006, 5099.773136, - 5119.772474 - }, - // log K = 10 - { - 737.833738, 757.236338, 776.997875, 797.119465, 817.602058, 838.445349, 859.650320, 881.216437, - 903.143414, 925.430957, 948.079220, 971.086231, 994.451449, 1018.173846, 1042.251928, 1066.683804, - 1091.467648, 1116.601416, 1142.083017, 1167.909918, 1194.079097, 1220.588887, 1247.435099, 1274.614860, - 1302.125360, 1329.962942, 1358.123177, 1386.601609, 1415.396299, 1444.501692, 1473.913256, 1503.628515, - 1533.642054, 1563.948888, 1594.544067, 1625.424305, 1656.582169, 1688.016543, 1719.718553, 1751.685990, - 1783.912130, 1816.393610, 1849.122123, 1882.095124, 1915.305647, 1948.748605, 1982.419843, 2016.313904, - 2050.422277, 2084.742618, 2119.270601, 2153.998538, 2188.920843, 2224.034736, 2259.333960, 2294.812594, - 2330.467059, 2366.291844, 2402.281356, 2438.428954, 2474.734330, 2511.187839, 2547.786319, 2584.527356, - 2621.406814, 2658.418551, 2695.554270, 2732.812564, 2770.190157, 2807.682744, 2845.287138, 2882.995251, - 2920.807982, 2958.719996, 2996.728771, 3034.826885, 3073.014082, 3111.287116, 3149.642093, 3188.073159, - 3226.577352, 3265.156836, 3303.803738, 3342.515111, 3381.291514, 3420.130671, 3459.024315, 3497.974631, - 3536.978221, 3576.034737, 3615.138610, 3654.285859, 3693.480455, 3732.715296, 3771.991792, 3811.305300, - 3850.654870, 3890.041152, 3929.457167, 3968.905021, 4008.381466, 4047.886976, 4087.419414, 4126.978997, - 4166.562624, 4206.166726, 4245.793284, 4285.445151, 4325.113012, 4364.802795, 4404.506274, 4444.228475, - 4483.965191, 4523.719569, 4563.487708, 4603.267460, 4643.060387, 4682.865430, 4722.680718, 4762.503248, - 4802.341326, 4842.185529, 4882.039088, 4921.900432, 4961.772625, 5001.649566, 5041.534380, 5081.425809, - 5121.323013, 5161.224908, 5201.130560, 5241.044625, 5280.962456, 5320.882373, 5360.810007, 5400.740058, - 5440.673843, 5480.606748, 5520.547394, 5560.493520, 5600.438100, 5640.383853, 5680.335386, 5720.292400, - 5760.250576, 5800.212705, 5840.172984, 5880.134991, 5920.097923, 5960.060294, 6000.031177, 6040.003398, - 6079.981696, 6119.954349, 6159.929074, 6199.908569, 6239.886163, 6279.863659, 6319.838261, 6359.815405, - 6399.795170, 6439.777225, 6479.755885, 6519.738857, 6559.723169, 6599.708549, 6639.695186, 6679.679788, - 6719.663289, 6759.651052, 6799.634129, 6839.624763, 6879.615013, 6919.605584, 6959.591310, 6999.586006, - 7039.577399, 7079.565236, 7119.557222, 7159.548481, 7199.533025, 7239.519648, 7279.511781, 7319.507639, - 7359.506105, 7399.497488, 7439.494944, 7479.491545, 7519.488415, 7559.480534, 7599.475646, 7639.470315, - 7679.468730, 7719.460928, 7759.455834, 7799.455686, 7839.451758, 7879.446841, 7919.443884, 7959.444138, - 7999.443141, 8039.446339, 8079.445285, 8119.444120, 8159.443157, 8199.446480, 8239.438893, 8279.437597, - 8319.439714, 8359.441566, 8399.440754, 8439.439156, 8479.440112, 8519.442365, 8559.444795, 8599.444497, - 8639.446714, 8679.449177, 8719.447620, 8759.443423, 8799.445995, 8839.446170, 8879.449622, 8919.450486, - 8959.450372, 8999.449731, 9039.448449, 9079.452579, 9119.451596, 9159.454020, 9199.456651, 9239.460902, - 9279.460419, 9319.461322, 9359.464611, 9399.467790, 9439.471448, 9479.468426, 9519.462982, 9559.464881, - 9599.462983, 9639.461706, 9679.457284, 9719.457023, 9759.455648, 9799.458786, 9839.456980, 9879.457411, - 9919.454971, 9959.451735, 9999.451916, 10039.443939, 10079.435325, 10119.432142, 10159.431313, 10199.431306, - 10239.429671 - }, - // log K = 11 - { - 1476.444530, 1515.260638, 1554.794859, 1595.048761, 1636.023652, 1677.720065, 1720.138513, 1763.279158, - 1807.141823, 1851.724811, 1897.027530, 1943.048153, 1989.784818, 2037.234835, 2085.395149, 2134.263580, - 2183.834818, 2234.105548, 2285.071077, 2336.726064, 2389.065940, 2442.084276, 2495.776521, 2550.134177, - 2605.153465, 2660.825522, 2717.142881, 2774.098631, 2831.683790, 2889.889911, 2948.711233, 3008.137464, - 3068.158605, 3128.766926, 3189.951984, 3251.704129, 3314.013826, 3376.873018, 3440.270569, 3504.194851, - 3568.636295, 3633.586039, 3699.031630, 3764.962925, 3831.371336, 3898.245744, 3965.574384, 4033.345701, - 4101.550888, 4170.180686, 4239.221393, 4308.664143, 4378.497100, 4448.712735, 4519.296212, 4590.243535, - 4661.538747, 4733.174738, 4805.142002, 4877.427081, 4950.019513, 5022.915001, 5096.098561, 5169.567185, - 5243.312012, 5317.314578, 5391.572253, 5466.077564, 5540.821377, 5615.792025, 5690.985894, 5766.392174, - 5842.007403, 5917.816734, 5993.815607, 6069.999957, 6146.362662, 6222.895187, 6299.592875, 6376.440778, - 6453.443173, 6530.588182, 6607.874560, 6685.288536, 6762.829840, 6840.490840, 6918.272948, 6996.164556, - 7074.161694, 7152.259404, 7230.451098, 7308.737035, 7387.113244, 7465.575350, 7544.120230, 7622.733447, - 7701.427750, 7780.188044, 7859.016102, 7937.904850, 8016.853624, 8095.860379, 8174.919884, 8254.034842, - 8333.197794, 8412.405307, 8491.657429, 8570.946804, 8650.278289, 8729.648657, 8809.056098, 8888.496764, - 8967.966663, 9047.466051, 9126.993636, 9206.547289, 9286.127523, 9365.733732, 9445.361201, 9525.008810, - 9604.680107, 9684.363532, 9764.066435, 9843.787987, 9923.523567, 10003.272886, 10083.037524, 10162.811803, - 10242.597755, 10322.402415, 10402.216522, 10482.042584, 10561.877077, 10641.722187, 10721.570740, 10801.435848, - 10881.301249, 10961.178474, 11041.059765, 11120.951444, 11200.845806, 11280.746075, 11360.652145, 11440.567398, - 11520.476709, 11600.395391, 11680.316855, 11760.241900, 11840.170134, 11920.103548, 12000.038206, 12079.975425, - 12159.912459, 12239.857191, 12319.802744, 12399.754385, 12479.707055, 12559.658981, 12639.614004, 12719.566502, - 12799.526877, 12879.488833, 12959.451231, 13039.416480, 13119.388158, 13199.360789, 13279.334923, 13359.298927, - 13439.261641, 13519.235871, 13599.204919, 13679.181082, 13759.157391, 13839.137425, 13919.112545, 13999.096522, - 14079.082789, 14159.060487, 14239.040581, 14319.025236, 14399.006995, 14478.994078, 14558.980576, 14638.962774, - 14718.952192, 14798.938522, 14878.931501, 14958.919062, 15038.907891, 15118.897247, 15198.889129, 15278.881057, - 15358.873272, 15438.867627, 15518.861931, 15598.858206, 15678.850014, 15758.849382, 15838.847872, 15918.837658, - 15998.837920, 16078.831305, 16158.827345, 16238.815546, 16318.817302, 16398.814389, 16478.815820, 16558.811634, - 16638.808126, 16718.807170, 16798.805652, 16878.813389, 16958.806543, 17038.807885, 17118.813146, 17198.813752, - 17278.817574, 17358.820511, 17438.819443, 17518.814262, 17598.815511, 17678.814160, 17758.816726, 17838.817584, - 17918.814197, 17998.821276, 18078.822342, 18158.828474, 18238.822064, 18318.826732, 18398.827758, 18478.827319, - 18558.834153, 18638.835651, 18718.839105, 18798.840903, 18878.836463, 18958.836015, 19038.836351, 19118.832583, - 19198.829856, 19278.822953, 19358.824866, 19438.823697, 19518.826538, 19598.826954, 19678.831393, 19758.822279, - 19838.818757, 19918.808247, 19998.804516, 20078.809201, 20158.808900, 20238.806398, 20318.798516, 20398.802224, - 20478.803179 - }, - // log K = 12 - { - 2953.666722, 3031.310137, 3110.389526, 3190.908699, 3272.865410, 3356.267166, 3441.114376, 3527.404284, - 3615.136846, 3704.310976, 3794.924283, 3886.973846, 3980.451903, 4075.355844, 4171.681168, 4269.423939, - 4368.569738, 4469.111760, 4571.043603, 4674.356370, 4779.038117, 4885.076002, 4992.460659, 5101.176875, - 5211.214098, 5322.553631, 5435.184633, 5549.088369, 5664.258175, 5780.673987, 5898.312682, 6017.158593, - 6137.195815, 6258.397951, 6380.761679, 6504.261630, 6628.870413, 6754.585867, 6881.374325, 7009.206926, - 7138.080376, 7267.979175, 7398.866805, 7530.722851, 7663.531580, 7797.269872, 7931.907340, 8067.451667, - 8203.855692, 8341.091306, 8479.155031, 8618.026003, 8757.682272, 8898.095612, 9039.253787, 9181.124777, - 9323.694329, 9466.944202, 9610.861899, 9755.403639, 9900.578346, 10046.356477, 10192.718770, 10339.635914, - 10487.081762, 10635.066232, 10783.560130, 10932.549371, 11082.024055, 11231.949071, 11382.332885, 11533.122831, - 11684.327555, 11835.935533, 11987.926999, 12140.281619, 12292.994375, 12446.046449, 12599.411083, 12753.088314, - 12907.079745, 13061.355923, 13215.895621, 13370.722085, 13525.795736, 13681.095971, 13836.645692, 13992.405906, - 14148.380716, 14304.566860, 14460.959382, 14617.539754, 14774.296125, 14931.214508, 15088.271748, 15245.493870, - 15402.867309, 15560.380994, 15718.035423, 15875.801492, 16033.687891, 16191.701231, 16349.808763, 16508.026001, - 16666.336068, 16824.745049, 16983.259302, 17141.848044, 17300.504517, 17459.240272, 17618.060296, 17776.914688, - 17935.848010, 18094.852645, 18253.914288, 18413.023567, 18572.168358, 18731.376016, 18890.631505, 19049.948196, - 19209.279260, 19368.638871, 19528.043860, 19687.498901, 19846.941765, 20006.443084, 20165.973535, 20325.525957, - 20485.109520, 20644.729917, 20804.363876, 20964.021778, 21123.698687, 21283.379344, 21443.080536, 21602.821439, - 21762.568135, 21922.305338, 22082.065878, 22241.856145, 22401.629436, 22561.435266, 22721.262644, 22881.080478, - 23040.916036, 23200.734053, 23360.583255, 23520.433188, 23680.275065, 23840.132678, 24000.012847, 24159.886135, - 24319.788338, 24479.654024, 24639.540316, 24799.466449, 24959.369335, 25119.276072, 25279.186502, 25439.091982, - 25599.020083, 25758.930671, 25918.847522, 26078.773060, 26238.704021, 26398.647566, 26558.603366, 26718.539855, - 26878.464425, 27038.402892, 27198.344989, 27358.270906, 27518.203448, 27678.169545, 27838.133625, 27998.111630, - 28158.064264, 28318.032491, 28477.994153, 28637.950838, 28797.910362, 28957.884994, 29117.861910, 29277.814384, - 29437.774223, 29597.762256, 29757.729819, 29917.688497, 30077.675371, 30237.667941, 30397.639431, 30557.644527, - 30717.622991, 30877.622641, 31037.598941, 31197.601527, 31357.599118, 31517.585221, 31677.569983, 31837.556138, - 31997.527880, 32157.500622, 32317.491709, 32477.504936, 32637.501123, 32797.516330, 32957.547336, 33117.541765, - 33277.561207, 33437.554332, 33597.564988, 33757.565321, 33917.561180, 34077.580598, 34237.597132, 34397.598246, - 34557.617536, 34717.623318, 34877.649722, 35037.645029, 35197.681143, 35357.700478, 35517.701804, 35677.734383, - 35837.736494, 35997.737103, 36157.732045, 36317.741539, 36477.735602, 36637.761491, 36797.742508, 36957.734137, - 37117.742952, 37277.789218, 37437.793798, 37597.779066, 37757.796449, 37917.794116, 38077.804399, 38237.797507, - 38397.788049, 38557.768583, 38717.768279, 38877.752553, 39037.747349, 39197.737646, 39357.774395, 39517.752643, - 39677.753347, 39837.740038, 39997.719486, 40157.709578, 40317.708657, 40477.719261, 40637.726978, 40797.711139, - 40957.707784 - }, - // log K = 13 - { - 5908.111420, 6063.410343, 6221.578483, 6382.623803, 6546.553966, 6713.369171, 6883.070010, 7055.656719, - 7231.129758, 7409.486672, 7590.720089, 7774.822139, 7961.786850, 8151.601206, 8344.261218, 8539.750086, - 8738.048786, 8939.141702, 9143.011205, 9349.645220, 9559.003557, 9771.078383, 9985.846791, 10203.277103, - 10423.349219, 10646.031323, 10871.293001, 11099.111735, 11329.434411, 11562.255804, 11797.522109, 12035.204106, - 12275.263649, 12517.670237, 12762.388671, 13009.375491, 13258.587519, 13510.006825, 13763.564399, 14019.227089, - 14276.975295, 14536.745792, 14798.511796, 15062.215057, 15327.806593, 15595.257499, 15864.529774, 16135.586770, - 16408.362074, 16682.849583, 16958.977019, 17236.708221, 17515.990972, 17796.798914, 18079.096585, 18362.834517, - 18647.959152, 18934.452073, 19222.251998, 19511.366053, 19801.717928, 20093.269020, 20385.960319, 20679.772736, - 20974.698498, 21270.684814, 21567.671010, 21865.649193, 22164.581341, 22464.423293, 22765.172894, 23066.785452, - 23369.201089, 23672.387494, 23976.354000, 24281.072155, 24586.465328, 24892.557323, 25199.303712, 25506.654130, - 25814.626835, 26123.148009, 26432.247046, 26741.889610, 27052.042135, 27362.685181, 27673.761784, 27985.292246, - 28297.219809, 28609.572368, 28922.317633, 29235.448741, 29548.944253, 29862.766175, 30176.910610, 30491.363107, - 30806.103787, 31121.126024, 31436.412153, 31751.975134, 32067.737444, 32383.768560, 32700.017044, 33016.458300, - 33333.101934, 33649.904492, 33966.923435, 34284.105041, 34601.429152, 34918.876076, 35236.481998, 35554.235511, - 35872.093847, 36190.101572, 36508.190892, 36826.420800, 37144.739624, 37463.138566, 37781.598984, 38100.191087, - 38418.846511, 38737.587005, 39056.391321, 39375.255819, 39694.182864, 40013.173503, 40332.221146, 40651.311460, - 40970.465534, 41289.697002, 41608.913381, 41928.242461, 42247.585089, 42566.988678, 42886.409594, 43205.849396, - 43525.322840, 43844.784209, 44164.327769, 44483.869861, 44803.383648, 45122.975593, 45442.593765, 45762.258110, - 46081.937012, 46401.605265, 46721.295022, 47041.004034, 47360.695978, 47680.435451, 48000.192231, 48319.953839, - 48639.726508, 48959.506239, 49279.318744, 49599.117846, 49918.951926, 50238.772730, 50558.620076, 50878.455501, - 51198.285377, 51518.135316, 51837.976134, 52157.809260, 52477.635805, 52797.492063, 53117.368983, 53437.262930, - 53757.142921, 54077.026859, 54396.907345, 54716.835955, 55036.713062, 55356.640827, 55676.537369, 55996.488865, - 56316.420754, 56636.355217, 56956.329593, 57276.245282, 57596.202473, 57916.159021, 58236.077854, 58556.010303, - 58875.938110, 59195.924442, 59515.871947, 59835.838035, 60155.809948, 60475.808167, 60795.765545, 61115.766398, - 61435.725825, 61755.677959, 62075.688445, 62395.647263, 62715.609853, 63035.591787, 63355.588060, 63675.579841, - 63995.560980, 64315.552298, 64635.582956, 64955.538779, 65275.512154, 65595.490993, 65915.477332, 66235.470693, - 66555.483426, 66875.455452, 67195.455039, 67515.435090, 67835.418300, 68155.401870, 68475.404599, 68795.452423, - 69115.474466, 69435.450344, 69755.439668, 70075.479966, 70395.468204, 70715.475957, 71035.472807, 71355.513734, - 71675.486047, 71995.450475, 72315.443410, 72635.425138, 72955.481520, 73275.482426, 73595.476688, 73915.469540, - 74235.426693, 74555.381683, 74875.368981, 75195.429157, 75515.480428, 75835.517265, 76155.557945, 76475.556134, - 76795.579451, 77115.605924, 77435.604178, 77755.572770, 78075.576305, 78395.562526, 78715.547599, 79035.551674, - 79355.540615, 79675.575726, 79995.547586, 80315.544278, 80635.546227, 80955.555617, 81275.540591, 81595.549538, - 81915.550079 - }, - // log K = 14 - { - 11817.000969, 12127.609164, 12443.958867, 12766.059919, 13093.926347, 13427.563687, 13766.972021, 14112.158775, - 14463.118632, 14819.833221, 15182.310838, 15550.514164, 15924.452624, 16304.097682, 16689.414687, 17080.390156, - 17476.985675, 17879.171048, 18286.913146, 18700.171223, 19118.909859, 19543.074108, 19972.606221, 20407.466793, - 20847.600290, 21292.965548, 21743.489087, 22199.109276, 22659.760749, 23125.379711, 23595.914325, 24071.277989, - 24551.407611, 25036.233071, 25525.671155, 26019.641791, 26518.074136, 27020.885189, 27528.004081, 28039.347478, - 28554.818908, 29074.343878, 29597.869471, 30125.254970, 30656.449891, 31191.351228, 31729.908970, 32272.003587, - 32817.586623, 33366.531359, 33918.769390, 34474.232727, 35032.798601, 35594.423192, 36159.024745, 36726.469786, - 37296.712851, 37869.686035, 38445.278953, 39023.442285, 39604.084062, 40187.147209, 40772.503600, 41360.148758, - 41949.978377, 42541.929077, 43135.892496, 43731.836459, 44329.664552, 44929.334224, 45530.772542, 46133.919152, - 46738.746702, 47345.120215, 47953.051656, 48562.469011, 49173.281212, 49785.453501, 50398.908717, 51013.645932, - 51629.563526, 52246.635759, 52864.820434, 53484.057447, 54104.303719, 54725.504675, 55347.680019, 55970.744363, - 56594.688890, 57219.458967, 57844.949821, 58471.197998, 59098.180259, 59725.774793, 60354.058215, 60982.962558, - 61612.427469, 62242.448368, 62873.013426, 63504.106743, 64135.672742, 64767.665213, 65400.082326, 66032.949331, - 66666.219558, 67299.817447, 67933.801373, 68568.092593, 69202.717636, 69837.643507, 70472.852133, 71108.305774, - 71744.023189, 72380.016332, 73016.168118, 73652.560876, 74289.210741, 74926.041959, 75563.048434, 76200.207724, - 76837.505542, 77474.999283, 78112.608284, 78750.375633, 79388.254423, 80026.267074, 80664.419197, 81302.602941, - 81940.909776, 82579.321050, 83217.801329, 83856.420605, 84495.098999, 85133.832545, 85772.588001, 86411.448347, - 87050.399262, 87689.358100, 88328.463714, 88967.516990, 89606.618839, 90245.788934, 90884.986443, 91524.243962, - 92163.523370, 92802.835394, 93442.198790, 94081.633840, 94721.043838, 95360.482304, 96000.002974, 96639.518339, - 97279.069377, 97918.584802, 98558.189888, 99197.773242, 99837.390001, 100476.994827, 101116.655652, 101756.293703, - 102395.977437, 103035.662337, 103675.360919, 104315.063845, 104954.783621, 105594.504004, 106234.229823, 106874.056079, - 107513.846129, 108153.562857, 108793.393622, 109433.202056, 110072.966808, 110712.777026, 111352.577741, 111992.441538, - 112632.256702, 113272.083743, 113911.943484, 114551.818432, 115191.687411, 115831.584194, 116471.522453, 117111.338979, - 117751.192777, 118391.070556, 119030.991702, 119670.888488, 120310.801509, 120950.761000, 121590.691826, 122230.618394, - 122870.618097, 123510.616056, 124150.552363, 124790.488946, 125430.445483, 126070.428297, 126710.409643, 127350.398562, - 127990.397846, 128630.413222, 129270.354937, 129910.365912, 130550.332174, 131190.259646, 131830.280970, 132470.304278, - 133110.295205, 133750.312426, 134390.364847, 135030.321000, 135670.319926, 136310.335570, 136950.324790, 137590.338289, - 138230.368657, 138870.374084, 139510.447896, 140150.468353, 140790.441338, 141430.438424, 142070.440787, 142710.431348, - 143350.433770, 143990.493350, 144630.548409, 145270.549935, 145910.530486, 146550.488808, 147190.510290, 147830.509426, - 148470.575641, 149110.541845, 149750.592427, 150390.634921, 151030.706500, 151670.646574, 152310.624482, 152950.686127, - 153590.659153, 154230.646236, 154870.720079, 155510.614028, 156150.596142, 156790.659641, 157430.633386, 158070.649047, - 158710.591350, 159350.585980, 159990.557711, 160630.530183, 161270.499427, 161910.521323, 162550.516603, 163190.482792, - 163830.422631 - }, - // log K = 15 - { - 23634.780143, 24256.008404, 24888.717596, 25532.934303, 26188.680791, 26855.965949, 27534.798395, 28225.179199, - 28927.099457, 29640.545847, 30365.501013, 31101.936533, 31849.825685, 32609.111850, 33379.755958, 34161.706474, - 34954.912131, 35759.291030, 36574.778310, 37401.280667, 38238.742234, 39087.060449, 39946.133936, 40815.861824, - 41696.151280, 42586.877221, 43487.927203, 44399.169293, 45320.460825, 46251.693279, 47192.741847, 48143.464216, - 49103.716679, 50073.349113, 51052.208336, 52040.138165, 53036.993192, 54042.604241, 55056.838449, 56079.501709, - 57110.434199, 58149.484623, 59196.455710, 60251.226284, 61313.593108, 62383.385277, 63460.484960, 64544.666337, - 65635.763495, 66733.629361, 67838.096489, 68948.987037, 70066.117363, 71189.338133, 72318.464573, 73453.423815, - 74593.923438, 75739.864335, 76891.058098, 78047.391508, 79208.654009, 80374.753680, 81545.514022, 82720.817799, - 83900.405263, 85084.273208, 86272.263471, 87464.134340, 88659.829437, 89859.204804, 91062.115479, 92268.425863, - 93478.041907, 94690.804589, 95906.647693, 97125.398400, 98347.018145, 99571.305992, 100798.274503, 102027.737913, - 103259.574749, 104493.727918, 105730.035415, 106968.465700, 108208.988306, 109451.445144, 110695.748927, 111941.827269, - 113189.666448, 114439.093665, 115690.116530, 116942.608958, 118196.501294, 119451.722652, 120708.276299, 121966.046247, - 123225.027480, 124485.082349, 125746.201609, 127008.357433, 128271.416054, 129535.417336, 130800.297278, 132066.008820, - 133332.483576, 134599.733640, 135867.681429, 137136.303792, 138405.538969, 139675.413251, 140945.839375, 142216.787412, - 143488.232199, 144760.234976, 146032.650196, 147305.459198, 148578.703708, 149852.356585, 151126.347770, 152400.641475, - 153675.275168, 154950.179904, 156225.390849, 157500.864126, 158776.585926, 160052.504602, 161328.716398, 162605.171897, - 163881.825931, 165158.677102, 166435.646121, 167712.814846, 168990.136047, 170267.619890, 171545.238277, 172823.011460, - 174100.890250, 175378.821293, 176656.920467, 177935.093547, 179213.318173, 180491.692642, 181770.130424, 183048.727206, - 184327.217835, 185605.921891, 186884.657773, 188163.418059, 189442.221838, 190721.122201, 192000.068271, 193279.087882, - 194558.139554, 195837.195523, 197116.400538, 198395.612565, 199674.831001, 200954.101970, 202233.365695, 203512.639968, - 204792.003319, 206071.379608, 207350.730914, 208630.080321, 209909.544216, 211189.014497, 212468.508049, 213748.055445, - 215027.584964, 216307.216078, 217586.896296, 218866.477232, 220146.109506, 221425.767458, 222705.465633, 223985.129542, - 225264.797531, 226544.544335, 227824.304232, 229104.031191, 230383.739676, 231663.424684, 232943.198829, 234222.906969, - 235502.669185, 236782.475696, 238062.262723, 239342.090234, 240622.002668, 241901.911022, 243181.742902, 244461.690551, - 245741.531359, 247021.432644, 248301.277604, 249581.168404, 250861.094078, 252141.038818, 253421.065594, 254701.020169, - 255980.887518, 257260.848328, 258540.873565, 259820.905666, 261100.908594, 262380.854763, 263660.862699, 264940.834842, - 266220.775656, 267500.745402, 268780.761926, 270060.823540, 271340.798715, 272620.823081, 273900.881190, 275180.928531, - 276460.914606, 277740.919081, 279020.967358, 280301.002010, 281581.054314, 282861.097638, 284141.109728, 285421.181335, - 286701.182750, 287981.231437, 289261.342952, 290541.328315, 291821.320901, 293101.395969, 294381.402286, 295661.374812, - 296941.357112, 298221.462446, 299501.443884, 300781.429735, 302061.512800, 303341.459364, 304621.530042, 305901.507763, - 307181.541613, 308461.506346, 309741.474814, 311021.458944, 312301.373851, 313581.258984, 314861.222655, 316141.192042, - 317421.179698, 318701.162346, 319981.143104, 321261.185706, 322541.120379, 323821.065555, 325100.961639, 326380.920540, - 327660.786948 - }, - // log K = 16 - { - 47270.338530, 48512.804588, 49778.235006, 51066.679846, 52378.178287, 53712.756179, 55070.430016, 56451.198432, - 57855.044557, 59281.941569, 60731.855114, 62204.727445, 63700.498656, 65219.087806, 66760.381754, 68324.278827, - 69910.681844, 71519.442760, 73150.426782, 74803.469853, 76478.400456, 78175.038414, 79893.184924, 81632.639705, - 83393.214587, 85174.662642, 86976.739912, 88799.210643, 90641.829434, 92504.355605, 94386.478165, 96287.925119, - 98208.422967, 100147.694840, 102105.387259, 104081.226364, 106074.916897, 108086.136683, 110114.560800, 112159.857579, - 114221.724675, 116299.785348, 118393.731853, 120503.258946, 122627.958417, 124767.540962, 126921.668848, 129090.003274, - 131272.204811, 133467.918004, 135676.870426, 137898.595565, 140132.829694, 142379.269230, 144637.536478, 146907.321805, - 149188.299797, 151480.151490, 153782.571459, 156095.292246, 158417.834407, 160749.983694, 163091.465145, 165441.984077, - 167801.236994, 170168.903670, 172544.767987, 174928.494171, 177319.918928, 179718.624717, 182124.426670, 184537.056818, - 186956.260737, 189381.869001, 191813.551321, 194251.107949, 196694.280093, 199142.910671, 201596.663557, 204055.453662, - 206519.090402, 208987.322132, 211460.079506, 213936.962995, 216417.945039, 218902.907481, 221391.594168, 223883.857806, - 226379.519239, 228878.478995, 231380.515508, 233885.422831, 236393.251620, 238903.734661, 241416.885791, 243932.462444, - 246450.361381, 248970.497360, 251492.768859, 254017.059221, 256543.244066, 259071.366198, 261601.098326, 264132.472390, - 266665.477130, 269200.003838, 271735.898262, 274273.128446, 276811.699617, 279351.334667, 281892.176977, 284434.126935, - 286977.141855, 289520.993664, 292065.816286, 294611.452586, 297157.986206, 299705.252956, 302253.226506, 304801.859484, - 307351.170990, 309901.148395, 312451.594894, 315002.530644, 317553.961670, 320105.951895, 322658.553440, 325211.299379, - 327764.626147, 330318.311300, 332872.331048, 335426.696106, 337981.358498, 340536.275072, 343091.446562, 345646.972942, - 348202.757347, 350758.693296, 353314.808579, 355871.203754, 358427.702337, 360984.491079, 363541.449032, 366098.493281, - 368655.687887, 371213.030472, 373770.561193, 376328.233445, 378886.001706, 381443.937538, 384001.856504, 386559.857503, - 389117.926075, 391676.219835, 394234.530250, 396792.812601, 399351.291660, 401909.794770, 404468.330377, 407026.964781, - 409585.614496, 412144.407471, 414703.175858, 417261.980659, 419820.958264, 422379.863083, 424938.751186, 427497.927620, - 430056.993719, 432616.066348, 435175.266190, 437734.382772, 440293.531277, 442852.711332, 445412.016423, 447971.502143, - 450530.798765, 453090.167199, 455649.502729, 458208.951251, 460768.459694, 463328.053373, 465887.570627, 468447.239271, - 471006.792818, 473566.544068, 476126.194227, 478685.887605, 481245.577573, 483805.348711, 486365.028302, 488924.844568, - 491484.612666, 494044.321666, 496604.011864, 499163.799789, 501723.629793, 504283.493711, 506843.290195, 509403.157856, - 511962.990320, 514522.941350, 517082.791953, 519642.848656, 522202.833761, 524762.686522, 527322.632758, 529882.529037, - 532442.420851, 535002.422317, 537562.386309, 540122.357425, 542682.434171, 545242.468829, 547802.466694, 550362.492718, - 552922.461624, 555482.539495, 558042.531431, 560602.467437, 563162.648952, 565722.750610, 568282.702877, 570842.810092, - 573402.917604, 575962.999235, 578523.081937, 581083.162584, 583643.265455, 586203.287883, 588763.260931, 591323.292027, - 593883.252456, 596443.273935, 599003.353442, 601563.492606, 604123.421135, 606683.438234, 609243.605174, 611803.638038, - 614363.628593, 616923.690580, 619483.675256, 622043.744171, 624603.673246, 627163.577236, 629723.677960, 632283.670157, - 634843.692958, 637403.576097, 639963.511752, 642523.482942, 645083.419327, 647643.330711, 650203.272467, 652763.290376, - 655323.267522 - }, - // log K = 17 - { - 94541.455324, 97026.403245, 99557.280165, 102134.178452, 104757.187033, 107426.362674, 110141.726029, 112903.278005, - 115710.975458, 118564.785344, 121464.629896, 124410.377345, 127401.910279, 130439.087070, 133521.683723, 136649.499031, - 139822.321627, 143039.848320, 146301.785984, 149607.844773, 152957.695333, 156350.945326, 159787.233040, 163266.157476, - 166787.301371, 170350.201319, 173954.353438, 177599.302692, 181284.526367, 185009.507089, 188773.757457, 192576.638207, - 196417.619925, 200296.089540, 204211.494530, 208163.221220, 212150.613086, 216173.056150, 220229.879308, 224320.462264, - 228444.146459, 232600.284426, 236788.187347, 241007.264352, 245256.725247, 249535.938618, 253844.217048, 258180.876528, - 262545.282090, 266936.686787, 271354.453768, 275797.958112, 280266.429404, 284759.298770, 289275.861948, 293815.386243, - 298377.390708, 302961.087179, 307565.895452, 312191.173759, 316836.362522, 321500.721532, 326183.652758, 330884.723656, - 335603.197219, 340338.617624, 345090.316855, 349857.860719, 354640.538362, 359438.001710, 364249.638745, 369074.940533, - 373913.351331, 378764.438864, 383627.767868, 388502.854215, 393389.259584, 398286.483436, 403194.238263, 408111.948151, - 413039.292303, 417975.909674, 422921.304084, 427875.195485, 432837.200959, 437807.062429, 442784.399966, 447768.726662, - 452760.032525, 457757.794185, 462761.810279, 467771.737196, 472787.226777, 477808.283249, 482834.411114, 487865.521166, - 492901.275392, 497941.616150, 502986.164281, 508034.749030, 513087.210697, 518143.298172, 523202.692981, 528265.454984, - 533331.384435, 538400.437943, 543472.278711, 548546.790172, 553623.737338, 558703.047575, 563784.666463, 568868.524932, - 573954.251207, 579041.935016, 584131.557779, 589222.910016, 594315.786547, 599410.314112, 604506.227555, 609603.610432, - 614702.124262, 619801.918486, 624902.903258, 630005.085347, 635107.990499, 640211.847431, 645316.755403, 650422.424613, - 655529.009211, 660636.166872, 665744.170495, 670852.806947, 675962.099161, 681072.042796, 686182.458370, 691293.269596, - 696404.763335, 701516.635253, 706628.965299, 711741.575313, 716854.769083, 721968.220605, 727082.027784, 732196.114131, - 737310.594653, 742425.339665, 747540.295793, 752655.505647, 757770.968129, 762886.636891, 768002.527720, 773118.559142, - 778234.871441, 783351.273881, 788467.944809, 793584.599211, 798701.497594, 803818.484285, 808935.619316, 814053.067243, - 819170.390229, 824287.946609, 829405.450988, 834523.054071, 839640.856519, 844758.800102, 849876.719924, 854994.831607, - 860112.896788, 865231.116455, 870349.453898, 875467.910756, 880586.444976, 885705.102070, 890823.822978, 895942.513436, - 901061.120048, 906179.716020, 911298.587548, 916417.583647, 921536.507373, 926655.570709, 931774.690027, 936893.879961, - 942012.956398, 947132.142141, 952251.503479, 957370.815448, 962490.012685, 967609.521437, 972729.002837, 977848.339983, - 982967.824448, 988087.392216, 993206.992691, 998326.635354, 1003446.304388, 1008565.985024, 1013685.706678, 1018805.581548, - 1023925.239073, 1029045.157502, 1034165.035124, 1039284.843524, 1044404.676526, 1049524.620186, 1054644.441170, 1059764.409794, - 1064884.318434, 1070004.338968, 1075124.268749, 1080244.471055, 1085364.528193, 1090484.511927, 1095604.595114, 1100724.598478, - 1105844.666500, 1110964.804168, 1116084.864159, 1121204.874577, 1126325.062599, 1131445.152321, 1136565.301592, 1141685.638897, - 1146805.806800, 1151925.790859, 1157045.932640, 1162166.112443, 1167286.221698, 1172406.273611, 1177526.581875, 1182646.832239, - 1187766.882661, 1192886.884388, 1198006.962839, 1203127.084377, 1208246.959060, 1213366.976076, 1218486.763464, 1223606.758568, - 1228726.721761, 1233846.593404, 1238966.815228, 1244086.865449, 1249206.854850, 1254326.996667, 1259447.092239, 1264567.198081, - 1269687.499091, 1274807.474194, 1279927.244161, 1285047.273317, 1290167.090035, 1295287.035620, 1300406.888764, 1305526.667946, - 1310646.540340 - }, - // log K = 18 - { - 189083.688921, 194053.597973, 199115.342781, 204269.157017, 209515.195566, 214853.553887, 220284.295855, 225807.399998, - 231422.826900, 237130.469824, 242930.139690, 248821.634191, 254804.718978, 260879.073467, 267044.289594, 273299.936993, - 279645.549742, 286080.586199, 292604.521050, 299216.651567, 305916.376160, 312702.908374, 319575.536730, 326533.420485, - 333575.639430, 340701.388339, 347909.713977, 355199.642852, 362570.108280, 370020.154080, 377548.652175, 385154.413997, - 392836.374125, 400593.371525, 408424.172521, 416327.671123, 424302.406749, 432347.292674, 440461.014310, 448642.241683, - 456889.603709, 465201.946081, 473577.749277, 482015.802141, 490514.770444, 499073.243760, 507689.794308, 516363.149230, - 525091.902823, 533874.850510, 542710.434311, 551597.433198, 560534.241273, 569520.019389, 578553.034265, 587632.180111, - 596756.084542, 605923.440522, 615133.037840, 624383.626242, 633673.841133, 643002.674316, 652368.578283, 661770.556501, - 671207.605795, 680678.417768, 690181.818697, 699716.780471, 709282.084973, 718876.864175, 728499.951143, 738150.280049, - 747827.053968, 757529.236597, 767255.784062, 777006.100829, 786779.065927, 796573.507429, 806388.828153, 816223.976258, - 826078.608350, 835951.751956, 845842.493689, 855750.225870, 865674.190527, 875613.809349, 885568.425527, 895537.272219, - 905519.763307, 915515.310346, 925523.353103, 935543.172648, 945574.292664, 955616.280042, 965668.428231, 975730.535479, - 985802.055447, 995882.596628, 1005971.583108, 1016068.664992, 1026173.649961, 1036285.774891, 1046404.955770, 1056530.588186, - 1066662.648243, 1076800.535542, 1086944.269881, 1097093.058652, 1107247.076183, 1117405.990557, 1127569.310917, 1137737.011345, - 1147908.717700, 1158084.362020, 1168263.501029, 1178446.221907, 1188632.206842, 1198821.131431, 1209013.020373, 1219207.570786, - 1229404.854893, 1239604.423801, 1249806.433263, 1260010.619993, 1270216.819018, 1280424.774173, 1290634.560600, 1300846.097203, - 1311059.128630, 1321273.628402, 1331489.832488, 1341707.300774, 1351925.947953, 1362145.802925, 1372366.802414, 1382588.547896, - 1392811.264776, 1403035.227449, 1413259.922280, 1423485.322819, 1433711.916106, 1443938.981360, 1454166.596984, 1464394.761679, - 1474623.684212, 1484853.156422, 1495083.020146, 1505313.735890, 1515544.731764, 1525776.086634, 1536007.742073, 1546239.679012, - 1556472.212370, 1566704.988763, 1576937.965495, 1587171.446007, 1597405.292186, 1607639.395274, 1617873.660775, 1628108.037273, - 1638342.741799, 1648577.832828, 1658813.325573, 1669048.803784, 1679284.679963, 1689520.927615, 1699757.050010, 1709993.263665, - 1720229.557663, 1730466.102090, 1740702.604009, 1750939.618504, 1761176.930182, 1771414.210528, 1781651.713742, 1791889.218503, - 1802126.805234, 1812364.257333, 1822602.054007, 1832839.687792, 1843077.871973, 1853315.944762, 1863554.202066, 1873792.633125, - 1884030.883830, 1894269.182711, 1904507.712050, 1914746.469507, 1924985.484753, 1935224.245956, 1945463.225215, 1955702.268883, - 1965941.321722, 1976180.037370, 1986419.052784, 1996658.429579, 2006897.450283, 2017136.904971, 2027376.240039, 2037615.549295, - 2047855.197425, 2058094.765906, 2068334.279787, 2078573.820075, 2088813.469730, 2099053.348620, 2109293.174176, 2119533.012704, - 2129772.820132, 2140012.744709, 2150252.607739, 2160492.533017, 2170732.406422, 2180972.400110, 2191212.436319, 2201452.637894, - 2211692.339292, 2221932.460057, 2232172.746036, 2242412.892705, 2252653.174824, 2262893.432271, 2273134.002270, 2283374.311008, - 2293614.537881, 2303854.703732, 2314095.191374, 2324335.236186, 2334575.624526, 2344816.313269, 2355056.224171, 2365296.361285, - 2375537.048184, 2385777.280284, 2396017.222502, 2406257.145546, 2416497.272190, 2426737.212210, 2436977.500856, 2447217.897426, - 2457458.423605, 2467698.536697, 2477938.448096, 2488178.544726, 2498418.640441, 2508658.160374, 2518898.274852, 2529138.509345, - 2539378.310538, 2549617.989497, 2559857.504886, 2570097.363128, 2580337.195261, 2590576.878833, 2600816.572159, 2611055.930087, - 2621295.625004 - }, - // log K = 19 - { - 378168.156126, 388107.986863, 398231.517433, 408539.178530, 419031.252008, 429707.954086, 440569.365328, 451615.642722, - 462846.490174, 474261.790112, 485861.190310, 497644.259253, 509610.438730, 521759.095095, 534089.573442, 546600.981190, - 559292.272697, 572162.409622, 585210.331052, 598434.669889, 611834.157416, 625407.271721, 639152.543961, 653068.262294, - 667152.777393, 681404.241581, 695820.778241, 710400.501586, 725141.425404, 740041.558661, 755098.503731, 770310.107475, - 785674.192935, 801188.297422, 816849.950298, 832656.623960, 848606.198026, 864696.151343, 880923.487841, 897285.841319, - 913780.530043, 930405.131973, 947156.655545, 964032.974599, 981030.762278, 998147.499138, 1015380.659035, 1032727.149847, - 1050184.616751, 1067750.330789, 1085421.716664, 1103195.771853, 1121069.796650, 1139041.324454, 1157107.373802, 1175265.377022, - 1193513.201704, 1211847.872855, 1230267.133114, 1248768.293478, 1267348.634472, 1286005.987451, 1304738.187318, 1323542.421988, - 1342416.458954, 1361357.807871, 1380364.530293, 1399434.095493, 1418564.587724, 1437754.116682, 1457000.254889, 1476301.275902, - 1495654.977143, 1515059.332212, 1534512.821906, 1554013.130304, 1573558.585534, 1593147.244450, 1612777.978405, 1632448.600136, - 1652157.704100, 1671904.308928, 1691686.012962, 1711501.716352, 1731349.849417, 1751229.053668, 1771138.423208, 1791076.196899, - 1811041.338260, 1831032.177526, 1851048.091817, 1871088.096683, 1891150.317142, 1911234.619162, 1931339.423184, 1951463.947205, - 1971606.994543, 1991767.606441, 2011945.852451, 2032140.098239, 2052349.709954, 2072574.274980, 2092812.387905, 2113063.537955, - 2133327.750182, 2153603.787963, 2173890.933053, 2194188.225246, 2214496.333997, 2234814.120065, 2255140.753372, 2275476.675949, - 2295820.689602, 2316172.220323, 2336530.258616, 2356894.932256, 2377266.633368, 2397645.173978, 2418028.419639, 2438417.586475, - 2458812.422593, 2479211.306360, 2499615.253217, 2520023.375080, 2540436.051898, 2560851.967345, 2581271.569076, 2601694.318944, - 2622120.693963, 2642549.418269, 2662981.070023, 2683415.520909, 2703852.500003, 2724291.876933, 2744733.213126, 2765177.477758, - 2785623.320019, 2806070.985142, 2826520.234343, 2846971.203929, 2867423.303616, 2887876.396540, 2908331.739769, 2928788.290672, - 2949245.276635, 2969704.620226, 2990164.657583, 3010625.841710, 3031087.855626, 3051550.619090, 3072014.642350, 3092479.163042, - 3112944.278087, 3133410.101603, 3153876.719100, 3174343.414117, 3194810.517970, 3215278.762802, 3235747.174277, 3256216.390486, - 3276685.652553, 3297155.394593, 3317625.911419, 3338096.547090, 3358567.567862, 3379038.637659, 3399510.649493, 3419983.382105, - 3440456.231853, 3460929.496047, 3481403.703904, 3501877.874941, 3522351.898403, 3542825.527074, 3563300.038829, 3583775.102749, - 3604249.896903, 3624724.967423, 3645201.027293, 3665676.534460, 3686152.061202, 3706628.308333, 3727104.271827, 3747580.803335, - 3768057.710876, 3788534.660048, 3809011.720864, 3829489.164523, 3849967.204462, 3870445.043912, 3890923.080446, 3911400.767281, - 3931879.061622, 3952357.218696, 3972836.284463, 3993314.516935, 4013793.278282, 4034272.661280, 4054751.814018, 4075230.503334, - 4095708.557968, 4116187.919814, 4136667.714093, 4157147.152355, 4177627.302553, 4198107.383728, 4218587.174918, 4239066.631662, - 4259545.994167, 4280026.100110, 4300506.380609, 4320986.617208, 4341466.696312, 4361945.995732, 4382426.527708, 4402907.058309, - 4423386.556967, 4443867.498542, 4464348.284664, 4484828.344391, 4505309.026083, 4525789.774619, 4546270.396129, 4566750.818685, - 4587231.362126, 4607711.356124, 4628191.883250, 4648673.308942, 4669153.953372, 4689634.118530, 4710114.637510, 4730595.217429, - 4751075.358693, 4771555.492921, 4792035.313408, 4812516.057037, 4832995.761283, 4853475.977619, 4873956.732160, 4894436.879314, - 4914917.149285, 4935397.069776, 4955877.550351, 4976357.852728, 4996838.246842, 5017318.023169, 5037798.008344, 5058278.290403, - 5078757.968956, 5099237.419344, 5119716.759591, 5140195.935830, 5160675.636320, 5181154.980843, 5201633.780713, 5222113.031789, - 5242591.881577 - }, - // log K = 20 - { - 756337.090537, 776216.744995, 796463.785646, 817079.035290, 838063.221300, 859416.678362, 881139.576270, 903232.151726, - 925693.940877, 948524.600346, 971723.442348, 995289.632784, 1019222.059448, 1043519.402588, 1068180.163485, 1093202.854610, - 1118585.515820, 1144326.031845, 1170421.828997, 1196870.617641, 1223669.453959, 1250815.679160, 1278306.298944, 1306137.726017, - 1334306.782451, 1362809.672011, 1391643.048887, 1420802.665486, 1450284.419390, 1480084.556504, 1510198.362531, 1540621.709038, - 1571349.988582, 1602377.885766, 1633700.853485, 1665314.443974, 1697213.607484, 1729393.242718, 1761847.799154, 1794572.464804, - 1827562.002973, 1860811.213417, 1894314.858503, 1928067.079352, 1962062.774535, 1996296.400592, 2030762.354026, 2065455.981656, - 2100370.818573, 2135502.224529, 2170844.722018, 2206392.452100, 2242140.795895, 2278083.565225, 2314215.470175, 2350532.238358, - 2387028.028531, 2423697.739702, 2460535.617283, 2497537.908190, 2534699.627071, 2572014.508248, 2609478.240813, 2647086.878671, - 2684834.738503, 2722717.495987, 2760730.659130, 2798869.445379, 2837130.937688, 2875509.782410, 2914002.086936, 2952603.395700, - 2991310.971904, 3030119.629799, 3069026.891217, 3108027.543585, 3147118.485322, 3186296.724369, 3225557.893026, 3264899.405158, - 3304317.806643, 3343809.532357, 3383372.875494, 3423003.239113, 3462699.855290, 3502458.588120, 3542276.984489, 3582151.461666, - 3622080.455509, 3662062.087297, 3702093.774268, 3742173.351913, 3782298.542025, 3822466.599295, 3862676.059061, 3902925.301466, - 3943212.313188, 3983534.655139, 4023890.682932, 4064278.948819, 4104698.644146, 4145147.867936, 4185624.200116, 4226127.607823, - 4266655.471909, 4307207.261933, 4347781.577688, 4388376.075665, 4428991.084860, 4469625.512791, 4510278.322018, 4550949.135583, - 4591635.061142, 4632337.290243, 4673054.034167, 4713783.999697, 4754527.016825, 4795282.199016, 4836049.304645, 4876828.217063, - 4917617.432795, 4958416.033283, 4999223.332994, 5040040.200620, 5080865.836319, 5121698.006953, 5162537.663489, 5203383.861562, - 5244235.368756, 5285093.542054, 5325957.172545, 5366826.006832, 5407700.602295, 5448579.444589, 5489462.237514, 5530348.767163, - 5571240.286944, 5612135.490023, 5653033.590430, 5693935.090249, 5734840.012969, 5775747.413811, 5816658.159197, 5857571.727542, - 5898486.810748, 5939403.918361, 5980324.159335, 6021245.922584, 6062167.462275, 6103093.061724, 6144019.021028, 6184948.477708, - 6225878.111073, 6266809.926593, 6307741.380274, 6348674.587241, 6389609.653586, 6430546.024311, 6471482.661256, 6512419.658468, - 6553358.313587, 6594299.462793, 6635239.780670, 6676180.809115, 6717122.614963, 6758064.640997, 6799009.935719, 6839954.567726, - 6880900.950276, 6921847.965357, 6962794.580261, 7003742.234176, 7044691.155209, 7085639.223984, 7126587.984374, 7167538.597843, - 7208487.508674, 7249437.307369, 7290389.448350, 7331341.752887, 7372292.872774, 7413245.082344, 7454198.512431, 7495151.878502, - 7536105.815461, 7577059.755263, 7618013.175400, 7658967.579066, 7699922.475951, 7740878.015144, 7781833.511721, 7822789.986990, - 7863745.987999, 7904702.500036, 7945659.757785, 7986615.385020, 8027573.168319, 8068531.917672, 8109489.438412, 8150447.742963, - 8191403.350221, 8232362.807587, 8273321.255913, 8314281.043410, 8355240.292724, 8396199.214301, 8437156.471990, 8478114.862372, - 8519073.457296, 8560034.832965, 8600993.512814, 8641954.368755, 8682914.667061, 8723875.362809, 8764837.809961, 8805797.690078, - 8846758.789178, 8887720.671501, 8928680.126482, 8969640.467726, 9010601.160006, 9051561.769905, 9092522.487783, 9133484.594542, - 9174446.122191, 9215406.809237, 9256366.837569, 9297328.747584, 9338288.901510, 9379250.948160, 9420212.503729, 9461173.228802, - 9502133.928845, 9543094.489131, 9584055.513956, 9625015.618922, 9665975.737758, 9706937.403885, 9747896.035874, 9788856.165941, - 9829816.994627, 9870777.228642, 9911737.327683, 9952698.937964, 9993660.635143, 10034620.747904, 10075579.526207, 10116539.739394, - 10157498.625700, 10198458.468474, 10239418.486051, 10280376.431741, 10321335.494132, 10362295.312860, 10403254.402980, 10444214.519042, - 10485173.027410 - }, - // log K = 21 - { - 1512674.959317, 1552434.197368, 1592928.155075, 1634158.593696, 1676126.959176, 1718834.017325, 1762279.726817, 1806464.610827, - 1851388.162884, 1897049.337397, 1943446.849678, 1990579.312415, 2038444.063365, 2087038.766553, 2136360.248426, 2186405.470599, - 2237170.640174, 2288651.015887, 2340842.752937, 2393739.986364, 2447337.958039, 2501630.515180, 2556611.361814, 2612274.289376, - 2668612.210872, 2725618.064986, 2783284.549430, 2841603.566294, 2900566.895724, 2960167.093438, 3020394.610851, 3081240.447614, - 3142696.078921, 3204751.105703, 3267397.808234, 3330624.834407, 3394422.872136, 3458781.966184, 3523690.805899, 3589140.856689, - 3655119.540256, 3721617.907853, 3788624.486645, 3856129.175227, 3924119.940026, 3992586.658818, 4061519.544440, 4130906.734075, - 4200737.500257, 4271000.909057, 4341685.842431, 4412781.306685, 4484277.199691, 4556162.287552, 4628426.495554, 4701059.642462, - 4774050.909933, 4847389.117100, 4921065.536469, 4995068.178578, 5069389.529141, 5144019.928509, 5218947.440841, 5294164.568050, - 5369660.364896, 5445425.915267, 5521454.727645, 5597734.642433, 5674257.411718, 5751014.463556, 5827999.822090, 5905203.759793, - 5982617.522812, 6060234.561845, 6138048.162353, 6216049.451496, 6294232.713331, 6372588.108087, 6451109.903764, 6529792.611180, - 6608629.912527, 6687615.097432, 6766740.086064, 6846000.116450, 6925391.839995, 7004908.093083, 7084544.127544, 7164293.822313, - 7244153.392582, 7324115.814384, 7404179.031163, 7484336.380737, 7564586.128001, 7644922.247694, 7725340.819662, 7805840.541693, - 7886412.416887, 7967054.301986, 8047764.087248, 8128539.447460, 8209376.477465, 8290273.766928, 8371225.884580, 8452230.183873, - 8533283.959811, 8614388.863382, 8695539.350564, 8776730.375553, 8857961.046732, 8939230.757845, 9020535.369667, 9101877.322129, - 9183251.420601, 9264654.743697, 9346087.109813, 9427548.372707, 9509034.441574, 9590547.753266, 9672081.682514, 9753639.600816, - 9835216.139507, 9916813.989591, 9998428.682824, 10080058.312759, 10161706.673718, 10243372.018016, 10325050.507034, 10406744.529470, - 10488447.296300, 10570163.109725, 10651893.512546, 10733632.712879, 10815382.384056, 10897140.573621, 10978907.646650, 11060681.383125, - 11142464.138730, 11224254.549571, 11306053.275368, 11387858.162207, 11469666.329635, 11551480.634292, 11633302.025569, 11715128.710512, - 11796961.403328, 11878795.670820, 11960634.652330, 12042477.348124, 12124323.950451, 12206172.128053, 12288028.811447, 12369886.306570, - 12451744.123236, 12533607.183832, 12615473.707341, 12697338.733240, 12779207.987968, 12861080.507718, 12942957.260823, 13024834.007606, - 13106715.252745, 13188597.806270, 13270478.933580, 13352362.482281, 13434247.263704, 13516133.477076, 13598020.834213, 13679909.264273, - 13761799.592878, 13843689.299819, 13925583.582108, 14007479.173806, 14089371.780210, 14171268.621526, 14253167.561983, 14335070.527750, - 14416971.620797, 14498873.784867, 14580778.789301, 14662681.662290, 14744586.311912, 14826493.286700, 14908400.702409, 14990305.605573, - 15072214.379125, 15154123.120545, 15236031.901296, 15317939.866920, 15399849.993076, 15481761.939120, 15563672.325616, 15645585.312945, - 15727497.406318, 15809411.780271, 15891325.875461, 15973239.145687, 16055155.936424, 16137069.783844, 16218984.663574, 16300899.732679, - 16382815.849682, 16464730.053474, 16546645.675799, 16628563.444017, 16710481.533611, 16792400.824636, 16874319.061886, 16956235.859045, - 17038151.394583, 17120072.629220, 17201992.200096, 17283914.365655, 17365836.161356, 17447756.880495, 17529681.545942, 17611601.675003, - 17693522.079185, 17775441.939609, 17857361.777214, 17939284.144858, 18021205.445833, 18103125.675947, 18185051.132189, 18266974.391463, - 18348894.689783, 18430817.526979, 18512736.992850, 18594657.001222, 18676577.636496, 18758497.698999, 18840421.426602, 18922345.360722, - 19004266.906157, 19086186.184618, 19168105.320223, 19250029.336282, 19331950.350200, 19413874.580826, 19495794.431194, 19577715.745558, - 19659638.264924, 19741557.363469, 19823478.431258, 19905400.862401, 19987318.682409, 20069238.585823, 20151157.549449, 20233076.181910, - 20314994.521260, 20396915.069140, 20478836.108717, 20560753.915833, 20642672.570035, 20724588.867440, 20806507.038063, 20888426.370670, - 20970344.006053 - } - }; - //CHECKSTYLE.ON: LineLength -} diff --git a/src/main/java/org/apache/datasketches/hll/Conversions.java b/src/main/java/org/apache/datasketches/hll/Conversions.java deleted file mode 100644 index a5e8ce4f0..000000000 --- a/src/main/java/org/apache/datasketches/hll/Conversions.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.HllUtil.AUX_TOKEN; -import static org.apache.datasketches.hll.HllUtil.EMPTY; -import static org.apache.datasketches.hll.HllUtil.LG_AUX_ARR_INTS; - -/** - * Converters for one TgtHllType to another. The source can be heap or direct, but the result is - * always on heap. These conversions only apply to sketches in HLL (dense) mode. - * - * @author Lee Rhodes - */ -final class Conversions { - - static Hll4Array convertToHll4(final AbstractHllArray srcAbsHllArr) { - final int lgConfigK = srcAbsHllArr.getLgConfigK(); - final Hll4Array hll4Array = new Hll4Array(lgConfigK); - hll4Array.putOutOfOrder(srcAbsHllArr.isOutOfOrder()); - - //1st pass: compute starting curMin and numAtCurMin: - final int pair = curMinAndNum(srcAbsHllArr); - final int curMin = HllUtil.getPairValue(pair); - final int numAtCurMin = HllUtil.getPairLow26(pair); - - //2nd pass: Must know curMin to create AuxHashMap. - //Populate KxQ registers, build AuxHashMap if needed - final PairIterator itr = srcAbsHllArr.iterator(); - AuxHashMap auxHashMap = hll4Array.getAuxHashMap(); //may be null - while (itr.nextValid()) { - final int slotNo = itr.getIndex(); - final int actualValue = itr.getValue(); - AbstractHllArray.hipAndKxQIncrementalUpdate(hll4Array, 0, actualValue); - if (actualValue >= (curMin + 15)) { - hll4Array.putNibble(slotNo, AUX_TOKEN); - if (auxHashMap == null) { - auxHashMap = new HeapAuxHashMap(LG_AUX_ARR_INTS[lgConfigK], lgConfigK); - hll4Array.putAuxHashMap(auxHashMap, false); - } - auxHashMap.mustAdd(slotNo, actualValue); - } else { - hll4Array.putNibble(slotNo, actualValue - curMin); - } - } - - hll4Array.putCurMin(curMin); - hll4Array.putNumAtCurMin(numAtCurMin); - hll4Array.putHipAccum(srcAbsHllArr.getHipAccum()); //intentional overwrite - hll4Array.putRebuildCurMinNumKxQFlag(false); - return hll4Array; - } - - /** - * This returns curMin and numAtCurMin as a pair and will be correct independent of the TgtHllType - * of the input AbstractHllArray. - * - *

In general, it is always true that for HLL_6 and HLL_8, curMin is always 0, and numAtCurMin - * is the number of zero slots. For these two types there is no need to track curMin nor to track - * numAtCurMin once all the slots are filled. - * - * @param absHllArr an instance of AbstractHllArray - * @return pair values representing numAtCurMin and curMin - */ - static int curMinAndNum(final AbstractHllArray absHllArr) { - int curMin = 64; - int numAtCurMin = 0; - final PairIterator itr = absHllArr.iterator(); - while (itr.nextAll()) { - final int v = itr.getValue(); - if (v > curMin) { continue; } - if (v < curMin) { - curMin = v; - numAtCurMin = 1; - } else { - numAtCurMin++; - } - } - return HllUtil.pair(numAtCurMin, curMin); - } - - static Hll6Array convertToHll6(final AbstractHllArray srcAbsHllArr) { - final int lgConfigK = srcAbsHllArr.lgConfigK; - final Hll6Array hll6Array = new Hll6Array(lgConfigK); - hll6Array.putOutOfOrder(srcAbsHllArr.isOutOfOrder()); - int numZeros = 1 << lgConfigK; - final PairIterator itr = srcAbsHllArr.iterator(); - while (itr.nextAll()) { - if (itr.getValue() != EMPTY) { - numZeros--; - hll6Array.couponUpdate(itr.getPair()); //couponUpdate creates KxQ registers - } - } - hll6Array.putNumAtCurMin(numZeros); - hll6Array.putHipAccum(srcAbsHllArr.getHipAccum()); //intentional overwrite - hll6Array.putRebuildCurMinNumKxQFlag(false); - return hll6Array; - } - - static Hll8Array convertToHll8(final AbstractHllArray srcAbsHllArr) { - final int lgConfigK = srcAbsHllArr.lgConfigK; - final Hll8Array hll8Array = new Hll8Array(lgConfigK); - hll8Array.putOutOfOrder(srcAbsHllArr.isOutOfOrder()); - int numZeros = 1 << lgConfigK; - final PairIterator itr = srcAbsHllArr.iterator(); - while (itr.nextAll()) { - if (itr.getValue() != EMPTY) { - numZeros--; - hll8Array.couponUpdate(itr.getPair()); //creates KxQ registers - } - } - hll8Array.putNumAtCurMin(numZeros); - hll8Array.putHipAccum(srcAbsHllArr.getHipAccum()); //intentional overwrite - hll8Array.putRebuildCurMinNumKxQFlag(false); - return hll8Array; - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/CouponHashSet.java b/src/main/java/org/apache/datasketches/hll/CouponHashSet.java deleted file mode 100644 index 4ba67c265..000000000 --- a/src/main/java/org/apache/datasketches/hll/CouponHashSet.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.hll.HllUtil.EMPTY; -import static org.apache.datasketches.hll.HllUtil.LG_INIT_SET_SIZE; -import static org.apache.datasketches.hll.HllUtil.RESIZE_DENOM; -import static org.apache.datasketches.hll.HllUtil.RESIZE_NUMER; -import static org.apache.datasketches.hll.PreambleUtil.HASH_SET_INT_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.HASH_SET_PREINTS; -import static org.apache.datasketches.hll.PreambleUtil.LIST_INT_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.computeLgArr; -import static org.apache.datasketches.hll.PreambleUtil.extractCompactFlag; -import static org.apache.datasketches.hll.PreambleUtil.extractCurMode; -import static org.apache.datasketches.hll.PreambleUtil.extractHashSetCount; -import static org.apache.datasketches.hll.PreambleUtil.extractInt; -import static org.apache.datasketches.hll.PreambleUtil.extractLgArr; -import static org.apache.datasketches.hll.PreambleUtil.extractLgK; -import static org.apache.datasketches.hll.PreambleUtil.extractTgtHllType; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -final class CouponHashSet extends CouponList { - - /** - * Constructs this sketch with the intent of loading it with data - * @param lgConfigK the configured Lg K - * @param tgtHllType the new target Hll type - */ - CouponHashSet(final int lgConfigK, final TgtHllType tgtHllType) { - super(lgConfigK, tgtHllType, CurMode.SET); - assert lgConfigK > 7; - } - - /** - * Copy constructor - * @param that another CouponHashSet - */ - CouponHashSet(final CouponHashSet that) { - super(that); - } - - /** - * Copy As constructor. - * @param that another CouponHashSet - * @param tgtHllType the new target Hll type - */ - CouponHashSet(final CouponHashSet that, final TgtHllType tgtHllType) { - super(that, tgtHllType); - } - - //will also accept List, but results in a Set - static CouponHashSet heapifySet(final MemorySegment seg) { - final int lgConfigK = extractLgK(seg); - final TgtHllType tgtHllType = extractTgtHllType(seg); - - final CurMode curMode = extractCurMode(seg); - final int segArrStart = (curMode == CurMode.LIST) ? LIST_INT_ARR_START : HASH_SET_INT_ARR_START; - final CouponHashSet set = new CouponHashSet(lgConfigK, tgtHllType); - final boolean segIsCompact = extractCompactFlag(seg); - final int couponCount = extractHashSetCount(seg); - int lgCouponArrInts = extractLgArr(seg); - if (lgCouponArrInts < LG_INIT_SET_SIZE) { - lgCouponArrInts = computeLgArr(seg, couponCount, lgConfigK); - } - if (segIsCompact) { - for (int i = 0; i < couponCount; i++) { - set.couponUpdate(extractInt(seg, segArrStart + (i << 2))); - } - } else { //updatable - set.couponCount = couponCount; - set.lgCouponArrInts = lgCouponArrInts; - final int couponArrInts = 1 << lgCouponArrInts; - set.couponIntArr = new int[couponArrInts]; - MemorySegment.copy(seg, JAVA_INT_UNALIGNED, HASH_SET_INT_ARR_START, set.couponIntArr, 0, couponArrInts); - } - return set; - } - - @Override - CouponHashSet copy() { - return new CouponHashSet(this); - } - - @Override - CouponHashSet copyAs(final TgtHllType tgtHllType) { - return new CouponHashSet(this, tgtHllType); - } - - @Override - HllSketchImpl couponUpdate(final int coupon) { - final int index = find(couponIntArr, lgCouponArrInts, coupon); - if (index >= 0) { - return this; //found duplicate, ignore - } - couponIntArr[~index] = coupon; //found empty - couponCount++; - if (checkGrowOrPromote()) { - return promoteHeapListOrSetToHll(this); - } - return this; - } - - @Override - int getSegDataStart() { - return HASH_SET_INT_ARR_START; - } - - @Override - int getPreInts() { - return HASH_SET_PREINTS; - } - - private boolean checkGrowOrPromote() { - if ((RESIZE_DENOM * couponCount) > (RESIZE_NUMER * (1 << lgCouponArrInts))) { - if (lgCouponArrInts == (lgConfigK - 3)) { //at max size - return true; // promote to HLL - } - couponIntArr = growHashSet(couponIntArr, ++lgCouponArrInts); - } - return false; - } - - private static int[] growHashSet(final int[] coupIntArr, final int tgtLgCoupArrSize) { - final int[] tgtCouponIntArr = new int[1 << tgtLgCoupArrSize]; //create tgt - final int len = coupIntArr.length; - for (int i = 0; i < len; i++) { //scan input arr for non-zero values - final int fetched = coupIntArr[i]; - if (fetched != EMPTY) { - final int idx = find(tgtCouponIntArr, tgtLgCoupArrSize, fetched); //find empty in tgt - if (idx < 0) { //found EMPTY - tgtCouponIntArr[~idx] = fetched; //insert - continue; - } - throw new SketchesStateException("Error: found duplicate."); - } - } - return tgtCouponIntArr; - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/CouponList.java b/src/main/java/org/apache/datasketches/hll/CouponList.java deleted file mode 100644 index bd70dd3ea..000000000 --- a/src/main/java/org/apache/datasketches/hll/CouponList.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.hll.HllUtil.EMPTY; -import static org.apache.datasketches.hll.HllUtil.LG_INIT_LIST_SIZE; -import static org.apache.datasketches.hll.HllUtil.LG_INIT_SET_SIZE; -import static org.apache.datasketches.hll.PreambleUtil.LIST_INT_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.LIST_PREINTS; -import static org.apache.datasketches.hll.PreambleUtil.extractLgK; -import static org.apache.datasketches.hll.PreambleUtil.extractListCount; -import static org.apache.datasketches.hll.PreambleUtil.extractTgtHllType; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -class CouponList extends AbstractCoupons { - int lgCouponArrInts; - int couponCount; - int[] couponIntArr; - - private static int checkLgConfigK(final CurMode curMode, final int lgConfigK) { - if (curMode == CurMode.SET) { assert lgConfigK > 7; } - return lgConfigK; - } - - /** - * New instance constructor for LIST or SET. - * @param lgConfigK the configured Lg K - * @param tgtHllType the configured HLL target - * @param curMode LIST or SET - */ - CouponList(final int lgConfigK, final TgtHllType tgtHllType, final CurMode curMode) { - super(checkLgConfigK(curMode, lgConfigK), tgtHllType, curMode); - if (curMode == CurMode.LIST) { - lgCouponArrInts = LG_INIT_LIST_SIZE; - } else { //SET - lgCouponArrInts = LG_INIT_SET_SIZE; - } - couponIntArr = new int[1 << lgCouponArrInts]; - couponCount = 0; - } - - /** - * Copy Constructor - * @param that another CouponArray - */ - CouponList(final CouponList that) { - super(that.lgConfigK, that.tgtHllType, that.curMode); - lgCouponArrInts = that.lgCouponArrInts; - couponCount = that.couponCount; - couponIntArr = that.couponIntArr.clone(); - } - - /** - * Copy As constructor. - * @param that another CouponList - * @param tgtHllType the new target Hll type - */ //also used by CouponHashSet - CouponList(final CouponList that, final TgtHllType tgtHllType) { - super(that.lgConfigK, tgtHllType, that.curMode); - lgCouponArrInts = that.lgCouponArrInts; - couponCount = that.couponCount; - couponIntArr = that.couponIntArr.clone(); - } - - static final CouponList heapifyList(final MemorySegment seg) { - final int lgConfigK = extractLgK(seg); - final TgtHllType tgtHllType = extractTgtHllType(seg); - - final CouponList list = new CouponList(lgConfigK, tgtHllType, CurMode.LIST); - final int couponCount = extractListCount(seg); - MemorySegment.copy(seg, JAVA_INT_UNALIGNED, LIST_INT_ARR_START, list.couponIntArr, 0, couponCount); - list.couponCount = couponCount; - return list; - } - - @Override - CouponList copy() { - return new CouponList(this); - } - - @Override - CouponList copyAs(final TgtHllType tgtHllType) { - return new CouponList(this, tgtHllType); - } - - @Override - HllSketchImpl couponUpdate(final int coupon) { - final int len = 1 << lgCouponArrInts; - for (int i = 0; i < len; i++) { //search for empty slot - final int couponAtIdx = couponIntArr[i]; - if (couponAtIdx == EMPTY) { - couponIntArr[i] = coupon; //update - couponCount++; - if (couponCount >= len) { //array full - if (lgConfigK < 8) { - return promoteHeapListOrSetToHll(this); //oooFlag = false - } - return promoteHeapListToSet(this); //oooFlag = true - } - return this; - } - //cell not empty - if (couponAtIdx == coupon) { - return this; //duplicate - } - //cell not empty & not a duplicate, continue - } //end for - throw new SketchesStateException("Array invalid: no empties & no duplicates"); - } - - @Override - int getCompactSerializationBytes() { - return getSegDataStart() + (couponCount << 2); - } - - @Override - int getCouponCount() { - return couponCount; - } - - @Override - int[] getCouponIntArr() { - return couponIntArr; - } - - @Override - int getLgCouponArrInts() { - return lgCouponArrInts; - } - - @Override - int getSegDataStart() { - return LIST_INT_ARR_START; - } - - @Override - MemorySegment getMemorySegment() { - return null; - } - - @Override - int getPreInts() { - return LIST_PREINTS; - } - - @Override - boolean isCompact() { - return false; - } - - @Override - boolean hasMemorySegment() { - return false; - } - - @Override - boolean isOffHeap() { - return false; - } - - @Override - boolean isSameResource(final MemorySegment seg) { - return false; - } - - @Override - PairIterator iterator() { - return new IntArrayPairIterator(couponIntArr, lgConfigK); - } - - @Override - void mergeTo(final HllSketch that) { - final int arrLen = couponIntArr.length; - for (int i = 0; i < arrLen; i++) { - final int pair = couponIntArr[i]; - if (pair == 0) { continue; } - that.couponUpdate(pair); - } - } - - @Override - CouponList reset() { - return new CouponList(lgConfigK, tgtHllType, CurMode.LIST); - } - - static final HllSketchImpl promoteHeapListToSet(final CouponList list) { - final int couponCount = list.couponCount; - final int[] arr = list.couponIntArr; - final CouponHashSet chSet = new CouponHashSet(list.lgConfigK, list.tgtHllType); - for (int i = 0; i < couponCount; i++) { - chSet.couponUpdate(arr[i]); - } - return chSet; - } - - //Promotional move of coupons to an HllSketch from either List or Set. - //called by CouponHashSet.couponUpdate() - //called by CouponList.couponUpdate() - static final HllSketchImpl promoteHeapListOrSetToHll(final CouponList src) { - final HllArray tgtHllArr = HllArray.newHeapHll(src.lgConfigK, src.tgtHllType); - final PairIterator srcItr = src.iterator(); - tgtHllArr.putKxQ0(1 << src.lgConfigK); - while (srcItr.nextValid()) { - tgtHllArr.couponUpdate(srcItr.getPair()); - } - tgtHllArr.putHipAccum(src.getEstimate()); - - tgtHllArr.putOutOfOrder(false); - return tgtHllArr; - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/CouponMapping.java b/src/main/java/org/apache/datasketches/hll/CouponMapping.java deleted file mode 100644 index 25d927679..000000000 --- a/src/main/java/org/apache/datasketches/hll/CouponMapping.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -/** - * @author Lee Rhodes - * @author Kevin Lang - * - */ -final class CouponMapping { - - //Computed for Coupon lgK = 26 ONLY. Designed for the cubic interpolator function. - static final double[] xArr = new double[] { - 0.0, 1.0, 20.0, 400.0, - 8000.0, 160000.0, 300000.0, 600000.0, - 900000.0, 1200000.0, 1500000.0, 1800000.0, - 2100000.0, 2400000.0, 2700000.0, 3000000.0, - 3300000.0, 3600000.0, 3900000.0, 4200000.0, - 4500000.0, 4800000.0, 5100000.0, 5400000.0, - 5700000.0, 6000000.0, 6300000.0, 6600000.0, - 6900000.0, 7200000.0, 7500000.0, 7800000.0, - 8100000.0, 8400000.0, 8700000.0, 9000000.0, - 9300000.0, 9600000.0, 9900000.0, 10200000.0 - }; - - // CHECKSTYLE:OFF LineLength - //Computed for Coupon lgK = 26 ONLY. Designed for the cubic interpolator function. - static final double[] yArr = new double[] { - 0.0000000000000000, 1.0000000000000000, 20.0000009437402611, 400.0003963713384110, - 8000.1589294602090376, 160063.6067763759638183, 300223.7071597663452849, 600895.5933856170158833, - 902016.8065120954997838, 1203588.4983199508860707, 1505611.8245524743106216, 1808087.9449319066479802, - 2111018.0231759352609515, 2414403.2270142501220107, 2718244.7282051891088486, 3022543.7025524540804327, - 3327301.3299219091422856, 3632518.7942584538832307, 3938197.2836029687896371, 4244337.9901093561202288, - 4550942.1100616492331028, 4858010.8438911894336343, 5165545.3961938973516226, 5473546.9757476449012756, - 5782016.7955296505242586, 6090956.0727340159937739, 6400366.0287892958149314, 6710247.8893762007355690, - 7020602.8844453142955899, 7331432.2482349723577499, 7642737.2192891482263803, 7954519.0404754765331745, - 8266778.9590033423155546, 8579518.2264420464634895, 8892738.0987390466034412, 9206439.8362383283674717, - 9520624.7036988288164139, 9835293.9703129194676876, 10150448.9097250290215015, 10466090.8000503256917000 - }; - // CHECKSTYLE:ON LineLength -} diff --git a/src/main/java/org/apache/datasketches/hll/CubicInterpolation.java b/src/main/java/org/apache/datasketches/hll/CubicInterpolation.java deleted file mode 100644 index 4bca1a02e..000000000 --- a/src/main/java/org/apache/datasketches/hll/CubicInterpolation.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -final class CubicInterpolation { - - /** - * Cubic interpolation using interpolation X and Y tables. - * - * @param xArr xArr - * @param yArr yArr - * @param x x - * @return cubic interpolation - */ - //Used by AbstractCoupons - //In C: again-two-registers cubic_interpolate_using_table L1377 - static double usingXAndYTables(final double[] xArr, final double[] yArr, - final double x) { - assert (xArr.length >= 4) && (xArr.length == yArr.length); - if ((x < xArr[0]) || (x > xArr[xArr.length - 1])) { - throw new SketchesArgumentException("X value out of range: " + x); - } - if (x == xArr[xArr.length - 1]) { - return yArr[yArr.length - 1]; // corner case - } - final int offset = findStraddle(xArr, x); //uses recursion - assert (offset >= 0) && (offset <= (xArr.length - 2)); - if (offset == 0) { - return interpolateUsingXAndYTables(xArr, yArr, offset, x); // corner case - } - if (offset == (xArr.length - 2)) { - return interpolateUsingXAndYTables(xArr, yArr, offset - 2, x); // corner case - } - return interpolateUsingXAndYTables(xArr, yArr, offset - 1, x); - } - - // In C: again-two-registers cubic_interpolate_aux L1368 - private static double interpolateUsingXAndYTables(final double[] xArr, final double[] yArr, - final int offset, final double x) { - return cubicInterpolate(xArr[offset], yArr[offset], xArr[offset + 1], yArr[offset + 1], - xArr[offset + 2], yArr[offset + 2], xArr[offset + 3], yArr[offset + 3], x); - } - - //Interpolate using X table and Y stride - - /** - * Cubic interpolation using interpolation X table and Y stride. - * - * @param xArr The x array - * @param yStride The y stride - * @param x The value x - * @return cubic interpolation - */ - //In C: again-two-registers cubic_interpolate_with_x_arr_and_y_stride L1411 - // Used by HllEstimators - static double usingXArrAndYStride( - final double[] xArr, final double yStride, final double x) { - final int xArrLen = xArr.length; - final int xArrLenM1 = xArrLen - 1; - - final int offset; - assert ((xArrLen >= 4) && (x >= xArr[0]) && (x <= xArr[xArrLenM1])); - - if (x == xArr[xArrLenM1]) { /* corner case */ - return (yStride * (xArrLenM1)); - } - - offset = findStraddle(xArr, x); //uses recursion - final int xArrLenM2 = xArrLen - 2; - assert ((offset >= 0) && (offset <= (xArrLenM2))); - - if (offset == 0) { /* corner case */ - return (interpolateUsingXArrAndYStride(xArr, yStride, (offset - 0), x)); - } - else if (offset == xArrLenM2) { /* corner case */ - return (interpolateUsingXArrAndYStride(xArr, yStride, (offset - 2), x)); - } - /* main case */ - return (interpolateUsingXArrAndYStride(xArr, yStride, (offset - 1), x)); - } - - //In C: again-two-registers cubic_interpolate_with_x_arr_and_y_stride_aux L1402 - private static double interpolateUsingXArrAndYStride(final double[] xArr, final double yStride, - final int offset, final double x) { - return cubicInterpolate( - xArr[offset + 0], yStride * (offset + 0), - xArr[offset + 1], yStride * (offset + 1), - xArr[offset + 2], yStride * (offset + 2), - xArr[offset + 3], yStride * (offset + 3), - x); - } - - //Cubic Interpolation used by both methods - - // Interpolate using the cubic curve that passes through the four given points, using the - // Lagrange interpolation formula. - // In C: again-two-registers cubic_interpolate_aux_aux L1346 - private static double cubicInterpolate(final double x0, final double y0, final double x1, - final double y1, final double x2, final double y2, final double x3, final double y3, - final double x) { - final double l0Numer = (x - x1) * (x - x2) * (x - x3); - final double l1Numer = (x - x0) * (x - x2) * (x - x3); - final double l2Numer = (x - x0) * (x - x1) * (x - x3); - final double l3Numer = (x - x0) * (x - x1) * (x - x2); - - final double l0Denom = (x0 - x1) * (x0 - x2) * (x0 - x3); - final double l1Denom = (x1 - x0) * (x1 - x2) * (x1 - x3); - final double l2Denom = (x2 - x0) * (x2 - x1) * (x2 - x3); - final double l3Denom = (x3 - x0) * (x3 - x1) * (x3 - x2); - - final double term0 = (y0 * l0Numer) / l0Denom; - final double term1 = (y1 * l1Numer) / l1Denom; - final double term2 = (y2 * l2Numer) / l2Denom; - final double term3 = (y3 * l3Numer) / l3Denom; - - return term0 + term1 + term2 + term3; - } - - //In C: again-two-registers.c find_straddle L1335 - private static int findStraddle(final double[] xArr, final double x) { - assert ((xArr.length >= 2) && (x >= xArr[0]) && (x <= xArr[xArr.length - 1])); - return (recursiveFindStraddle(xArr, 0, xArr.length - 1, x)); - } - - //In C: again-two-registers.c find_straddle_aux L1322 - private static int recursiveFindStraddle(final double[] xArr, final int left, final int right, - final double x) { - final int middle; - assert (left < right); - assert ((xArr[left] <= x) && (x < xArr[right])); /* the invariant */ - if ((left + 1) == right) { - return (left); - } - middle = left + ((right - left) / 2); - if (xArr[middle] <= x) { - return (recursiveFindStraddle(xArr, middle, right, x)); - } else { - return (recursiveFindStraddle(xArr, left, middle, x)); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/CurMode.java b/src/main/java/org/apache/datasketches/hll/CurMode.java deleted file mode 100644 index a31266ce4..000000000 --- a/src/main/java/org/apache/datasketches/hll/CurMode.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -/** - * Represents the three fundamental modes of the HLL Sketch. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -enum CurMode { LIST, SET, HLL; //do not change the order. - - public static final CurMode values[] = values(); - - /** - * Returns the CurMode given its ordinal - * @param ordinal the order of appearance in the enum definition. - * @return the CurMode given its ordinal - */ - public static CurMode fromOrdinal(final int ordinal) { - return values[ordinal]; - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/DirectAuxHashMap.java b/src/main/java/org/apache/datasketches/hll/DirectAuxHashMap.java deleted file mode 100644 index 0f18aa24a..000000000 --- a/src/main/java/org/apache/datasketches/hll/DirectAuxHashMap.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.common.Util.clear; -import static org.apache.datasketches.hll.HllUtil.EMPTY; -import static org.apache.datasketches.hll.HllUtil.RESIZE_DENOM; -import static org.apache.datasketches.hll.HllUtil.RESIZE_NUMER; -import static org.apache.datasketches.hll.HllUtil.noWriteAccess; -import static org.apache.datasketches.hll.PreambleUtil.extractAuxCount; -import static org.apache.datasketches.hll.PreambleUtil.extractLgArr; -import static org.apache.datasketches.hll.PreambleUtil.insertAuxCount; -import static org.apache.datasketches.hll.PreambleUtil.insertLgArr; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; - -/** - * @author Lee Rhodes - */ -final class DirectAuxHashMap implements AuxHashMap { - private final DirectHllArray host; //hosts the MemorySegment and read-only MemorySegment - private final boolean readOnly; - - DirectAuxHashMap(final DirectHllArray host, final boolean initialize) { - this.host = host; - readOnly = (host.wseg == null); - final int initLgArrInts = HllUtil.LG_AUX_ARR_INTS[host.lgConfigK]; - - if (initialize) { //must be writable - if (readOnly) { noWriteAccess(); } - insertLgArr(host.wseg, initLgArrInts); - clear(host.wseg, host.auxStart, 4 << initLgArrInts); - } else if (extractLgArr(host.seg) < initLgArrInts) { - if (readOnly) { - throw new SketchesArgumentException( - "Possible MemorySegment image corruption, incorrect LgArr field in preamble."); - } - //insert the correct LgArr value - final int lgArr = - PreambleUtil.computeLgArr(host.wseg, host.auxHashMap.getAuxCount(), host.lgConfigK); - insertLgArr(host.wseg, lgArr); - } - } - - @Override - public DirectAuxHashMap copy() { //a no-op - return null; - } - - @Override - public int getAuxCount() { - return extractAuxCount(host.seg); - } - - @Override - public int[] getAuxIntArr() { - return null; - } - - @Override - public int getCompactSizeBytes() { - return getAuxCount() << 2; - } - - @Override - public PairIterator getIterator() { - return new IntMemorySegmentPairIterator( - host.seg, host.auxStart, 1 << getLgAuxArrInts(), host.lgConfigK); - } - - @Override - public int getLgAuxArrInts() { - return extractLgArr(host.seg); - } - - @Override - public int getUpdatableSizeBytes() { - return 4 << getLgAuxArrInts(); - } - - @Override - public boolean hasMemorySegment() { - return host.hasMemorySegment(); - } - - @Override - public boolean isOffHeap() { - return host.isOffHeap(); - } - - @Override - public boolean isSameResource(final MemorySegment seg) { - return host.isSameResource(seg); - } - - @Override - public void mustAdd(final int slotNo, final int value) { - if (readOnly) { noWriteAccess(); } - final int index = find(host, slotNo); - final int pair = HllUtil.pair(slotNo, value); - if (index >= 0) { - final String pairStr = HllUtil.pairString(pair); - throw new SketchesStateException("Found a slotNo that should not be there: " + pairStr); - } - //Found empty entry - host.wseg.set(JAVA_INT_UNALIGNED, host.auxStart + (~index << 2), pair); - int auxCount = extractAuxCount(host.seg); - insertAuxCount(host.wseg, ++auxCount); - final int lgAuxArrInts = extractLgArr(host.seg); - if ((RESIZE_DENOM * auxCount) > (RESIZE_NUMER * (1 << lgAuxArrInts))) { - grow(host, lgAuxArrInts); - } - } - - @Override - public int mustFindValueFor(final int slotNo) { - final int index = find(host, slotNo); - if (index >= 0) { - final int pair = host.seg.get(JAVA_INT_UNALIGNED, host.auxStart + (index << 2)); - return HllUtil.getPairValue(pair); - } - throw new SketchesStateException("SlotNo not found: " + slotNo); - } - - @Override - public void mustReplace(final int slotNo, final int value) { - if (readOnly) { noWriteAccess(); } - final int index = find(host, slotNo); - if (index >= 0) { - host.wseg.set(JAVA_INT_UNALIGNED, host.auxStart + (index << 2), HllUtil.pair(slotNo, value)); - return; - } - final String pairStr = HllUtil.pairString(HllUtil.pair(slotNo, value)); - throw new SketchesStateException("Pair not found: " + pairStr); - } - - //Searches the Aux arr hash table (embedded in MemorySegment) for an empty or a matching slotNo - // depending on the context. - //If entire entry is empty, returns one's complement of index = found empty. - //If entry contains given slotNo, returns its index = found slotNo. - //Continues searching. - //If the probe comes back to original index, throws an exception. - private static int find(final DirectHllArray host, final int slotNo) { - final int lgAuxArrInts = extractLgArr(host.seg); - assert lgAuxArrInts < host.lgConfigK : lgAuxArrInts; - final int auxInts = 1 << lgAuxArrInts; - final int auxArrMask = auxInts - 1; - final int configKmask = (1 << host.lgConfigK) - 1; - int probe = slotNo & auxArrMask; - final int loopIndex = probe; - do { - final int arrVal = host.seg.get(JAVA_INT_UNALIGNED, host.auxStart + (probe << 2)); - if (arrVal == EMPTY) { - return ~probe; //empty - } - else if (slotNo == (arrVal & configKmask)) { //found given slotNo - return probe; //return aux array index - } - final int stride = (slotNo >>> lgAuxArrInts) | 1; - probe = (probe + stride) & auxArrMask; - } while (probe != loopIndex); - throw new SketchesArgumentException("Key not found and no empty slots!"); - } - - private static void grow(final DirectHllArray host, final int oldLgAuxArrInts) { - if (host.wseg == null) { noWriteAccess(); } - final int oldAuxArrInts = 1 << oldLgAuxArrInts; - final int[] oldIntArray = new int[oldAuxArrInts]; //buffer old aux data - MemorySegment.copy(host.wseg, JAVA_INT_UNALIGNED, host.auxStart, oldIntArray, 0, oldAuxArrInts); - - insertLgArr(host.wseg, oldLgAuxArrInts + 1); //update LgArr field - - final long newAuxBytes = oldAuxArrInts << 3; - final long requestBytes = host.auxStart + newAuxBytes; - final long oldCapBytes = host.wseg.byteSize(); - - if (requestBytes > oldCapBytes) { - final MemorySegment newWseg = MemorySegment.ofArray(new byte[(int)requestBytes]); - MemorySegment.copy(host.wseg, 0, newWseg, 0, host.auxStart); - - clear(newWseg, host.auxStart, newAuxBytes); //clear space for new aux data - host.updateMemorySegment(newWseg); - } - //rehash into larger aux array - final int configKmask = (1 << host.lgConfigK) - 1; - - for (int i = 0; i < oldAuxArrInts; i++) { - final int fetched = oldIntArray[i]; - if (fetched != EMPTY) { - //find empty in new array - final int index = find(host, fetched & configKmask); - host.wseg.set(JAVA_INT_UNALIGNED, host.auxStart + (~index << 2), fetched); - } - } - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/DirectCouponHashSet.java b/src/main/java/org/apache/datasketches/hll/DirectCouponHashSet.java deleted file mode 100644 index e00d4a888..000000000 --- a/src/main/java/org/apache/datasketches/hll/DirectCouponHashSet.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.common.Util.clear; -import static org.apache.datasketches.hll.HllUtil.EMPTY; -import static org.apache.datasketches.hll.HllUtil.KEY_MASK_26; -import static org.apache.datasketches.hll.HllUtil.RESIZE_DENOM; -import static org.apache.datasketches.hll.HllUtil.RESIZE_NUMER; -import static org.apache.datasketches.hll.HllUtil.noWriteAccess; -import static org.apache.datasketches.hll.PreambleUtil.HASH_SET_INT_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.HASH_SET_PREINTS; -import static org.apache.datasketches.hll.PreambleUtil.LG_K_BYTE; -import static org.apache.datasketches.hll.PreambleUtil.extractHashSetCount; -import static org.apache.datasketches.hll.PreambleUtil.extractInt; -import static org.apache.datasketches.hll.PreambleUtil.extractLgArr; -import static org.apache.datasketches.hll.PreambleUtil.insertHashSetCount; -import static org.apache.datasketches.hll.PreambleUtil.insertInt; -import static org.apache.datasketches.hll.PreambleUtil.insertLgArr; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesException; -import org.apache.datasketches.common.SketchesStateException; - -/** - * @author Lee Rhodes - */ -final class DirectCouponHashSet extends DirectCouponList { - - //Constructs this sketch with data. - DirectCouponHashSet(final int lgConfigK, final TgtHllType tgtHllType, final MemorySegment wseg) { - super(lgConfigK, tgtHllType, CurMode.SET, wseg); - assert wseg.get(JAVA_BYTE, LG_K_BYTE) > 7; - } - - //Constructs this sketch with read-only data, may be compact. - DirectCouponHashSet(final int lgConfigK, final TgtHllType tgtHllType, final MemorySegment seg, final boolean readOnly) { - super(lgConfigK, tgtHllType, CurMode.SET, seg, readOnly); - assert seg.get(JAVA_BYTE, LG_K_BYTE) > 7; - } - - @Override //returns on-heap Set - CouponHashSet copy() { - return CouponHashSet.heapifySet(seg); - } - - @Override //returns on-heap Set - CouponHashSet copyAs(final TgtHllType tgtHllType) { - final CouponHashSet clist = CouponHashSet.heapifySet(seg); - return new CouponHashSet(clist, tgtHllType); - } - - @Override - HllSketchImpl couponUpdate(final int coupon) { - if (wseg == null) { noWriteAccess(); } - //avoid array copy - final int index = find(seg, getLgCouponArrInts(), coupon); - if (index >= 0) { - return this; //found duplicate, ignore - } - insertInt(wseg, HASH_SET_INT_ARR_START + (~index << 2), coupon); - insertHashSetCount(wseg, getCouponCount() + 1); - final boolean promote = checkGrowOrPromote(); - if (!promote) { return this; } - return promoteListOrSetToHll(this); - } - - @Override - int getCouponCount() { - return extractHashSetCount(seg); - } - - @Override - int getSegDataStart() { - return HASH_SET_INT_ARR_START; - } - - @Override - int getPreInts() { - return HASH_SET_PREINTS; - } - - private boolean checkGrowOrPromote() { - int lgCouponArrInts = getLgCouponArrInts(); - if ((RESIZE_DENOM * getCouponCount()) > (RESIZE_NUMER * (1 << lgCouponArrInts))) { - if (lgCouponArrInts == (getLgConfigK() - 3)) { - return true; // promote - } - insertLgArr(wseg, ++lgCouponArrInts); - growHashSet(wseg, lgCouponArrInts); - } - return false; - } - - //This could fail if the user has undersized the given MemorySegment - // and not used the public methods for sizing the MemorySegment. See exception. - private static void growHashSet(final MemorySegment wseg, final int tgtLgCouponArrSize) { - final int tgtArrSize = 1 << tgtLgCouponArrSize; - final int[] tgtCouponIntArr = new int[tgtArrSize]; - final int oldLen = 1 << extractLgArr(wseg); - for (int i = 0; i < oldLen; i++) { - final int fetched = extractInt(wseg, HASH_SET_INT_ARR_START + (i << 2)); - if (fetched != EMPTY) { - final int idx = find(tgtCouponIntArr, tgtLgCouponArrSize, fetched); - if (idx < 0) { //found EMPTY - tgtCouponIntArr[~idx] = fetched; //insert - continue; - } - throw new SketchesStateException("Error: found duplicate."); - } - } - clear(wseg, HASH_SET_INT_ARR_START, tgtArrSize << 2); - try { MemorySegment.copy(tgtCouponIntArr, 0, wseg, JAVA_INT_UNALIGNED, HASH_SET_INT_ARR_START, tgtArrSize); } - catch (final IndexOutOfBoundsException e) { - throw new SketchesException( - "The MemorySegment is undersized. Use the public methods for properly sizing MemorySegment.", e); - } - } - - //Searches the Coupon hash table (embedded in MemorySegment) for an empty slot - // or a duplicate depending on the context. - //If entire entry is empty, returns one's complement of index = found empty. - //If entry equals given coupon, returns its index = found duplicate coupon - //Continues searching - //If the probe comes back to original index, throws an exception. - private static int find(final MemorySegment seg, final int lgArr, - final int coupon) { - final int arrMask = (1 << lgArr) - 1; - int probe = coupon & arrMask; - final int loopIndex = probe; - do { - final int couponAtIndex = extractInt(seg, HASH_SET_INT_ARR_START + (probe << 2)); - if (couponAtIndex == EMPTY) { return ~probe; } //empty - else if (coupon == couponAtIndex) { return probe; } //duplicate - final int stride = ((coupon & KEY_MASK_26) >>> lgArr) | 1; - probe = (probe + stride) & arrMask; - } while (probe != loopIndex); - throw new SketchesArgumentException("Key not found and no empty slots!"); - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/DirectCouponList.java b/src/main/java/org/apache/datasketches/hll/DirectCouponList.java deleted file mode 100644 index 90a19a6f7..000000000 --- a/src/main/java/org/apache/datasketches/hll/DirectCouponList.java +++ /dev/null @@ -1,321 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.common.Util.clear; -import static org.apache.datasketches.hll.HllUtil.EMPTY; -import static org.apache.datasketches.hll.HllUtil.LG_INIT_LIST_SIZE; -import static org.apache.datasketches.hll.HllUtil.LG_INIT_SET_SIZE; -import static org.apache.datasketches.hll.HllUtil.noWriteAccess; -import static org.apache.datasketches.hll.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.hll.PreambleUtil.HASH_SET_PREINTS; -import static org.apache.datasketches.hll.PreambleUtil.HLL_PREINTS; -import static org.apache.datasketches.hll.PreambleUtil.LIST_INT_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.LIST_PREINTS; -import static org.apache.datasketches.hll.PreambleUtil.computeLgArr; -import static org.apache.datasketches.hll.PreambleUtil.extractCompactFlag; -import static org.apache.datasketches.hll.PreambleUtil.extractInt; -import static org.apache.datasketches.hll.PreambleUtil.extractLgArr; -import static org.apache.datasketches.hll.PreambleUtil.extractListCount; -import static org.apache.datasketches.hll.PreambleUtil.insertCurMin; -import static org.apache.datasketches.hll.PreambleUtil.insertCurMode; -import static org.apache.datasketches.hll.PreambleUtil.insertEmptyFlag; -import static org.apache.datasketches.hll.PreambleUtil.insertFamilyId; -import static org.apache.datasketches.hll.PreambleUtil.insertFlags; -import static org.apache.datasketches.hll.PreambleUtil.insertInt; -import static org.apache.datasketches.hll.PreambleUtil.insertKxQ0; -import static org.apache.datasketches.hll.PreambleUtil.insertLgArr; -import static org.apache.datasketches.hll.PreambleUtil.insertLgK; -import static org.apache.datasketches.hll.PreambleUtil.insertListCount; -import static org.apache.datasketches.hll.PreambleUtil.insertModes; -import static org.apache.datasketches.hll.PreambleUtil.insertNumAtCurMin; -import static org.apache.datasketches.hll.PreambleUtil.insertPreInts; -import static org.apache.datasketches.hll.PreambleUtil.insertSerVer; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; - -/** - * @author Lee Rhodes - */ -class DirectCouponList extends AbstractCoupons { - MemorySegment wseg; - MemorySegment seg; - final boolean compact; - - private static int checkSegCompactFlag(final MemorySegment wseg, final int lgConfigK) { - assert !extractCompactFlag(wseg) : "Compact Flag must not be set."; - return lgConfigK; - } - - //called from newInstance, writableWrap and DirectCouponHashSet, must not be compact - DirectCouponList(final int lgConfigK, final TgtHllType tgtHllType, final CurMode curMode, final MemorySegment wseg) { - super(checkSegCompactFlag(wseg, lgConfigK), tgtHllType, curMode); - this.wseg = wseg; - seg = wseg; - compact = extractCompactFlag(wseg); - } - - //called from HllSketch.wrap and from DirectCouponHashSet constructor, may or may not be compact - DirectCouponList(final int lgConfigK, final TgtHllType tgtHllType, final CurMode curMode, final MemorySegment seg, - final boolean readOnly) { - super(lgConfigK, tgtHllType, curMode); - wseg = null; - this.seg = readOnly ? seg.asReadOnly() : seg; - compact = extractCompactFlag(seg); - } - - /** - * Standard factory for new DirectCouponList. - * This initializes the given MemorySegment. - * @param lgConfigK the configured Lg K - * @param tgtHllType the configured HLL target - * @param dstSeg the destination MemorySegment for the sketch. - * @return a new DirectCouponList - */ - static DirectCouponList newInstance(final int lgConfigK, final TgtHllType tgtHllType, - final MemorySegment dstSeg) { - insertPreInts(dstSeg, LIST_PREINTS); - insertSerVer(dstSeg); - insertFamilyId(dstSeg); - insertLgK(dstSeg, lgConfigK); - insertLgArr(dstSeg, LG_INIT_LIST_SIZE); - insertFlags(dstSeg, EMPTY_FLAG_MASK); //empty and not compact - insertListCount(dstSeg, 0); - insertModes(dstSeg, tgtHllType, CurMode.LIST); - return new DirectCouponList(lgConfigK, tgtHllType, CurMode.LIST, dstSeg); - } - - @Override //returns on-heap List - CouponList copy() { - return CouponList.heapifyList(seg); - } - - @Override //returns on-heap List - CouponList copyAs(final TgtHllType tgtHllType) { - final CouponList clist = CouponList.heapifyList(seg); - return new CouponList(clist, tgtHllType); - } - - @Override - HllSketchImpl couponUpdate(final int coupon) { - if (wseg == null) { noWriteAccess(); } - final int len = 1 << getLgCouponArrInts(); - for (int i = 0; i < len; i++) { //search for empty slot and duplicates - final int couponAtIdx = extractInt(seg, LIST_INT_ARR_START + (i << 2)); - if (couponAtIdx == EMPTY) { - insertInt(wseg, LIST_INT_ARR_START + (i << 2), coupon); - int couponCount = extractListCount(seg); - insertListCount(wseg, ++couponCount); - insertEmptyFlag(wseg, false); //only first time - if (couponCount >= len) { //array full - if (lgConfigK < 8) { - return promoteListOrSetToHll(this);//oooFlag = false - } - return promoteListToSet(this); //oooFlag = true - } - return this; - } - //cell not empty - if (couponAtIdx == coupon) { return this; } //return if duplicate - //cell not empty & not a duplicate, continue - } //end for - throw new SketchesStateException("Invalid State: no empties & no duplicates"); - } - - @Override - int getCompactSerializationBytes() { - return getSegDataStart() + (getCouponCount() << 2); - } - - @Override //Overridden by DirectCouponHashSet - int getCouponCount() { - return extractListCount(seg); - } - - @Override - int[] getCouponIntArr() { //here only to satisfy the abstract, should not be used - return null; - } - - @Override - int getLgCouponArrInts() { - final int lgArr = extractLgArr(seg); - if (lgArr >= LG_INIT_LIST_SIZE) { return lgArr; } - //early versions of compact images did not use this lgArr field - final int coupons = getCouponCount(); - return computeLgArr(seg, coupons, lgConfigK); - } - - @Override - int getSegDataStart() { - return LIST_INT_ARR_START; - } - - @Override - MemorySegment getMemorySegment() { - return seg; - } - - @Override - int getPreInts() { - return LIST_PREINTS; - } - - @Override - boolean isCompact() { - return compact; - } - - @Override - boolean hasMemorySegment() { - return seg.scope().isAlive(); - } - - @Override - boolean isOffHeap() { - return seg.isNative(); - } - - @Override - boolean isSameResource(final MemorySegment seg) { - return MemorySegmentStatus.isSameResource(this.seg, seg); - } - - @Override - PairIterator iterator() { - final long dataStart = getSegDataStart(); - final int lenInts = (compact) ? getCouponCount() : 1 << getLgCouponArrInts(); - return new IntMemorySegmentPairIterator(seg, dataStart, lenInts, lgConfigK); - } - - @Override - void mergeTo(final HllSketch that) { - final int lenInts = (compact) ? getCouponCount() : 1 << getLgCouponArrInts(); - final int dataStart = getSegDataStart(); - for (int i = 0; i < lenInts; i++) { - final int pair = seg.get(JAVA_INT_UNALIGNED, dataStart + (i << 2)); - if (pair == 0) { continue; } - that.couponUpdate(pair); - } - } - - @Override - DirectCouponList reset() { - if (wseg == null) { - throw new SketchesArgumentException("Cannot reset a read-only sketch"); - } - insertEmptyFlag(wseg, true); - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType); - clear(wseg, 0, bytes); - - return DirectCouponList.newInstance(lgConfigK, tgtHllType, wseg); - } - - //Called by DirectCouponList.couponUpdate() - static final DirectCouponHashSet promoteListToSet(final DirectCouponList src) { - final MemorySegment wseg = src.wseg; - - //get the data from the current MemorySegment - HllUtil.checkPreamble(wseg); //sanity check - final int lgConfigK = src.lgConfigK; - final TgtHllType tgtHllType = src.tgtHllType; - final int srcOffset = LIST_INT_ARR_START; - final int couponArrInts = 1 << src.getLgCouponArrInts(); - final int[] couponArr = new int[couponArrInts]; //buffer - MemorySegment.copy(wseg, JAVA_INT_UNALIGNED, srcOffset, couponArr, 0, couponArrInts); - - //rewrite the MemorySegment image as a SET: - insertPreInts(wseg, HASH_SET_PREINTS); - //SerVer, FamID, LgK should be OK - insertLgArr(wseg, LG_INIT_SET_SIZE); - insertCurMin(wseg, 0); //was list count - insertCurMode(wseg, CurMode.SET); - //tgtHllType should already be ok - final int maxBytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType); - clear(wseg, LIST_INT_ARR_START, maxBytes - LIST_INT_ARR_START); //clear all past first 8 - - //create the tgt - final DirectCouponHashSet dchSet = new DirectCouponHashSet(src.lgConfigK, src.tgtHllType, src.wseg); - - //now reload the coupon data into the set - for (int i = 0; i < couponArrInts; i++) { - final int coupon = couponArr[i]; - if (coupon != EMPTY) { - dchSet.couponUpdate(coupon); - } - } - return dchSet; - } - - static final DirectHllArray promoteListOrSetToHll(final DirectCouponList src) { - final MemorySegment wseg = src.wseg; - - //get the data from the current list or set MemorySegment - HllUtil.checkPreamble(wseg); //sanity check - final int lgConfigK = src.lgConfigK; - final TgtHllType tgtHllType = src.tgtHllType; - final int srcSegDataStart = src.getSegDataStart(); - final double est = src.getEstimate(); - final int couponArrInts = 1 << src.getLgCouponArrInts(); - final int[] couponArr = new int[couponArrInts]; //buffer - MemorySegment.copy(wseg, JAVA_INT_UNALIGNED, srcSegDataStart, couponArr, 0, couponArrInts); - - //rewrite the MemorySegment image as an HLL - insertPreInts(wseg, HLL_PREINTS); - //SerVer, FamID, LgK should be OK - insertLgArr(wseg, 0); //no Aux possible yet - insertFlags(wseg, 0); //clear all flags - insertCurMin(wseg, 0); - insertCurMode(wseg, CurMode.HLL); - //tgtHllType should already be set - //we update HipAccum at the end - //clear KxQ0, KxQ1, NumAtCurMin, AuxCount, hllArray, auxArr - final int maxBytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType); - clear(wseg, LIST_INT_ARR_START, maxBytes - LIST_INT_ARR_START); //clear all past first 8 - insertNumAtCurMin(wseg, 1 << lgConfigK); //set numAtCurMin - insertKxQ0(wseg, 1 << lgConfigK); - - //choose the tgt - final DirectHllArray dirHllArr; - if (tgtHllType == TgtHllType.HLL_4) { - dirHllArr = new DirectHll4Array(lgConfigK, wseg); - } else if (tgtHllType == TgtHllType.HLL_6) { - dirHllArr = new DirectHll6Array(lgConfigK, wseg); - } else { //Hll_8 - dirHllArr = new DirectHll8Array(lgConfigK, wseg); - } - - //now load the coupon data into HLL - for (int i = 0; i < couponArrInts; i++) { - final int coupon = couponArr[i]; - if (coupon != EMPTY) { - dirHllArr.couponUpdate(coupon); - } - } - dirHllArr.putHipAccum(est); - return dirHllArr; - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/DirectHll4Array.java b/src/main/java/org/apache/datasketches/hll/DirectHll4Array.java deleted file mode 100644 index 03eefdc01..000000000 --- a/src/main/java/org/apache/datasketches/hll/DirectHll4Array.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.hll.HllUtil.AUX_TOKEN; -import static org.apache.datasketches.hll.HllUtil.KEY_BITS_26; -import static org.apache.datasketches.hll.HllUtil.LG_AUX_ARR_INTS; -import static org.apache.datasketches.hll.HllUtil.hiNibbleMask; -import static org.apache.datasketches.hll.HllUtil.loNibbleMask; -import static org.apache.datasketches.hll.HllUtil.noWriteAccess; -import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.extractAuxCount; -import static org.apache.datasketches.hll.PreambleUtil.extractCompactFlag; -import static org.apache.datasketches.hll.PreambleUtil.insertAuxCount; -import static org.apache.datasketches.hll.PreambleUtil.insertCompactFlag; -import static org.apache.datasketches.hll.PreambleUtil.insertInt; -import static org.apache.datasketches.hll.PreambleUtil.insertLgArr; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * @author Lee Rhodes - */ -final class DirectHll4Array extends DirectHllArray { - - //Called by HllSketch.writableWrap(), DirectCouponList.promoteListOrSetToHll - DirectHll4Array(final int lgConfigK, final MemorySegment wseg) { - super(lgConfigK, TgtHllType.HLL_4, wseg); - if (extractAuxCount(seg) > 0) { - putAuxHashMap(new DirectAuxHashMap(this, false), false); - } - } - - //Called by HllSketch.wrap(MemorySegment) - DirectHll4Array(final int lgConfigK, final MemorySegment seg, final boolean readOnly) { - super(lgConfigK, TgtHllType.HLL_4, seg, readOnly); - final int auxCount = extractAuxCount(seg); - if (auxCount > 0) { - final boolean compact = extractCompactFlag(seg); - final AuxHashMap auxHashMap; - if (compact) { - auxHashMap = HeapAuxHashMap.heapify(seg, auxStart, lgConfigK, auxCount, compact); - } else { - auxHashMap = new DirectAuxHashMap(this, false); //not compact - } - putAuxHashMap(auxHashMap, compact); - } - } - - @Override - HllSketchImpl copy() { - return Hll4Array.heapify(seg); - } - - @Override - HllSketchImpl couponUpdate(final int coupon) { - if (wseg == null) { noWriteAccess(); } - final int newValue = coupon >>> KEY_BITS_26; - final int configKmask = (1 << getLgConfigK()) - 1; - final int slotNo = coupon & configKmask; - updateSlotWithKxQ(slotNo, newValue); - return this; - } - - @Override - int getHllByteArrBytes() { - return hll4ArrBytes(lgConfigK); - } - - @Override - int getNibble(final int slotNo) { - final long offset = HLL_BYTE_ARR_START + (slotNo >>> 1); - int theByte = seg.get(JAVA_BYTE, offset); - if ((slotNo & 1) > 0) { //odd? - theByte >>>= 4; - } - return theByte & loNibbleMask; - } - - @Override - int getSlotValue(final int slotNo) { - final int nib = getNibble(slotNo); - if (nib == AUX_TOKEN) { - final AuxHashMap auxHashMap = getAuxHashMap(); - return auxHashMap.mustFindValueFor(slotNo); //auxHashMap cannot be null here - } else { - return nib + getCurMin(); - } - } - - @Override - int getUpdatableSerializationBytes() { - final AuxHashMap auxHashMap = getAuxHashMap(); - final int auxBytes; - if (auxHashMap == null) { - auxBytes = 4 << LG_AUX_ARR_INTS[lgConfigK]; - } else { - auxBytes = 4 << auxHashMap.getLgAuxArrInts(); - } - return HLL_BYTE_ARR_START + getHllByteArrBytes() + auxBytes; - } - - @Override - PairIterator iterator() { - return new DirectHll4Iterator(1 << lgConfigK); - } - - @Override - void putNibble(final int slotNo, final int nibValue) { - final long offset = HLL_BYTE_ARR_START + (slotNo >>> 1); - final int oldValue = seg.get(JAVA_BYTE, offset); - final byte value = ((slotNo & 1) == 0) //even? - ? (byte) ((oldValue & hiNibbleMask) | (nibValue & loNibbleMask)) //set low nibble - : (byte) ((oldValue & loNibbleMask) | ((nibValue << 4) & hiNibbleMask)); //set high nibble - wseg.set(JAVA_BYTE, offset, value); - } - - @Override - //Would be used by HllUnion, but not used because the gadget is always HLL8 type - void updateSlotNoKxQ(final int slotNo, final int newValue) { - throw new SketchesStateException("Improper access."); - } - - @Override - //Used by this couponUpdate() - //updates HipAccum, CurMin, NumAtCurMin, KxQs and checks newValue > oldValue - void updateSlotWithKxQ(final int slotNo, final int newValue) { - Hll4Update.internalHll4Update(this, slotNo, newValue); - } - - @Override - byte[] toCompactByteArray() { - final boolean srcSegIsCompact = extractCompactFlag(seg); - final int totBytes = getCompactSerializationBytes(); - final byte[] byteArr = new byte[totBytes]; - final MemorySegment segOut = MemorySegment.ofArray(byteArr); - if (srcSegIsCompact) { //seg is already consistent with result - MemorySegment.copy(seg, 0, segOut, 0, totBytes); - return byteArr; - } - //everything but the aux array is consistent - MemorySegment.copy(seg, 0, segOut, 0, auxStart); - if (auxHashMap != null) { - final int auxCount = auxHashMap.getAuxCount(); - insertAuxCount(segOut, auxCount); - insertLgArr(segOut, auxHashMap.getLgAuxArrInts()); //only used for direct HLL - final PairIterator itr = auxHashMap.getIterator(); - int cnt = 0; - while (itr.nextValid()) { //works whether src has compact MemorySegment or not - insertInt(segOut, auxStart + (cnt++ << 2), itr.getPair()); - } - assert cnt == auxCount; - } - insertCompactFlag(segOut, true); - return byteArr; - } - - @Override - byte[] toUpdatableByteArray() { - final boolean segIsCompact = extractCompactFlag(seg); - final int totBytes = getUpdatableSerializationBytes(); - final byte[] byteArr = new byte[totBytes]; - final MemorySegment segOut = MemorySegment.ofArray(byteArr); - - if (!segIsCompact) { //both seg and target are updatable - MemorySegment.copy(seg, 0, segOut, 0, totBytes); - - return byteArr; - } - //seg is compact, need to handle auxArr. Easiest way: - final HllSketch heapSk = HllSketch.heapify(seg); - return heapSk.toUpdatableByteArray(); - } - - //ITERATOR - - final class DirectHll4Iterator extends HllPairIterator { - - DirectHll4Iterator(final int lengthPairs) { - super(lengthPairs); - } - - @Override - int value() { - return getSlotValue(index); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/DirectHll6Array.java b/src/main/java/org/apache/datasketches/hll/DirectHll6Array.java deleted file mode 100644 index 4d35be674..000000000 --- a/src/main/java/org/apache/datasketches/hll/DirectHll6Array.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.hll.HllUtil.VAL_MASK_6; -import static org.apache.datasketches.hll.HllUtil.noWriteAccess; -import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * @author Lee Rhodes - */ -final class DirectHll6Array extends DirectHllArray { - - //Called by HllSketch.writableWrap(), DirectCouponList.promoteListOrSetToHll - DirectHll6Array(final int lgConfigK, final MemorySegment wseg) { - super(lgConfigK, TgtHllType.HLL_6, wseg); - } - - //Called by HllSketch.wrap(MemorySegment) - DirectHll6Array(final int lgConfigK, final MemorySegment seg, final boolean readOnly) { - super(lgConfigK, TgtHllType.HLL_6, seg, readOnly); - } - - @Override - HllSketchImpl copy() { - return Hll6Array.heapify(seg); - } - - @Override - HllSketchImpl couponUpdate(final int coupon) { - if (wseg == null) { noWriteAccess(); } - final int newValue = HllUtil.getPairValue(coupon); - final int configKmask = (1 << getLgConfigK()) - 1; - final int slotNo = HllUtil.getPairLow26(coupon) & configKmask; - updateSlotWithKxQ(slotNo, newValue); - return this; - } - - @Override - int getHllByteArrBytes() { - return hll6ArrBytes(lgConfigK); - } - - @Override - int getNibble(final int slotNo) { - throw new SketchesStateException("Improper access."); - } - - @Override int getSlotValue(final int slotNo) { - return get6Bit(seg, HLL_BYTE_ARR_START, slotNo); - } - - @Override - PairIterator iterator() { - return new DirectHll6Iterator(1 << lgConfigK); - } - - @Override - void putNibble(final int slotNo, final int nibValue) { - throw new SketchesStateException("Improper access."); - } - - @Override - //Would be used by HllUnion, but not used because the gadget is always HLL8 type - void updateSlotNoKxQ(final int slotNo, final int newValue) { - throw new SketchesStateException("Improper access."); - } - - @Override - //Used by this couponUpdate() - //updates HipAccum, CurMin, NumAtCurMin, KxQs and checks newValue > oldValue - void updateSlotWithKxQ(final int slotNo, final int newValue) { - final int oldValue = getSlotValue(slotNo); - if (newValue > oldValue) { - put6Bit(wseg, HLL_BYTE_ARR_START, slotNo, newValue); - hipAndKxQIncrementalUpdate(this, oldValue, newValue); - if (oldValue == 0) { - decNumAtCurMin(); //overloaded as num zeros - assert getNumAtCurMin() >= 0; - } - } - } - - //off-heap / direct - private static void put6Bit(final MemorySegment wseg, final int offsetBytes, final int slotNo, - final int newValue) { - final int startBit = slotNo * 6; - final int shift = startBit & 0X7; - final int byteIdx = (startBit >>> 3) + offsetBytes; - final int valShifted = (newValue & 0X3F) << shift; - final int curMasked = wseg.get(JAVA_SHORT_UNALIGNED, byteIdx) & (~(VAL_MASK_6 << shift)); - final short insert = (short) (curMasked | valShifted); - wseg.set(JAVA_SHORT_UNALIGNED, byteIdx, insert); - } - - //off-heap / direct - private static int get6Bit(final MemorySegment seg, final int offsetBytes, final int slotNo) { - final int startBit = slotNo * 6; - final int shift = startBit & 0X7; - final int byteIdx = (startBit >>> 3) + offsetBytes; - return (byte) ((seg.get(JAVA_SHORT_UNALIGNED, byteIdx) >>> shift) & 0X3F); - } - - //ITERATOR - - final class DirectHll6Iterator extends HllPairIterator { - int bitOffset; - - DirectHll6Iterator(final int lengthPairs) { - super(lengthPairs); - bitOffset = -6; - } - - @Override - int value() { - bitOffset += 6; - final int tmp = seg.get(JAVA_SHORT_UNALIGNED, HLL_BYTE_ARR_START + (bitOffset / 8)); - final int shift = (bitOffset % 8) & 0X7; - return (tmp >>> shift) & VAL_MASK_6; - } - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/DirectHll8Array.java b/src/main/java/org/apache/datasketches/hll/DirectHll8Array.java deleted file mode 100644 index 34714fb75..000000000 --- a/src/main/java/org/apache/datasketches/hll/DirectHll8Array.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.hll.HllUtil.VAL_MASK_6; -import static org.apache.datasketches.hll.HllUtil.noWriteAccess; -import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * Uses 8 bits per slot in a byte array. - * @author Lee Rhodes - * @author Kevin Lang - */ -final class DirectHll8Array extends DirectHllArray { - - //Called by HllSketch.writableWrap(), DirectCouponList.promoteListOrSetToHll - DirectHll8Array(final int lgConfigK, final MemorySegment wseg) { - super(lgConfigK, TgtHllType.HLL_8, wseg); - } - - //Called by HllSketch.wrap(MemorySegment) - DirectHll8Array(final int lgConfigK, final MemorySegment seg, final boolean readOnly) { - super(lgConfigK, TgtHllType.HLL_8, seg, readOnly); - } - - @Override - HllSketchImpl copy() { - return Hll8Array.heapify(seg); - } - - @Override - HllSketchImpl couponUpdate(final int coupon) { - if (wseg == null) { noWriteAccess(); } - final int newValue = HllUtil.getPairValue(coupon); - final int configKmask = (1 << getLgConfigK()) - 1; - final int slotNo = HllUtil.getPairLow26(coupon) & configKmask; - - updateSlotWithKxQ(slotNo, newValue); - return this; - } - - @Override - int getHllByteArrBytes() { - return hll8ArrBytes(lgConfigK); - } - - @Override - int getNibble(final int slotNo) { - throw new SketchesStateException("Improper access."); - } - - @Override int getSlotValue(final int slotNo) { - return seg.get(JAVA_BYTE, HLL_BYTE_ARR_START + slotNo) & VAL_MASK_6; - } - - @Override - PairIterator iterator() { - return new DirectHll8Iterator(1 << lgConfigK); - } - - @Override - void putNibble(final int slotNo, final int nibValue) { - throw new SketchesStateException("Improper access."); - } - - @Override - //Used by HllUnion when source is not HLL8 - void updateSlotNoKxQ(final int slotNo, final int newValue) { - final int oldValue = getSlotValue(slotNo); - if (newValue > oldValue) { - wseg.set(JAVA_BYTE, HLL_BYTE_ARR_START + slotNo, (byte) (newValue & VAL_MASK_6)); - } - } - - @Override - //Used by this couponUpdate() - //updates HipAccum, CurMin, NumAtCurMin, KxQs and checks newValue > oldValue - void updateSlotWithKxQ(final int slotNo, final int newValue) { - final int oldValue = getSlotValue(slotNo); - if (newValue > oldValue) { - wseg.set(JAVA_BYTE, HLL_BYTE_ARR_START + slotNo, (byte) (newValue & VAL_MASK_6)); - hipAndKxQIncrementalUpdate(this, oldValue, newValue); - if (oldValue == 0) { - decNumAtCurMin(); - assert getNumAtCurMin() >= 0; - } - } - } - - //ITERATOR - - final class DirectHll8Iterator extends HllPairIterator { - - DirectHll8Iterator(final int lengthPairs) { - super(lengthPairs); - } - - @Override - int value() { - final int tmp = seg.get(JAVA_BYTE, HLL_BYTE_ARR_START + index); - return tmp & VAL_MASK_6; - } - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/DirectHllArray.java b/src/main/java/org/apache/datasketches/hll/DirectHllArray.java deleted file mode 100644 index e0fb7594e..000000000 --- a/src/main/java/org/apache/datasketches/hll/DirectHllArray.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.common.Util.clear; -import static org.apache.datasketches.hll.PreambleUtil.CUR_MIN_COUNT_INT; -import static org.apache.datasketches.hll.PreambleUtil.HIP_ACCUM_DOUBLE; -import static org.apache.datasketches.hll.PreambleUtil.extractCompactFlag; -import static org.apache.datasketches.hll.PreambleUtil.extractCurMin; -import static org.apache.datasketches.hll.PreambleUtil.extractCurMode; -import static org.apache.datasketches.hll.PreambleUtil.extractEmptyFlag; -import static org.apache.datasketches.hll.PreambleUtil.extractHipAccum; -import static org.apache.datasketches.hll.PreambleUtil.extractKxQ0; -import static org.apache.datasketches.hll.PreambleUtil.extractKxQ1; -import static org.apache.datasketches.hll.PreambleUtil.extractLgK; -import static org.apache.datasketches.hll.PreambleUtil.extractNumAtCurMin; -import static org.apache.datasketches.hll.PreambleUtil.extractOooFlag; -import static org.apache.datasketches.hll.PreambleUtil.extractRebuildCurMinNumKxQFlag; -import static org.apache.datasketches.hll.PreambleUtil.extractTgtHllType; -import static org.apache.datasketches.hll.PreambleUtil.insertAuxCount; -import static org.apache.datasketches.hll.PreambleUtil.insertCompactFlag; -import static org.apache.datasketches.hll.PreambleUtil.insertCurMin; -import static org.apache.datasketches.hll.PreambleUtil.insertEmptyFlag; -import static org.apache.datasketches.hll.PreambleUtil.insertHipAccum; -import static org.apache.datasketches.hll.PreambleUtil.insertKxQ0; -import static org.apache.datasketches.hll.PreambleUtil.insertKxQ1; -import static org.apache.datasketches.hll.PreambleUtil.insertLgArr; -import static org.apache.datasketches.hll.PreambleUtil.insertNumAtCurMin; -import static org.apache.datasketches.hll.PreambleUtil.insertOooFlag; -import static org.apache.datasketches.hll.PreambleUtil.insertRebuildCurMinNumKxQFlag; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * @author Lee Rhodes - */ -abstract class DirectHllArray extends AbstractHllArray { - MemorySegment wseg; //used for writable direct - MemorySegment seg; //used for compact, read-only direct - Object segObj; //used temporarily for byte-array - final boolean compact; - - private static int checkSegCompactFlag(final MemorySegment wseg, final int lgConfigK) { - assert !extractCompactFlag(wseg); - return lgConfigK; - } - - //MemorySegment must be already initialized and may have data. Writable, must not be Compact. - DirectHllArray(final int lgConfigK, final TgtHllType tgtHllType, final MemorySegment wseg) { - super(checkSegCompactFlag(wseg, lgConfigK), tgtHllType, CurMode.HLL); - this.wseg = wseg; - seg = wseg; - segObj = wseg.toArray(JAVA_BYTE); - compact = extractCompactFlag(seg); - insertEmptyFlag(wseg, false); - } - - //MemorySegment must already be initialized and should have data. Read-only. May be Compact or not - DirectHllArray(final int lgConfigK, final TgtHllType tgtHllType, final MemorySegment seg, final boolean readOnly) { - super(lgConfigK, tgtHllType, CurMode.HLL); - wseg = null; - this.seg = readOnly ? seg.asReadOnly() : seg; - segObj = seg.toArray(JAVA_BYTE); - compact = extractCompactFlag(seg); - } - - //only called by DirectAuxHashMap - final void updateMemorySegment(final MemorySegment newWseg) { - wseg = newWseg; - seg = newWseg; - segObj = wseg.toArray(JAVA_BYTE); - } - - @Override - void addToHipAccum(final double delta) { - checkReadOnly(wseg); - final double hipAccum = seg.get(JAVA_DOUBLE_UNALIGNED, HIP_ACCUM_DOUBLE); - wseg.set(JAVA_DOUBLE_UNALIGNED, HIP_ACCUM_DOUBLE, hipAccum + delta); - } - - @Override - void decNumAtCurMin() { - checkReadOnly(wseg); - int numAtCurMin = seg.get(JAVA_INT_UNALIGNED, CUR_MIN_COUNT_INT); - wseg.set(JAVA_INT_UNALIGNED, CUR_MIN_COUNT_INT, --numAtCurMin); - } - - @Override - int getCurMin() { - return extractCurMin(seg); - } - - @Override - CurMode getCurMode() { - return extractCurMode(seg); - } - - @Override - double getHipAccum() { - return extractHipAccum(seg); - } - - @Override - double getKxQ0() { - return extractKxQ0(seg); - } - - @Override - double getKxQ1() { - return extractKxQ1(seg); - } - - @Override - int getLgConfigK() { - return extractLgK(seg); - } - - @Override - MemorySegment getMemorySegment() { - return seg; - } - - @Override - AuxHashMap getNewAuxHashMap() { - return new DirectAuxHashMap(this, true); - } - - @Override - int getNumAtCurMin() { - return extractNumAtCurMin(seg); - } - - @Override - TgtHllType getTgtHllType() { - return extractTgtHllType(seg); - } - - @Override - boolean isCompact() { - return compact; - } - - @Override - boolean isEmpty() { - return extractEmptyFlag(seg); - } - - @Override - boolean hasMemorySegment() { - return seg.scope().isAlive(); - } - - @Override - boolean isOffHeap() { - return seg.isNative(); - } - - @Override - boolean isOutOfOrder() { - return extractOooFlag(seg); - } - - @Override - boolean isSameResource(final MemorySegment seg) { - return MemorySegmentStatus.isSameResource(this.seg, seg); - } - - @Override - boolean isRebuildCurMinNumKxQFlag() { - return extractRebuildCurMinNumKxQFlag(seg); - } - - @Override - void putAuxHashMap(final AuxHashMap auxHashMap, final boolean compact) { - if (auxHashMap instanceof HeapAuxHashMap) { - if (compact) { - this.auxHashMap = auxHashMap; //heap and compact - } else { //heap and not compact - final int[] auxArr = auxHashMap.getAuxIntArr(); - MemorySegment.copy(auxArr, 0, wseg, JAVA_INT_UNALIGNED, auxStart, auxArr.length); - insertLgArr(wseg, auxHashMap.getLgAuxArrInts()); - insertAuxCount(wseg, auxHashMap.getAuxCount()); - this.auxHashMap = new DirectAuxHashMap(this, false); - } - } else { //DirectAuxHashMap - assert !compact; //must not be compact - this.auxHashMap = auxHashMap; //In case of read-only this works. - } - } - - @Override - void putCurMin(final int curMin) { - checkReadOnly(wseg); - insertCurMin(wseg, curMin); - } - - @Override - void putEmptyFlag(final boolean empty) { - checkReadOnly(wseg); - insertEmptyFlag(wseg, empty); - } - - @Override - void putHipAccum(final double hipAccum) { - checkReadOnly(wseg); - insertHipAccum(wseg, hipAccum); - } - - @Override - void putKxQ0(final double kxq0) { - checkReadOnly(wseg); - insertKxQ0(wseg, kxq0); - } - - @Override //called very very very rarely - void putKxQ1(final double kxq1) { - checkReadOnly(wseg); - insertKxQ1(wseg, kxq1); - } - - @Override - void putNumAtCurMin(final int numAtCurMin) { - checkReadOnly(wseg); - insertNumAtCurMin(wseg, numAtCurMin); - } - - @Override //not used on the direct side - void putOutOfOrder(final boolean oooFlag) { - if (oooFlag) { putHipAccum(0); } - checkReadOnly(wseg); - insertOooFlag(wseg, oooFlag); - } - - @Override - void putRebuildCurMinNumKxQFlag(final boolean rebuild) { - checkReadOnly(wseg); - insertRebuildCurMinNumKxQFlag(wseg, rebuild); - } - - @Override //used by HLL6 and HLL8, overridden by HLL4 - byte[] toCompactByteArray() { - return toUpdatableByteArray(); //indistinguishable for HLL6 and HLL8 - } - - @Override //used by HLL6 and HLL8, overridden by HLL4 - byte[] toUpdatableByteArray() { - final int totBytes = getCompactSerializationBytes(); - final byte[] byteArr = new byte[totBytes]; - final MemorySegment segOut = MemorySegment.ofArray(byteArr); - MemorySegment.copy(seg, 0, segOut, 0, totBytes); - insertCompactFlag(segOut, false); - return byteArr; - } - - @Override - HllSketchImpl reset() { - checkReadOnly(wseg); - insertEmptyFlag(wseg, true); - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType); - clear(wseg, 0, bytes); - return DirectCouponList.newInstance(lgConfigK, tgtHllType, wseg); - } - - private static final void checkReadOnly(final MemorySegment wseg) { - if (wseg == null) { - throw new SketchesArgumentException("Cannot modify a read-only sketch"); - } - } -} diff --git a/src/main/java/org/apache/datasketches/hll/HarmonicNumbers.java b/src/main/java/org/apache/datasketches/hll/HarmonicNumbers.java deleted file mode 100644 index 1d236d2f6..000000000 --- a/src/main/java/org/apache/datasketches/hll/HarmonicNumbers.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -final class HarmonicNumbers { - - /** - * This is the estimator you would use for flat bit map random accessed, similar to a Bloom filter. - * @param bitVectorLength the length of the bit vector in bits. Must be > 0. - * @param numBitsSet the number of bits set in this bit vector. Must be ≥ 0 and ≤ - * bitVectorLength. - * @return the estimate. - */ - static double getBitMapEstimate(final int bitVectorLength, final int numBitsSet) { - return (bitVectorLength * (harmonicNumber(bitVectorLength) - - harmonicNumber(bitVectorLength - numBitsSet))); //converts to numZeros - } - - //In C: two-registers.c Line 1170 - private static final int NUM_EXACT_HARMONIC_NUMBERS = 25; - - private static double[] tableOfExactHarmonicNumbers = { - 0.0, // 0 - 1.0, // 1 - 1.5, // 2 - 11.0 / 6.0, // 3 - 25.0 / 12.0, // 4 - 137.0 / 60.0, // 5 - 49.0 / 20.0, // 6 - 363.0 / 140.0, // 7 - 761.0 / 280.0, // 8 - 7129.0 / 2520.0, // 9 - 7381.0 / 2520.0, // 10 - 83711.0 / 27720.0, // 11 - 86021.0 / 27720.0, // 12 - 1145993.0 / 360360.0, // 13 - 1171733.0 / 360360.0, // 14 - 1195757.0 / 360360.0, // 15 - 2436559.0 / 720720.0, // 16 - 42142223.0 / 12252240.0, // 17 - 14274301.0 / 4084080.0, // 18 - 275295799.0 / 77597520.0, // 19 - 55835135.0 / 15519504.0, // 20 - 18858053.0 / 5173168.0, // 21 - 19093197.0 / 5173168.0, // 22 - 444316699.0 / 118982864.0, // 23 - 1347822955.0 / 356948592.0 // 24 - }; - - //In C: two-register.c Line 1202 - private static final double EULER_MASCHERONI_CONSTANT = 0.577215664901532860606512090082; - - private static double harmonicNumber(final long x_i) { - if (x_i < NUM_EXACT_HARMONIC_NUMBERS) { - return tableOfExactHarmonicNumbers[(int) x_i]; - } else { - final double x = x_i; - final double invSq = 1.0 / (x * x); - double sum = Math.log(x) + EULER_MASCHERONI_CONSTANT + (1.0 / (2.0 * x)); - /* note: the number of terms included from this series expansion is appropriate - for the size of the exact table (25) and the precision of doubles */ - double pow = invSq; /* now n^-2 */ - sum -= pow * (1.0 / 12.0); - pow *= invSq; /* now n^-4 */ - sum += pow * (1.0 / 120.0); - pow *= invSq; /* now n^-6 */ - sum -= pow * (1.0 / 252.0); - pow *= invSq; /* now n^-8 */ - sum += pow * (1.0 / 240.0); - return sum; - } - } -} diff --git a/src/main/java/org/apache/datasketches/hll/HeapAuxHashMap.java b/src/main/java/org/apache/datasketches/hll/HeapAuxHashMap.java deleted file mode 100644 index 3a1600676..000000000 --- a/src/main/java/org/apache/datasketches/hll/HeapAuxHashMap.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.HllUtil.EMPTY; -import static org.apache.datasketches.hll.HllUtil.RESIZE_DENOM; -import static org.apache.datasketches.hll.HllUtil.RESIZE_NUMER; -import static org.apache.datasketches.hll.PreambleUtil.extractInt; -import static org.apache.datasketches.hll.PreambleUtil.extractLgArr; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -final class HeapAuxHashMap implements AuxHashMap { - private final int lgConfigK; //required for #slot bits - private int lgAuxArrInts; - private int auxCount; - private int[] auxIntArr; //used by Hll4Array - - /** - * Standard constructor - * @param lgAuxArrInts the log size of the aux integer array - * @param lgConfigK must be 7 to 21 - */ - HeapAuxHashMap(final int lgAuxArrInts, final int lgConfigK) { - this.lgConfigK = lgConfigK; - this.lgAuxArrInts = lgAuxArrInts; - auxIntArr = new int[1 << lgAuxArrInts]; - } - - /** - * Copy constructor - * @param that another AuxHashMap - */ - HeapAuxHashMap(final HeapAuxHashMap that) { - lgConfigK = that.lgConfigK; - lgAuxArrInts = that.lgAuxArrInts; - auxCount = that.auxCount; - auxIntArr = that.auxIntArr.clone(); - } - - static HeapAuxHashMap heapify(final MemorySegment seg, final long offset, final int lgConfigK, - final int auxCount, final boolean srcCompact) { - final int lgAuxArrInts; - final HeapAuxHashMap auxMap; - if (srcCompact) { //early versions did not use LgArr byte field - lgAuxArrInts = PreambleUtil.computeLgArr(seg, auxCount, lgConfigK); - } else { //updatable - lgAuxArrInts = extractLgArr(seg); - } - auxMap = new HeapAuxHashMap(lgAuxArrInts, lgConfigK); - - final int configKmask = (1 << lgConfigK) - 1; - - if (srcCompact) { - for (int i = 0; i < auxCount; i++) { - final int pair = extractInt(seg, offset + (i << 2)); - final int slotNo = HllUtil.getPairLow26(pair) & configKmask; - final int value = HllUtil.getPairValue(pair); - auxMap.mustAdd(slotNo, value); //increments count - } - } else { //updatable - final int auxArrInts = 1 << lgAuxArrInts; - for (int i = 0; i < auxArrInts; i++) { - final int pair = extractInt(seg, offset + (i << 2)); - if (pair == EMPTY) { continue; } - final int slotNo = HllUtil.getPairLow26(pair) & configKmask; - final int value = HllUtil.getPairValue(pair); - auxMap.mustAdd(slotNo, value); //increments count - } - } - return auxMap; - } - - @Override - public HeapAuxHashMap copy() { - return new HeapAuxHashMap(this); - } - - @Override - public int getAuxCount() { - return auxCount; - } - - @Override - public int[] getAuxIntArr() { - return auxIntArr; - } - - @Override - public int getCompactSizeBytes() { - return auxCount << 2; - } - - @Override - public PairIterator getIterator() { - return new IntArrayPairIterator(auxIntArr, lgConfigK); - } - - @Override - public int getLgAuxArrInts() { - return lgAuxArrInts; - } - - @Override - public int getUpdatableSizeBytes() { - return 4 << lgAuxArrInts; - } - - @Override - public boolean hasMemorySegment() { - return false; - } - - @Override - public boolean isOffHeap() { - return false; - } - - @Override - public boolean isSameResource(final MemorySegment seg) { - return false; - } - - //In C: two-registers.c Line 300. - @Override - public void mustAdd(final int slotNo, final int value) { - final int index = find(auxIntArr, lgAuxArrInts, lgConfigK, slotNo); - final int pair = HllUtil.pair(slotNo, value); - if (index >= 0) { - final String pairStr = HllUtil.pairString(pair); - throw new SketchesStateException("Found a slotNo that should not be there: " + pairStr); - } - //Found empty entry - auxIntArr[~index] = pair; - auxCount++; - checkGrow(); - } - - //In C: two-registers.c Line 205 - @Override - public int mustFindValueFor(final int slotNo) { - final int index = find(auxIntArr, lgAuxArrInts, lgConfigK, slotNo); - if (index >= 0) { - return HllUtil.getPairValue(auxIntArr[index]); - } - throw new SketchesStateException("SlotNo not found: " + slotNo); - } - - //In C: two-registers.c Line 321. - @Override - public void mustReplace(final int slotNo, final int value) { - final int idx = find(auxIntArr, lgAuxArrInts, lgConfigK, slotNo); - if (idx >= 0) { - auxIntArr[idx] = HllUtil.pair(slotNo, value); //replace - return; - } - final String pairStr = HllUtil.pairString(HllUtil.pair(slotNo, value)); - throw new SketchesStateException("Pair not found: " + pairStr); - } - - //Searches the Aux arr hash table for an empty or a matching slotNo depending on the context. - //If entire entry is empty, returns one's complement of index = found empty. - //If entry contains given slotNo, returns its index = found slotNo. - //Continues searching. - //If the probe comes back to original index, throws an exception. - private static int find(final int[] auxArr, final int lgAuxArrInts, final int lgConfigK, - final int slotNo) { - assert lgAuxArrInts < lgConfigK; - final int auxArrMask = (1 << lgAuxArrInts) - 1; - final int configKmask = (1 << lgConfigK) - 1; - int probe = slotNo & auxArrMask; - final int loopIndex = probe; - do { - final int arrVal = auxArr[probe]; - if (arrVal == EMPTY) { //Compares on entire entry - return ~probe; //empty - } - else if (slotNo == (arrVal & configKmask)) { //Compares only on slotNo - return probe; //found given slotNo, return probe = index into aux array - } - final int stride = (slotNo >>> lgAuxArrInts) | 1; - probe = (probe + stride) & auxArrMask; - } while (probe != loopIndex); - throw new SketchesArgumentException("Key not found and no empty slots!"); - } - - private void checkGrow() { - if ((RESIZE_DENOM * auxCount) > (RESIZE_NUMER * auxIntArr.length)) { - growAuxSpace(); - } - } - - private void growAuxSpace() { - final int[] oldArray = auxIntArr; - final int configKmask = (1 << lgConfigK) - 1; - auxIntArr = new int[1 << ++lgAuxArrInts]; - for (int i = 0; i < oldArray.length; i++) { - final int fetched = oldArray[i]; - if (fetched != EMPTY) { - //find empty in new array - final int idx = find(auxIntArr, lgAuxArrInts, lgConfigK, fetched & configKmask); - auxIntArr[~idx] = fetched; - } - } - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/Hll4Array.java b/src/main/java/org/apache/datasketches/hll/Hll4Array.java deleted file mode 100644 index f6295fa78..000000000 --- a/src/main/java/org/apache/datasketches/hll/Hll4Array.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.HllUtil.AUX_TOKEN; -import static org.apache.datasketches.hll.HllUtil.KEY_BITS_26; -import static org.apache.datasketches.hll.HllUtil.LG_AUX_ARR_INTS; -import static org.apache.datasketches.hll.HllUtil.hiNibbleMask; -import static org.apache.datasketches.hll.HllUtil.loNibbleMask; -import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.extractAuxCount; -import static org.apache.datasketches.hll.PreambleUtil.extractCompactFlag; -import static org.apache.datasketches.hll.PreambleUtil.extractLgK; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * Uses 4 bits per slot in a packed byte array. - * @author Lee Rhodes - */ -final class Hll4Array extends HllArray { - - /** - * Standard constructor for new instance - * @param lgConfigK the configured Lg K - */ - Hll4Array(final int lgConfigK) { - super(lgConfigK, TgtHllType.HLL_4); - hllByteArr = new byte[hll4ArrBytes(lgConfigK)]; - } - - /** - * Copy constructor - * @param that another Hll4Array - */ - Hll4Array(final Hll4Array that) { - super(that); - } - - static Hll4Array heapify(final MemorySegment seg) { - final int lgConfigK = extractLgK(seg); - final Hll4Array hll4Array = new Hll4Array(lgConfigK); - HllArray.extractCommonHll(seg, hll4Array); - - //load AuxHashMap - final int auxStart = hll4Array.auxStart; - final int auxCount = extractAuxCount(seg); - final boolean compact = extractCompactFlag(seg); - HeapAuxHashMap auxHashMap = null; - if (auxCount > 0) { - auxHashMap = HeapAuxHashMap.heapify(seg, auxStart, lgConfigK, auxCount, compact); - } - hll4Array.putAuxHashMap(auxHashMap, false); - return hll4Array; - } - - @Override - Hll4Array copy() { - return new Hll4Array(this); - } - - @Override - HllSketchImpl couponUpdate(final int coupon) { - final int newValue = coupon >>> KEY_BITS_26; - final int configKmask = (1 << getLgConfigK()) - 1; - final int slotNo = coupon & configKmask; - updateSlotWithKxQ(slotNo, newValue); - return this; - } - - @Override - int getNibble(final int slotNo) { - int theByte = hllByteArr[slotNo >>> 1]; - if ((slotNo & 1) > 0) { //odd? - theByte >>>= 4; - } - return theByte & loNibbleMask; - } - - @Override - int getSlotValue(final int slotNo) { - final int nib = getNibble(slotNo); - if (nib == AUX_TOKEN) { - final AuxHashMap auxHashMap = getAuxHashMap(); - return auxHashMap.mustFindValueFor(slotNo); //auxHashMap cannot be null here - } else { - return nib + getCurMin(); - } - } - - @Override - int getUpdatableSerializationBytes() { - final AuxHashMap auxHashMap = getAuxHashMap(); - final int auxBytes; - if (auxHashMap == null) { - auxBytes = 4 << LG_AUX_ARR_INTS[lgConfigK]; - } else { - auxBytes = 4 << auxHashMap.getLgAuxArrInts(); - } - return HLL_BYTE_ARR_START + getHllByteArrBytes() + auxBytes; - } - - @Override - PairIterator iterator() { - return new HeapHll4Iterator(1 << lgConfigK); - } - - @Override - void putNibble(final int slotNo, final int nibValue) { - final int byteno = slotNo >>> 1; - final int oldValue = hllByteArr[byteno]; - if ((slotNo & 1) == 0) { // set low nibble - hllByteArr[byteno] = (byte) ((oldValue & hiNibbleMask) | (nibValue & loNibbleMask)); - } else { //set high nibble - hllByteArr[byteno] = (byte) ((oldValue & loNibbleMask) | ((nibValue << 4) & hiNibbleMask)); - } - } - - @Override - //Would be used by HllUnion, but not used because the gadget is always HLL8 type - void updateSlotNoKxQ(final int slotNo, final int newValue) { - throw new SketchesStateException("Improper access."); - } - - @Override - //Used by this couponUpdate() - //updates HipAccum, CurMin, NumAtCurMin, KxQs and checks newValue > oldValue - void updateSlotWithKxQ(final int slotNo, final int newValue) { - Hll4Update.internalHll4Update(this, slotNo, newValue); - } - - @Override - byte[] toCompactByteArray() { - return ToByteArrayImpl.toHllByteArray(this, true); - } - - //ITERATOR - - final class HeapHll4Iterator extends HllPairIterator { - - HeapHll4Iterator(final int lengthPairs) { - super(lengthPairs); - } - - @Override - int value() { - return getSlotValue(index); - } - } - - @Override - MemorySegment getMemorySegment() { - return null; - } - - @Override - boolean isSameResource(final MemorySegment seg) { - return false; - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/Hll4Update.java b/src/main/java/org/apache/datasketches/hll/Hll4Update.java deleted file mode 100644 index a1b67275b..000000000 --- a/src/main/java/org/apache/datasketches/hll/Hll4Update.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.HllUtil.AUX_TOKEN; -import static org.apache.datasketches.hll.HllUtil.LG_AUX_ARR_INTS; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * Update process common to Heap Hll 4 and Direct Hll 4 - * @author Lee Rhodes - * @author Kevin Lang - */ -final class Hll4Update { - - //Uses lgConfigK, curMin, numAtCurMin, auxMap - //Only called by Hll4Array and DirectHll4Array - //In C: two-registers.c Line 836 in "hhb_abstract_set_slot_if_new_value_bigger" non-sparse - static void internalHll4Update(final AbstractHllArray host, final int slotNo, - final int newValue) { - assert ((0 <= slotNo) && (slotNo < (1 << host.getLgConfigK()))); - - final int curMin = host.getCurMin(); - final int rawStoredOldNibble = host.getNibble(slotNo); //could be 0 - final int lbOnOldValue = rawStoredOldNibble + curMin; //provable lower bound, could be 0 - - if (newValue <= lbOnOldValue) { return; } - //Thus: newValue > lbOnOldValue AND newValue > curMin - - AuxHashMap auxHashMap; // = host.getAuxHashMap(); - final int actualOldValue; - final int shiftedNewValue; //value - curMin - - //Based on whether we have an AUX_TOKEN and whether the shiftedNewValue is greater than - // AUX_TOKEN, we have four cases for how to actually modify the data structure: - // 1. (shiftedNewValue >= AUX_TOKEN) && (rawStoredOldNibble = AUX_TOKEN) //881: - // The byte array already contains aux token - // This is the case where old and new values are both exceptions. - // Therefore, the 4-bit array already is AUX_TOKEN. Only need to update auxMap - // 2. (shiftedNewValue < AUX_TOKEN) && (rawStoredOldNibble = AUX_TOKEN) //885 - // This is the (hypothetical) case where old value is an exception and the new one is not, - // which is impossible given that curMin has not changed here and the newValue > oldValue. - // 3. (shiftedNewValue >= AUX_TOKEN) && (rawStoredOldNibble < AUX_TOKEN) //892 - // This is the case where the old value is not an exception and the new value is. - // Therefore the AUX_TOKEN must be stored in the 4-bit array and the new value - // added to the exception table. - // 4. (shiftedNewValue < AUX_TOKEN) && (rawStoredOldNibble < AUX_TOKEN) //897 - // This is the case where neither the old value nor the new value is an exception. - // Therefore we just overwrite the 4-bit array with the shifted new value. - - if (rawStoredOldNibble == AUX_TOKEN) { //846 Note: This is rare and really hard to test! - auxHashMap = host.getAuxHashMap(); //auxHashMap must already exist. - assert auxHashMap != null; - actualOldValue = auxHashMap.mustFindValueFor(slotNo);//lgtm [java/dereferenced-value-may-be-null] - if (newValue <= actualOldValue) { return; } - //We know that the array will be changed, but we haven't actually updated yet. - AbstractHllArray.hipAndKxQIncrementalUpdate(host, actualOldValue, newValue); - shiftedNewValue = newValue - curMin; - assert (shiftedNewValue >= 0); - - if (shiftedNewValue >= AUX_TOKEN) { //CASE 1: - auxHashMap.mustReplace(slotNo, newValue); //lgtm [java/dereferenced-value-may-be-null] - } - //else //CASE 2: impossible - - } else { //rawStoredOldNibble < AUX_TOKEN - actualOldValue = lbOnOldValue; - //We know that the array will be changed, but we haven't actually updated yet. - AbstractHllArray.hipAndKxQIncrementalUpdate(host, actualOldValue, newValue); - shiftedNewValue = newValue - curMin; - assert (shiftedNewValue >= 0); - - if (shiftedNewValue >= AUX_TOKEN) { //CASE 3: //892 - host.putNibble(slotNo, AUX_TOKEN); - auxHashMap = host.getAuxHashMap(); - if (auxHashMap == null) { - auxHashMap = host.getNewAuxHashMap(); - host.putAuxHashMap(auxHashMap, false); - } - auxHashMap.mustAdd(slotNo, newValue); - } - else { // CASE 4: //897 - host.putNibble(slotNo, shiftedNewValue); - } - } - - // We just changed the HLL array, so it might be time to change curMin - if (actualOldValue == curMin) { //908 - assert (host.getNumAtCurMin() >= 1); - host.decNumAtCurMin(); - while (host.getNumAtCurMin() == 0) { - //increases curMin by 1, and builds a new aux table, - // shifts values in 4-bit table, and recounts curMin - shiftToBiggerCurMin(host); - } - } - } - - //This scheme only works with two double registers (2 kxq values). - // HipAccum, kxq0 and kxq1 remain untouched. - // This changes curMin, numAtCurMin, hllByteArr and auxMap. - //Entering this routine assumes that all slots have valid nibbles > 0 and <= 15. - //An AuxHashMap must exist if any values in the current hllByteArray are already 15. - //In C: again-two-registers.c Lines 710 "hhb_shift_to_bigger_curmin" - private static void shiftToBiggerCurMin(final AbstractHllArray host) { - final int oldCurMin = host.getCurMin(); - final int newCurMin = oldCurMin + 1; - final int lgConfigK = host.getLgConfigK(); - final int configK = 1 << lgConfigK; - final int configKmask = configK - 1; - - int numAtNewCurMin = 0; - int numAuxTokens = 0; - - // Walk through the slots of 4-bit array decrementing stored values by one unless it - // equals AUX_TOKEN, where it is left alone but counted to be checked later. - // If oldStoredValue is 0 it is an error. - // If the decremented value is 0, we increment numAtNewCurMin. - // Because getNibble is masked to 4 bits oldStoredValue can never be > 15 or negative - for (int i = 0; i < configK; i++) { //724 - int oldStoredNibble = host.getNibble(i); - if (oldStoredNibble == 0) { - throw new SketchesStateException("Array slots cannot be 0 at this point."); - } - if (oldStoredNibble < AUX_TOKEN) { - host.putNibble(i, --oldStoredNibble); - if (oldStoredNibble == 0) { numAtNewCurMin++; } - } else { //oldStoredNibble == AUX_TOKEN - numAuxTokens++; - assert host.getAuxHashMap() != null : "AuxHashMap cannot be null at this point."; - } - } - - //If old AuxHashMap exists, walk through it updating some slots and build a new AuxHashMap - // if needed. - AuxHashMap newAuxMap = null; - final AuxHashMap oldAuxMap = host.getAuxHashMap(); - if (oldAuxMap != null) { - int slotNum; - int oldActualVal; - int newShiftedVal; - - final PairIterator itr = oldAuxMap.getIterator(); - while (itr.nextValid()) { - slotNum = itr.getKey() & configKmask; - oldActualVal = itr.getValue(); - newShiftedVal = oldActualVal - newCurMin; - assert newShiftedVal >= 0; - - assert host.getNibble(slotNum) == AUX_TOKEN - : "Array slot != AUX_TOKEN: " + host.getNibble(slotNum); - if (newShiftedVal < AUX_TOKEN) { //756 - assert (newShiftedVal == 14); - // The former exception value isn't one anymore, so it stays out of new AuxHashMap. - // Correct the AUX_TOKEN value in the HLL array to the newShiftedVal (14). - host.putNibble(slotNum, newShiftedVal); - numAuxTokens--; - } - else { //newShiftedVal >= AUX_TOKEN - // the former exception remains an exception, so must be added to the newAuxMap - if (newAuxMap == null) { - //Note: even in the direct case we use a heap aux map temporarily - newAuxMap = new HeapAuxHashMap(LG_AUX_ARR_INTS[lgConfigK], lgConfigK); - } - newAuxMap.mustAdd(slotNum, oldActualVal); - } - } //end scan of oldAuxMap - } //end if (auxHashMap != null) - else { //oldAuxMap == null - assert numAuxTokens == 0 : "auxTokens: " + numAuxTokens; - } - - if (newAuxMap != null) { - assert newAuxMap.getAuxCount() == numAuxTokens : "auxCount: " + newAuxMap.getAuxCount() - + ", HLL tokens: " + numAuxTokens; - } - host.putAuxHashMap(newAuxMap, false); //if we are direct, this will do the right thing - - host.putCurMin(newCurMin); - host.putNumAtCurMin(numAtNewCurMin); - } //end of shiftToBiggerCurMin - -} diff --git a/src/main/java/org/apache/datasketches/hll/Hll6Array.java b/src/main/java/org/apache/datasketches/hll/Hll6Array.java deleted file mode 100644 index a0ddcbf59..000000000 --- a/src/main/java/org/apache/datasketches/hll/Hll6Array.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.common.ByteArrayUtil.getShortLE; -import static org.apache.datasketches.common.ByteArrayUtil.putShortLE; -import static org.apache.datasketches.hll.HllUtil.KEY_BITS_26; -import static org.apache.datasketches.hll.HllUtil.VAL_MASK_6; -import static org.apache.datasketches.hll.PreambleUtil.extractLgK; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * Uses 6 bits per slot in a packed byte array. - * @author Lee Rhodes - */ -final class Hll6Array extends HllArray { - - /** - * Standard constructor for new instance - * @param lgConfigK the configured Lg K - */ - Hll6Array(final int lgConfigK) { - super(lgConfigK, TgtHllType.HLL_6); - hllByteArr = new byte[hll6ArrBytes(lgConfigK)]; - } - - /** - * Copy constructor - * @param that another Hll6Array - */ - Hll6Array(final Hll6Array that) { - super(that); - } - - static Hll6Array heapify(final MemorySegment seg) { - final int lgConfigK = extractLgK(seg); - final Hll6Array hll6Array = new Hll6Array(lgConfigK); - HllArray.extractCommonHll(seg, hll6Array); - return hll6Array; - } - - @Override - Hll6Array copy() { - return new Hll6Array(this); - } - - @Override - HllSketchImpl couponUpdate(final int coupon) { - final int newValue = coupon >>> KEY_BITS_26; - final int configKmask = (1 << lgConfigK) - 1; - final int slotNo = coupon & configKmask; - updateSlotWithKxQ(slotNo, newValue); - return this; - } - - @Override - int getNibble(final int slotNo) { - throw new SketchesStateException("Improper access."); - } - - @Override int getSlotValue(final int slotNo) { - return get6Bit(hllByteArr, 0, slotNo); - } - - @Override - PairIterator iterator() { - return new HeapHll6Iterator(1 << lgConfigK); - } - - @Override - void putNibble(final int slotNo, final int nibValue) { - throw new SketchesStateException("Improper access."); - } - - @Override - //Would be used by HllUnion, but not used because the gadget is always HLL8 type - void updateSlotNoKxQ(final int slotNo, final int newValue) { - throw new SketchesStateException("Improper access."); - } - - @Override - //Used by this couponUpdate() - //updates HipAccum, CurMin, NumAtCurMin, KxQs and checks newValue > oldValue - void updateSlotWithKxQ(final int slotNo, final int newValue) { - final int oldValue = getSlotValue(slotNo); - if (newValue > oldValue) { - put6Bit(hllByteArr, 0, slotNo, newValue); - hipAndKxQIncrementalUpdate(this, oldValue, newValue); - if (oldValue == 0) { - numAtCurMin--; //interpret numAtCurMin as num Zeros - assert getNumAtCurMin() >= 0; - } - } - } - - //on-heap - private static void put6Bit(final byte[] arr, final int offsetBytes, final int slotNo, - final int newValue) { - final int startBit = slotNo * 6; - final int shift = startBit & 0X7; - final int byteIdx = (startBit >>> 3) + offsetBytes; - final int valShifted = (newValue & 0X3F) << shift; - final int curMasked = getShortLE(arr, byteIdx) & (~(VAL_MASK_6 << shift)); - final short insert = (short) (curMasked | valShifted); - putShortLE(arr, byteIdx, insert); - } - - //on-heap - private static int get6Bit(final byte[] arr, final int offsetBytes, final int slotNo) { - final int startBit = slotNo * 6; - final int shift = startBit & 0X7; - final int byteIdx = (startBit >>> 3) + offsetBytes; - return (byte) ((getShortLE(arr, byteIdx) >>> shift) & 0X3F); - } - - //ITERATOR - - private final class HeapHll6Iterator extends HllPairIterator { - int bitOffset; - - HeapHll6Iterator(final int lengthPairs) { - super(lengthPairs); - bitOffset = - 6; - } - - @Override - int value() { - bitOffset += 6; - final int tmp = getShortLE(hllByteArr, bitOffset / 8); - final int shift = (bitOffset % 8) & 0X7; - return (tmp >>> shift) & VAL_MASK_6; - } - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/Hll8Array.java b/src/main/java/org/apache/datasketches/hll/Hll8Array.java deleted file mode 100644 index 423cebfee..000000000 --- a/src/main/java/org/apache/datasketches/hll/Hll8Array.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.HllUtil.EMPTY; -import static org.apache.datasketches.hll.HllUtil.KEY_BITS_26; -import static org.apache.datasketches.hll.HllUtil.VAL_MASK_6; -import static org.apache.datasketches.hll.PreambleUtil.extractLgK; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * Uses 8 bits per slot in a byte array. - * @author Lee Rhodes - */ -final class Hll8Array extends HllArray { - - /** - * Standard constructor for new instance - * @param lgConfigK the configured Lg K - */ - Hll8Array(final int lgConfigK) { - super(lgConfigK, TgtHllType.HLL_8); - hllByteArr = new byte[hll8ArrBytes(lgConfigK)]; - } - - /** - * Copy constructor - * @param that another Hll8Array - */ - Hll8Array(final Hll8Array that) { - super(that); - } - - static Hll8Array heapify(final MemorySegment seg) { - final int lgConfigK = extractLgK(seg); - final Hll8Array hll8Array = new Hll8Array(lgConfigK); - HllArray.extractCommonHll(seg, hll8Array); - return hll8Array; - } - - @Override - Hll8Array copy() { - return new Hll8Array(this); - } - - @Override - HllSketchImpl couponUpdate(final int coupon) { - final int newValue = coupon >>> KEY_BITS_26; - final int configKmask = (1 << lgConfigK) - 1; - final int slotNo = coupon & configKmask; - updateSlotWithKxQ(slotNo, newValue); - return this; - } - - @Override - int getNibble(final int slotNo) { - throw new SketchesStateException("Improper access."); - } - - @Override int getSlotValue(final int slotNo) { - return hllByteArr[slotNo] & VAL_MASK_6; - } - - @Override - PairIterator iterator() { - return new HeapHll8Iterator(1 << lgConfigK); - } - - @Override - void putNibble(final int slotNo, final int nibValue) { - throw new SketchesStateException("Improper access."); - } - - @Override - //Used by HllUnion when source is not HLL8 - void updateSlotNoKxQ(final int slotNo, final int newValue) { - final int oldValue = getSlotValue(slotNo); - hllByteArr[slotNo] = (byte) Math.max(newValue, oldValue); - } - - @Override - //Used by this couponUpdate() - //updates HipAccum, CurMin, NumAtCurMin, KxQs and checks newValue > oldValue - void updateSlotWithKxQ(final int slotNo, final int newValue) { - final int oldValue = getSlotValue(slotNo); - if (newValue > oldValue) { - hllByteArr[slotNo] = (byte) (newValue & VAL_MASK_6); - hipAndKxQIncrementalUpdate(this, oldValue, newValue); - if (oldValue == 0) { - numAtCurMin--; //interpret numAtCurMin as num Zeros - assert getNumAtCurMin() >= 0; - } - } - } - - //ITERATOR - - final class HeapHll8Iterator extends HllPairIterator { - - HeapHll8Iterator(final int lengthPairs) { - super(lengthPairs); - } - - @Override - int value() { - return hllByteArr[index] & VAL_MASK_6; - } - - @Override - public boolean nextValid() { - while (++index < lengthPairs) { - value = hllByteArr[index] & VAL_MASK_6; - if (value != EMPTY) { - return true; - } - } - return false; - } - - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/HllArray.java b/src/main/java/org/apache/datasketches/hll/HllArray.java deleted file mode 100644 index ba86cb1bc..000000000 --- a/src/main/java/org/apache/datasketches/hll/HllArray.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.hll.HllUtil.LG_AUX_ARR_INTS; -import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.extractCurMin; -import static org.apache.datasketches.hll.PreambleUtil.extractEmptyFlag; -import static org.apache.datasketches.hll.PreambleUtil.extractHipAccum; -import static org.apache.datasketches.hll.PreambleUtil.extractKxQ0; -import static org.apache.datasketches.hll.PreambleUtil.extractKxQ1; -import static org.apache.datasketches.hll.PreambleUtil.extractNumAtCurMin; -import static org.apache.datasketches.hll.PreambleUtil.extractOooFlag; -import static org.apache.datasketches.hll.PreambleUtil.extractRebuildCurMinNumKxQFlag; -import static org.apache.datasketches.hll.TgtHllType.HLL_4; -import static org.apache.datasketches.hll.TgtHllType.HLL_6; - -import java.lang.foreign.MemorySegment; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -abstract class HllArray extends AbstractHllArray { - boolean oooFlag = false; //Out-Of-Order Flag - boolean rebuildCurMinNumKxQ = false; - int curMin; //always zero for Hll6 and Hll8, only used by Hll4Array - int numAtCurMin; //# of values at curMin. If curMin = 0, it is # of zeros - double hipAccum; - double kxq0; - double kxq1; - byte[] hllByteArr = null; //init by sub-classes - - /** - * Standard constructor for new instance - * @param lgConfigK the configured Lg K - * @param tgtHllType the type of target HLL sketch - */ - HllArray(final int lgConfigK, final TgtHllType tgtHllType) { - super(lgConfigK, tgtHllType, CurMode.HLL); - curMin = 0; - numAtCurMin = 1 << lgConfigK; - hipAccum = 0; - kxq0 = 1 << lgConfigK; - kxq1 = 0; - } - - /** - * Copy constructor - * @param that another HllArray - */ - HllArray(final HllArray that) { - super(that.getLgConfigK(), that.getTgtHllType(), CurMode.HLL); - oooFlag = that.isOutOfOrder(); - rebuildCurMinNumKxQ = that.isRebuildCurMinNumKxQFlag(); - curMin = that.getCurMin(); - numAtCurMin = that.getNumAtCurMin(); - hipAccum = that.getHipAccum(); - kxq0 = that.getKxQ0(); - kxq1 = that.getKxQ1(); - hllByteArr = that.hllByteArr.clone(); //that.hllByteArr should never be null. - final AuxHashMap thatAuxMap = that.getAuxHashMap(); - if (thatAuxMap != null) { - putAuxHashMap(thatAuxMap.copy(), false); - } else { - putAuxHashMap(null, false); - } - } - - static final HllArray newHeapHll(final int lgConfigK, final TgtHllType tgtHllType) { - if (tgtHllType == HLL_4) { return new Hll4Array(lgConfigK); } - if (tgtHllType == HLL_6) { return new Hll6Array(lgConfigK); } - return new Hll8Array(lgConfigK); - } - - @Override - void addToHipAccum(final double delta) { - hipAccum += delta; - } - - @Override - void decNumAtCurMin() { - numAtCurMin--; - } - - @Override - int getCurMin() { - return curMin; - } - - @Override - CurMode getCurMode() { - return curMode; - } - - @Override - double getHipAccum() { - return hipAccum; - } - - @Override - int getHllByteArrBytes() { - return hllByteArr.length; - } - - @Override - double getKxQ0() { - return kxq0; - } - - @Override - double getKxQ1() { - return kxq1; - } - - @Override - int getLgConfigK() { - return lgConfigK; - } - - @Override - MemorySegment getMemorySegment() { - return null; - } - - @Override - AuxHashMap getNewAuxHashMap() { - return new HeapAuxHashMap(LG_AUX_ARR_INTS[lgConfigK], lgConfigK); - } - - @Override - int getNumAtCurMin() { - return numAtCurMin; - } - - @Override - boolean isCompact() { - return false; - } - - @Override - boolean isEmpty() { - return false; //because there should be no normal way to create an HllArray that is empty - } - - @Override - boolean hasMemorySegment() { - return false; - } - - @Override - boolean isOffHeap() { - return false; - } - - @Override - boolean isOutOfOrder() { - return oooFlag; - } - - @Override - boolean isSameResource(final MemorySegment seg) { - return false; - } - - @Override - boolean isRebuildCurMinNumKxQFlag() { - return rebuildCurMinNumKxQ; - } - - @Override - void putAuxHashMap(final AuxHashMap auxHashMap, final boolean compact) { - this.auxHashMap = auxHashMap; - } - - @Override - void putCurMin(final int curMin) { - this.curMin = curMin; - } - - @Override - void putEmptyFlag(final boolean empty) { /* meaningless for HllArray classes */ } - - @Override - void putHipAccum(final double value) { - hipAccum = value; - } - - @Override - void putKxQ0(final double kxq0) { - this.kxq0 = kxq0; - } - - @Override - void putKxQ1(final double kxq1) { - this.kxq1 = kxq1; - } - - @Override - void putNumAtCurMin(final int numAtCurMin) { - this.numAtCurMin = numAtCurMin; - } - - @Override - void putOutOfOrder(final boolean oooFlag) { - if (oooFlag) { putHipAccum(0); } - this.oooFlag = oooFlag; - } - - @Override - void putRebuildCurMinNumKxQFlag(final boolean rebuild) { - rebuildCurMinNumKxQ = rebuild; - } - - @Override - HllSketchImpl reset() { - return new CouponList(lgConfigK, tgtHllType, CurMode.LIST); - } - - @Override //used by HLL6 and HLL8, overridden by HLL4 - byte[] toCompactByteArray() { - return toUpdatableByteArray(); //indistinguishable for HLL6 and HLL8 - } - - @Override //used by HLL4, HLL6 and HLL8 - byte[] toUpdatableByteArray() { - return ToByteArrayImpl.toHllByteArray(this, false); - } - - //used by heapify by all Heap HLL - static final void extractCommonHll(final MemorySegment srcSeg, final HllArray hllArray) { - hllArray.putOutOfOrder(extractOooFlag(srcSeg)); - hllArray.putEmptyFlag(extractEmptyFlag(srcSeg)); - hllArray.putCurMin(extractCurMin(srcSeg)); - hllArray.putHipAccum(extractHipAccum(srcSeg)); - hllArray.putKxQ0(extractKxQ0(srcSeg)); - hllArray.putKxQ1(extractKxQ1(srcSeg)); - hllArray.putNumAtCurMin(extractNumAtCurMin(srcSeg)); - hllArray.putRebuildCurMinNumKxQFlag(extractRebuildCurMinNumKxQFlag(srcSeg)); - - //load Hll array - MemorySegment.copy(srcSeg, JAVA_BYTE, HLL_BYTE_ARR_START, hllArray.hllByteArr, 0, hllArray.hllByteArr.length); - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/HllEstimators.java b/src/main/java/org/apache/datasketches/hll/HllEstimators.java deleted file mode 100644 index 21bbd4249..000000000 --- a/src/main/java/org/apache/datasketches/hll/HllEstimators.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.HllUtil.MIN_LOG_K; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -final class HllEstimators { - - //HLL UPPER AND LOWER BOUNDS - - /* - * The upper and lower bounds are not symmetric and thus are treated slightly differently. - * For the lower bound, when the unique count is <= k, LB >= numNonZeros, where - * numNonZeros = k - numAtCurMin AND curMin == 0. - * - * For HLL6 and HLL8, curMin is always 0 and numAtCurMin is initialized to k and is decremented - * down for each valid update until it reaches 0, where it stays. Thus, for these two - * isomorphs, when numAtCurMin = 0, means the true curMin is > 0 and the unique count must be - * greater than k. - * - * HLL4 always maintains both curMin and numAtCurMin dynamically. Nonetheless, the rules for - * the very small values <= k where curMin = 0 still apply. - */ - - static double hllLowerBound(final AbstractHllArray absHllArr, final int numStdDev) { - final int lgConfigK = absHllArr.lgConfigK; - final int configK = 1 << lgConfigK; - final double numNonZeros = - (absHllArr.getCurMin() == 0) ? configK - absHllArr.getNumAtCurMin() : configK; - final double estimate = absHllArr.getEstimate(); - final boolean oooFlag = absHllArr.isOutOfOrder(); - final double relErr = BaseHllSketch.getRelErr(false, oooFlag, lgConfigK, numStdDev); - return Math.max(estimate / (1.0 + relErr), numNonZeros); - } - - static double hllUpperBound(final AbstractHllArray absHllArr, final int numStdDev) { - final int lgConfigK = absHllArr.lgConfigK; - final double estimate = absHllArr.getEstimate(); - final boolean oooFlag = absHllArr.isOutOfOrder(); - final double relErr = BaseHllSketch.getRelErr(true, oooFlag, lgConfigK, numStdDev); - return estimate / (1.0 - relErr); - } - - //THE HLL COMPOSITE ESTIMATOR - - /** - * This is the (non-HIP) estimator. - * It is called "composite" because multiple estimators are pasted together. - * @param absHllArr an instance of the AbstractHllArray class. - * @return the composite estimate - */ - //In C: again-two-registers.c hhb_get_composite_estimate L1489 - static double hllCompositeEstimate(final AbstractHllArray absHllArr) { - final int lgConfigK = absHllArr.getLgConfigK(); - final double rawEst = getHllRawEstimate(lgConfigK, absHllArr.getKxQ0() + absHllArr.getKxQ1()); - - final double[] xArr = CompositeInterpolationXTable.xArrs[lgConfigK - MIN_LOG_K]; - final double yStride = CompositeInterpolationXTable.yStrides[lgConfigK - MIN_LOG_K]; - final int xArrLen = xArr.length; - - if (rawEst < xArr[0]) { return 0; } - - final int xArrLenM1 = xArrLen - 1; - - if (rawEst > xArr[xArrLenM1]) { - final double finalY = yStride * (xArrLenM1); - final double factor = finalY / xArr[xArrLenM1]; - return rawEst * factor; - } - - final double adjEst = - CubicInterpolation.usingXArrAndYStride(xArr, yStride, rawEst); - - // We need to completely avoid the linear_counting estimator if it might have a crazy value. - // Empirical evidence suggests that the threshold 3*k will keep us safe if 2^4 <= k <= 2^21. - - if (adjEst > (3 << lgConfigK)) { return adjEst; } - //Alternate call - //if ((adjEst > (3 << lgConfigK)) || ((curMin != 0) || (numAtCurMin == 0)) ) { return adjEst; } - - final double linEst = - getHllBitMapEstimate(lgConfigK, absHllArr.getCurMin(), absHllArr.getNumAtCurMin()); - - // Bias is created when the value of an estimator is compared with a threshold to decide whether - // to use that estimator or a different one. - // We conjecture that less bias is created when the average of the two estimators - // is compared with the threshold. Empirical measurements support this conjecture. - - final double avgEst = (adjEst + linEst) / 2.0; - - // The following constants comes from empirical measurements of the crossover point - // between the average error of the linear estimator and the adjusted HLL estimator - double crossOver = 0.64; - if (lgConfigK == 4) { crossOver = 0.718; } - else if (lgConfigK == 5) { crossOver = 0.672; } - - return (avgEst > (crossOver * (1 << lgConfigK))) ? adjEst : linEst; - } - - /** - * Estimator when N is small, roughly less than k log(k). - * Refer to Wikipedia: Coupon Collector Problem - * @param lgConfigK the current configured lgK of the sketch - * @param curMin the current minimum value of the HLL window - * @param numAtCurMin the current number of slots with the value curMin - * @return the very low range estimate - */ - //In C: again-two-registers.c hhb_get_improved_linear_counting_estimate L1274 - private static double getHllBitMapEstimate( - final int lgConfigK, final int curMin, final int numAtCurMin) { - final int configK = 1 << lgConfigK; - final int numUnhitBuckets = (curMin == 0) ? numAtCurMin : 0; - - //This will eventually go away. - if (numUnhitBuckets == 0) { - return configK * Math.log(configK / 0.5); - } - - final int numHitBuckets = configK - numUnhitBuckets; - return HarmonicNumbers.getBitMapEstimate(configK, numHitBuckets); - } - - //In C: again-two-registers.c hhb_get_raw_estimate L1167 - //This algorithm is from Flajolet's, et al, 2007 HLL paper, Fig 3. - private static double getHllRawEstimate(final int lgConfigK, final double kxqSum) { - final int configK = 1 << lgConfigK; - final double correctionFactor; - if (lgConfigK == 4) { correctionFactor = 0.673; } - else if (lgConfigK == 5) { correctionFactor = 0.697; } - else if (lgConfigK == 6) { correctionFactor = 0.709; } - else { correctionFactor = 0.7213 / (1.0 + (1.079 / configK)); } - return (correctionFactor * configK * configK) / kxqSum; - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/HllPairIterator.java b/src/main/java/org/apache/datasketches/hll/HllPairIterator.java deleted file mode 100644 index 6b9f2f078..000000000 --- a/src/main/java/org/apache/datasketches/hll/HllPairIterator.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.HllUtil.EMPTY; -import static org.apache.datasketches.hll.HllUtil.pair; - -/** - * Iterates over an on-heap HLL byte array producing pairs of index, value. - * - * @author Lee Rhodes - */ -abstract class HllPairIterator extends PairIterator { - final int lengthPairs; - int index; - int value; - - //Used by Direct<4,6,8>Array, Heap<4,6,8>Array - HllPairIterator(final int lengthPairs) { - this.lengthPairs = lengthPairs; - index = - 1; - } - - @Override - public String getHeader() { - return String.format("%10s%6s", "Slot", "Value"); - } - - @Override - public int getIndex() { - return index; - } - - @Override - public int getKey() { - return index; - } - - @Override - public int getPair() { - return pair(index, value); - } - - @Override - public int getSlot() { - return index; - } - - @Override - public String getString() { - final int slot = getSlot(); - final int value = getValue(); - return String.format("%10d%6d", slot, value); - } - - @Override - public int getValue() { - return value; - } - - @Override - public boolean nextAll() { - if (++index < lengthPairs) { - value = value(); - return true; - } - return false; - } - - @Override - public boolean nextValid() { - while (++index < lengthPairs) { - value = value(); - if (value != EMPTY) { - return true; - } - } - return false; - } - - abstract int value(); - -} diff --git a/src/main/java/org/apache/datasketches/hll/HllSketch.java b/src/main/java/org/apache/datasketches/hll/HllSketch.java deleted file mode 100644 index 0ff0c1e97..000000000 --- a/src/main/java/org/apache/datasketches/hll/HllSketch.java +++ /dev/null @@ -1,566 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.checkBounds; -import static org.apache.datasketches.common.Util.clear; -import static org.apache.datasketches.hll.HllUtil.EMPTY; -import static org.apache.datasketches.hll.HllUtil.KEY_BITS_26; -import static org.apache.datasketches.hll.HllUtil.LG_AUX_ARR_INTS; -import static org.apache.datasketches.hll.HllUtil.checkPreamble; -import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.extractCompactFlag; -import static org.apache.datasketches.hll.PreambleUtil.extractLgK; -import static org.apache.datasketches.hll.PreambleUtil.extractTgtHllType; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * The HllSketch is actually a collection of compact implementations of Phillipe Flajolet’s HyperLogLog (HLL) - * sketch but with significantly improved error behavior and excellent speed performance. - * - *

If the use case for sketching is primarily counting uniques and merging, the HLL sketch is the 2nd highest - * performing in terms of accuracy for storage space consumed in the DataSketches library - * (the new CPC sketch developed by Kevin J. Lang now beats HLL in terms of accuracy / space). - * For large counts, HLL sketches can be 2 to 8 times smaller for the same accuracy than the DataSketches Theta - * Sketches when serialized, but the Theta sketches can do set intersections and differences while HLL and CPC cannot. - * The CPC sketch and HLL share similar use cases, but the CPC sketch is about 30 to 40% smaller than the HLL sketch - * when serialized and larger than the HLL when active in a MemorySegment. Choose your weapons!

- * - *

A new HLL sketch is created with a simple constructor:

- *
{@code
- * int lgK = 12; //This is log-base2 of k, so k = 4096. lgK can be from 4 to 21
- * HllSketch sketch = new HllSketch(lgK); //TgtHllType.HLL_4 is the default
- * //OR
- * HllSketch sketch = new HllSketch(lgK, TgtHllType.HLL_6);
- * //OR
- * HllSketch sketch = new HllSketch(lgK, TgtHllType.HLL_8);
- * }
- * - *

All three different sketch types are targets in that the sketches start out in a warm-up mode that is small in - * size and gradually grows as needed until the full HLL array is allocated. The HLL_4, HLL_6 and HLL_8 represent - * different levels of compression of the final HLL array where the 4, 6 and 8 refer to the number of bits each - * bucket of the HLL array is compressed down to. - * The HLL_4 is the most compressed but generally slower than the other two, especially during union operations.

- * - *

All three types share the same API. Updating the HllSketch is very simple:

- * - *
{@code
- * long n = 1000000;
- * for (int i = 0; i < n; i++) {
- *   sketch.update(i);
- * }
- * }
- * - *

Each of the presented integers above are first hashed into 128-bit hash values that are used by the sketch - * HLL algorithm, so the above loop is essentially equivalent to using a random number generator initialized with a - * seed so that the sequence is deterministic and random.

- * - *

Obtaining the cardinality results from the sketch is also simple:

- * - *
{@code
- * double estimate = sketch.getEstimate();
- * double estUB = sketch.getUpperBound(1.0); //the upper bound at 1 standard deviation.
- * double estLB = sketch.getLowerBound(1.0); //the lower bound at 1 standard deviation.
- * //OR
- * System.out.println(sketch.toString()); //will output a summary of the sketch.
- * }
- * - *

Which produces a console output something like this:

- * - *
{@code
- * ### HLL SKETCH SUMMARY:
- *   Log Config K   : 12
- *   Hll Target     : HLL_4
- *   Current Mode   : HLL
- *   LB             : 977348.7024560181
- *   Estimate       : 990116.6007366662
- *   UB             : 1003222.5095308956
- *   OutOfOrder Flag: false
- *   CurMin         : 5
- *   NumAtCurMin    : 1
- *   HipAccum       : 990116.6007366662
- * }
- * - * @author Lee Rhodes - * @author Kevin Lang - */ -public class HllSketch extends BaseHllSketch { - - /** - * The default Log_base2 of K - */ - public static final int DEFAULT_LG_K = 12; - - /** - * The default HLL-TYPE is HLL_4 - */ - public static final TgtHllType DEFAULT_HLL_TYPE = TgtHllType.HLL_4; - - HllSketchImpl hllSketchImpl = null; - - /** - * Constructs a new on-heap sketch with the default lgConfigK and tgtHllType. - */ - public HllSketch() { - this(DEFAULT_LG_K, DEFAULT_HLL_TYPE); - } - - /** - * Constructs a new on-heap sketch with the default tgtHllType. - * @param lgConfigK The Log2 of K for the target HLL sketch. This value must be - * between 4 and 21 inclusively. - */ - public HllSketch(final int lgConfigK) { - this(lgConfigK, DEFAULT_HLL_TYPE); - } - - /** - * Constructs a new on-heap sketch with the type of HLL sketch to configure. - * @param lgConfigK The Log2 of K for the target HLL sketch. This value must be - * between 4 and 21 inclusively. - * @param tgtHllType the desired HLL type. - */ - public HllSketch(final int lgConfigK, final TgtHllType tgtHllType) { - hllSketchImpl = new CouponList(HllUtil.checkLgK(lgConfigK), tgtHllType, CurMode.LIST); - } - - /** - * Constructs a new sketch with the type of HLL sketch to configure and the given - * MemorySegment as the destination for the sketch. This MemorySegment is usually configured - * for off-heap MemorySegment. What remains on the java heap is a thin wrapper object that reads and - * writes to the given MemorySegment. - * - *

The given dstSeg is checked for the required capacity as determined by - * {@link #getMaxUpdatableSerializationBytes(int, TgtHllType)}. - * @param lgConfigK The Log2 of K for the target HLL sketch. This value must be - * between 4 and 21 inclusively. - * @param tgtHllType the desired HLL type. - * @param dstSeg the destination MemorySegment for the sketch. - */ - public HllSketch(final int lgConfigK, final TgtHllType tgtHllType, final MemorySegment dstSeg) { - Objects.requireNonNull(dstSeg, "Destination MemorySegment must not be null"); - final long minBytes = getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType); - final long capBytes = dstSeg.byteSize(); - HllUtil.checkSegSize(minBytes, capBytes); - clear(dstSeg, 0, minBytes); - hllSketchImpl = DirectCouponList.newInstance(lgConfigK, tgtHllType, dstSeg); - } - - /** - * Copy constructor used by copy(). - * @param that another HllSketch - */ - HllSketch(final HllSketch that) { - hllSketchImpl = that.hllSketchImpl.copy(); - } - - /** - * Special constructor used by copyAs, heapify - * @param that another HllSketchImpl, which must already be a copy - */ - HllSketch(final HllSketchImpl that) { - hllSketchImpl = that; - } - - /** - * Heapify the given byte array, which must be a valid HllSketch image and may have data. - * @param byteArray the given byte array. This byteArray is not modified and is not retained - * by the on-heap sketch. - * @return an HllSketch on the java heap. - */ - public static final HllSketch heapify(final byte[] byteArray) { - return heapify(MemorySegment.ofArray(byteArray)); - } - - /** - * Heapify the given MemorySegment, which must be a valid HllSketch image and may have data. - * @param srcSeg the given MemorySegment, which is read-only. - * @return an HllSketch on the java heap. - */ - public static final HllSketch heapify(final MemorySegment srcSeg) { - return heapify(srcSeg, true); - } - - //used by HllUnion and above - static final HllSketch heapify(final MemorySegment srcSeg, final boolean checkRebuild) { - Objects.requireNonNull(srcSeg, "Source MemorySegment must not be null"); - checkBounds(0, 8, srcSeg.byteSize()); //need min 8 bytes - final CurMode curMode = checkPreamble(srcSeg); - final HllSketch heapSketch; - if (curMode == CurMode.HLL) { - final TgtHllType tgtHllType = extractTgtHllType(srcSeg); - if (tgtHllType == TgtHllType.HLL_4) { - heapSketch = new HllSketch(Hll4Array.heapify(srcSeg)); - } else if (tgtHllType == TgtHllType.HLL_6) { - heapSketch = new HllSketch(Hll6Array.heapify(srcSeg)); - } else { //Hll_8 - heapSketch = new HllSketch(Hll8Array.heapify(srcSeg)); - if (checkRebuild) { - HllUnion.checkRebuildCurMinNumKxQ(heapSketch); - } - } - } else if (curMode == CurMode.LIST) { - heapSketch = new HllSketch(CouponList.heapifyList(srcSeg)); - } else { - heapSketch = new HllSketch(CouponHashSet.heapifySet(srcSeg)); - } - return heapSketch; - } - - /** - * Wraps the given MemorySegment, which must be a image of a valid updatable sketch, - * and may have data. What remains on the java heap is a - * thin wrapper object that reads and writes to the given MemorySegment, which, depending on - * how the user configures the MemorySegment, may actually reside on the Java heap or off-heap. - * - *

The given dstSeg is checked for the required capacity as determined by - * {@link #getMaxUpdatableSerializationBytes(int, TgtHllType)}. - * @param srcWseg an writable image of a valid source sketch with data. - * @return an HllSketch where the sketch data is in the given srcWseg. - */ - public static final HllSketch writableWrap(final MemorySegment srcWseg) { - if (srcWseg.isReadOnly()) { return wrap(srcWseg); } - return writableWrap(srcWseg, true); - } - - //used by HllUnion and above - static final HllSketch writableWrap( final MemorySegment srcWseg, final boolean checkRebuild) { - Objects.requireNonNull(srcWseg, "Source MemorySegment must not be null"); - checkBounds(0, 8, srcWseg.byteSize()); //need min 8 bytes - if (extractCompactFlag(srcWseg)) { - throw new SketchesArgumentException( - "Cannot perform a writableWrap of a sketch image that is in compact form. " - + "Compact sketches are by definition immutable."); - } - final int lgConfigK = extractLgK(srcWseg); - final TgtHllType tgtHllType = extractTgtHllType(srcWseg); - final long minBytes = getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType); - final long capBytes = srcWseg.byteSize(); - HllUtil.checkSegSize(minBytes, capBytes); - final CurMode curMode = checkPreamble(srcWseg); - final HllSketch directSketch; - if (curMode == CurMode.HLL) { - if (tgtHllType == TgtHllType.HLL_4) { - directSketch = new HllSketch(new DirectHll4Array(lgConfigK, srcWseg)); - } else if (tgtHllType == TgtHllType.HLL_6) { - directSketch = new HllSketch(new DirectHll6Array(lgConfigK, srcWseg)); - } else { //Hll_8 - directSketch = new HllSketch(new DirectHll8Array(lgConfigK, srcWseg)); - if (checkRebuild) { //HllUnion only uses HLL_8, we allow non-finalized from a HllUnion call. - HllUnion.checkRebuildCurMinNumKxQ(directSketch); - } - } - } else if (curMode == CurMode.LIST) { - directSketch = - new HllSketch(new DirectCouponList(lgConfigK, tgtHllType, curMode, srcWseg)); - } else { //SET - directSketch = - new HllSketch(new DirectCouponHashSet(lgConfigK, tgtHllType, srcWseg)); - } - return directSketch; - } - - /** - * Wraps the given read-only MemorySegment that must be a image of a valid sketch, - * which may be in compact or updatable form, and should have data. Any attempt to update the - * given source MemorySegment will throw an exception. - * @param srcSeg a read-only image of a valid source sketch. - * @return an HllSketch, where the read-only data of the sketch is in the given srcSeg. - * - */ - public static final HllSketch wrap(final MemorySegment srcSeg) { //read only - Objects.requireNonNull(srcSeg, "Source MemorySegment must not be null"); - checkBounds(0, 8, srcSeg.byteSize()); //need min 8 bytes - final int lgConfigK = extractLgK(srcSeg); - final TgtHllType tgtHllType = extractTgtHllType(srcSeg); - - final CurMode curMode = checkPreamble(srcSeg); - final HllSketch directSketch; - if (curMode == CurMode.HLL) { - if (tgtHllType == TgtHllType.HLL_4) { - directSketch = new HllSketch(new DirectHll4Array(lgConfigK, srcSeg, true)); - } else if (tgtHllType == TgtHllType.HLL_6) { - directSketch = new HllSketch(new DirectHll6Array(lgConfigK, srcSeg, true)); - } else { //Hll_8 - directSketch = new HllSketch(new DirectHll8Array(lgConfigK, srcSeg, true)); - //rebuild if srcSeg came from a HllUnion and was not finalized, rather than throw exception. - HllUnion.checkRebuildCurMinNumKxQ(directSketch); - } - } else if (curMode == CurMode.LIST) { - directSketch = - new HllSketch(new DirectCouponList(lgConfigK, tgtHllType, curMode, srcSeg, true)); - } else { //SET - directSketch = - new HllSketch(new DirectCouponHashSet(lgConfigK, tgtHllType, srcSeg, true)); - } - return directSketch; - } - - /** - * Return a copy of this sketch onto the Java heap. - * @return a copy of this sketch onto the Java heap. - */ - public HllSketch copy() { - return new HllSketch(this); - } - - /** - * Return a deep copy of this sketch onto the Java heap with the specified TgtHllType. - * @param tgtHllType the TgtHllType enum - * @return a deep copy of this sketch with the specified TgtHllType. - */ - public HllSketch copyAs(final TgtHllType tgtHllType) { - return new HllSketch(hllSketchImpl.copyAs(tgtHllType)); - } - - @Override - public double getCompositeEstimate() { - return hllSketchImpl.getCompositeEstimate(); - } - - @Override - public double getEstimate() { - return hllSketchImpl.getEstimate(); - } - - double getHipEstimate() { - return hllSketchImpl.getHipEstimate(); - } - - @Override - public int getLgConfigK() { - return hllSketchImpl.getLgConfigK(); - } - - @Override - public int getCompactSerializationBytes() { - return hllSketchImpl.getCompactSerializationBytes(); - } - - @Override - public double getLowerBound(final int numStdDev) { - return hllSketchImpl.getLowerBound(numStdDev); - } - - /** - * Returns the maximum size in bytes that this sketch can grow to given lgConfigK. - * However, for the HLL_4 sketch type, this value can be exceeded in extremely rare cases. - * If exceeded, it will be larger by only a few percent. - * - * @param lgConfigK The Log2 of K for the target HLL sketch. This value must be - * between 4 and 21 inclusively. - * @param tgtHllType the desired Hll type - * @return the maximum size in bytes that this sketch can grow to. - */ - public static final int getMaxUpdatableSerializationBytes(final int lgConfigK, - final TgtHllType tgtHllType) { - final int arrBytes; - if (tgtHllType == TgtHllType.HLL_4) { - final int auxBytes = 4 << LG_AUX_ARR_INTS[lgConfigK]; - arrBytes = AbstractHllArray.hll4ArrBytes(lgConfigK) + auxBytes; - } - else if (tgtHllType == TgtHllType.HLL_6) { - arrBytes = AbstractHllArray.hll6ArrBytes(lgConfigK); - } - else { //HLL_8 - arrBytes = AbstractHllArray.hll8ArrBytes(lgConfigK); - } - return HLL_BYTE_ARR_START + arrBytes; - } - - MemorySegment getMemorySegment() { - return hllSketchImpl.getMemorySegment(); - } - - @Override - public TgtHllType getTgtHllType() { - return hllSketchImpl.getTgtHllType(); - } - - @Override - public int getUpdatableSerializationBytes() { - return hllSketchImpl.getUpdatableSerializationBytes(); - } - - @Override - public double getUpperBound(final int numStdDev) { - return hllSketchImpl.getUpperBound(numStdDev); - } - - @Override - public boolean isCompact() { - return hllSketchImpl.isCompact(); - } - - @Override - public boolean isEmpty() { - return hllSketchImpl.isEmpty(); - } - - @Override - public boolean hasMemorySegment() { - return hllSketchImpl.hasMemorySegment(); - } - - @Override - public boolean isOffHeap() { - return hllSketchImpl.isOffHeap(); - } - - @Override - boolean isOutOfOrder() { - return hllSketchImpl.isOutOfOrder(); - } - - @Override - public boolean isSameResource(final MemorySegment seg) { - return hllSketchImpl.isSameResource(seg); - } - - void mergeTo(final HllSketch that) { - hllSketchImpl.mergeTo(that); - } - - HllSketch putOutOfOrderFlag(final boolean oooFlag) { - hllSketchImpl.putOutOfOrder(oooFlag); - return this; - } - - @Override - public void reset() { - hllSketchImpl = hllSketchImpl.reset(); - } - - @Override - public byte[] toCompactByteArray() { - return hllSketchImpl.toCompactByteArray(); - } - - @Override - public byte[] toUpdatableByteArray() { - return hllSketchImpl.toUpdatableByteArray(); - } - - @Override - public String toString(final boolean summary, final boolean detail, final boolean auxDetail, - final boolean all) { - final StringBuilder sb = new StringBuilder(); - if (summary) { - sb.append("### HLL SKETCH SUMMARY: ").append(LS); - sb.append(" Log Config K : ").append(getLgConfigK()).append(LS); - sb.append(" Hll Target : ").append(getTgtHllType()).append(LS); - sb.append(" Current Mode : ").append(getCurMode()).append(LS); - sb.append(" MemorySegment : ").append(hasMemorySegment()).append(LS); - sb.append(" LB : ").append(getLowerBound(1)).append(LS); - sb.append(" Estimate : ").append(getEstimate()).append(LS); - sb.append(" UB : ").append(getUpperBound(1)).append(LS); - sb.append(" OutOfOrder Flag: ").append(isOutOfOrder()).append(LS); - if (getCurMode() == CurMode.HLL) { - final AbstractHllArray absHll = (AbstractHllArray) hllSketchImpl; - sb.append(" CurMin : ").append(absHll.getCurMin()).append(LS); - sb.append(" NumAtCurMin : ").append(absHll.getNumAtCurMin()).append(LS); - sb.append(" HipAccum : ").append(absHll.getHipAccum()).append(LS); - sb.append(" KxQ0 : ").append(absHll.getKxQ0()).append(LS); - sb.append(" KxQ1 : ").append(absHll.getKxQ1()).append(LS); - sb.append(" Rebuild KxQ Flg: ").append(absHll.isRebuildCurMinNumKxQFlag()).append(LS); - } else { - sb.append(" Coupon Count : ") - .append(((AbstractCoupons)hllSketchImpl).getCouponCount()).append(LS); - } - } - if (detail) { - sb.append("### HLL SKETCH DATA DETAIL: ").append(LS); - final PairIterator pitr = iterator(); - sb.append(pitr.getHeader()).append(LS); - if (all) { - while (pitr.nextAll()) { - sb.append(pitr.getString()).append(LS); - } - } else { - while (pitr.nextValid()) { - sb.append(pitr.getString()).append(LS); - } - } - } - if (auxDetail && ((getCurMode() == CurMode.HLL) && (getTgtHllType() == TgtHllType.HLL_4))) { - final AbstractHllArray absHll = (AbstractHllArray) hllSketchImpl; - final PairIterator auxItr = absHll.getAuxIterator(); - if (auxItr != null) { - sb.append("### HLL SKETCH AUX DETAIL: ").append(LS); - sb.append(auxItr.getHeader()).append(LS); - if (all) { - while (auxItr.nextAll()) { - sb.append(auxItr.getString()).append(LS); - } - } else { - while (auxItr.nextValid()) { - sb.append(auxItr.getString()).append(LS); - } - } - } - } - return sb.toString(); - } - - /** - * Returns a human readable string of the preamble of a byte array image of an HllSketch. - * @param byteArr the given byte array - * @return a human readable string of the preamble of a byte array image of an HllSketch. - */ - public static String toString(final byte[] byteArr) { - return PreambleUtil.toString(byteArr); - } - - /** - * Returns a human readable string of the preamble of a MemorySegment image of an HllSketch. - * @param seg the given MemorySegment object - * @return a human readable string of the preamble of a MemorySegment image of an HllSketch. - */ - public static String toString(final MemorySegment seg) { - return PreambleUtil.toString(seg); - } - - //restricted methods - - /** - * Returns a PairIterator over the key, value pairs of the HLL array. - * @return a PairIterator over the key, value pairs of the HLL array. - */ - PairIterator iterator() { - return hllSketchImpl.iterator(); - } - - @Override - CurMode getCurMode() { - return hllSketchImpl.getCurMode(); - } - - @Override - void couponUpdate(final int coupon) { - if ((coupon >>> KEY_BITS_26 ) == EMPTY) { return; } - hllSketchImpl = hllSketchImpl.couponUpdate(coupon); - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/HllSketchImpl.java b/src/main/java/org/apache/datasketches/hll/HllSketchImpl.java deleted file mode 100644 index bcc74d255..000000000 --- a/src/main/java/org/apache/datasketches/hll/HllSketchImpl.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import java.lang.foreign.MemorySegment; - -/** - * The Abstract HllSketch implementation - * - * @author Lee Rhodes - */ -abstract class HllSketchImpl { - final int lgConfigK; - final TgtHllType tgtHllType; - final CurMode curMode; - - HllSketchImpl(final int lgConfigK, final TgtHllType tgtHllType, final CurMode curMode) { - this.lgConfigK = lgConfigK; - this.tgtHllType = tgtHllType; - this.curMode = curMode; - } - - /** - * Returns a copy of this sketch on the Heap. - * The LgConfigK, TgtHllType and CurMode are not changed. - * @return Returns a copy of this sketch on the Heap. - */ - abstract HllSketchImpl copy(); - - /** - * Returns a copy of this sketch on the Heap with the given TgtHllType. - * The LgConfigK and CurMode are not changed. - * @return Returns a copy of this sketch on the Heap with the given TgtHllType. - */ - abstract HllSketchImpl copyAs(TgtHllType tgtHllType); - - abstract HllSketchImpl couponUpdate(int coupon); - - abstract int getCompactSerializationBytes(); - - abstract double getCompositeEstimate(); - - CurMode getCurMode() { - return curMode; - } - - abstract double getEstimate(); - - abstract double getHipEstimate(); - - int getLgConfigK() { - return lgConfigK; - } - - abstract double getLowerBound(int numStdDev); - - abstract int getSegDataStart(); - - abstract MemorySegment getMemorySegment(); - - abstract int getPreInts(); - - TgtHllType getTgtHllType() { - return tgtHllType; - } - - abstract int getUpdatableSerializationBytes(); - - abstract double getUpperBound(int numStdDev); - - abstract boolean isCompact(); - - abstract boolean isEmpty(); - - abstract boolean hasMemorySegment(); - - abstract boolean isOffHeap(); - - abstract boolean isOutOfOrder(); - - abstract boolean isRebuildCurMinNumKxQFlag(); - - abstract boolean isSameResource(MemorySegment seg); - - abstract PairIterator iterator(); - - abstract void mergeTo(HllSketch that); - - abstract void putEmptyFlag(boolean empty); - - abstract void putOutOfOrder(boolean oooFlag); - - abstract void putRebuildCurMinNumKxQFlag(boolean rebuild); - - abstract HllSketchImpl reset(); - - abstract byte[] toCompactByteArray(); - - abstract byte[] toUpdatableByteArray(); - -} diff --git a/src/main/java/org/apache/datasketches/hll/HllUnion.java b/src/main/java/org/apache/datasketches/hll/HllUnion.java deleted file mode 100644 index 2738d68d7..000000000 --- a/src/main/java/org/apache/datasketches/hll/HllUnion.java +++ /dev/null @@ -1,834 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.common.Util.invPow2; -import static org.apache.datasketches.hll.HllUtil.AUX_TOKEN; -import static org.apache.datasketches.hll.HllUtil.EMPTY; -import static org.apache.datasketches.hll.HllUtil.loNibbleMask; -import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.extractTgtHllType; -import static org.apache.datasketches.hll.TgtHllType.HLL_4; -import static org.apache.datasketches.hll.TgtHllType.HLL_8; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This performs union operations for all HllSketches. This HllUnion operator can be configured to be - * on or off heap. The source sketch given to this HllUnion using the {@link #update(HllSketch)} can - * be configured with any precision value lgConfigK (from 4 to 21), any TgtHllType - * (HLL_4, HLL_6, HLL_8), and either on or off-heap; and it can be in either of the sparse modes - * (LIST or SET), or the dense mode (HLL). - * - *

Although the API for this HllUnion operator parallels many of the methods of the - * HllSketch, the behavior of the HllUnion operator has some fundamental differences.

- * - *

First, this HllUnion operator is configured with a lgMaxK instead of the normal - * lgConfigK. Generally, this HllUnion operator will inherit the lowest lgConfigK - * less than lgMaxK that it has seen. However, the lgConfigK of incoming sketches that - * are still in sparse are ignored. The lgMaxK provides the user the ability to specify the - * largest maximum size for the HllUnion operation. - * - *

Second, the user cannot specify the {@link TgtHllType} as an input parameter to the HllUnion. - * Instead, it is specified for the sketch returned with {@link #getResult(TgtHllType)}. - * - *

The following graph illustrates the HLL Merge speed.

- * - *

HLL_UnionTime4_6_8_Java_CPP.png

- * This graph illustrates the relative merging speed of the HLL 4,6,8 Java HLL sketches compared to - * the DataSketches C++ implementations of the same sketches. With this particular test (merging 32 relative large - * sketches together), the Java HLL 8 is the fastest and the Java HLL 4 the slowest, with a mixed cluster in the middle. - * HllUnion / Merging speed is somewhat difficult to measure as the performance is very dependent on the mix of sketch - * sizes (and types) you are merging. So your mileage will vary! - * - *

For a complete example of using the HllUnion operator - * see HllUnion Example.

- * - * @author Lee Rhodes - * @author Kevin Lang - */ -public class HllUnion extends BaseHllSketch { - final int lgMaxK; - private final HllSketch gadget; - - /** - * Construct this HllUnion operator with the default maximum log-base-2 of K. - */ - public HllUnion() { - lgMaxK = HllSketch.DEFAULT_LG_K; - gadget = new HllSketch(lgMaxK, HLL_8); - } - - /** - * Construct this HllUnion operator with a given maximum log-base-2 of K. - * @param lgMaxK the desired maximum log-base-2 of K. This value must be - * between 4 and 21 inclusively. - */ - public HllUnion(final int lgMaxK) { - this.lgMaxK = HllUtil.checkLgK(lgMaxK); - gadget = new HllSketch(lgMaxK, HLL_8); - } - - /** - * Construct this HllUnion operator with a given maximum log-base-2 of K and the given - * MemorySegment as the destination for this HllUnion. This MemorySegment is usually configured - * for off-heap MemorySegment. What remains on the java heap is a thin wrapper object that reads and - * writes to the given MemorySegment. - * - *

The given dstSeg is checked for the required capacity as determined by - * {@link HllSketch#getMaxUpdatableSerializationBytes(int, TgtHllType)}. - * @param lgMaxK the desired maximum log-base-2 of K. This value must be - * between 4 and 21 inclusively. - * @param dstWseg the destination writable MemorySegment for the sketch. - */ - public HllUnion(final int lgMaxK, final MemorySegment dstWseg) { - this.lgMaxK = HllUtil.checkLgK(lgMaxK); - gadget = new HllSketch(lgMaxK, HLL_8, dstWseg); - } - - //used only by writableWrap - private HllUnion(final HllSketch sketch) { - lgMaxK = sketch.getLgConfigK(); - gadget = sketch; - } - - /** - * Construct a HllUnion operator populated with the given byte array image of an HllSketch. - * @param byteArray the given byte array - * @return a HllUnion operator populated with the given byte array image of an HllSketch. - */ - public static final HllUnion heapify(final byte[] byteArray) { - return heapify(MemorySegment.ofArray(byteArray)); - } - - /** - * Construct a HllUnion operator populated with the given MemorySegment image of an HllSketch. - * @param seg the given MemorySegment - * @return a HllUnion operator populated with the given MemorySegment image of an HllSketch. - */ - public static final HllUnion heapify(final MemorySegment seg) { - final int lgK = HllUtil.checkLgK(seg.get(JAVA_BYTE, PreambleUtil.LG_K_BYTE)); - final HllSketch sk = HllSketch.heapify(seg, false); //allows non-finalized image - final HllUnion union = new HllUnion(lgK); - union.update(sk); - return union; - } - - /** - * Wraps the given MemorySegment, which must be a image of a valid updatable HLL_8 sketch, - * and may have data. What remains on the java heap is a - * thin wrapper object that reads and writes to the given MemorySegment, which, depending on - * how the user configures the MemorySegment, may actually reside on the Java heap or off-heap. - * - *

The given dstSeg is checked for the required capacity as determined by - * {@link HllSketch#getMaxUpdatableSerializationBytes(int, TgtHllType)}, and for the correct type. - * @param srcWseg an writable image of a valid sketch with data. - * @return a HllUnion operator where the sketch data is in the given dstSeg. - */ - public static final HllUnion writableWrap(final MemorySegment srcWseg) { - final TgtHllType tgtHllType = extractTgtHllType(srcWseg); - if (tgtHllType != TgtHllType.HLL_8) { - throw new SketchesArgumentException( - "HllUnion can only wrap writable HLL_8 sketches that were the Gadget of a HllUnion."); - } - //allows writableWrap of non-finalized image - return new HllUnion(HllSketch.writableWrap(srcWseg, false)); - } - - @Override - public double getCompositeEstimate() { - checkRebuildCurMinNumKxQ(gadget); - return gadget.hllSketchImpl.getCompositeEstimate(); - } - - @Override - CurMode getCurMode() { - return gadget.getCurMode(); - } - - @Override - public int getCompactSerializationBytes() { - return gadget.getCompactSerializationBytes(); - } - - @Override - public double getEstimate() { - checkRebuildCurMinNumKxQ(gadget); - return gadget.getEstimate(); - } - - /** - * Gets the effective lgConfigK for the HllUnion operator, which may be less than - * lgMaxK. - * @return the lgConfigK. - */ - @Override - public int getLgConfigK() { - return gadget.getLgConfigK(); - } - - @Override - public double getLowerBound(final int numStdDev) { - checkRebuildCurMinNumKxQ(gadget); - return gadget.getLowerBound(numStdDev); - } - - /** - * Returns the maximum size in bytes that this HllUnion operator can grow to given a lgK. - * - * @param lgK The maximum Log2 of K for this HllUnion operator. This value must be - * between 4 and 21 inclusively. - * @return the maximum size in bytes that this HllUnion operator can grow to. - */ - public static int getMaxSerializationBytes(final int lgK) { - return HllSketch.getMaxUpdatableSerializationBytes(lgK, TgtHllType.HLL_8); - } - - /** - * Return the result of this HllUnion operator as an HLL_4 sketch. - * @return the result of this HllUnion operator as an HLL_4 sketch. - */ - public HllSketch getResult() { - return getResult(HllSketch.DEFAULT_HLL_TYPE); - } - - /** - * Return the result of this HllUnion operator with the specified {@link TgtHllType} - * @param tgtHllType the TgtHllType enum - * @return the result of this HllUnion operator with the specified TgtHllType - */ - public HllSketch getResult(final TgtHllType tgtHllType) { - checkRebuildCurMinNumKxQ(gadget); - return gadget.copyAs(tgtHllType); - } - - @Override - public TgtHllType getTgtHllType() { - return TgtHllType.HLL_8; - } - - @Override - public int getUpdatableSerializationBytes() { - return gadget.getUpdatableSerializationBytes(); - } - - @Override - public double getUpperBound(final int numStdDev) { - checkRebuildCurMinNumKxQ(gadget); - return gadget.getUpperBound(numStdDev); - } - - @Override - public boolean isCompact() { - return gadget.isCompact(); - } - - @Override - public boolean isEmpty() { - return gadget.isEmpty(); - } - - @Override - public boolean hasMemorySegment() { - return gadget.hasMemorySegment(); - } - - @Override - public boolean isOffHeap() { - return gadget.isOffHeap(); - } - - @Override - boolean isOutOfOrder() { - return gadget.isOutOfOrder(); - } - - @Override - public boolean isSameResource(final MemorySegment seg) { - return gadget.isSameResource(seg); - } - - boolean isRebuildCurMinNumKxQFlag() { - return gadget.hllSketchImpl.isRebuildCurMinNumKxQFlag(); - } - - void putRebuildCurMinNumKxQFlag(final boolean rebuild) { - gadget.hllSketchImpl.putRebuildCurMinNumKxQFlag(rebuild); - } - - /** - * Resets to empty and retains the current lgK, but does not change the configured value of - * lgMaxK. - */ - @Override - public void reset() { - gadget.reset(); - } - - /** - * Gets the serialization of this HllUnion operator as a byte array in compact form, which is - * designed to be heapified only. It is not directly updatable. - * For the HllUnion operator, this is the serialization of the internal state of - * the HllUnion operator as a sketch. - * @return the serialization of this HllUnion operator as a byte array. - */ - @Override - public byte[] toCompactByteArray() { - checkRebuildCurMinNumKxQ(gadget); - return gadget.toCompactByteArray(); - } - - @Override - public byte[] toUpdatableByteArray() { - checkRebuildCurMinNumKxQ(gadget); - return gadget.toUpdatableByteArray(); - } - - @Override - public String toString(final boolean summary, final boolean hllDetail, - final boolean auxDetail, final boolean all) { - final HllSketch clone = gadget.copy(); - checkRebuildCurMinNumKxQ(clone); - return clone.toString(summary, hllDetail, auxDetail, all); - } - - /** - * Update this HllUnion operator with the given sketch. - * @param sketch the given sketch. - */ - public void update(final HllSketch sketch) { - gadget.hllSketchImpl = unionImpl(sketch, gadget, lgMaxK); - } - - /** - * Update this HllUnion operator with the given HllUnion. - * @param union the given HllUnion. - */ - public void update(final HllUnion union) { - gadget.hllSketchImpl = unionImpl(union.gadget, gadget, lgMaxK); - } - - @Override - void couponUpdate(final int coupon) { - if (coupon == EMPTY) { return; } - gadget.hllSketchImpl = gadget.hllSketchImpl.couponUpdate(coupon); - } - - // HllUnion operator logic - - /** - * Union the given source and destination sketches. This static method examines the state of - * the current internal gadget and the incoming sketch and determines the optimum way to - * perform the union. This may involve swapping the merge order, downsampling, transforming, - * and / or copying one of the arguments and may completely replace the internals of the HllUnion. - * - *

If the HllUnion gadget is empty, the source sketch is effectively copied to the HllUnion gadget - * after any required transformations. - * - *

The direction of the merge is reversed if the HllUnion gadget is in LIST or SET mode, and the - * source sketch is in HLL mode. This is done to maintain maximum accuracy of the union process. - * - *

The source sketch is downsampled if the source LgK is larger than maxLgK and in HLL mode. - * - *

The HllUnion gadget is downsampled if both source and HllUnion gadget are in HLL mode - * and the source LgK less than the HllUnion gadget LgK. - * - * @param source the given incoming sketch, which cannot be modified. - * @param gadget the given gadget sketch, which has a target of HLL_8 and holds the result. - * @param lgMaxK the maximum value of log2 K for this union operation. - * @return the union of the two sketches in the form of the internal HllSketchImpl, which is - * always in HLL_8 form. - */ - private static HllSketchImpl unionImpl(final HllSketch source, final HllSketch gadget, - final int lgMaxK) { - assert gadget.getTgtHllType() == HLL_8; - if ((source == null) || source.isEmpty()) { - return gadget.hllSketchImpl; - } - - final CurMode srcMode = source.getCurMode(); - if (srcMode == CurMode.LIST ) { - source.mergeTo(gadget); - return gadget.hllSketchImpl; - } - - final int srcLgK = source.getLgConfigK(); - final int gadgetLgK = gadget.getLgConfigK(); - final boolean srcHasSeg = source.hasMemorySegment(); - final boolean gdtHasSeg = gadget.hasMemorySegment(); - final boolean gdtEmpty = gadget.isEmpty(); - - if (srcMode == CurMode.SET ) { - if (gdtEmpty && (srcLgK == gadgetLgK) && (!srcHasSeg) && (!gdtHasSeg)) { - gadget.hllSketchImpl = source.copyAs(HLL_8).hllSketchImpl; - return gadget.hllSketchImpl; - } - source.mergeTo(gadget); - return gadget.hllSketchImpl; - } - - //Hereafter, the source is in HLL mode. - final int bit0 = gdtHasSeg ? 1 : 0; - final int bits1_2 = (gdtEmpty ? 3 : gadget.getCurMode().ordinal()) << 1; - final int bit3 = (srcLgK < gadgetLgK) ? 8 : 0; - final int bit4 = (srcLgK > lgMaxK) ? 16 : 0; - final int sw = bit4 | bit3 | bits1_2 | bit0; - HllSketchImpl hllSketchImpl = null; //never returned as null - - switch (sw) { - case 0: //src <= max, src >= gdt, gdtLIST, gdtHeap - case 8: //src <= max, src < gdt, gdtLIST, gdtHeap - case 2: //src <= max, src >= gdt, gdtSET, gdtHeap - case 10://src <= max, src < gdt, gdtSET, gdtHeap - { //Action: copy src, reverse merge w/autofold, ooof=src - final HllSketch srcHll8Heap = source.copyAs(HLL_8); - gadget.mergeTo(srcHll8Heap); //merge gdt(Hll8,heap,list/set) -> src(Hll8,heap,hll) - hllSketchImpl = srcHll8Heap.hllSketchImpl; - break; - } - case 16://src > max, src >= gdt, gdtList, gdtHeap - case 18://src > max, src >= gdt, gdtSet, gdtHeap - { //Action: downsample src to MaxLgK, reverse merge w/autofold, ooof=src - final HllSketch srcHll8Heap = downsample(source, lgMaxK); - gadget.mergeTo(srcHll8Heap); //merge gdt(Hll8,heap,list/set) -> src(Hll8,heap,hll) - hllSketchImpl = srcHll8Heap.hllSketchImpl; - break; - } - - case 1: //src <= max, src >= gdt, gdtLIST, gdtMemorySegment - case 9: //src <= max, src < gdt, gdtLIST, gdtMemorySegment - case 3: //src <= max, src >= gdt, gdtSET, gdtMemorySegment - case 11://src <= max, src < gdt, gdtSET, gdtMemorySegment - { //Action: copy src, reverse merge w/autofold, use gdt MemorySegment, ooof=src - final HllSketch srcHll8Heap = source.copyAs(HLL_8); - gadget.mergeTo(srcHll8Heap); //merge gdt(Hll8,seg,list/set) -> src(Hll8,heap,hll) - hllSketchImpl = useGadgetMemorySegment(gadget, srcHll8Heap, false).hllSketchImpl; - break; - } - case 17://src > max, src >= gdt, gdtList, gdtMemorySegment - case 19://src > max, src >= gdt, gdtSet, gdtMemorySegment - { //Action: downsample src to MaxLgK, reverse merge w/autofold, use gdt MemorySegment, ooof=src - final HllSketch srcHll8Heap = downsample(source, lgMaxK); - gadget.mergeTo(srcHll8Heap); //merge gdt(Hll8,seg,list/set) -> src(Hll8,heap,hll), autofold - hllSketchImpl = useGadgetMemorySegment(gadget, srcHll8Heap, false).hllSketchImpl; - break; - } - - case 4: //src <= max, src >= gdt, gdtHLL, gdtHeap - case 20://src > max, src >= gdt, gdtHLL, gdtHeap - case 5: //src <= max, src >= gdt, gdtHLL, gdtMemorySegment - case 21://src > max, src >= gdt, gdtHLL, gdtMemorySegment - { //Action: forward HLL merge w/autofold, ooof=True - //merge src(Hll4,6,8,heap/seg,Mode=HLL) -> gdt(Hll8,heap,Mode=HLL) - mergeHlltoHLLmode(source, gadget, srcLgK, gadgetLgK, srcHasSeg, gdtHasSeg); - hllSketchImpl = gadget.putOutOfOrderFlag(true).hllSketchImpl; - break; - } - case 12://src <= max, src < gdt, gdtHLL, gdtHeap - { //Action: downsample gdt to srcLgK, forward HLL merge w/autofold, ooof=True - final HllSketch gdtHll8Heap = downsample(gadget, srcLgK); - //merge src(Hll4,6,8;heap/seg,Mode=HLL) -> gdt(Hll8,heap,hll) - mergeHlltoHLLmode(source, gdtHll8Heap, srcLgK, gadgetLgK, srcHasSeg, false); - hllSketchImpl = gdtHll8Heap.putOutOfOrderFlag(true).hllSketchImpl; - break; - } - case 13://src <= max, src < gdt, gdtHLL, gdtMemorySegment - { //Action: downsample gdt to srcLgK, forward HLL merge w/autofold, use gdt MemorySegment, ooof=True - final HllSketch gdtHll8Heap = downsample(gadget, srcLgK); - //merge src(Hll4,6,8;heap/seg;Mode=HLL) -> gdt(Hll8,heap,Mode=HLL) - mergeHlltoHLLmode(source, gdtHll8Heap, srcLgK, gadgetLgK, srcHasSeg, false); - hllSketchImpl = useGadgetMemorySegment(gadget, gdtHll8Heap, true).hllSketchImpl; - break; - } - - case 6: //src <= max, src >= gdt, gdtEmpty, gdtHeap - case 14://src <= max, src < gdt, gdtEmpty, gdtHeap - { //Action: copy src, replace gdt, ooof=src - final HllSketch srcHll8Heap = source.copyAs(HLL_8); - hllSketchImpl = srcHll8Heap.hllSketchImpl; - break; - } - case 22://src > max, src >= gdt, gdtEmpty, gdtHeap - { //Action: downsample src to lgMaxK, replace gdt, ooof=src - final HllSketch srcHll8Heap = downsample(source, lgMaxK); - hllSketchImpl = srcHll8Heap.hllSketchImpl; - break; - } - - case 7: //src <= max, src >= gdt, gdtEmpty, gdtMemorySegment - case 15://src <= max, src < gdt, gdtEmpty, gdtMemorySegment - { //Action: copy src, use gdt MemorySegment, ooof=src - final HllSketch srcHll8Heap = source.copyAs(HLL_8); - hllSketchImpl = useGadgetMemorySegment(gadget, srcHll8Heap, false).hllSketchImpl; - break; - } - case 23://src > max, src >= gdt, gdtEmpty, gdtMemorySegment, replace seg, downsample src, ooof=src - { //Action: downsample src to lgMaxK, use gdt MemorySegment, ooof=src - final HllSketch srcHll8Heap = downsample(source, lgMaxK); - hllSketchImpl = useGadgetMemorySegment(gadget, srcHll8Heap, false).hllSketchImpl; - break; - } - default: return gadget.hllSketchImpl; //not possible - } - return hllSketchImpl; - } - - private static final HllSketch useGadgetMemorySegment( - final HllSketch gadget, final HllSketch hll8Heap, final boolean setOooFlag) { - final MemorySegment wseg = gadget.getMemorySegment(); //use the gdt wseg - final byte[] byteArr = hll8Heap.toUpdatableByteArray(); //serialize srcCopy - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, 0, byteArr.length); //replace old data with new - return (setOooFlag) - ? HllSketch.writableWrap(wseg, false).putOutOfOrderFlag(true) //wrap, set oooflag, return - : HllSketch.writableWrap(wseg, false); //wrap & return - } - - private static final void mergeHlltoHLLmode(final HllSketch src, final HllSketch tgt, - final int srcLgK, final int tgtLgK, final boolean srcHasSeg, final boolean tgtHasSeg) { - final int sw = (tgtHasSeg ? 1 : 0) | (srcHasSeg ? 2 : 0) - | ((srcLgK > tgtLgK) ? 4 : 0) | ((src.getTgtHllType() != HLL_8) ? 8 : 0); - final int srcK = 1 << srcLgK; - - switch (sw) { - case 0: { //HLL_8, srcLgK=tgtLgK, src=heap, tgt=heap - final byte[] srcArr = ((Hll8Array) src.hllSketchImpl).hllByteArr; - final byte[] tgtArr = ((Hll8Array) tgt.hllSketchImpl).hllByteArr; - for (int i = 0; i < srcK; i++) { - final byte srcV = srcArr[i]; - final byte tgtV = tgtArr[i]; - tgtArr[i] = (byte) Math.max(srcV, tgtV); - } - break; - } - case 1: { //HLL_8, srcLgK=tgtLgK, src=heap, tgt=seg - final byte[] srcArr = ((Hll8Array) src.hllSketchImpl).hllByteArr; - final MemorySegment tgtSeg = tgt.getMemorySegment(); - for (int i = 0; i < srcK; i++) { - final byte srcV = srcArr[i]; - final byte tgtV = tgtSeg.get(JAVA_BYTE, HLL_BYTE_ARR_START + i); - tgtSeg.set(JAVA_BYTE, HLL_BYTE_ARR_START + i, (byte) Math.max(srcV, tgtV)); - } - break; - } - case 2: { //HLL_8, srcLgK=tgtLgK, src=seg, tgt=heap - final MemorySegment srcSeg = src.getMemorySegment(); - final byte[] tgtArr = ((Hll8Array) tgt.hllSketchImpl).hllByteArr; - for (int i = 0; i < srcK; i++) { - final byte srcV = srcSeg.get(JAVA_BYTE, HLL_BYTE_ARR_START + i); - final byte tgtV = tgtArr[i]; - tgtArr[i] = (byte) Math.max(srcV, tgtV); - } - break; - } - case 3: { //HLL_8, srcLgK=tgtLgK, src=seg, tgt=seg - final MemorySegment srcSeg = src.getMemorySegment(); - final MemorySegment tgtSeg = tgt.getMemorySegment(); - for (int i = 0; i < srcK; i++) { - final byte srcV = srcSeg.get(JAVA_BYTE, HLL_BYTE_ARR_START + i); - final byte tgtV = tgtSeg.get(JAVA_BYTE, HLL_BYTE_ARR_START + i); - tgtSeg.set(JAVA_BYTE, HLL_BYTE_ARR_START + i, (byte) Math.max(srcV, tgtV)); - } - break; - } - case 4: { //HLL_8, srcLgK>tgtLgK, src=heap, tgt=heap - final int tgtKmask = (1 << tgtLgK) - 1; - final byte[] srcArr = ((Hll8Array) src.hllSketchImpl).hllByteArr; - final byte[] tgtArr = ((Hll8Array) tgt.hllSketchImpl).hllByteArr; - for (int i = 0; i < srcK; i++) { - final byte srcV = srcArr[i]; - final int j = i & tgtKmask; - final byte tgtV = tgtArr[j]; - tgtArr[j] = (byte) Math.max(srcV, tgtV); - } - break; - } - case 5: { //HLL_8, srcLgK>tgtLgK, src=heap, tgt=seg - final int tgtKmask = (1 << tgtLgK) - 1; - final byte[] srcArr = ((Hll8Array) src.hllSketchImpl).hllByteArr; - final MemorySegment tgtSeg = tgt.getMemorySegment(); - for (int i = 0; i < srcK; i++) { - final byte srcV = srcArr[i]; - final int j = i & tgtKmask; - final byte tgtV = tgtSeg.get(JAVA_BYTE, HLL_BYTE_ARR_START + j); - tgtSeg.set(JAVA_BYTE, HLL_BYTE_ARR_START + j, (byte) Math.max(srcV, tgtV)); - } - break; - } - case 6: { //HLL_8, srcLgK>tgtLgK, src=seg, tgt=heap - final int tgtKmask = (1 << tgtLgK) - 1; - final MemorySegment srcSeg = src.getMemorySegment(); - final byte[] tgtArr = ((Hll8Array) tgt.hllSketchImpl).hllByteArr; - for (int i = 0; i < srcK; i++) { - final byte srcV = srcSeg.get(JAVA_BYTE, HLL_BYTE_ARR_START + i); - final int j = i & tgtKmask; - final byte tgtV = tgtArr[j]; - tgtArr[j] = (byte) Math.max(srcV, tgtV); - } - break; - } - case 7: { //HLL_8, srcLgK>tgtLgK, src=seg, tgt=seg - final int tgtKmask = (1 << tgtLgK) - 1; - final MemorySegment srcSeg = src.getMemorySegment(); - final MemorySegment tgtSeg = tgt.getMemorySegment(); - for (int i = 0; i < srcK; i++) { - final byte srcV = srcSeg.get(JAVA_BYTE, HLL_BYTE_ARR_START + i); - final int j = i & tgtKmask; - final byte tgtV = tgtSeg.get(JAVA_BYTE, HLL_BYTE_ARR_START + j); - tgtSeg.set(JAVA_BYTE, HLL_BYTE_ARR_START + j, (byte) Math.max(srcV, tgtV)); - } - break; - } - case 8: case 9: - { - //!HLL_8, srcLgK=tgtLgK, src=heap, tgt=heap/seg - final AbstractHllArray tgtAbsHllArr = (AbstractHllArray)(tgt.hllSketchImpl); - if (src.getTgtHllType() == HLL_4) { - final Hll4Array src4 = (Hll4Array) src.hllSketchImpl; - final AuxHashMap auxHashMap = src4.getAuxHashMap(); - final int curMin = src4.getCurMin(); - int i = 0; - int j = 0; - while (j < srcK) { - final byte b = src4.hllByteArr[i++]; - int value = Byte.toUnsignedInt(b) & loNibbleMask; - tgtAbsHllArr.updateSlotNoKxQ(j, value == AUX_TOKEN ? auxHashMap.mustFindValueFor(j) : value + curMin); - j++; - value = Byte.toUnsignedInt(b) >>> 4; - tgtAbsHllArr.updateSlotNoKxQ(j, value == AUX_TOKEN ? auxHashMap.mustFindValueFor(j) : value + curMin); - j++; - } - } else { - final Hll6Array src6 = (Hll6Array) src.hllSketchImpl; - int i = 0; - int j = 0; - while (j < srcK) { - final byte b1 = src6.hllByteArr[i++]; - final byte b2 = src6.hllByteArr[i++]; - final byte b3 = src6.hllByteArr[i++]; - int value = Byte.toUnsignedInt(b1) & 0x3f; - tgtAbsHllArr.updateSlotNoKxQ(j++, value); - value = Byte.toUnsignedInt(b1) >>> 6; - value |= (Byte.toUnsignedInt(b2) & 0x0f) << 2; - tgtAbsHllArr.updateSlotNoKxQ(j++, value); - value = Byte.toUnsignedInt(b2) >>> 4; - value |= (Byte.toUnsignedInt(b3) & 3) << 4; - tgtAbsHllArr.updateSlotNoKxQ(j++, value); - value = Byte.toUnsignedInt(b3) >>> 2; - tgtAbsHllArr.updateSlotNoKxQ(j++, value); - } - } - break; - } - case 10: case 11: - { - //!HLL_8, srcLgK=tgtLgK, src=seg, tgt=heap/seg - final AbstractHllArray tgtAbsHllArr = (AbstractHllArray)(tgt.hllSketchImpl); - if (src.getTgtHllType() == HLL_4) { - final DirectHll4Array src4 = (DirectHll4Array) src.hllSketchImpl; - final AuxHashMap auxHashMap = src4.getAuxHashMap(); - final int curMin = src4.getCurMin(); - int i = 0; - int j = 0; - while (j < srcK) { - final byte b = src4.seg.get(JAVA_BYTE, HLL_BYTE_ARR_START + i++); - int value = Byte.toUnsignedInt(b) & loNibbleMask; - tgtAbsHllArr.updateSlotNoKxQ(j, value == AUX_TOKEN ? auxHashMap.mustFindValueFor(j) : value + curMin); - j++; - value = Byte.toUnsignedInt(b) >>> 4; - tgtAbsHllArr.updateSlotNoKxQ(j, value == AUX_TOKEN ? auxHashMap.mustFindValueFor(j) : value + curMin); - j++; - } - } else { - final DirectHll6Array src6 = (DirectHll6Array) src.hllSketchImpl; - int i = 0; - int offset = HLL_BYTE_ARR_START; - while (i < srcK) { - final byte b1 = src6.seg.get(JAVA_BYTE, offset++); - final byte b2 = src6.seg.get(JAVA_BYTE, offset++); - final byte b3 = src6.seg.get(JAVA_BYTE, offset++); - int value = Byte.toUnsignedInt(b1) & 0x3f; - tgtAbsHllArr.updateSlotNoKxQ(i++, value); - value = Byte.toUnsignedInt(b1) >>> 6; - value |= (Byte.toUnsignedInt(b2) & 0x0f) << 2; - tgtAbsHllArr.updateSlotNoKxQ(i++, value); - value = Byte.toUnsignedInt(b2) >>> 4; - value |= (Byte.toUnsignedInt(b3) & 3) << 4; - tgtAbsHllArr.updateSlotNoKxQ(i++, value); - value = Byte.toUnsignedInt(b3) >>> 2; - tgtAbsHllArr.updateSlotNoKxQ(i++, value); - } - } - break; - } - case 12: case 13: - { - //!HLL_8, srcLgK>tgtLgK, src=heap, tgt=heap/seg - final int tgtKmask = (1 << tgtLgK) - 1; - final AbstractHllArray tgtAbsHllArr = (AbstractHllArray)(tgt.hllSketchImpl); - if (src.getTgtHllType() == HLL_4) { - final Hll4Array src4 = (Hll4Array) src.hllSketchImpl; - final AuxHashMap auxHashMap = src4.getAuxHashMap(); - final int curMin = src4.getCurMin(); - int i = 0; - int j = 0; - while (j < srcK) { - final byte b = src4.hllByteArr[i++]; - int value = Byte.toUnsignedInt(b) & loNibbleMask; - tgtAbsHllArr.updateSlotNoKxQ(j & tgtKmask, value == AUX_TOKEN - ? auxHashMap.mustFindValueFor(j) : value + curMin); - j++; - value = Byte.toUnsignedInt(b) >>> 4; - tgtAbsHllArr.updateSlotNoKxQ(j & tgtKmask, value == AUX_TOKEN - ? auxHashMap.mustFindValueFor(j) : value + curMin); - j++; - } - } else { - final Hll6Array src6 = (Hll6Array) src.hllSketchImpl; - int i = 0; - int j = 0; - while (j < srcK) { - final byte b1 = src6.hllByteArr[i++]; - final byte b2 = src6.hllByteArr[i++]; - final byte b3 = src6.hllByteArr[i++]; - int value = Byte.toUnsignedInt(b1) & 0x3f; - tgtAbsHllArr.updateSlotNoKxQ(j++ & tgtKmask, value); - value = Byte.toUnsignedInt(b1) >>> 6; - value |= (Byte.toUnsignedInt(b2) & 0x0f) << 2; - tgtAbsHllArr.updateSlotNoKxQ(j++ & tgtKmask, value); - value = Byte.toUnsignedInt(b2) >>> 4; - value |= (Byte.toUnsignedInt(b3) & 3) << 4; - tgtAbsHllArr.updateSlotNoKxQ(j++ & tgtKmask, value); - value = Byte.toUnsignedInt(b3) >>> 2; - tgtAbsHllArr.updateSlotNoKxQ(j++ & tgtKmask, value); - } - } - break; - } - case 14: case 15: - { - //!HLL_8, srcLgK>tgtLgK, src=seg, tgt=heap/seg - final int tgtKmask = (1 << tgtLgK) - 1; - final AbstractHllArray tgtAbsHllArr = (AbstractHllArray)(tgt.hllSketchImpl); - if (src.getTgtHllType() == HLL_4) { - final DirectHll4Array src4 = (DirectHll4Array) src.hllSketchImpl; - final AuxHashMap auxHashMap = src4.getAuxHashMap(); - final int curMin = src4.getCurMin(); - int i = 0; - int j = 0; - while (j < srcK) { - final byte b = src4.seg.get(JAVA_BYTE, HLL_BYTE_ARR_START + i++); - int value = Byte.toUnsignedInt(b) & loNibbleMask; - tgtAbsHllArr.updateSlotNoKxQ(j & tgtKmask, value == AUX_TOKEN - ? auxHashMap.mustFindValueFor(j) : value + curMin); - j++; - value = Byte.toUnsignedInt(b) >>> 4; - tgtAbsHllArr.updateSlotNoKxQ(j & tgtKmask, value == AUX_TOKEN - ? auxHashMap.mustFindValueFor(j) : value + curMin); - j++; - } - } else { - final DirectHll6Array src6 = (DirectHll6Array) src.hllSketchImpl; - int i = 0; - int offset = HLL_BYTE_ARR_START; - while (i < srcK) { - final byte b1 = src6.seg.get(JAVA_BYTE, offset++); - final byte b2 = src6.seg.get(JAVA_BYTE, offset++); - final byte b3 = src6.seg.get(JAVA_BYTE, offset++); - int value = Byte.toUnsignedInt(b1) & 0x3f; - tgtAbsHllArr.updateSlotNoKxQ(i++ & tgtKmask, value); - value = Byte.toUnsignedInt(b1) >>> 6; - value |= (Byte.toUnsignedInt(b2) & 0x0f) << 2; - tgtAbsHllArr.updateSlotNoKxQ(i++ & tgtKmask, value); - value = Byte.toUnsignedInt(b2) >>> 4; - value |= (Byte.toUnsignedInt(b3) & 3) << 4; - tgtAbsHllArr.updateSlotNoKxQ(i++ & tgtKmask, value); - value = Byte.toUnsignedInt(b3) >>> 2; - tgtAbsHllArr.updateSlotNoKxQ(i++ & tgtKmask, value); - } - } - break; - } - default: break; //not possible - } - tgt.hllSketchImpl.putRebuildCurMinNumKxQFlag(true); - } - - //Used by HllUnion operator. Always copies or downsamples to Heap HLL_8. - //Caller must ultimately manage oooFlag, as caller has more context. - /** - * Copies or downsamples the given candidate HLLmode sketch to tgtLgK, HLL_8, on the heap. - * - * @param candidate the HllSketch to downsample, must be in HLL mode. - * @param tgtLgK the LgK to downsample to. - * @return the downsampled HllSketch. - */ - private static final HllSketch downsample(final HllSketch candidate, final int tgtLgK) { - final AbstractHllArray candArr = (AbstractHllArray) candidate.hllSketchImpl; - final HllArray tgtHllArr = HllArray.newHeapHll(tgtLgK, TgtHllType.HLL_8); - final PairIterator candItr = candArr.iterator(); - while (candItr.nextValid()) { - tgtHllArr.couponUpdate(candItr.getPair()); //rebuilds KxQ, etc. - } - //both of these are required for isomorphism - tgtHllArr.putHipAccum(candArr.getHipAccum()); - tgtHllArr.putOutOfOrder(candidate.isOutOfOrder()); - tgtHllArr.putRebuildCurMinNumKxQFlag(false); - return new HllSketch(tgtHllArr); - } - - //Used to rebuild curMin, numAtCurMin and KxQ registers, due to high performance merge operation - static final void checkRebuildCurMinNumKxQ(final HllSketch sketch) { - final HllSketchImpl hllSketchImpl = sketch.hllSketchImpl; - final CurMode curMode = sketch.getCurMode(); - final TgtHllType tgtHllType = sketch.getTgtHllType(); - final boolean rebuild = hllSketchImpl.isRebuildCurMinNumKxQFlag(); - if ( !rebuild || (curMode != CurMode.HLL) || (tgtHllType != HLL_8) ) { return; } - final AbstractHllArray absHllArr = (AbstractHllArray)(hllSketchImpl); - int curMin = 64; - int numAtCurMin = 0; - double kxq0 = 1 << absHllArr.getLgConfigK(); - double kxq1 = 0; - final PairIterator itr = absHllArr.iterator(); - while (itr.nextAll()) { - final int v = itr.getValue(); - if (v > 0) { - if (v < 32) { kxq0 += invPow2(v) - 1.0; } - else { kxq1 += invPow2(v) - 1.0; } - } - if (v > curMin) { continue; } - if (v < curMin) { - curMin = v; - numAtCurMin = 1; - } else { - numAtCurMin++; - } - } - absHllArr.putKxQ0(kxq0); - absHllArr.putKxQ1(kxq1); - absHllArr.putCurMin(curMin); - absHllArr.putNumAtCurMin(numAtCurMin); - absHllArr.putRebuildCurMinNumKxQFlag(false); - //HipAccum is not affected - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/HllUtil.java b/src/main/java/org/apache/datasketches/hll/HllUtil.java deleted file mode 100644 index 500f946f7..000000000 --- a/src/main/java/org/apache/datasketches/hll/HllUtil.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.Math.log; -import static java.lang.Math.sqrt; -import static org.apache.datasketches.common.Util.checkBounds; -import static org.apache.datasketches.hll.PreambleUtil.HASH_SET_PREINTS; -import static org.apache.datasketches.hll.PreambleUtil.HLL_PREINTS; -import static org.apache.datasketches.hll.PreambleUtil.LIST_PREINTS; -import static org.apache.datasketches.hll.PreambleUtil.extractCurMode; -import static org.apache.datasketches.hll.PreambleUtil.extractFamilyId; -import static org.apache.datasketches.hll.PreambleUtil.extractPreInts; -import static org.apache.datasketches.hll.PreambleUtil.extractSerVer; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesReadOnlyException; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -final class HllUtil { - static final int KEY_BITS_26 = 26; - static final int VAL_BITS_6 = 6; - static final int KEY_MASK_26 = (1 << KEY_BITS_26) - 1; - static final int VAL_MASK_6 = (1 << VAL_BITS_6) - 1; - static final int EMPTY = 0; - static final int MIN_LOG_K = 4; - static final int MAX_LOG_K = 21; - - static final double HLL_HIP_RSE_FACTOR = sqrt(log(2.0)); //.8325546 - static final double HLL_NON_HIP_RSE_FACTOR = sqrt((3.0 * log(2.0)) - 1.0); //1.03896 - static final double COUPON_RSE_FACTOR = .409; //at transition point not the asymptote - - static final double COUPON_RSE = COUPON_RSE_FACTOR / (1 << 13); - - static final int LG_INIT_LIST_SIZE = 3; - static final int LG_INIT_SET_SIZE = 5; - static final int RESIZE_NUMER = 3; - static final int RESIZE_DENOM = 4; - - static final int loNibbleMask = 0x0f; - static final int hiNibbleMask = 0xf0; - static final int AUX_TOKEN = 0xf; - - /** - * Log2 table sizes for exceptions based on lgK from 0 to 26. - * However, only lgK from 4 to 21 are used. - */ - static final int[] LG_AUX_ARR_INTS = { - 0, 2, 2, 2, 2, 2, 2, 3, 3, 3, //0 - 9 - 4, 4, 5, 5, 6, 7, 8, 9, 10, 11, //10 - 19 - 12, 13, 14, 15, 16, 17, 18 //20 - 26 - }; - - //Checks - static int checkLgK(final int lgK) { - if ((lgK >= MIN_LOG_K) && (lgK <= MAX_LOG_K)) { return lgK; } - throw new SketchesArgumentException( - "Log K must be between 4 and 21, inclusive: " + lgK); - } - - static void checkSegSize(final long minBytes, final long capBytes) { - if (capBytes < minBytes) { - throw new SketchesArgumentException( - "Given MemorySegment is not large enough: " + capBytes); - } - } - - static void checkNumStdDev(final int numStdDev) { - if ((numStdDev < 1) || (numStdDev > 3)) { - throw new SketchesArgumentException( - "NumStdDev may not be less than 1 or greater than 3."); - } - } - - static CurMode checkPreamble(final MemorySegment seg) { - checkBounds(0, 8, seg.byteSize()); //need min 8 bytes - final int preInts = extractPreInts(seg); - checkBounds(0, (long)preInts * Integer.BYTES, seg.byteSize()); - final int serVer = extractSerVer(seg); - final int famId = extractFamilyId(seg); - final CurMode curMode = extractCurMode(seg); - if ( - (famId != Family.HLL.getID()) - || (serVer != 1) - || ((preInts != LIST_PREINTS) && (preInts != HASH_SET_PREINTS) && (preInts != HLL_PREINTS)) - || ((curMode == CurMode.LIST) && (preInts != LIST_PREINTS)) - || ((curMode == CurMode.SET) && (preInts != HASH_SET_PREINTS)) - || ((curMode == CurMode.HLL) && (preInts != HLL_PREINTS)) - ) { - throw new SketchesArgumentException("Possible Corruption, Invalid Preamble:" - + PreambleUtil.toString(seg)); - } - return curMode; - } - - //Exceptions - static void noWriteAccess() { - throw new SketchesReadOnlyException( - "This sketch is compact or does not have write access to the underlying resource."); - } - - //Used for thrown exceptions - static String pairString(final int pair) { - return "SlotNo: " + getPairLow26(pair) + ", Value: " - + getPairValue(pair); - } - - //Pairs - static int pair(final int slotNo, final int value) { - return (value << KEY_BITS_26) | (slotNo & KEY_MASK_26); - } - - static int getPairLow26(final int coupon) { - return coupon & KEY_MASK_26; - } - - static int getPairValue(final int coupon) { - return coupon >>> KEY_BITS_26; - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/IntArrayPairIterator.java b/src/main/java/org/apache/datasketches/hll/IntArrayPairIterator.java deleted file mode 100644 index 85603773c..000000000 --- a/src/main/java/org/apache/datasketches/hll/IntArrayPairIterator.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.HllUtil.EMPTY; - -/** - * Iterates over an on-heap integer array of pairs extracting - * the components of the pair at a given index. - * - * @author Lee Rhodes - */ -final class IntArrayPairIterator extends PairIterator { - private final int[] array; - private final int arrLen; - private final int slotMask; - private int index; - private int pair; - - //used by CouponList, HeapAuxHashMap - IntArrayPairIterator(final int[] array, final int lgConfigK) { - this.array = array; - slotMask = (1 << lgConfigK) - 1; - arrLen = array.length; - index = - 1; - } - - @Override - public int getIndex() { - return index; - } - - @Override - public int getKey() { - return HllUtil.getPairLow26(pair); - } - - @Override - public int getPair() { - return pair; - } - - @Override - public int getSlot() { - return getKey() & slotMask; - } - - @Override - public int getValue() { - return HllUtil.getPairValue(pair); - } - - @Override - public boolean nextAll() { - if (++index < arrLen) { - pair = array[index]; - return true; - } - return false; - } - - @Override - public boolean nextValid() { - while (++index < arrLen) { - final int pair = array[index]; - if (pair != EMPTY) { - this.pair = pair; - return true; - } - } - return false; - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/IntMemorySegmentPairIterator.java b/src/main/java/org/apache/datasketches/hll/IntMemorySegmentPairIterator.java deleted file mode 100644 index 7f510de18..000000000 --- a/src/main/java/org/apache/datasketches/hll/IntMemorySegmentPairIterator.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.hll.HllUtil.EMPTY; - -import java.lang.foreign.MemorySegment; - -/** - * Iterates within a given MemorySegment extracting integer pairs. - * - * @author Lee Rhodes - */ -final class IntMemorySegmentPairIterator extends PairIterator { - private final MemorySegment seg; - private final long offsetBytes; - private final int arrLen; - private final int slotMask; - private int index; - private int pair; - - //Used by DirectAuxHashMap, DirectCouponList - IntMemorySegmentPairIterator( - final MemorySegment seg, final long offsetBytes, final int arrayLength, final int lgConfigK) { - this.seg = seg; - this.offsetBytes = offsetBytes; - arrLen = arrayLength; - slotMask = (1 << lgConfigK) - 1; - index = -1; - } - - IntMemorySegmentPairIterator(final byte[] byteArr, final long offsetBytes, final int lengthPairs, - final int lgConfigK) { - this(MemorySegment.ofArray(byteArr), offsetBytes, lengthPairs, lgConfigK); - } - - @Override - public int getIndex() { - return index; - } - - @Override - public int getKey() { - return HllUtil.getPairLow26(pair); - } - - @Override - public int getPair() { - return pair; - } - - @Override - public int getSlot() { - return getKey() & slotMask; - } - - @Override - public int getValue() { - return HllUtil.getPairValue(pair); - } - - @Override - public boolean nextAll() { - if (++index < arrLen) { - pair = pair(); - return true; - } - return false; - } - - @Override - public boolean nextValid() { - while (++index < arrLen) { - final int pair = pair(); - if (pair != EMPTY) { - this.pair = pair; - return true; - } - } - return false; - } - - int pair() { - return seg.get(JAVA_INT_UNALIGNED, offsetBytes + (index << 2)); - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/PairIterator.java b/src/main/java/org/apache/datasketches/hll/PairIterator.java deleted file mode 100644 index 0282152a3..000000000 --- a/src/main/java/org/apache/datasketches/hll/PairIterator.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -/** - * @author Lee Rhodes - */ -abstract class PairIterator { - - /** - * Gets the header string for a list of pairs - * @return the header string for a list of pairs - */ - String getHeader() { - return String.format("%10s%10s%10s%6s", "Index", "Key", "Slot", "Value"); - } - - /** - * In LIST and SET modes, this gets the iterating index into the integer array of HLL key/value - * pairs. - * In HLL mode, this is the iterating index into the hypothetical array of HLL values, which may - * be physically contructed differently based on the compaction scheme (HLL_4, HLL_6, HLL_8). - * @return the index. - */ - abstract int getIndex(); - - /** - * Gets the key, the low 26 bits of an pair, and can be up to 26 bits in length. - * @return the key - */ - abstract int getKey(); - - /** - * Gets the key, value pair as a single int where the key is the lower 26 bits - * and the value is in the upper 6 bits. - * @return the key, value pair. - */ - abstract int getPair(); - - /** - * Gets the target or actual HLL slot number, which is derived from the key and LgConfigK. - * The slot number is the index into a hypothetical array of length K and has LgConfigK bits. - * If in LIST or SET mode this is the index into the hypothetical target HLL array of size K. - * In HLL mode, this will be the actual index into the hypothetical target HLL array of size K. - * @return the target or actual HLL slot number. - */ - abstract int getSlot(); - - /** - * Gets the current pair as a string - * @return the current pair as a string - */ - String getString() { - final int index = getIndex(); - final int key = getKey(); - final int slot = getSlot(); - final int value = getValue(); - return String.format("%10d%10d%10d%6d", index, key, slot, value); - } - - /** - * Gets the HLL value of a particular slot or pair. - * @return the HLL value of a particular slot or pair. - */ - abstract int getValue(); - - /** - * Returns true at the next pair in sequence. - * If false, the iteration is done. - * @return true at the next pair in sequence. - */ - abstract boolean nextAll(); - - /** - * Returns true at the next pair where getKey() and getValue() are valid. - * If false, the iteration is done. - * @return true at the next pair where getKey() and getValue() are valid. - */ - abstract boolean nextValid(); - -} diff --git a/src/main/java/org/apache/datasketches/hll/PreambleUtil.java b/src/main/java/org/apache/datasketches/hll/PreambleUtil.java deleted file mode 100644 index b86b65fc6..000000000 --- a/src/main/java/org/apache/datasketches/hll/PreambleUtil.java +++ /dev/null @@ -1,465 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.common.Util.exactLog2OfLong; -import static org.apache.datasketches.common.Util.zeroPad; -import static org.apache.datasketches.hll.HllUtil.LG_AUX_ARR_INTS; -import static org.apache.datasketches.hll.HllUtil.LG_INIT_SET_SIZE; -import static org.apache.datasketches.hll.HllUtil.RESIZE_DENOM; -import static org.apache.datasketches.hll.HllUtil.RESIZE_NUMER; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; - -//@formatter:off -/** - *

- * CouponList Layout
- * Long || Start Byte Adr, Big Endian Illustration
- * Adr:
- *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |    0   |
- *  0   ||  Mode  | ListCnt| Flags  |  LgArr |   lgK  | FamID  | SerVer |  PI=2  |
- *
- *      ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |    8   |
- *  1   ||                                   |------Coupon Int List Start--------|
- * 
- * - *
- * CouponHashSet Layout
- * Long || Start Byte Adr, Big Endian Illustration
- * Adr:
- *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |    0   |
- *  0   ||  Mode  |        | Flags  |  LgArr |   lgK  | FamID  | SerVer |  PI=3  |
- *
- *      ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |    8   |
- *  1   ||-----Coupon Int Hash Set Start-----|---------Hash Set Count------------|
- * 
- * - *
- * HllArray Layout
- * Long || Start Byte Adr, Big Endian Illustration
- * Adr:
- *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |    0   |
- *  0   ||  Mode  | CurMin | Flags  |  LgArr |   lgK  | FamID  | SerVer | PI=10  |
- *
- *      ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |    8   |
- *  1   ||-------------------------------HIP Accum-------------------------------|
- *
- *      ||   23   |   22   |   21   |   20   |   19   |   18   |   17   |   16   |
- *  2   ||----------------------------------KxQ0---------------------------------|
- *
- *      ||   31   |   30   |   29   |   28   |   27   |   26   |   25   |   24   |
- *  3   ||----------------------------------KxQ1---------------------------------|
- *
- *      ||   39   |   38   |   37   |   36   |   35   |   34   |   33   |   32   |
- *  4   ||-------------Aux Count-------------|----------Num At Cur Min-----------|
- *
- *      ||   47   |   46   |   45   |   44   |   43   |   42   |   41   |   40   |
- *  5   ||...................................|------Start of HLL_X Byte Array----|
- *
- *  N   ||----End of Byte Array for HLL_4----|...................................|
- *  N+1 ||...................................|-----Start of Aux Array for HLL_4--|
- * 
- * If in compact form exceptions array will be compacted. - * - * @author Lee Rhodes - */ -final class PreambleUtil { - - private PreambleUtil() {} - - // ###### DO NOT MESS WITH THIS ... - // Preamble byte start addresses - // First 8 Bytes: - static int PREAMBLE_INTS_BYTE = 0; - static int SER_VER_BYTE = 1; - static int FAMILY_BYTE = 2; - static int LG_K_BYTE = 3; - static int LG_ARR_BYTE = 4; //used for LIST, SET & HLL_4 - static int FLAGS_BYTE = 5; - static int LIST_COUNT_BYTE = 6; - static int HLL_CUR_MIN_BYTE = 6; - static int MODE_BYTE = 7; //lo2bits = curMode, next 2 bits = tgtHllType - //mode encoding of combined CurMode and TgtHllType: - // Dec Lo4Bits TgtHllType, CurMode - // 0 0000 HLL_4, LIST - // 1 0001 HLL_4, SET - // 2 0010 HLL_4, HLL - // 4 0100 HLL_6, LIST - // 5 0101 HLL_6, SET - // 6 0110 HLL_6, HLL - // 8 1000 HLL_8, LIST - // 9 1001 HLL_8, SET - // 10 1010 HLL_8, HLL - - //Coupon List - static int LIST_INT_ARR_START = 8; - - //Coupon Hash Set - static int HASH_SET_COUNT_INT = 8; - static int HASH_SET_INT_ARR_START = 12; - - //HLL - static int HIP_ACCUM_DOUBLE = 8; - static int KXQ0_DOUBLE = 16; - static int KXQ1_DOUBLE = 24; - static int CUR_MIN_COUNT_INT = 32; - static int AUX_COUNT_INT = 36; - static int HLL_BYTE_ARR_START = 40; - - //Flag bit masks - static final int RESERVED_FLAG_MASK = 1; //Set to 0 but not read. - static final int READ_ONLY_FLAG_MASK = 2; //Set but not read. Reserved. - static final int EMPTY_FLAG_MASK = 4; - static final int COMPACT_FLAG_MASK = 8; - static final int OUT_OF_ORDER_FLAG_MASK = 16; - static final int REBUILD_CURMIN_NUM_KXQ_MASK = 32; //used only by HllUnion - - //Mode byte masks - static final int CUR_MODE_MASK = 3; - static final int TGT_HLL_TYPE_MASK = 12; - - //Other constants - static final int SER_VER = 1; - static final int FAMILY_ID = 7; - static final int LIST_PREINTS = 2; - static final int HASH_SET_PREINTS = 3; - static final int HLL_PREINTS = 10; - - static String toString(final byte[] byteArr) { - final MemorySegment seg = MemorySegment.ofArray(byteArr); - return toString(seg); - } - - static String toString(final MemorySegment seg) { - //First 8 bytes - final int preInts = seg.get(JAVA_BYTE, PREAMBLE_INTS_BYTE); - final int serVer = seg.get(JAVA_BYTE, SER_VER_BYTE); - final Family family = Family.idToFamily(seg.get(JAVA_BYTE, FAMILY_BYTE)); - final int lgK = seg.get(JAVA_BYTE, LG_K_BYTE); - final int lgArr = seg.get(JAVA_BYTE, LG_ARR_BYTE); - final int flags = seg.get(JAVA_BYTE, FLAGS_BYTE); - //Flags - final String flagsStr = zeroPad(Integer.toBinaryString(flags), 8) + ", " + (flags); - final boolean compact = (flags & COMPACT_FLAG_MASK) > 0; - final boolean oooFlag = (flags & OUT_OF_ORDER_FLAG_MASK) > 0; - final boolean readOnly = (flags & READ_ONLY_FLAG_MASK) > 0; - final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; - final boolean rebuildKxQ = (flags & REBUILD_CURMIN_NUM_KXQ_MASK) > 0; - - final int hllCurMin = seg.get(JAVA_BYTE, HLL_CUR_MIN_BYTE); - final int listCount = hllCurMin; - final int modeByte = seg.get(JAVA_BYTE, MODE_BYTE); - final CurMode curMode = CurMode.fromOrdinal(modeByte & 3); - final TgtHllType tgtHllType = TgtHllType.fromOrdinal((modeByte >>> 2) & 3); - - double hipAccum = 0; - double kxq0 = 0; - double kxq1 = 0; - int hashSetCount = 0; - int curMinCount = 0; - int exceptionCount = 0; - - if (curMode == CurMode.SET) { - hashSetCount = seg.get(JAVA_INT_UNALIGNED, HASH_SET_COUNT_INT); - } - else if (curMode == CurMode.HLL) { - hipAccum = seg.get(JAVA_DOUBLE_UNALIGNED, HIP_ACCUM_DOUBLE); - kxq0 = seg.get(JAVA_DOUBLE_UNALIGNED, KXQ0_DOUBLE); - kxq1 = seg.get(JAVA_DOUBLE_UNALIGNED, KXQ1_DOUBLE); - curMinCount = seg.get(JAVA_INT_UNALIGNED, CUR_MIN_COUNT_INT); - exceptionCount = seg.get(JAVA_INT_UNALIGNED, AUX_COUNT_INT); - } - - final StringBuilder sb = new StringBuilder(); - sb.append(LS); - sb.append("### HLL SKETCH PREAMBLE:").append(LS); - sb.append("Byte 0: Preamble Ints : ").append(preInts).append(LS); - sb.append("Byte 1: SerVer : ").append(serVer).append(LS); - sb.append("Byte 2: Family : ").append(family).append(LS); - sb.append("Byte 3: lgK : ").append(lgK).append(LS); - //expand byte 4: LgArr - if (curMode == CurMode.LIST) { - sb.append("Byte 4: LgArr: List Arr : ").append(lgArr).append(LS); - } - if (curMode == CurMode.SET) { - sb.append("Byte 4: LgArr: Hash Set Arr : ").append(lgArr).append(LS); - } - if (curMode == CurMode.HLL) { - sb.append("Byte 4: LgArr or Aux LgArr : ").append(lgArr).append(LS); - } - //expand byte 5: Flags - sb.append("Byte 5: Flags: : ").append(flagsStr).append(LS); - sb.append(" READ_ONLY : ").append(readOnly).append(LS); - sb.append(" EMPTY : ").append(empty).append(LS); - sb.append(" COMPACT : ").append(compact).append(LS); - sb.append(" OUT_OF_ORDER : ").append(oooFlag).append(LS); - sb.append(" REBUILD_KXQ : ").append(rebuildKxQ).append(LS); - //expand byte 6: ListCount, CurMin - if (curMode == CurMode.LIST) { - sb.append("Byte 6: List Count/CurMin : ").append(listCount).append(LS); - } - if (curMode == CurMode.SET) { - sb.append("Byte 6: (not used) : ").append(LS); - } - if (curMode == CurMode.HLL) { - sb.append("Byte 6: Cur Min : ").append(hllCurMin).append(LS); - } - final String modes = curMode.toString() + ", " + tgtHllType.toString(); - sb.append("Byte 7: Mode : ").append(modes).append(LS); - if (curMode == CurMode.SET) { - sb.append("Hash Set Count : ").append(hashSetCount).append(LS); - } - if (curMode == CurMode.HLL) { - sb.append("HIP Accum : ").append(hipAccum).append(LS); - sb.append("KxQ0 : ").append(kxq0).append(LS); - sb.append("KxQ1 : ").append(kxq1).append(LS); - sb.append("Num At Cur Min : ").append(curMinCount).append(LS); - sb.append("Aux Count : ").append(exceptionCount).append(LS); - } - sb.append("### END HLL SKETCH PREAMBLE").append(LS); - return sb.toString(); - } - //@formatter:on - - static int extractPreInts(final MemorySegment seg) { - return seg.get(JAVA_BYTE, PREAMBLE_INTS_BYTE) & 0X3F; - } - - static void insertPreInts(final MemorySegment wseg, final int preInts) { - wseg.set(JAVA_BYTE, PREAMBLE_INTS_BYTE, (byte) (preInts & 0X3F)); - } - - static int extractSerVer(final MemorySegment seg) { - return seg.get(JAVA_BYTE, SER_VER_BYTE) & 0XFF; - } - - static void insertSerVer(final MemorySegment wseg) { - wseg.set(JAVA_BYTE, SER_VER_BYTE, (byte) SER_VER); - } - - static int extractFamilyId(final MemorySegment seg) { - return seg.get(JAVA_BYTE, FAMILY_BYTE) & 0XFF; - } - - static void insertFamilyId(final MemorySegment wseg) { - wseg.set(JAVA_BYTE, FAMILY_BYTE, (byte) FAMILY_ID); - } - - static int extractLgK(final MemorySegment seg) { - return seg.get(JAVA_BYTE, LG_K_BYTE) & 0XFF; - } - - static void insertLgK(final MemorySegment wseg, final int lgK) { - wseg.set(JAVA_BYTE, LG_K_BYTE, (byte) lgK); - } - - static int extractLgArr(final MemorySegment seg) { - return seg.get(JAVA_BYTE, LG_ARR_BYTE) & 0XFF; - } - - static void insertLgArr(final MemorySegment wseg, final int lgArr) { - wseg.set(JAVA_BYTE, LG_ARR_BYTE, (byte) lgArr); - } - - static int extractListCount(final MemorySegment seg) { - return seg.get(JAVA_BYTE, LIST_COUNT_BYTE) & 0XFF; - } - - static void insertListCount(final MemorySegment wseg, final int listCnt) { - wseg.set(JAVA_BYTE, LIST_COUNT_BYTE, (byte) listCnt); - } - - static int extractCurMin(final MemorySegment seg) { - return seg.get(JAVA_BYTE, HLL_CUR_MIN_BYTE) & 0XFF; - } - - static void insertCurMin(final MemorySegment wseg, final int curMin) { - wseg.set(JAVA_BYTE, HLL_CUR_MIN_BYTE, (byte) curMin); - } - - static double extractHipAccum(final MemorySegment seg) { - return seg.get(JAVA_DOUBLE_UNALIGNED, HIP_ACCUM_DOUBLE); - } - - static void insertHipAccum(final MemorySegment wseg, final double hipAccum) { - wseg.set(JAVA_DOUBLE_UNALIGNED, HIP_ACCUM_DOUBLE, hipAccum); - } - - static double extractKxQ0(final MemorySegment seg) { - return seg.get(JAVA_DOUBLE_UNALIGNED, KXQ0_DOUBLE); - } - - static void insertKxQ0(final MemorySegment wseg, final double kxq0) { - wseg.set(JAVA_DOUBLE_UNALIGNED, KXQ0_DOUBLE, kxq0); - } - - static double extractKxQ1(final MemorySegment seg) { - return seg.get(JAVA_DOUBLE_UNALIGNED, KXQ1_DOUBLE); - } - - static void insertKxQ1(final MemorySegment wseg, final double kxq1) { - wseg.set(JAVA_DOUBLE_UNALIGNED, KXQ1_DOUBLE, kxq1); - } - - static int extractHashSetCount(final MemorySegment seg) { - return seg.get(JAVA_INT_UNALIGNED, HASH_SET_COUNT_INT); - } - - static void insertHashSetCount(final MemorySegment wseg, final int hashSetCnt) { - wseg.set(JAVA_INT_UNALIGNED, HASH_SET_COUNT_INT, hashSetCnt); - } - - static int extractNumAtCurMin(final MemorySegment seg) { - return seg.get(JAVA_INT_UNALIGNED, CUR_MIN_COUNT_INT); - } - - static void insertNumAtCurMin(final MemorySegment wseg, final int numAtCurMin) { - wseg.set(JAVA_INT_UNALIGNED, CUR_MIN_COUNT_INT, numAtCurMin); - } - - static int extractAuxCount(final MemorySegment seg) { - return seg.get(JAVA_INT_UNALIGNED, AUX_COUNT_INT); - } - - static void insertAuxCount(final MemorySegment wseg, final int auxCount) { - wseg.set(JAVA_INT_UNALIGNED, AUX_COUNT_INT, auxCount); - } - - //Mode bits - static void insertCurMode(final MemorySegment wseg, final CurMode curMode) { - final int curModeId = curMode.ordinal(); - int mode = wseg.get(JAVA_BYTE, MODE_BYTE) & ~CUR_MODE_MASK; //strip bits 0, 1 - mode |= (curModeId & CUR_MODE_MASK); - wseg.set(JAVA_BYTE, MODE_BYTE, (byte) mode); - } - - static CurMode extractCurMode(final MemorySegment seg) { - final int curModeId = seg.get(JAVA_BYTE, MODE_BYTE) & CUR_MODE_MASK; - return CurMode.fromOrdinal(curModeId); - } - - static void insertTgtHllType(final MemorySegment wseg, final TgtHllType tgtHllType) { - final int typeId = tgtHllType.ordinal(); - int mode = wseg.get(JAVA_BYTE, MODE_BYTE) & ~TGT_HLL_TYPE_MASK; //strip bits 2, 3 - mode |= (typeId << 2) & TGT_HLL_TYPE_MASK; - wseg.set(JAVA_BYTE, MODE_BYTE, (byte) mode); - } - - static TgtHllType extractTgtHllType(final MemorySegment seg) { - final int typeId = seg.get(JAVA_BYTE, MODE_BYTE) & TGT_HLL_TYPE_MASK; - return TgtHllType.fromOrdinal(typeId >>> 2); - } - - static void insertModes(final MemorySegment wseg, final TgtHllType tgtHllType, - final CurMode curMode) { - final int curModeId = curMode.ordinal() & 3; - final int typeId = (tgtHllType.ordinal() & 3) << 2; - final int mode = typeId | curModeId; - wseg.set(JAVA_BYTE, MODE_BYTE, (byte) mode); - } - - //Flags - static void insertEmptyFlag(final MemorySegment wseg, final boolean empty) { - int flags = wseg.get(JAVA_BYTE, FLAGS_BYTE); - if (empty) { flags |= EMPTY_FLAG_MASK; } - else { flags &= ~EMPTY_FLAG_MASK; } - wseg.set(JAVA_BYTE, FLAGS_BYTE, (byte) flags); - } - - static boolean extractEmptyFlag(final MemorySegment seg) { - final int flags = seg.get(JAVA_BYTE, FLAGS_BYTE); - return (flags & EMPTY_FLAG_MASK) > 0; - } - - static void insertCompactFlag(final MemorySegment wseg, final boolean compact) { - int flags = wseg.get(JAVA_BYTE, FLAGS_BYTE); - if (compact) { flags |= COMPACT_FLAG_MASK; } - else { flags &= ~COMPACT_FLAG_MASK; } - wseg.set(JAVA_BYTE, FLAGS_BYTE, (byte) flags); - } - - static boolean extractCompactFlag(final MemorySegment seg) { - final int flags = seg.get(JAVA_BYTE, FLAGS_BYTE); - return (flags & COMPACT_FLAG_MASK) > 0; - } - - static void insertOooFlag(final MemorySegment wseg, final boolean oooFlag) { - int flags = wseg.get(JAVA_BYTE, FLAGS_BYTE); - if (oooFlag) { flags |= OUT_OF_ORDER_FLAG_MASK; } - else { flags &= ~OUT_OF_ORDER_FLAG_MASK; } - wseg.set(JAVA_BYTE, FLAGS_BYTE, (byte) flags); - } - - static boolean extractOooFlag(final MemorySegment seg) { - final int flags = seg.get(JAVA_BYTE, FLAGS_BYTE); - return (flags & OUT_OF_ORDER_FLAG_MASK) > 0; - } - - static void insertRebuildCurMinNumKxQFlag(final MemorySegment wseg, final boolean rebuild) { - int flags = wseg.get(JAVA_BYTE, FLAGS_BYTE); - if (rebuild) { flags |= REBUILD_CURMIN_NUM_KXQ_MASK; } - else { flags &= ~REBUILD_CURMIN_NUM_KXQ_MASK; } - wseg.set(JAVA_BYTE, FLAGS_BYTE, (byte) flags); - } - - static boolean extractRebuildCurMinNumKxQFlag(final MemorySegment seg) { - final int flags = seg.get(JAVA_BYTE, FLAGS_BYTE); - return (flags & REBUILD_CURMIN_NUM_KXQ_MASK) > 0; - } - - static void insertFlags(final MemorySegment wseg, final int flags) { - wseg.set(JAVA_BYTE, FLAGS_BYTE, (byte) flags); - } - - static int extractFlags(final MemorySegment seg) { - return seg.get(JAVA_BYTE, FLAGS_BYTE) & 0XFF; - } - - //Other - static int extractInt(final MemorySegment seg, final long byteOffset) { - return seg.get(JAVA_INT_UNALIGNED, byteOffset); - } - - static void insertInt(final MemorySegment wseg, final long byteOffset, final int value) { - wseg.set(JAVA_INT_UNALIGNED, byteOffset, value); - } - - static int computeLgArr(final MemorySegment seg, final int count, final int lgConfigK) { - //value is missing, recompute - final CurMode curMode = extractCurMode(seg); - if (curMode == CurMode.LIST) { return HllUtil.LG_INIT_LIST_SIZE; } - int ceilPwr2 = ceilingPowerOf2(count); - if ((RESIZE_DENOM * count) > (RESIZE_NUMER * ceilPwr2)) { ceilPwr2 <<= 1; } - if (curMode == CurMode.SET) { - return Math.max(LG_INIT_SET_SIZE, exactLog2OfLong(ceilPwr2)); - } - //only used for HLL4 - return Math.max(LG_AUX_ARR_INTS[lgConfigK], exactLog2OfLong(ceilPwr2)); - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/RelativeErrorTables.java b/src/main/java/org/apache/datasketches/hll/RelativeErrorTables.java deleted file mode 100644 index 5a167f996..000000000 --- a/src/main/java/org/apache/datasketches/hll/RelativeErrorTables.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -final class RelativeErrorTables { - - /** - * Return Relative Error for UB or LB for HIP or Non-HIP as a function of numStdDev. - * @param upperBound true if for upper bound - * @param oooFlag true if for Non-HIP - * @param lgK must be between 4 and 12 inclusive - * @param stdDev must be between 1 and 3 inclusive - * @return Relative Error for UB or LB for HIP or Non-HIP as a function of numStdDev. - */ - static double getRelErr(final boolean upperBound, final boolean oooFlag, - final int lgK, final int stdDev) { - final int idx = ((lgK - 4) * 3) + (stdDev - 1); - final int sw = (oooFlag ? 2 : 0) | (upperBound ? 1 : 0); - double f = 0; - switch (sw) { - case 0 : { //HIP, LB - f = HIP_LB[idx]; - break; - } - case 1 : { //HIP, UB - f = HIP_UB[idx]; - break; - } - case 2 : { //NON_HIP, LB - f = NON_HIP_LB[idx]; - break; - } - case 3 : { //NON_HIP, UB - f = NON_HIP_UB[idx]; - break; - } - default: f = 0;//can't happen - } - return f; - } - - //case 0 - private static double[] HIP_LB = //sd 1, 2, 3 - { //Q(.84134), Q(.97725), Q(.99865) respectively - 0.207316195, 0.502865572, 0.882303765, //4 - 0.146981579, 0.335426881, 0.557052, //5 - 0.104026721, 0.227683872, 0.365888317, //6 - 0.073614601, 0.156781585, 0.245740374, //7 - 0.05205248, 0.108783763, 0.168030442, //8 - 0.036770852, 0.075727545, 0.11593785, //9 - 0.025990219, 0.053145536, 0.080772263, //10 - 0.018373987, 0.037266176, 0.056271814, //11 - 0.012936253, 0.02613829, 0.039387631, //12 - }; - - //case 1 - private static double[] HIP_UB = //sd 1, 2, 3 - { //Q(.15866), Q(.02275), Q(.00135) respectively - -0.207805347, -0.355574279, -0.475535095, //4 - -0.146988328, -0.262390832, -0.360864026, //5 - -0.103877775, -0.191503663, -0.269311582, //6 - -0.073452978, -0.138513438, -0.198487447, //7 - -0.051982806, -0.099703123, -0.144128618, //8 - -0.036768609, -0.07138158, -0.104430324, //9 - -0.025991325, -0.050854296, -0.0748143, //10 - -0.01834533, -0.036121138, -0.05327616, //11 - -0.012920332, -0.025572893, -0.037896952, //12 - }; - - //case 2 - private static double[] NON_HIP_LB = //sd 1, 2, 3 - { //Q(.84134), Q(.97725), Q(.99865) respectively - 0.254409839, 0.682266712, 1.304022158, //4 - 0.181817353, 0.443389054, 0.778776219, //5 - 0.129432281, 0.295782195, 0.49252279, //6 - 0.091640655, 0.201175925, 0.323664385, //7 - 0.064858051, 0.138523393, 0.218805328, //8 - 0.045851855, 0.095925072, 0.148635751, //9 - 0.032454144, 0.067009668, 0.102660669, //10 - 0.022921382, 0.046868565, 0.071307398, //11 - 0.016155679, 0.032825719, 0.049677541 //12 - }; - - //case 3 - private static double[] NON_HIP_UB = //sd 1, 2, 3 - { //Q(.15866), Q(.02275), Q(.00135) respectively - -0.256980172, -0.411905944, -0.52651057, //4 - -0.182332109, -0.310275547, -0.412660505, //5 - -0.129314228, -0.230142294, -0.315636197, //6 - -0.091584836, -0.16834013, -0.236346847, //7 - -0.06487411, -0.122045231, -0.174112107, //8 - -0.04591465, -0.08784505, -0.126917615, //9 - -0.032433119, -0.062897613, -0.091862929, //10 - -0.022960633, -0.044875401, -0.065736049, //11 - -0.016186662, -0.031827816, -0.046973459 //12 - }; - -} diff --git a/src/main/java/org/apache/datasketches/hll/TgtHllType.java b/src/main/java/org/apache/datasketches/hll/TgtHllType.java deleted file mode 100644 index 78aaafd1b..000000000 --- a/src/main/java/org/apache/datasketches/hll/TgtHllType.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -/** - * Specifies the target type of HLL sketch to be created. It is a target in that the actual - * allocation of the HLL array is deferred until sufficient number of items have been received by - * the warm-up phases. - * - *

These three target types are isomorphic representations of the same underlying HLL algorithm. - * Thus, given the same value of lgConfigK and the same input, all three HLL target types - * will produce identical estimates and have identical error distributions.

- * - *

The memory usage and the serialization size of the sketch during this early warmup phase starts - * out very small (8 bytes, when empty) and then grows in increments of 4 bytes as required - * until the full HLL array is allocated. This transition point occurs at about 10% of K for - * sketches where lgConfigK is > 8.

- * - *
    - *
  • HLL 8 This uses an 8-bit byte per HLL bucket. It is generally the - * fastest in terms of update time, but has the largest storage footprint of about - * K bytes.
  • - * - *
  • HLL 6 This uses a 6-bit field per HLL bucket. It is the generally the next fastest - * in terms of update time with a storage footprint of about 3/4 * K bytes.
  • - * - *
  • HLL 4 This uses a 4-bit field per HLL bucket and for large counts may require - * the use of a small internal auxiliary array for storing statistical exceptions, which are rare. - * For the values of lgConfigK > 13 (K = 8192), - * this additional array adds about 3% to the overall storage. It is generally the slowest in - * terms of update time, but has the smallest storage footprint of about - * K/2 * 1.03 bytes.
  • - *
- * @author Lee Rhodes - */ -public enum TgtHllType { - /** - * An HLL sketch with a bin size of 4 bits - */ - HLL_4, - /** - * An HLL sketch with a bin size of 6 bits - */ - HLL_6, - /** - * An HLL Sketch with a bin size of 8 bits - */ - HLL_8; - - private static final TgtHllType values[] = values(); - - /** - * Convert the typeId to the enum type - * @param typeId the given typeId - * @return the enum type - */ - public static final TgtHllType fromOrdinal(final int typeId) { - return values[typeId]; - } -} diff --git a/src/main/java/org/apache/datasketches/hll/ToByteArrayImpl.java b/src/main/java/org/apache/datasketches/hll/ToByteArrayImpl.java deleted file mode 100644 index 4b0c6a96e..000000000 --- a/src/main/java/org/apache/datasketches/hll/ToByteArrayImpl.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.hll.AbstractCoupons.find; -import static org.apache.datasketches.hll.HllUtil.LG_AUX_ARR_INTS; -import static org.apache.datasketches.hll.PreambleUtil.AUX_COUNT_INT; -import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.insertAuxCount; -import static org.apache.datasketches.hll.PreambleUtil.insertCompactFlag; -import static org.apache.datasketches.hll.PreambleUtil.insertCurMin; -import static org.apache.datasketches.hll.PreambleUtil.insertCurMode; -import static org.apache.datasketches.hll.PreambleUtil.insertEmptyFlag; -import static org.apache.datasketches.hll.PreambleUtil.insertFamilyId; -import static org.apache.datasketches.hll.PreambleUtil.insertHashSetCount; -import static org.apache.datasketches.hll.PreambleUtil.insertHipAccum; -import static org.apache.datasketches.hll.PreambleUtil.insertInt; -import static org.apache.datasketches.hll.PreambleUtil.insertKxQ0; -import static org.apache.datasketches.hll.PreambleUtil.insertKxQ1; -import static org.apache.datasketches.hll.PreambleUtil.insertLgArr; -import static org.apache.datasketches.hll.PreambleUtil.insertLgK; -import static org.apache.datasketches.hll.PreambleUtil.insertListCount; -import static org.apache.datasketches.hll.PreambleUtil.insertNumAtCurMin; -import static org.apache.datasketches.hll.PreambleUtil.insertOooFlag; -import static org.apache.datasketches.hll.PreambleUtil.insertPreInts; -import static org.apache.datasketches.hll.PreambleUtil.insertRebuildCurMinNumKxQFlag; -import static org.apache.datasketches.hll.PreambleUtil.insertSerVer; -import static org.apache.datasketches.hll.PreambleUtil.insertTgtHllType; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * @author Lee Rhodes - */ -final class ToByteArrayImpl { - - // To byte array used by the heap HLL modes. - static byte[] toHllByteArray(final AbstractHllArray impl, final boolean compact) { - int auxBytes = 0; - if (impl.tgtHllType == TgtHllType.HLL_4) { - final AuxHashMap auxHashMap = impl.getAuxHashMap(); - if (auxHashMap != null) { - auxBytes = (compact) - ? auxHashMap.getCompactSizeBytes() - : auxHashMap.getUpdatableSizeBytes(); - } else { - auxBytes = (compact) ? 0 : 4 << LG_AUX_ARR_INTS[impl.lgConfigK]; - } - } - final int totBytes = HLL_BYTE_ARR_START + impl.getHllByteArrBytes() + auxBytes; - final byte[] byteArr = new byte[totBytes]; - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - insertHll(impl, wseg, compact); - return byteArr; - } - - private static void insertHll(final AbstractHllArray impl, final MemorySegment wseg, - final boolean compact) { - insertCommonHll(impl, wseg, compact); - final byte[] hllByteArr = ((HllArray)impl).hllByteArr; - MemorySegment.copy(hllByteArr, 0, wseg, JAVA_BYTE, HLL_BYTE_ARR_START, hllByteArr.length); - if (impl.getAuxHashMap() != null) { - insertAux(impl, wseg, compact); - } else { - wseg.set(JAVA_INT_UNALIGNED, AUX_COUNT_INT, 0); - } - } - - private static void insertCommonHll(final AbstractHllArray srcImpl, - final MemorySegment tgtWseg, final boolean compact) { - insertPreInts(tgtWseg, srcImpl.getPreInts()); - insertSerVer(tgtWseg); - insertFamilyId(tgtWseg); - insertLgK(tgtWseg, srcImpl.getLgConfigK()); - insertEmptyFlag(tgtWseg, srcImpl.isEmpty()); - insertCompactFlag(tgtWseg, compact); - insertOooFlag(tgtWseg, srcImpl.isOutOfOrder()); - insertCurMin(tgtWseg, srcImpl.getCurMin()); - insertCurMode(tgtWseg, srcImpl.getCurMode()); - insertTgtHllType(tgtWseg, srcImpl.getTgtHllType()); - insertHipAccum(tgtWseg, srcImpl.getHipAccum()); - insertKxQ0(tgtWseg, srcImpl.getKxQ0()); - insertKxQ1(tgtWseg, srcImpl.getKxQ1()); - insertNumAtCurMin(tgtWseg, srcImpl.getNumAtCurMin()); - insertRebuildCurMinNumKxQFlag(tgtWseg, srcImpl.isRebuildCurMinNumKxQFlag()); - } - - private static void insertAux(final AbstractHllArray srcImpl, final MemorySegment tgtWseg, - final boolean tgtCompact) { - final AuxHashMap auxHashMap = srcImpl.getAuxHashMap(); - final int auxCount = auxHashMap.getAuxCount(); - insertAuxCount(tgtWseg, auxCount); - insertLgArr(tgtWseg, auxHashMap.getLgAuxArrInts()); //only used for direct HLL - final long auxStart = srcImpl.auxStart; - if (tgtCompact) { - final PairIterator itr = auxHashMap.getIterator(); - int cnt = 0; - while (itr.nextValid()) { //works whether src has compact MemorySegment or not - insertInt(tgtWseg, auxStart + (cnt++ << 2), itr.getPair()); - } - assert cnt == auxCount; - } else { //updatable - final int auxInts = 1 << auxHashMap.getLgAuxArrInts(); - final int[] auxArr = auxHashMap.getAuxIntArr(); - MemorySegment.copy(auxArr, 0, tgtWseg, JAVA_INT_UNALIGNED, auxStart, auxInts); - } - } - - //To byte array for coupons - static byte[] toCouponByteArray(final AbstractCoupons impl, final boolean dstCompact) { - final int srcCouponCount = impl.getCouponCount(); - final int srcLgCouponArrInts = impl.getLgCouponArrInts(); - final int srcCouponArrInts = 1 << srcLgCouponArrInts; - final byte[] byteArrOut; - final boolean list = impl.getCurMode() == CurMode.LIST; - //prepare switch - final int sw = (impl.hasMemorySegment() ? 0 : 4) | (impl.isCompact() ? 0 : 2) | (dstCompact ? 0 : 1); - switch (sw) { - case 0: { //Src MemorySegment, Src Compact, Dst Compact - final MemorySegment srcSeg = impl.getMemorySegment(); - final int bytesOut = impl.getSegDataStart() + (srcCouponCount << 2); - byteArrOut = new byte[bytesOut]; - MemorySegment.copy(srcSeg, JAVA_BYTE, 0, byteArrOut, 0, bytesOut); - break; - } - case 1: { //Src MemorySegment, Src Compact, Dst Updatable - final int dataStart = impl.getSegDataStart(); - final int bytesOut = dataStart + (srcCouponArrInts << 2); - byteArrOut = new byte[bytesOut]; - final MemorySegment segOut = MemorySegment.ofArray(byteArrOut); - copyCommonListAndSet(impl, segOut); - insertCompactFlag(segOut, dstCompact); - - final int[] tgtCouponIntArr = new int[srcCouponArrInts]; - final PairIterator itr = impl.iterator(); - while (itr.nextValid()) { - final int pair = itr.getPair(); - final int idx = find(tgtCouponIntArr, srcLgCouponArrInts, pair); - if (idx < 0) { //found EMPTY - tgtCouponIntArr[~idx] = pair; //insert - continue; - } - throw new SketchesStateException("Error: found duplicate."); - } - MemorySegment.copy(tgtCouponIntArr, 0, segOut, JAVA_INT_UNALIGNED, dataStart, srcCouponArrInts); - - if (list) { - insertListCount(segOut, srcCouponCount); - } else { - insertHashSetCount(segOut, srcCouponCount); - } - break; - } - - case 6: //Src Heap, Src Updatable, Dst Compact - case 2: { //Src MemorySegment, Src Updatable, Dst Compact - final int dataStart = impl.getSegDataStart(); - final int bytesOut = dataStart + (srcCouponCount << 2); - byteArrOut = new byte[bytesOut]; - final MemorySegment segOut = MemorySegment.ofArray(byteArrOut); - copyCommonListAndSet(impl, segOut); - insertCompactFlag(segOut, dstCompact); - - final PairIterator itr = impl.iterator(); - int cnt = 0; - while (itr.nextValid()) { - insertInt(segOut, dataStart + (cnt++ << 2), itr.getPair()); - } - if (list) { - insertListCount(segOut, srcCouponCount); - } else { - insertHashSetCount(segOut, srcCouponCount); - } - break; - } - case 3: { //Src MemorySegment, Src Updatable, Dst Updatable - final MemorySegment srcSeg = impl.getMemorySegment(); - final int bytesOut = impl.getSegDataStart() + (srcCouponArrInts << 2); - byteArrOut = new byte[bytesOut]; - MemorySegment.copy(srcSeg, JAVA_BYTE, 0, byteArrOut, 0, bytesOut); - break; - } - case 7: { //Src Heap, Src Updatable, Dst Updatable - final int dataStart = impl.getSegDataStart(); - final int bytesOut = dataStart + (srcCouponArrInts << 2); - byteArrOut = new byte[bytesOut]; - final MemorySegment segOut = MemorySegment.ofArray(byteArrOut); - copyCommonListAndSet(impl, segOut); - - MemorySegment.copy(impl.getCouponIntArr(), 0, segOut, JAVA_INT_UNALIGNED, dataStart, srcCouponArrInts); - if (list) { - insertListCount(segOut, srcCouponCount); - } else { - insertHashSetCount(segOut, srcCouponCount); - } - break; - } - default: throw new SketchesStateException("Corruption, should not happen: " + sw); - } - return byteArrOut; - } - - private static void copyCommonListAndSet(final AbstractCoupons impl, - final MemorySegment wseg) { - insertPreInts(wseg, impl.getPreInts()); - insertSerVer(wseg); - insertFamilyId(wseg); - insertLgK(wseg, impl.getLgConfigK()); - insertLgArr(wseg, impl.getLgCouponArrInts()); - insertEmptyFlag(wseg, impl.isEmpty()); - insertOooFlag(wseg, impl.isOutOfOrder()); - insertCurMode(wseg, impl.getCurMode()); - insertTgtHllType(wseg, impl.getTgtHllType()); - } - -} diff --git a/src/main/java/org/apache/datasketches/hll/package-info.java b/src/main/java/org/apache/datasketches/hll/package-info.java deleted file mode 100644 index ad2f22fa9..000000000 --- a/src/main/java/org/apache/datasketches/hll/package-info.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - *

The DataSketches™ HllSketch family package

- * {@link org.apache.datasketches.hll.HllSketch HllSketch} and {@link org.apache.datasketches.hll.HllUnion HllUnion} - * are the public facing classes of this high performance implementation of Phillipe Flajolet's - * HyperLogLog algorithm[1] but with significantly improved error behavior and important features that can be - * essential for large production systems that must handle massive data. - * - *

Key Features of the DataSketches™ HllSketch and its companion HllUnion

- * - *

Advanced Estimation Algorithms for Optimum Accuracy

- * - *

Zero error at low cardinalities

- * The HllSketch leverages highly compact arrays and hash tables to keep exact counts until the transition to - * dense mode is required for space reasons. The result is perfect accuracy for very low cardinalities. - * - *

Accuracy for very small streams can be important because Big Data is often fragmented into millions of smaller - * streams (or segments) that inevitably are power-law distributed in size. If you are sketching all these fragments, - * as a general rule, more than 80% of your sketches will be very small, 20% will be much larger, and only a few will - * be very large in cardinality.

- * - *

HIP / Martingale Estimator

- * When obtaining a cardinality estimate, the sketch automatically determines if it was the result of the capture of - * a single stream, or if was the result of certain qualifying union operations. If this is the case the sketch will - * take advantage of Edith Cohen's Historical Inverse Probability (HIP) estimation algorithm[2], which was - * also independently developed by Daniel Ting as the Martingale estimation algorithm[3]. - * This will result in a 20% improvement in accuracy over the standard Flajolet estimator. - * If it is not a single stream or if the specific union operation did not qualify, - * the estimator will default to the Composite Estimator. - * - *

Composite Estimator

- * This advanced estimator is a blend of several algorithms including new algorithms developed by Kevin Lang for his - * Compressed Probabilistic Counting (CPC) sketch[4]. These algorithms provide near optimal estimation accuracy - * for cases that don't qualify for HIP / Martingale estimation. - * - *

As a result of all of this work on accuracy, one will get a very smooth curve of the underlying accuracy of the - * sketch once the statistical randomness is removed through multiple trials. This can be observed in the - * following graph.

- * - *

HLL_HIP_K12T20U20.png[6]

- * - *

The above graph has 7 curves. At y = 0, is the median line that hugs the x-axis so closely that it can't be seen. - * The two curves, just above and just below the x-axis, correspond to +/- 1 standard deviation (SD) of error. - * The distance between either one of this pair and the x-axis is also known as the Relative Standard Error (RSE). - * This type of graph for illustrating sketch error we call a "pitchfork plot".

- * - *

The next two curves above and below correspond to +/- 2 SD, and - * the top-most and bottom-most curves correspond to +/- 3 SD. - * The chart grid lines are set at +/- multiples of Relative Standard Error (RSE) that correspond to +/- 1,2,3 SD. - * Below the cardinality of about 512 there is no error at all. This is the point where this particular - * sketch transitions from sparse to dense (or estimation) mode.

- * - *

Three HllSketch Types

- * This HLL implementation offers three different types of HllSketch, each with different - * trade-offs with accuracy, space and performance. These types are selected with the - * {@link org.apache.datasketches.hll.TgtHllType TgtHllType} parameter. - * - *

In terms of accuracy, all three types, for the same lgConfigK, have the same error - * distribution as a function of cardinality.

- * - *

The configuration parameter lgConfigK is the log-base-2 of K, - * where K is the number of buckets or slots for the sketch. lgConfigK impacts both accuracy and - * the size of the sketch in memory and when stored.

- * - *

HLL 8

- * This uses an 8-bit byte per HLL bucket. It is generally the - * fastest in terms of update time but has the largest storage footprint of about K bytes. - * - *

HLL 6

- * This uses a 6-bit field per HLL bucket. It is the generally the next fastest - * in terms of update time with a storage footprint of about 3/4 * K bytes. - * - *

HLL 4

- * This uses a 4-bit field per HLL bucket and for large counts may require - * the use of a small internal auxiliary array for storing statistical exceptions, which are rare. - * For the values of lgConfigK > 13 (K = 8192), - * this additional array adds about 3% to the overall storage. It is generally the slowest in - * terms of update time, but has the smallest storage footprint of about K/2 * 1.03 bytes. - * - *

Off-Heap Operation

- * This HllSketch also offers the capability of operating off-heap. Given a MemorySegment[5] object - * created by the user, the sketch will perform all of its updates and internal phase transitions - * in that object, which can actually reside either on-heap or off-heap based on how it was - * configured. In large systems that must update and union many millions of sketches, having the - * sketch operate off-heap avoids the serialization and deserialization costs of moving sketches from heap to - * off-heap and back, and reduces the need for garbage collection. - * - *

Merging sketches with different configured lgConfigK

- * This enables a user to union an HllSketch that was configured with, say, lgConfigK = 12 - * with another loaded HllSketch that was configured with, say, lgConfigK = 14. - * - *

Why is this important? Suppose you have been building a history of sketches of your customer's - * data that go back a full year (or 5 or 10!) that were all configured with lgConfigK = 12. Because sketches - * are so much smaller than the raw data it is possible that the raw data was discarded keeping only the sketches. - * Even if you have the raw data, it might be very expensive and time consuming to reload and rebuild all your - * sketches with a larger more accurate size, say, lgConfigK = 14. - * This capability enables you to merge last year's data with this year's data built with larger sketches and still - * have meaningful results.

- * - *

In other words, you can change your mind about what size sketch you need for your application at any time and - * will not lose access to the data contained in your older historical sketches.

- * - *

This capability does come with a caveat: The resulting accuracy of the merged sketch will be the accuracy of the - * smaller of the two sketches. Without this capability, you would either be stuck with the configuration you first - * chose forever, or you would have to rebuild all your sketches from scratch, or worse, not be able to recover your - * historical data.

- * - *

Multi-language, multi-platform.

- * The binary structures for our sketch serializations are language and platform independent. - * This means it is possible to generate an HllSketch on a C++ Windows platform and it can be used on a - * Java or Python Unix platform. - * - *

[1] Philippe Flajolet, et al, -HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm. - * DMTCS proc. AH, 2007, 127-146. - * - *

[2] Edith Cohen, -All-Distances Sketches, Revisited: HIP Estimators for Massive Graphs Analysis. - * PODS'14, June 22-27, Snowbird, UT, USA. - * - *

[3] Daniel Ting, - * -Streamed Approximate Counting of Distinct Elements, Beating Optimal Batch Methods. - * KDD'14 August 24, 2014 New York, New York USA. - * - *

[4] Kevin Lang, - * -Back to the Future: an Even More Nearly Optimal Cardinality Estimation Algorithm. - * arXiv 1708.06839, August 22, 2017, Yahoo Research. - * - *

[5] MemorySegment Component, See - * JEP 454: Foreign Function And Memory API - * - *

[6] MacBook Pro 2.3 GHz 8-Core Intel Core i9 - * - * @see org.apache.datasketches.cpc.CpcSketch - * - * @author Lee Rhodes - * @author Kevin Lang - */ -package org.apache.datasketches.hll; diff --git a/src/main/java/org/apache/datasketches/hllmap/CouponHashMap.java b/src/main/java/org/apache/datasketches/hllmap/CouponHashMap.java deleted file mode 100644 index d69d65e7c..000000000 --- a/src/main/java/org/apache/datasketches/hllmap/CouponHashMap.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hllmap; - -import static org.apache.datasketches.common.Util.checkIfPowerOf2; -import static org.apache.datasketches.common.Util.invPow2; - -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.hash.MurmurHash3; - -/** - * Implements a key-value map where the value is a hash map of coupons. - * - *

The outer map is implemented as a prime-sized, Open Address, Double Hash, with deletes, so - * this table can grow and shrink. Each entry row has a 1-byte count where 255 is a marker for - * "dirty" and zero is empty. - * - *

The inner hash tables are implemented with linear probing or OASH and a load factor of 0.75. - * - * @author Lee Rhodes - * @author Alexander Saydakov - * @author Kevin Lang - */ -final class CouponHashMap extends Map { - private static final double INNER_LOAD_FACTOR = 0.75; - private static final byte DELETED_KEY_MARKER = (byte) 255; - private static final int BYTE_MASK = 0XFF; - private static final int COUPON_K = 1024; - private static final double RSE = 0.408 / Math.sqrt(1024); - - private final int maxCouponsPerKey_; - private final int capacityCouponsPerKey_; - private final int entrySizeBytes_; - - private int tableEntries_; - private int capacityEntries_; - private int numActiveKeys_; - private int numDeletedKeys_; - - //Arrays - private byte[] keysArr_; - private short[] couponsArr_; - private byte[] curCountsArr_; //also acts as a stateArr: 0 empty, 255 deleted - private float[] invPow2SumArr_; - private float[] hipEstAccumArr_; - - private CouponHashMap(final int keySizeBytes, final int maxCouponsPerKey) { - super(keySizeBytes); - maxCouponsPerKey_ = maxCouponsPerKey; - capacityCouponsPerKey_ = (int)(maxCouponsPerKey * INNER_LOAD_FACTOR); - entrySizeBytes_ = keySizeBytes + (maxCouponsPerKey * Short.BYTES) + 1 + 4 + 4; - } - - static CouponHashMap getInstance(final int keySizeBytes, final int maxCouponsPerKey) { - checkMaxCouponsPerKey(maxCouponsPerKey); - final int tableEntries = COUPON_MAP_MIN_NUM_ENTRIES; - - final CouponHashMap map = new CouponHashMap(keySizeBytes, maxCouponsPerKey); - map.tableEntries_ = tableEntries; - map.capacityEntries_ = (int)(tableEntries * COUPON_MAP_GROW_TRIGGER_FACTOR); - map.numActiveKeys_ = 0; - map.numDeletedKeys_ = 0; - - map.keysArr_ = new byte[tableEntries * keySizeBytes]; - map.couponsArr_ = new short[tableEntries * maxCouponsPerKey]; - map.curCountsArr_ = new byte[tableEntries]; - map.invPow2SumArr_ = new float[tableEntries]; - map.hipEstAccumArr_ = new float[tableEntries]; - return map; - } - - @Override - double update(final byte[] key, final short coupon) { - final int entryIndex = findOrInsertKey(key); - return update(entryIndex, coupon); //negative when time to promote - } - - @Override - double update(final int entryIndex, final short coupon) { - final int couponMapArrEntryIndex = entryIndex * maxCouponsPerKey_; - - int innerCouponIndex = (coupon & 0xFFFF) % maxCouponsPerKey_; - - while (couponsArr_[couponMapArrEntryIndex + innerCouponIndex] != 0) { - if (couponsArr_[couponMapArrEntryIndex + innerCouponIndex] == coupon) { - return hipEstAccumArr_[entryIndex]; //duplicate, returns the estimate - } - innerCouponIndex = (innerCouponIndex + 1) % maxCouponsPerKey_; //linear search - } - if (((curCountsArr_[entryIndex] + 1) & BYTE_MASK) > capacityCouponsPerKey_) { - //returns the negative estimate, as signal to promote - return -hipEstAccumArr_[entryIndex]; - } - - couponsArr_[couponMapArrEntryIndex + innerCouponIndex] = coupon; //insert - curCountsArr_[entryIndex]++; - //hip += k/qt; qt -= 1/2^(val); - hipEstAccumArr_[entryIndex] += COUPON_K / invPow2SumArr_[entryIndex]; - invPow2SumArr_[entryIndex] -= invPow2(coupon16Value(coupon)); - return hipEstAccumArr_[entryIndex]; //returns the estimate - } - - @Override - double getEstimate(final byte[] key) { - final int index = findKey(key); - if (index < 0) { return 0; } - return hipEstAccumArr_[index]; - } - - @Override - double getUpperBound(final byte[] key) { - return getEstimate(key) * (1 + RSE); - } - - @Override - double getLowerBound(final byte[] key) { - return getEstimate(key) * (1 - RSE); - } - - @Override - void updateEstimate(final int entryIndex, final double estimate) { - if (entryIndex < 0) { - throw new SketchesArgumentException("Key not found."); - } - hipEstAccumArr_[entryIndex] = (float) estimate; - } - - /** - * Returns entryIndex if the given key is found. If not found, returns one's complement index - * of an empty slot for insertion, which may be over a deleted key. - * @param key the given key - * @return the entryIndex - */ - @Override - int findKey(final byte[] key) { - final long[] hash = MurmurHash3.hash(key, SEED); - int entryIndex = getIndex(hash[0], tableEntries_); - int firstDeletedIndex = -1; - final int loopIndex = entryIndex; - do { - if (curCountsArr_[entryIndex] == 0) { - return firstDeletedIndex == -1 ? ~entryIndex : ~firstDeletedIndex; // found empty or deleted - } - if (curCountsArr_[entryIndex] == DELETED_KEY_MARKER) { - if (firstDeletedIndex == -1) { - firstDeletedIndex = entryIndex; - } - } else if (Map.arraysEqual(keysArr_, entryIndex * keySizeBytes_, key, 0, keySizeBytes_)) { - return entryIndex; // found key - } - entryIndex = (entryIndex + getStride(hash[1], tableEntries_)) % tableEntries_; - } while (entryIndex != loopIndex); - throw new SketchesArgumentException("Key not found and no empty slots!"); - } - - @Override - int findOrInsertKey(final byte[] key) { - int entryIndex = findKey(key); - if (entryIndex < 0) { //key not found - entryIndex = ~entryIndex; - if (curCountsArr_[entryIndex] == DELETED_KEY_MARKER) { // reusing slot from a deleted key - Arrays.fill(couponsArr_, entryIndex * maxCouponsPerKey_, - (entryIndex + 1) * maxCouponsPerKey_, (short) 0); - curCountsArr_[entryIndex] = 0; - numDeletedKeys_--; - } - if ((numActiveKeys_ + numDeletedKeys_) >= capacityEntries_) { - resize(); - entryIndex = ~findKey(key); - assert entryIndex >= 0; - } - //insert new key - System.arraycopy(key, 0, keysArr_, entryIndex * keySizeBytes_, keySizeBytes_); - //initialize HIP: qt <- k; hip <- 0; - invPow2SumArr_[entryIndex] = COUPON_K; - hipEstAccumArr_[entryIndex] = 0; - numActiveKeys_++; - } - return entryIndex; - } - - @Override - void deleteKey(final int entryIndex) { - curCountsArr_[entryIndex] = DELETED_KEY_MARKER; - numActiveKeys_--; - numDeletedKeys_++; - if ((numActiveKeys_ > COUPON_MAP_MIN_NUM_ENTRIES) - && (numActiveKeys_ < (tableEntries_ * COUPON_MAP_SHRINK_TRIGGER_FACTOR))) { - resize(); - } - } - - @Override - CouponsIterator getCouponsIterator(final int entryIndex) { - return new CouponsIterator(couponsArr_, entryIndex * maxCouponsPerKey_, maxCouponsPerKey_); - } - - @Override - double getEntrySizeBytes() { - return entrySizeBytes_; - } - - @Override - int getTableEntries() { - return tableEntries_; - } - - @Override - int getCapacityEntries() { - return capacityEntries_; - } - - @Override - int getCurrentCountEntries() { - return numActiveKeys_ + numDeletedKeys_; - } - - @Override - long getTotalUsageBytes() { - final long arrays = keysArr_.length - + ((long) couponsArr_.length * Short.BYTES) - + curCountsArr_.length - + ((long) invPow2SumArr_.length * Float.BYTES) - + ((long) hipEstAccumArr_.length * Float.BYTES); - final long other = 4 * 5; - return arrays + other; - } - - @Override - int getActiveEntries() { - return numActiveKeys_; - } - - @Override - int getDeletedEntries() { - return numDeletedKeys_; - } - - @Override - int getMaxCouponsPerEntry() { - return maxCouponsPerKey_; - } - - @Override - int getCapacityCouponsPerEntry() { - return capacityCouponsPerKey_; - } - - private static final void checkMaxCouponsPerKey(final int maxCouponsPerKey) { - checkIfPowerOf2(maxCouponsPerKey, "maxCouponsPerKey"); - final int cpk = maxCouponsPerKey; - if ((cpk < 16) || (cpk > 256)) { - throw new SketchesArgumentException( - "Required: 16 <= maxCouponsPerKey <= 256 : " + maxCouponsPerKey); - } - } - - private void resize() { - final byte[] oldKeysArr = keysArr_; - final short[] oldCouponMapArr = couponsArr_; - final byte[] oldCurCountsArr = curCountsArr_; - final float[] oldInvPow2SumArr = invPow2SumArr_; - final float[] oldHipEstAccumArr = hipEstAccumArr_; - final int oldNumEntries = tableEntries_; - tableEntries_ = Math.max( - nextPrime((int) (numActiveKeys_ / COUPON_MAP_TARGET_FILL_FACTOR)), - COUPON_MAP_MIN_NUM_ENTRIES - ); - capacityEntries_ = (int)(tableEntries_ * COUPON_MAP_GROW_TRIGGER_FACTOR); - keysArr_ = new byte[tableEntries_ * keySizeBytes_]; - couponsArr_ = new short[tableEntries_ * maxCouponsPerKey_]; - curCountsArr_ = new byte[tableEntries_]; - invPow2SumArr_ = new float[tableEntries_]; - hipEstAccumArr_ = new float[tableEntries_]; - numActiveKeys_ = 0; - numDeletedKeys_ = 0; - for (int i = 0; i < oldNumEntries; i++) { - if ((oldCurCountsArr[i] != 0) && (oldCurCountsArr[i] != DELETED_KEY_MARKER)) { - //extract an old valid key - final byte[] key = - Arrays.copyOfRange(oldKeysArr, i * keySizeBytes_, (i * keySizeBytes_) + keySizeBytes_); - //insert the key and get its index - final int index = insertKey(key); - //copy the coupons array into that index - System.arraycopy(oldCouponMapArr, i * maxCouponsPerKey_, couponsArr_, - index * maxCouponsPerKey_, maxCouponsPerKey_); - //transfer the count - curCountsArr_[index] = oldCurCountsArr[i]; - //transfer the HIP registers - invPow2SumArr_[index] = oldInvPow2SumArr[i]; - hipEstAccumArr_[index] = oldHipEstAccumArr[i]; - } - } - } - - // for internal use by resize, no resize check and no deleted key check here - // no changes to HIP - private int insertKey(final byte[] key) { - final long[] hash = MurmurHash3.hash(key, SEED); - int entryIndex = getIndex(hash[0], tableEntries_); - final int loopIndex = entryIndex; - do { - if (curCountsArr_[entryIndex] == 0) { - System.arraycopy(key, 0, keysArr_, entryIndex * keySizeBytes_, keySizeBytes_); - numActiveKeys_++; - return entryIndex; - } - entryIndex = (entryIndex + getStride(hash[1], tableEntries_)) % tableEntries_; - } while (entryIndex != loopIndex); - throw new SketchesArgumentException("Key not found and no empty slots!"); - } - -} diff --git a/src/main/java/org/apache/datasketches/hllmap/CouponTraverseMap.java b/src/main/java/org/apache/datasketches/hllmap/CouponTraverseMap.java deleted file mode 100644 index ae5e0a523..000000000 --- a/src/main/java/org/apache/datasketches/hllmap/CouponTraverseMap.java +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hllmap; - -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.hash.MurmurHash3; - -/** - * Implements a key-value map where the value is a simple array of coupons. Search operations are a - * simple traverse of the consecutive coupons. Because of this, the maximum practical size of the - * coupon array is about 8 coupons. - * - *

The map is implemented as a prime-sized, Open Address, Double Hash, with deletes and a 1-bit - * state array. The size of this map can grow or shrink. - * - * @author Lee Rhodes - * @author Alexander Saydakov - * @author Kevin Lang - */ -final class CouponTraverseMap extends Map { - private static final double RSE = 0.408 / Math.sqrt(1024); - //private static int - private final int maxCouponsPerKey_; - - private int tableEntries_; - private int capacityEntries_; - private int numActiveKeys_; - private int numDeletedKeys_; - private double entrySizeBytes_; - - //Arrays - private byte[] keysArr_; - private short[] couponsArr_; - - /** - *

  • State: 0: Empty always, don't need to look at 1st coupon. Coupons could be dirty.
  • - *
  • State: 1: Valid entry or dirty. During rebuild, look at the first coupon to determine. - * If first coupon != 0 means valid entry; first coupon == 0: dirty (we set to 0 when deleted)
  • - *
- */ - private byte[] stateArr_; - - private CouponTraverseMap(final int keySizeBytes, final int maxCouponsPerKey) { - super(keySizeBytes); - maxCouponsPerKey_ = maxCouponsPerKey; - } - - static CouponTraverseMap getInstance(final int keySizeBytes, final int maxCouponsPerKey) { - final CouponTraverseMap map = new CouponTraverseMap(keySizeBytes, maxCouponsPerKey); - map.tableEntries_ = COUPON_MAP_MIN_NUM_ENTRIES; - map.capacityEntries_ = (int)(map.tableEntries_ * COUPON_MAP_GROW_TRIGGER_FACTOR); - map.numActiveKeys_ = 0; - map.numDeletedKeys_ = 0; - map.entrySizeBytes_ = updateEntrySizeBytes(map.tableEntries_, keySizeBytes, maxCouponsPerKey); - - map.keysArr_ = new byte[COUPON_MAP_MIN_NUM_ENTRIES * keySizeBytes]; - map.couponsArr_ = new short[COUPON_MAP_MIN_NUM_ENTRIES * maxCouponsPerKey]; - map.stateArr_ = new byte[COUPON_MAP_MIN_NUM_ENTRIES_ARR_SIZE]; - return map; - } - - @Override //used for test - double update(final byte[] key, final short coupon) { - final int entryIndex = findOrInsertKey(key); - return update(entryIndex, coupon); - } - - @Override - double update(final int entryIndex, final short value) { - final int offset = entryIndex * maxCouponsPerKey_; - boolean wasFound = false; - for (int i = 0; i < maxCouponsPerKey_; i++) { - if (couponsArr_[offset + i] == 0) { - if (wasFound) { return i; } - couponsArr_[offset + i] = value; - return i + 1; - } - if (couponsArr_[offset + i] == value) { - wasFound = true; - } - } - if (wasFound) { return maxCouponsPerKey_; } - return -maxCouponsPerKey_; //signal to promote - } - - @Override - double getEstimate(final byte[] key) { - final int entryIndex = findKey(key); - if (entryIndex < 0) { return 0; } - return getCouponCount(entryIndex); - } - - @Override - double getUpperBound(final byte[] key) { - return getEstimate(key) * (1 + RSE); - } - - @Override - double getLowerBound(final byte[] key) { - return getEstimate(key) * (1 - RSE); - } - - /** - * Returns entryIndex if the given key is found. If not found, returns one's complement entryIndex - * of an empty slot for insertion, which may be over a deleted key. - * @param key the given key - * @return the entryIndex - */ - @Override - int findKey(final byte[] key) { - final long[] hash = MurmurHash3.hash(key, SEED); - int entryIndex = getIndex(hash[0], tableEntries_); - int firstDeletedIndex = -1; - final int loopIndex = entryIndex; - do { - if (isBitClear(stateArr_, entryIndex)) { - return firstDeletedIndex == -1 ? ~entryIndex : ~firstDeletedIndex; // found empty or deleted - } - if (couponsArr_[entryIndex * maxCouponsPerKey_] == 0) { //found deleted - if (firstDeletedIndex == -1) { firstDeletedIndex = entryIndex; } - } else if (Map.arraysEqual(keysArr_, entryIndex * keySizeBytes_, key, 0, keySizeBytes_)) { - return entryIndex; // found key - } - entryIndex = (entryIndex + getStride(hash[1], tableEntries_)) % tableEntries_; - } while (entryIndex != loopIndex); - throw new SketchesArgumentException("Key not found and no empty slots!"); - } - - @Override - int findOrInsertKey(final byte[] key) { - int entryIndex = findKey(key); - if (entryIndex < 0) { - entryIndex = ~entryIndex; - if (isBitSet(stateArr_, entryIndex)) { // reusing slot from a deleted key - clearCouponArea(entryIndex); - numDeletedKeys_--; - } - if ((numActiveKeys_ + numDeletedKeys_ + 1) > capacityEntries_) { - resize(); - entryIndex = ~findKey(key); - assert entryIndex >= 0; - } - System.arraycopy(key, 0, keysArr_, entryIndex * keySizeBytes_, keySizeBytes_); - setBit(stateArr_, entryIndex); - numActiveKeys_++; - } - return entryIndex; - } - - @Override - void deleteKey(final int entryIndex) { - couponsArr_[entryIndex * maxCouponsPerKey_] = 0; - numActiveKeys_--; - numDeletedKeys_++; - if ((numActiveKeys_ > COUPON_MAP_MIN_NUM_ENTRIES) - && (numActiveKeys_ < (tableEntries_ * COUPON_MAP_SHRINK_TRIGGER_FACTOR))) { - resize(); - } - } - - private int getCouponCount(final int entryIndex) { - final int offset = entryIndex * maxCouponsPerKey_; - for (int i = 0; i < maxCouponsPerKey_; i++) { - if (couponsArr_[offset + i] == 0) { - return i; - } - } - return maxCouponsPerKey_; - } - - @Override - CouponsIterator getCouponsIterator(final int entryIndex) { - return new CouponsIterator(couponsArr_, entryIndex * maxCouponsPerKey_, maxCouponsPerKey_); - } - - @Override - double getEntrySizeBytes() { - return entrySizeBytes_; - } - - @Override - int getTableEntries() { - return tableEntries_; - } - - @Override - int getCapacityEntries() { - return capacityEntries_; - } - - @Override - int getCurrentCountEntries() { - return numActiveKeys_ + numDeletedKeys_; - } - - @Override - long getTotalUsageBytes() { - return keysArr_.length - + ((long)couponsArr_.length * Short.BYTES) - + stateArr_.length + (4L * Integer.BYTES); - } - - @Override - int getActiveEntries() { - return numActiveKeys_; - } - - @Override - int getDeletedEntries() { - return numDeletedKeys_; - } - - @Override - int getMaxCouponsPerEntry() { - return maxCouponsPerKey_; - } - - @Override - int getCapacityCouponsPerEntry() { - return maxCouponsPerKey_; - } - - private void resize() { //can grow or shrink - final byte[] oldKeysArr = keysArr_; - final short[] oldCouponsArr = couponsArr_; - final byte[] oldStateArr = stateArr_; - final int oldSizeKeys = tableEntries_; - tableEntries_ = Math.max( - nextPrime((int) (numActiveKeys_ / COUPON_MAP_TARGET_FILL_FACTOR)), - COUPON_MAP_MIN_NUM_ENTRIES - ); - capacityEntries_ = (int)(tableEntries_ * COUPON_MAP_GROW_TRIGGER_FACTOR); - numActiveKeys_ = 0; - numDeletedKeys_ = 0; - entrySizeBytes_ = updateEntrySizeBytes(tableEntries_, keySizeBytes_, maxCouponsPerKey_); - - keysArr_ = new byte[tableEntries_ * keySizeBytes_]; - couponsArr_ = new short[tableEntries_ * maxCouponsPerKey_]; - stateArr_ = new byte[(int) Math.ceil(tableEntries_ / 8.0)]; - - //move data - for (int i = 0; i < oldSizeKeys; i++) { - if (isBitSet(oldStateArr, i) && (oldCouponsArr[i * maxCouponsPerKey_] != 0)) { - final byte[] key = - Arrays.copyOfRange(oldKeysArr, i * keySizeBytes_, (i * keySizeBytes_) + keySizeBytes_); - final int index = insertKey(key); - System.arraycopy(oldCouponsArr, i * maxCouponsPerKey_, couponsArr_, - index * maxCouponsPerKey_, maxCouponsPerKey_); - } - } - } - - // for internal use during resize, so no resize check here - private int insertKey(final byte[] key) { - final long[] hash = MurmurHash3.hash(key, SEED); - int entryIndex = getIndex(hash[0], tableEntries_); - final int loopIndex = entryIndex; - do { - if (isBitClear(stateArr_, entryIndex)) { - System.arraycopy(key, 0, keysArr_, entryIndex * keySizeBytes_, keySizeBytes_); - setBit(stateArr_, entryIndex); - numActiveKeys_++; - return entryIndex; - } - entryIndex = (entryIndex + getStride(hash[1], tableEntries_)) % tableEntries_; - } while (entryIndex != loopIndex); - throw new SketchesArgumentException("Key not found and no empty slots!"); - } - - private void clearCouponArea(final int entryIndex) { - final int couponAreaIndex = entryIndex * maxCouponsPerKey_; - for (int i = 0; i < maxCouponsPerKey_; i++) { - couponsArr_[couponAreaIndex + i] = 0; - } - } - - private static final double updateEntrySizeBytes(final int tableEntries, final int keySizeBytes, - final int maxCouponsPerKey) { - final double byteFraction = Math.ceil(tableEntries / 8.0) / tableEntries; - return keySizeBytes + ((double) maxCouponsPerKey * Short.BYTES) + byteFraction; - } - -} diff --git a/src/main/java/org/apache/datasketches/hllmap/CouponsIterator.java b/src/main/java/org/apache/datasketches/hllmap/CouponsIterator.java deleted file mode 100644 index 81f2d75c7..000000000 --- a/src/main/java/org/apache/datasketches/hllmap/CouponsIterator.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hllmap; - -/** - * Common iterator class for maps that need one. - * - * @author Alex Saydakov - */ -class CouponsIterator { - - private final int offset_; - private final int maxEntries_; - private final short[] couponsArr_; - private int index_; - - CouponsIterator(final short[] couponsArr, final int offset, final int maxEntries) { - offset_ = offset; - maxEntries_ = maxEntries; - couponsArr_ = couponsArr; - index_ = -1; - } - - /** - * next() must be called before the first getValue(). This skips over zero values. - * @return the next coupon in the array. - */ - boolean next() { - index_++; - while (index_ < maxEntries_) { - if (couponsArr_[offset_ + index_] != 0) { return true; } - index_++; - } - return false; - } - - /** - * Returns the value at the current index. - * @return the value at the current index. - */ - short getValue() { - return couponsArr_[offset_ + index_]; - } - -} diff --git a/src/main/java/org/apache/datasketches/hllmap/HllMap.java b/src/main/java/org/apache/datasketches/hllmap/HllMap.java deleted file mode 100644 index 36d9b7c1e..000000000 --- a/src/main/java/org/apache/datasketches/hllmap/HllMap.java +++ /dev/null @@ -1,344 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hllmap; - -import static java.lang.Math.log; -import static java.lang.Math.sqrt; -import static org.apache.datasketches.common.Util.invPow2; - -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SuppressFBWarnings; -import org.apache.datasketches.hash.MurmurHash3; - -/** - * Implements a key-value map where the value is a compact HLL sketch of size k. - * The HLL bins are compacted into 10 bins per long so that a 1024 bins are compacted into - * 824 bytes, which is a 20% reduction in space. Higher density compressions are possible - * (up to 50%), but the required code is much more complex and considerably slower. - * - *

Each entry row, associated with a key, also contains 3 double registers for accurately - * tracking the HIP (Historical Inverse Probability) estimator. HLL implementations have multiple - * estimators and the early estimators in this implementation are quite novel and provide superior - * error performance over most other HLL implementations. - * - * @author Lee Rhodes - * @author KevinLang - * @author Alexander Saydakov - */ -final class HllMap extends Map { - private static final double LOAD_FACTOR = 15.0 / 16.0; - private static final int HLL_INIT_NUM_ENTRIES = 157; - private static final int HLL_INIT_NUM_ENTRIES_ARR_SIZE = (int) Math.ceil(HLL_INIT_NUM_ENTRIES / 8.0); - private static final float HLL_RESIZE_FACTOR = 2.0F; - private static final double RSE = sqrt(log(2.0)) / 32.0; - private final int k_; - private final int hllArrLongs_; //# of longs required to store the HLL array - - private int tableEntries_; //Full size of the table - private int capacityEntries_; //max capacity entries defined by Load factor - private int curCountEntries_; //current count of valid entries - private float growthFactor_; //e.g., 1.2 to 2.0 - private double entrySizeBytes_; - - //Arrays - private byte[] keysArr_; //keys of zero are allowed - private long[] arrOfHllArr_; - private double[] invPow2SumHiArr_; - private double[] invPow2SumLoArr_; - private double[] hipEstAccumArr_; - private byte[] stateArr_; - - /** - * Private constructor used to set all finals - * @param keySizeBytes size of key in bytes - * @param k size of HLL sketch - */ - private HllMap(final int keySizeBytes, final int k) { - super(keySizeBytes); - k_ = k; - hllArrLongs_ = (k / 10) + 1; - } - - static HllMap getInstance(final int keySizeBytes, final int k) { - - final HllMap map = new HllMap(keySizeBytes, k); - map.tableEntries_ = HLL_INIT_NUM_ENTRIES; - map.capacityEntries_ = (int)(HLL_INIT_NUM_ENTRIES * LOAD_FACTOR); - map.curCountEntries_ = 0; - map.growthFactor_ = HLL_RESIZE_FACTOR; - map.entrySizeBytes_ = updateEntrySizeBytes(map.tableEntries_, keySizeBytes, map.hllArrLongs_); - - map.keysArr_ = new byte[HLL_INIT_NUM_ENTRIES * map.keySizeBytes_]; - map.arrOfHllArr_ = new long[HLL_INIT_NUM_ENTRIES * map.hllArrLongs_]; - map.invPow2SumHiArr_ = new double[HLL_INIT_NUM_ENTRIES]; - map.invPow2SumLoArr_ = new double[HLL_INIT_NUM_ENTRIES]; - map.hipEstAccumArr_ = new double[HLL_INIT_NUM_ENTRIES]; - map.stateArr_ = new byte[HLL_INIT_NUM_ENTRIES_ARR_SIZE]; - return map; - } - - @Override - double update(final byte[] key, final short coupon) { - final int entryIndex = findOrInsertKey(key); - return update(entryIndex, coupon); - } - - @Override - double update(final int entryIndex, final short coupon) { - updateHll(entryIndex, coupon); //update HLL array, updates HIP - return hipEstAccumArr_[entryIndex]; - } - - @Override - double getEstimate(final byte[] key) { - if (key == null) { return Double.NaN; } - final int entryIndex = findKey(key); - if (entryIndex < 0) { - return 0; - } - return hipEstAccumArr_[entryIndex]; - } - - @Override - double getUpperBound(final byte[] key) { - return getEstimate(key) * (1 + RSE); - } - - @Override - double getLowerBound(final byte[] key) { - return getEstimate(key) * (1 - RSE); - } - - @Override - void updateEstimate(final int entryIndex, final double estimate) { - hipEstAccumArr_[entryIndex] = estimate; - } - - /** - * Returns the entry index for the given key given the array of keys, if found. - * Otherwise, returns the one's complement of first empty entry found; - * @param key the key to search for - * @return the entry index of the given key, or the one's complement of the index if not found. - */ - @Override - final int findKey(final byte[] key) { - final int keyLen = key.length; - final long[] hash = MurmurHash3.hash(key, SEED); - int entryIndex = getIndex(hash[0], tableEntries_); - final int stride = getStride(hash[1], tableEntries_); - final int loopIndex = entryIndex; - - do { - if (isBitClear(stateArr_, entryIndex)) { //check if slot is empty - return ~entryIndex; - } - if (arraysEqual(key, 0, keysArr_, entryIndex * keyLen, keyLen)) { //check for key match - return entryIndex; - } - entryIndex = (entryIndex + stride) % tableEntries_; - } while (entryIndex != loopIndex); - throw new SketchesArgumentException("Key not found and no empty slots!"); - } - - @Override - int findOrInsertKey(final byte[] key) { - int entryIndex = findKey(key); - if (entryIndex < 0) { //key not found, initialize new row - entryIndex = ~entryIndex; - System.arraycopy(key, 0, keysArr_, entryIndex * keySizeBytes_, keySizeBytes_); - setBit(stateArr_, entryIndex); - invPow2SumHiArr_[entryIndex] = k_; - invPow2SumLoArr_[entryIndex] = 0; - hipEstAccumArr_[entryIndex] = 0; - curCountEntries_++; - if (curCountEntries_ > capacityEntries_) { - resize(); - entryIndex = findKey(key); - assert entryIndex >= 0; - } - } - return entryIndex; - } - - @Override - double getEntrySizeBytes() { - return entrySizeBytes_; - } - - @Override - int getTableEntries() { - return tableEntries_; - } - - @Override - int getCapacityEntries() { - return capacityEntries_; - } - - @Override - int getCurrentCountEntries() { - return curCountEntries_; - } - - @Override - long getTotalUsageBytes() { - final long arrays = keysArr_.length - + ((long) arrOfHllArr_.length * Long.BYTES) - + ((long) invPow2SumLoArr_.length * Double.BYTES) - + ((long) invPow2SumHiArr_.length * Double.BYTES) - + ((long) hipEstAccumArr_.length * Double.BYTES) - + stateArr_.length; - final long other = (5L * Integer.BYTES) + Float.BYTES + Double.BYTES; - return arrays + other; - } - - @Override - CouponsIterator getCouponsIterator(final int index) { - // not applicable - return null; - } - - @Override - int getMaxCouponsPerEntry() { - // not applicable - return 0; - } - - @Override - int getCapacityCouponsPerEntry() { - // not applicable - return 0; - } - - @Override - int getActiveEntries() { - return curCountEntries_; - } - - @Override - int getDeletedEntries() { - return 0; - } - - /** - * Find the first empty slot for the given key. - * Only used by resize, where it is known that the key does not exist in the table. - * Throws an exception if no empty slots. - * @param key the given key - * @param tableEntries prime size of table - * @param stateArr the valid bit array - * @return the first empty slot for the given key - */ - private static final int findEmpty(final byte[] key, final int tableEntries, final byte[] stateArr) { - final long[] hash = MurmurHash3.hash(key, SEED); - int entryIndex = getIndex(hash[0], tableEntries); - final int stride = getStride(hash[1], tableEntries); - final int loopIndex = entryIndex; - - do { - if (isBitClear(stateArr, entryIndex)) { //check if slot is empty - return entryIndex; - } - entryIndex = (entryIndex + stride) % tableEntries; - } while (entryIndex != loopIndex); - throw new SketchesArgumentException("No empty slots."); - } - - //This method is specifically tied to the HLL array layout - @SuppressFBWarnings(value = "IM_MULTIPLYING_RESULT_OF_IREM", justification = "False Positive") - private final boolean updateHll(final int entryIndex, final int coupon) { - final int newValue = coupon16Value(coupon); - - final int hllIdx = coupon & (k_ - 1); //lower lgK bits - final int longIdx = hllIdx / 10; - final int shift = ((hllIdx % 10) * 6) & SIX_BIT_MASK; - - long hllLong = arrOfHllArr_[(entryIndex * hllArrLongs_) + longIdx]; - final int oldValue = (int)(hllLong >>> shift) & SIX_BIT_MASK; - if (newValue <= oldValue) { return false; } - // newValue > oldValue - - //update hipEstAccum BEFORE updating invPow2Sum - final double invPow2Sum = invPow2SumHiArr_[entryIndex] + invPow2SumLoArr_[entryIndex]; - final double oneOverQ = k_ / invPow2Sum; - hipEstAccumArr_[entryIndex] += oneOverQ; - - //update invPow2Sum - if (oldValue < 32) { invPow2SumHiArr_[entryIndex] -= invPow2(oldValue); } - else { invPow2SumLoArr_[entryIndex] -= invPow2(oldValue); } - if (newValue < 32) { invPow2SumHiArr_[entryIndex] += invPow2(newValue); } - else { invPow2SumLoArr_[entryIndex] += invPow2(newValue); } - - //insert the new value - hllLong &= ~(0X3FL << shift); //zero out the 6-bit field - hllLong |= ((long)newValue) << shift; //insert - arrOfHllArr_[(entryIndex * hllArrLongs_) + longIdx] = hllLong; - return true; - } - - private final void resize() { - final int newTableEntries = nextPrime((int)(tableEntries_ * growthFactor_)); - final int newCapacityEntries = (int)(newTableEntries * LOAD_FACTOR); - - final byte[] newKeysArr = new byte[newTableEntries * keySizeBytes_]; - final long[] newArrOfHllArr = new long[newTableEntries * hllArrLongs_]; - final double[] newInvPow2Sum1 = new double[newTableEntries]; - final double[] newInvPow2Sum2 = new double[newTableEntries]; - final double[] newHipEstAccum = new double[newTableEntries]; - final byte[] newStateArr = new byte[(int) Math.ceil(newTableEntries / 8.0)]; - - for (int oldIndex = 0; oldIndex < tableEntries_; oldIndex++) { - if (isBitClear(stateArr_, oldIndex)) { continue; } - // extract an old key - final byte[] key = - Arrays.copyOfRange(keysArr_, oldIndex * keySizeBytes_, (oldIndex + 1) * keySizeBytes_); - final int newIndex = findEmpty(key, newTableEntries, newStateArr); - System.arraycopy(key, 0, newKeysArr, newIndex * keySizeBytes_, keySizeBytes_); //put key - //put the rest of the row - System.arraycopy(arrOfHllArr_, oldIndex * hllArrLongs_, newArrOfHllArr, - newIndex * hllArrLongs_, hllArrLongs_); - newInvPow2Sum1[newIndex] = invPow2SumHiArr_[oldIndex]; - newInvPow2Sum2[newIndex] = invPow2SumLoArr_[oldIndex]; - newHipEstAccum[newIndex] = hipEstAccumArr_[oldIndex]; - setBit(newStateArr, newIndex); - } - //restore into sketch - tableEntries_ = newTableEntries; - capacityEntries_ = newCapacityEntries; - //curCountEntries_, growthFactor_ unchanged - entrySizeBytes_ = updateEntrySizeBytes(tableEntries_, keySizeBytes_, hllArrLongs_); - - keysArr_ = newKeysArr; - arrOfHllArr_ = newArrOfHllArr; - invPow2SumHiArr_ = newInvPow2Sum1; //init to k - invPow2SumLoArr_ = newInvPow2Sum2; //init to 0 - hipEstAccumArr_ = newHipEstAccum; //init to 0 - stateArr_ = newStateArr; - } - - private static final double updateEntrySizeBytes(final int tableEntries, final int keySizeBytes, - final int hllArrLongs) { - final double byteFraction = Math.ceil(tableEntries / 8.0) / tableEntries; - return keySizeBytes + ((double) hllArrLongs * Long.BYTES) + (3.0 * Double.BYTES) + byteFraction; - } - -} diff --git a/src/main/java/org/apache/datasketches/hllmap/Map.java b/src/main/java/org/apache/datasketches/hllmap/Map.java deleted file mode 100644 index df730e3d4..000000000 --- a/src/main/java/org/apache/datasketches/hllmap/Map.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hllmap; - -import static org.apache.datasketches.common.Util.LS; - -import java.math.BigInteger; - -import org.apache.datasketches.hash.MurmurHash3; - -/** - * Base class and API for all the maps. - * - * @author Lee Rhodes - * @author Alexander Saydakov - * @author Kevin Lang - */ -abstract class Map { - - static final long SEED = 1234567890L; - static final int SIX_BIT_MASK = 0X3F; // 6 bits - static final int TEN_BIT_MASK = 0X3FF; //10 bits - - // These parameters are tuned as a set to avoid pathological resizing. - // Consider modeling the behavior before changing any of them - static final int COUPON_MAP_MIN_NUM_ENTRIES = 157; - static final double COUPON_MAP_SHRINK_TRIGGER_FACTOR = 0.5; - static final double COUPON_MAP_GROW_TRIGGER_FACTOR = 15.0 / 16.0; - static final double COUPON_MAP_TARGET_FILL_FACTOR = 2.0 / 3.0; - static final int COUPON_MAP_MIN_NUM_ENTRIES_ARR_SIZE = (int)Math.ceil(COUPON_MAP_MIN_NUM_ENTRIES / 8.0); - - final int keySizeBytes_; - - Map(final int keySizeBytes) { - keySizeBytes_ = keySizeBytes; - } - - /** - * Update this map with a key and a coupon. - * Return the cardinality estimate of all identifiers that have been associated with this key, - * including this update. - * @param key the dimensional criteria for measuring cardinality - * @param coupon the property associated with the key for which cardinality is to be measured. - * @return the cardinality estimate of all identifiers that have been associated with this key, - * including this update. - */ - abstract double update(byte[] key, short coupon); - - /** - * Updates this map with an index and a coupon - * @param index the given index - * @param coupon the given coupon - * @return the cardinality estimate of all identifiers that have been associated with this key, - * including this update. - */ - abstract double update(int index, short coupon); - - /** - * Returns the estimate of the cardinality of identifiers associated with the given key. - * @param key the given key - * @return the estimate of the cardinality of identifiers associated with the given key. - */ - abstract double getEstimate(byte[] key); - - /** - * Update the internal estimate at the given index - * @param index the given index - * @param estimate the given estimate - */ - void updateEstimate(final int index, final double estimate) { /* overridden by sub-classes */ } - - /** - * Returns the upper bound cardinality with respect to {@link #getEstimate(byte[])} associated - * with the given key. This approximates the RSE with 68% confidence. - * @param key the given key - * @return the upper bound cardinality with respect to {@link #getEstimate(byte[])} associated - * with the given key. - */ - abstract double getUpperBound(byte[] key); - - /** - * Returns the lower bound cardinality with respect to {@link #getEstimate(byte[])} associated - * with the given key. This approximates the RSE with 68% confidence. - * @param key the given key - * @return the lower bound cardinality with respect to {@link #getEstimate(byte[])} associated - * with the given key. - */ - abstract double getLowerBound(byte[] key); - - abstract int findKey(byte[] key); - - abstract int findOrInsertKey(byte[] key); - - abstract CouponsIterator getCouponsIterator(int index); - - abstract int getMaxCouponsPerEntry(); - - abstract int getCapacityCouponsPerEntry(); - - abstract int getActiveEntries(); - - abstract int getDeletedEntries(); - - abstract double getEntrySizeBytes(); - - abstract int getTableEntries(); - - abstract int getCapacityEntries(); - - abstract int getCurrentCountEntries(); - - abstract long getTotalUsageBytes(); - - int getKeySizeBytes() { - return keySizeBytes_; - } - - /** - * Delete the key at the given index - * @param index the given index - */ - void deleteKey(final int index) { /* overridden by sub-classes */ } - - /** - * Returns true if the two specified sub-arrays of bytes are equal to one another. - * Two arrays are considered equal if all corresponding pairs of elements in the two arrays are - * equal. In other words, two arrays are equal if and only if they contain the same elements - * in the same order. - * - * @param a one sub-array to be tested for equality - * @param offsetA the offset in bytes of the start of sub-array a. - * @param b the other sub-array to be tested for equality - * @param offsetB the offset in bytes of the start of sub-array b. - * @param length the length in bytes of the two sub-arrays. - * @return true if the two sub-arrays are equal - */ - static final boolean arraysEqual(final byte[] a, final int offsetA, final byte[] b, - final int offsetB, final int length) { - for (int i = 0; i < length; i++) { - if (a[i + offsetA] != b[i + offsetB]) { - return false; - } - } - return true; - } - - /** - * Returns the HLL array index and value as a 16-bit coupon given the identifier to be hashed - * and k. - * @param identifier the given identifier - * @return the HLL array index and value - */ - static final int coupon16(final byte[] identifier) { - final long[] hash = MurmurHash3.hash(identifier, SEED); - final int hllIdx = (int) (((hash[0] >>> 1) % 1024) & TEN_BIT_MASK); //hash[0] for 10-bit address - final int lz = Long.numberOfLeadingZeros(hash[1]); - final int value = (lz > 62 ? 62 : lz) + 1; - return (value << 10) | hllIdx; - } - - static final int coupon16Value(final int coupon) { - return (coupon >>> 10) & SIX_BIT_MASK; - } - - static final int getIndex(final long hash, final int tableEntries) { - return (int) ((hash >>> 1) % tableEntries); - } - - static final int getStride(final long hash, final int tableEntries) { - return (int) (((hash >>> 1) % (tableEntries - 2L)) + 1L); - } - - static boolean isBitSet(final byte[] byteArr, final int bitIndex) { - final int byteIndex = bitIndex / 8; - final int mask = 1 << (bitIndex % 8); - return (byteArr[byteIndex] & mask) > 0; - } - - static boolean isBitClear(final byte[] byteArr, final int bitIndex) { - final int byteIndex = bitIndex / 8; - final int mask = 1 << (bitIndex % 8); - return (byteArr[byteIndex] & mask) == 0; - } - - static void clearBit(final byte[] byteArr, final int index) { - final int byteIndex = index / 8; - final int mask = 1 << (index % 8); - byteArr[byteIndex] &= ~mask; - } - - static void setBit(final byte[] bits, final int index) { - final int byteIndex = index / 8; - final int mask = 1 << (index % 8); - bits[byteIndex] |= mask; - } - - /** - * Returns the next prime number that is greater than the given target. There will be - * no prime numbers less than the returned prime number that are greater than the given target. - * @param target the starting value to begin the search for the next prime - * @return the next prime number that is greater than the given target. - */ - static int nextPrime(final int target) { - return BigInteger.valueOf(target).nextProbablePrime().intValueExact(); - } - - static String fmtLong(final long value) { - return String.format("%,d", value); - } - - static String fmtDouble(final double value) { - return String.format("%,.3f", value); - } - - @Override - public String toString() { - final String mcpe = Map.fmtLong(getMaxCouponsPerEntry()); - final String ccpe = Map.fmtLong(getCapacityCouponsPerEntry()); - final String te = Map.fmtLong(getTableEntries()); - final String ce = Map.fmtLong(getCapacityEntries()); - final String cce = Map.fmtLong(getCurrentCountEntries()); - final String ae = Map.fmtLong(getActiveEntries()); - final String de = Map.fmtLong(getDeletedEntries()); - final String esb = Map.fmtDouble(getEntrySizeBytes()); - final String mub = Map.fmtLong(getTotalUsageBytes()); - - final StringBuilder sb = new StringBuilder(); - final String thisSimpleName = this.getClass().getSimpleName(); - sb.append("### ").append(thisSimpleName).append(" SUMMARY: ").append(LS); - sb.append(" Max Coupons Per Entry : ").append(mcpe).append(LS); - sb.append(" Capacity Coupons Per Entry: ").append(ccpe).append(LS); - sb.append(" Table Entries : ").append(te).append(LS); - sb.append(" Capacity Entries : ").append(ce).append(LS); - sb.append(" Current Count Entries : ").append(cce).append(LS); - sb.append(" Active Entries : ").append(ae).append(LS); - sb.append(" Deleted Entries : ").append(de).append(LS); - sb.append(" Entry Size Bytes : ").append(esb).append(LS); - sb.append(" Memory Usage Bytes : ").append(mub).append(LS); - sb.append("### END SKETCH SUMMARY").append(LS); - return sb.toString(); - } - -} diff --git a/src/main/java/org/apache/datasketches/hllmap/SingleCouponMap.java b/src/main/java/org/apache/datasketches/hllmap/SingleCouponMap.java deleted file mode 100644 index 4f96b120d..000000000 --- a/src/main/java/org/apache/datasketches/hllmap/SingleCouponMap.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hllmap; - -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.hash.MurmurHash3; - -/** - * Implements a key-value map where the value is a single coupon or a map reference. - * This map holds all keys for all levels of the {@link UniqueCountMap}. - * This map is implemented with a prime sized Open Address, Double Hash, with a 1-bit state array, - * which indicates the contents of the value. - * - * @author Lee Rhodes - * @author Alexander Saydakov - * @author Kevin Lang - */ -final class SingleCouponMap extends Map { - private static final double RSE = 0.408 / Math.sqrt(1024); - - private int tableEntries_; - private int capacityEntries_; - private int curCountEntries_; - private double entrySizeBytes_; - - // Arrays - private byte[] keysArr_; - private short[] couponsArr_; - - /** - *

  • state: 0: empty or valid; empty if coupon is 0, otherwise valid.
  • - *
  • state: 1: original coupon has been promoted, current coupon contains a table # - * reference instead.
  • - *
- */ - private byte[] stateArr_; - - private SingleCouponMap(final int keySizeBytes) { - super(keySizeBytes); - } - - static SingleCouponMap getInstance(final int initialNumEntries, final int keySizeBytes) { - final int tableEntries = nextPrime(initialNumEntries); - - final SingleCouponMap map = new SingleCouponMap(keySizeBytes); - map.tableEntries_ = tableEntries; - map.capacityEntries_ = (int)(tableEntries * COUPON_MAP_GROW_TRIGGER_FACTOR); - map.curCountEntries_ = 0; - map.entrySizeBytes_ = updateEntrySizeBytes(tableEntries, keySizeBytes); - - map.keysArr_ = new byte[tableEntries * map.keySizeBytes_]; - map.couponsArr_ = new short[tableEntries]; - map.stateArr_ = new byte[(int) Math.ceil(tableEntries / 8.0)]; - return map; - } - - @Override - double update(final byte[] key, final short coupon) { - final int entryIndex = findOrInsertKey(key); - return update(entryIndex, coupon); - } - - @Override - double update(final int entryIndex, final short coupon) { - if (couponsArr_[entryIndex] == 0) { - couponsArr_[entryIndex] = coupon; - return 1; - } - if (isCoupon(entryIndex)) { - if (couponsArr_[entryIndex] == coupon) { //duplicate - return 1; - } - return 0; // signal to promote - } - return -couponsArr_[entryIndex]; // negative level number - } - - @Override - double getEstimate(final byte[] key) { - final int entryIndex = findKey(key); - if (entryIndex < 0) { return 0; } - if (isCoupon(entryIndex)) { return 1; } - return -getCoupon(entryIndex); // negative: level #, zero: signal to promote - } - - @Override - double getUpperBound(final byte[] key) { - return getEstimate(key) * (1 + RSE); - } - - @Override - double getLowerBound(final byte[] key) { - return getEstimate(key) * (1 - RSE); - } - - /** - * Returns entryIndex if the given key is found. The coupon may be valid or contain a table index. - * If not found, returns one's complement entryIndex - * of an empty slot for insertion, which may be over a deleted key. - * @param key the given key - * @return the entryIndex - */ - @Override - int findKey(final byte[] key) { - final long[] hash = MurmurHash3.hash(key, SEED); - int entryIndex = getIndex(hash[0], tableEntries_); - final int stride = getStride(hash[1], tableEntries_); - final int loopIndex = entryIndex; - - do { - if (couponsArr_[entryIndex] == 0) { - return ~entryIndex; //empty - } - if (Map.arraysEqual(key, 0, keysArr_, entryIndex * keySizeBytes_, keySizeBytes_)) { - return entryIndex; - } - entryIndex = (entryIndex + stride) % tableEntries_; - } while (entryIndex != loopIndex); - throw new SketchesArgumentException("Key not found and no empty slots!"); - } - - @Override - int findOrInsertKey(final byte[] key) { - int entryIndex = findKey(key); - if (entryIndex < 0) { - if (curCountEntries_ + 1 > capacityEntries_) { - resize(); - entryIndex = findKey(key); - assert entryIndex < 0; - } - entryIndex = ~entryIndex; - System.arraycopy(key, 0, keysArr_, entryIndex * keySizeBytes_, keySizeBytes_); - curCountEntries_++; - } - return entryIndex; - } - - @Override - CouponsIterator getCouponsIterator(final int entryIndex) { - return new CouponsIterator(couponsArr_, entryIndex, 1); - } - - @Override - int getMaxCouponsPerEntry() { - return 1; - } - - @Override - int getCapacityCouponsPerEntry() { - return 1; - } - - @Override - int getActiveEntries() { - return curCountEntries_; - } - - @Override - int getDeletedEntries() { - return 0; - } - - boolean isCoupon(final int entryIndex) { - return !isBitSet(stateArr_, entryIndex); - } - - short getCoupon(final int entryIndex) { - return couponsArr_[entryIndex]; - } - - void setCoupon(final int entryIndex, final short coupon, final boolean isLevel) { - couponsArr_[entryIndex] = coupon; - if (isLevel) { - setBit(stateArr_, entryIndex); - } else { - clearBit(stateArr_, entryIndex); - } - } - - void setLevel(final int entryIndex, final int level) { - couponsArr_[entryIndex] = (short) level; - setBit(stateArr_, entryIndex); - } - - @Override - double getEntrySizeBytes() { - return entrySizeBytes_; - } - - @Override - int getTableEntries() { - return tableEntries_; - } - - @Override - int getCapacityEntries() { - return capacityEntries_; - } - - @Override - int getCurrentCountEntries() { - return curCountEntries_; - } - - @Override - long getTotalUsageBytes() { - final long arrays = keysArr_.length - + (long)couponsArr_.length * Short.BYTES - + stateArr_.length; - final long other = 4 * 4 + 8; - return arrays + other; - } - - private void resize() { - final byte[] oldKeysArr = keysArr_; - final short[] oldCouponsArr = couponsArr_; - final byte[] oldStateArr = stateArr_; - final int oldTableEntries = tableEntries_; - tableEntries_ = nextPrime((int) (curCountEntries_ / COUPON_MAP_TARGET_FILL_FACTOR)); - capacityEntries_ = (int)(tableEntries_ * COUPON_MAP_GROW_TRIGGER_FACTOR); - keysArr_ = new byte[tableEntries_ * keySizeBytes_]; - couponsArr_ = new short[tableEntries_]; - stateArr_ = new byte[(int) Math.ceil(tableEntries_ / 8.0)]; - entrySizeBytes_ = updateEntrySizeBytes(tableEntries_, keySizeBytes_); - //move the data - for (int i = 0; i < oldTableEntries; i++) { - if (oldCouponsArr[i] != 0) { - final byte[] key = - Arrays.copyOfRange(oldKeysArr, i * keySizeBytes_, i * keySizeBytes_ + keySizeBytes_); - insertEntry(key, oldCouponsArr[i], isBitSet(oldStateArr, i)); - } - } - } - - // for internal use during resize, so no resize check here - private void insertEntry(final byte[] key, final int coupon, final boolean setStateOne) { - final long[] hash = MurmurHash3.hash(key, SEED); - int entryIndex = getIndex(hash[0], tableEntries_); - final int stride = getStride(hash[1], tableEntries_); - final int loopIndex = entryIndex; - do { - if (couponsArr_[entryIndex] == 0) { - System.arraycopy(key, 0, keysArr_, entryIndex * keySizeBytes_, keySizeBytes_); - setCoupon(entryIndex, (short)coupon, setStateOne); - return; - } - entryIndex = (entryIndex + stride) % tableEntries_; - } while (entryIndex != loopIndex); - throw new SketchesArgumentException("Key not found and no empty slots!"); - } - - private static final double updateEntrySizeBytes(final int tableEntries, final int keySizeBytes) { - final double byteFraction = Math.ceil(tableEntries / 8.0) / tableEntries; - return keySizeBytes + Short.BYTES + byteFraction; - } - -} diff --git a/src/main/java/org/apache/datasketches/hllmap/UniqueCountMap.java b/src/main/java/org/apache/datasketches/hllmap/UniqueCountMap.java deleted file mode 100644 index 28274f648..000000000 --- a/src/main/java/org/apache/datasketches/hllmap/UniqueCountMap.java +++ /dev/null @@ -1,364 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hllmap; - -import static org.apache.datasketches.common.Util.LS; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This is a real-time, key-value HLL mapping sketch that tracks approximate unique counts of - * identifiers (the values) associated with each key. An example might be tracking the number of - * unique user identifiers associated with each IP address. This map has been specifically designed - * for the use-case where the number of keys is quite large (many millions) and the distribution of - * identifiers per key is very skewed. A typical distribution where this works well is a - * power-law distribution of identifiers per key of the form y = Cx, - * where α < 0.5, and C is roughly ymax. - * For example, with 100M keys, over 75% of the keys would have only - * one identifier, 99% of the keys would have less than 20 identifiers, 99.9% would have less than - * 200 identifiers, and a very tiny fraction might have identifiers in the thousands. - * - *

The space consumed by this map is quite sensitive to the actual distribution of identifiers - * per key, so you should characterize and or experiment with your typical input streams. - * Nonetheless, our experiments on live streams of over 100M keys required about 1.4GB of space. - * This is about 14 bytes per key for key storage and unique count storage. - * - *

Given such highly-skewed distributions, using this map is far more efficient space-wise than - * the alternative of dedicating an HLL sketch per key. Based on our use cases, after - * subtracting the space required for key storage, the average bytes per key required for unique - * count estimation ({@link #getAverageSketchBytesPerKey()}) is about 10. - * - *

Internally, this map is implemented as a hierarchy of internal hash maps with progressively - * increasing storage allocated for unique count estimation. As a key acquires more identifiers it - * is "promoted" up to a higher internal map. The final map of keys is a map of compact HLL - * sketches. - * - *

The unique values in all the internal maps, except the final HLL map, are stored in a special - * form called a coupon. A coupon is a 16-bit value that fully describes a k=1024 HLL bin. - * It contains 10 bits of address and a 6-bit HLL value. - * - *

All internal maps use a prime number size and Knuth's Open Addressing Double Hash (OADH) - * search algorithm. - * - *

The internal base map holds all the keys and each key is associated with one 16-bit value. - * Initially, the value is a single coupon. Once the key is promoted, this 16-bit field contains a - * reference to the internal map where the key is still active. - * - *

The intermediate maps between the base map and the final HLL map are of two types. - * The first few of these are called traverse maps where the coupons are - * stored as unsorted arrays. After the traverse maps are the coupon hash maps, where the coupons - * are stored in small OASH hash tables. - * - *

All the intermediate maps support deletes and can dynamically grow and shrink as required by - * the input stream. - * - *

The sketch estimator algorithms are unbiased with a Relative Standard Error (RSE) - * of about 2.6% with 68% confidence, or equivalently, about 5.2% with a 95% confidence. - * - *

In a parallel package in the sketches-misc repository, there are 2 classes that can be used - * from the command line to feed this mapping sketch piped from standard-in for experimental - * evaluation. The first is ProcessIpStream, which processes simple IP/ID pairs and the second, - * ProcessDistributionStream, which processes pairs that describe a distribution. - * In this same package is the VariousMapRSETest class that was used to generate the error plots - * for the web site. Please refer to the javadocs for those classes for more information. - * - * @author Lee Rhodes - * @author Alexander Saydakov - * @author Kevin Lang - */ -public final class UniqueCountMap { - private static final int NUM_LEVELS = 10; // total of single coupon + traverse + coupon maps + hll - private static final int NUM_TRAVERSE_MAPS = 3; - private static final int HLL_K = 1024; - private static final int INITIAL_NUM_ENTRIES = 1000003; - private static final int MIN_INITIAL_NUM_ENTRIES = 157; - private final int keySizeBytes_; - - /** TraverseCouponMap or HashCouponMap instances */ - private final Map[] maps_; - - /** - * Constructs a UniqueCountMap with an initial capacity of one million entries. - * @param keySizeBytes must be at least 4 bytes to have sufficient entropy. - */ - public UniqueCountMap(final int keySizeBytes) { - this(INITIAL_NUM_ENTRIES, keySizeBytes); - } - - /** - * Constructs a UniqueCountMap with a given initial number of entries. - * - * @param initialNumEntries The initial number of entries provides a tradeoff between - * wasted space, if too high, and wasted time resizing the table, if too low. - * @param keySizeBytes must be at least 4 bytes to have sufficient entropy - */ - public UniqueCountMap(final int initialNumEntries, final int keySizeBytes) { - checkConstructorKeySize(keySizeBytes); - final int initEntries = Math.max(initialNumEntries, MIN_INITIAL_NUM_ENTRIES); - keySizeBytes_ = keySizeBytes; - maps_ = new Map[NUM_LEVELS]; // includes base level and top level - maps_[0] = SingleCouponMap.getInstance(initEntries, keySizeBytes); - } - - /** - * Updates the map with a given key and identifier and returns the estimate of the number of - * unique identifiers encountered so far for the given key. - * @param key the given key - * @param identifier the given identifier for unique counting associated with the key - * @return the estimate of the number of unique identifiers encountered so far for the given key. - */ - public double update(final byte[] key, final byte[] identifier) { - if (key == null) { return Double.NaN; } - checkMethodKeySize(key); - if (identifier == null) { return getEstimate(key); } - final short coupon = (short) Map.coupon16(identifier); - - final int baseMapIndex = maps_[0].findOrInsertKey(key); - final double baseMapEstimate = maps_[0].update(baseMapIndex, coupon); - if (baseMapEstimate > 0) { return baseMapEstimate; } - final int level = -(int) baseMapEstimate; // base map is level 0 - if (level == 0) { - return promote(key, coupon, maps_[0], baseMapIndex, level, baseMapIndex, 0); - } - - final Map map = maps_[level]; - final int index = map.findOrInsertKey(key); - final double estimate = map.update(index, coupon); - if (estimate > 0) { return estimate; } - return promote(key, coupon, map, index, level, baseMapIndex, -estimate); - } - - /** - * Retrieves the current estimate of unique count for a given key. - * @param key given key - * @return estimate of unique count so far - */ - public double getEstimate(final byte[] key) { - if (key == null) { return Double.NaN; } - checkMethodKeySize(key); - final double est = maps_[0].getEstimate(key); - if (est >= 0.0) { return est; } - //key has been promoted - final int level = -(int)est; - final Map map = maps_[level]; - return map.getEstimate(key); - } - - /** - * Returns the upper bound cardinality with respect to {@link #getEstimate(byte[])} associated - * with the given key. - * @param key the given key - * @return the upper bound cardinality with respect to {@link #getEstimate(byte[])} associated - * with the given key. - */ - public double getUpperBound(final byte[] key) { - if (key == null) { return Double.NaN; } - checkMethodKeySize(key); - final double est = maps_[0].getEstimate(key); - if (est >= 0.0) { return est; } - //key has been promoted - final int level = -(int)est; - final Map map = maps_[level]; - return map.getUpperBound(key); - } - - /** - * Returns the lower bound cardinality with respect to {@link #getEstimate(byte[])} associated - * with the given key. - * @param key the given key - * @return the lower bound cardinality with respect to {@link #getEstimate(byte[])} associated - * with the given key. - */ - public double getLowerBound(final byte[] key) { - if (key == null) { return Double.NaN; } - checkMethodKeySize(key); - final double est = maps_[0].getEstimate(key); - if (est >= 0.0) { return est; } - //key has been promoted - final int level = -(int)est; - final Map map = maps_[level]; - return map.getLowerBound(key); - } - - /** - * Returns the number of active, unique keys across all internal maps - * @return the number of active, unique keys across all internal maps - */ - public int getActiveEntries() { - return maps_[0].getCurrentCountEntries(); - } - - /** - * Returns total bytes used by all internal maps - * @return total bytes used by all internal maps - */ - public long getTotalUsageBytes() { - long total = 0; - for (int i = 0; i < maps_.length; i++) { - if (maps_[i] != null) { - total += maps_[i].getTotalUsageBytes(); - } - } - return total; - } - - /** - * Returns total bytes used for key storage - * @return total bytes used for key storage - */ - public long getKeyUsageBytes() { - long total = 0; - for (int i = 0; i < maps_.length; i++) { - if (maps_[i] != null) { - total += (long) (maps_[i].getActiveEntries()) * keySizeBytes_; - } - } - return total; - } - - /** - * Returns the average bytes storage per key that is dedicated to sketching the unique counts. - * @return the average bytes storage per key that is dedicated to sketching the unique counts. - */ - public double getAverageSketchBytesPerKey() { - return (double) (getTotalUsageBytes() - getKeyUsageBytes()) / getActiveEntries(); - } - - /** - * Returns the number of active internal maps so far. - * Only the base map is initialized in the constructor, so this method would return 1. - * As more keys are promoted up to higher level maps, the return value would grow until the - * last level HLL map is allocated. - * @return the number of active levels so far - */ - int getActiveMaps() { - int levels = 0; - final int iMapsLen = maps_.length; - for (int i = 0; i < iMapsLen; i++) { - if (maps_[i] != null) { levels++; } - } - return levels; - } - - /** - * Returns the base map - * @return the base map - */ - Map getBaseMap() { - return maps_[0]; - } - - /** - * Returns the top-level HllMap. It may be null. - * @return the top-level HllMap. - */ - Map getHllMap() { - return maps_[maps_.length - 1]; - } - - /** - * Returns a string with a human-readable summary of the UniqueCountMap and all the internal maps - * @return human-readable summary - */ - @Override - public String toString() { - final long totKeys = getActiveEntries(); - final long totBytes = getTotalUsageBytes(); - final long keyBytes = getKeyUsageBytes(); - final double avgValBytesPerKey = getAverageSketchBytesPerKey(); - - final String ksb = Map.fmtLong(keySizeBytes_); - final String alvls = Map.fmtLong(getActiveMaps()); - final String tKeys = Map.fmtLong(totKeys); - final String tBytes = Map.fmtLong(totBytes); - final String kBytes = Map.fmtLong(keyBytes); - final String avgValBytes = Map.fmtDouble(avgValBytesPerKey); - - - final StringBuilder sb = new StringBuilder(); - final String thisSimpleName = this.getClass().getSimpleName(); - sb.append("## ").append(thisSimpleName).append(" SUMMARY: ").append(LS); - sb.append(" Key Size Bytes : ").append(ksb).append(LS); - sb.append(" Active Map Levels : ").append(alvls).append(LS); - sb.append(" Total keys : ").append(tKeys).append(LS); - sb.append(" Total Usage Bytes : ").append(tBytes).append(LS); - sb.append(" Total Key Usage Bytes : ").append(kBytes).append(LS); - sb.append(" Avg Sketch Usage Bytes/Key : ").append(avgValBytes).append(LS); - sb.append(LS); - for (int i = 0; i < maps_.length; i++) { - final Map cMap = maps_[i]; - if (cMap != null) { - sb.append(cMap.toString()); - sb.append(LS); - } - } - sb.append("## ").append("END UNIQUE COUNT MAP SUMMARY"); - sb.append(LS); - return sb.toString(); - } - - private void setLevelInBaseMap(final int index, final int level) { - ((SingleCouponMap) maps_[0]).setLevel(index, level); - } - - private double promote(final byte[] key, final short coupon, final Map fromMap, final int fromIndex, - final int fromLevel, final int baseMapIndex, final double estimate) { - final Map newMap = getMapForLevel(fromLevel + 1); - final int newMapIndex = newMap.findOrInsertKey(key); - final CouponsIterator it = fromMap.getCouponsIterator(fromIndex); - while (it.next()) { - final double est = newMap.update(newMapIndex, it.getValue()); - assert est > 0; - } - fromMap.deleteKey(fromIndex); - newMap.updateEstimate(newMapIndex, estimate); - final double newEstimate = newMap.update(newMapIndex, coupon); - setLevelInBaseMap(baseMapIndex, fromLevel + 1); - assert newEstimate > 0; // this must be positive since we have just promoted - return newEstimate; - } - - private Map getMapForLevel(final int level) { - if (maps_[level] == null) { - final int newLevelCapacity = 1 << level; - if (level <= NUM_TRAVERSE_MAPS) { - maps_[level] = CouponTraverseMap.getInstance(keySizeBytes_, newLevelCapacity); - } else if (level < (maps_.length - 1)) { - maps_[level] = CouponHashMap.getInstance(keySizeBytes_, newLevelCapacity); - } else { - maps_[level] = HllMap.getInstance(keySizeBytes_, HLL_K); - } - } - return maps_[level]; - } - - private static final void checkConstructorKeySize(final int keySizeBytes) { - if (keySizeBytes < 4) { - throw new SketchesArgumentException("KeySizeBytes must be >= 4: " + keySizeBytes); - } - } - - private final void checkMethodKeySize(final byte[] key) { - if (key.length != keySizeBytes_) { - throw new SketchesArgumentException("Key size must be " + keySizeBytes_ + " bytes."); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/hllmap/package-info.java b/src/main/java/org/apache/datasketches/hllmap/package-info.java deleted file mode 100644 index 20428b04f..000000000 --- a/src/main/java/org/apache/datasketches/hllmap/package-info.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * The hllmap package contains a space efficient HLL mapping sketch of keys to approximate unique - * count of identifiers. For example, counting the number of unique users (identifiers) per IP - * address. - * - *

In cases where the number of keys is very large, having an individual HLL sketch per key may - * not be practical. If the distribution of values per key is highly skewed where the vast - * majority of keys have only a few values then this mapping sketch will make sense as it will be - * far more space efficient than dedicating individual HLL sketches per key. - * - *

From our own testing, sketching 100 million IPv4 addresses with such a - * highly skewed distribution of identifiers per IP uses only 1.4GB of memory. This translates to - * an average of about 10 bytes per IP allocated to the equivalent of a full k=1024 HLL sketch - * and provides an RSE of less than 2.5%. Your results will vary depending on the actual - * distribution of identifiers per key. - * - * @see org.apache.datasketches.hllmap.UniqueCountMap - */ -package org.apache.datasketches.hllmap; diff --git a/src/main/java/org/apache/datasketches/kll/KllDirectCompactItemsSketch.java b/src/main/java/org/apache/datasketches/kll/KllDirectCompactItemsSketch.java deleted file mode 100644 index 477a7fc5e..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllDirectCompactItemsSketch.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR_SINGLE_ITEM; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentK; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentLevelZeroSortedFlag; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentM; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentMinK; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentN; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; - -import java.lang.foreign.MemorySegment; -import java.lang.reflect.Array; -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfBooleansSerDe; -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This class implements an off-heap, read-only KllItemsSketch using MemorySegment. - * - *

Please refer to the documentation in the package-info:
- * {@link org.apache.datasketches.kll}

- * - * @author Lee Rhodes, Kevin Lang - */ -@SuppressWarnings("unchecked") -final class KllDirectCompactItemsSketch extends KllItemsSketch { - private final MemorySegment seg; - - /** - * Internal implementation of the wrapped MemorySegment KllSketch. - * @param segVal the MemoryValadate object - * @param comparator to compare items - * @param serDe Serializer / deserializer for items of type T and T[]. - */ - KllDirectCompactItemsSketch( //called below and KllItemsSketch - final KllMemorySegmentValidate segVal, - final Comparator comparator, - final ArrayOfItemsSerDe serDe) { - super(segVal.sketchStructure, comparator, serDe); - seg = segVal.srcSeg.asReadOnly(); - readOnly = true; - levelsArr = segVal.levelsArr; //always converted to writable form. - } - - //End of constructors - - @Override - String getItemAsString(final int index) { - if (isEmpty()) { return "Null"; } - return serDe.toString(getTotalItemsArray()[index]); - } - - @Override - public int getK() { - return getMemorySegmentK(seg); - } - - //MinMax Methods - - @Override - public T getMaxItem() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { - throw new SketchesArgumentException(EMPTY_MSG); - } - if (sketchStructure == COMPACT_SINGLE) { - return serDe.deserializeFromMemorySegment(seg, DATA_START_ADR_SINGLE_ITEM, 1)[0]; - } - //sketchStructure == COMPACT_FULL - final int baseOffset = DATA_START_ADR + (getNumLevels() * Integer.BYTES); - final int offset = baseOffset + serDe.sizeOf(seg, baseOffset, 1); //size of minItem - - return serDe.deserializeFromMemorySegment(seg, offset, 1)[0]; - } - - @Override - String getMaxItemAsString() { - if (isEmpty()) { return "Null"; } - return serDe.toString(getMaxItem()); - } - - @Override - public T getMinItem() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { - throw new SketchesArgumentException(EMPTY_MSG); - } - if (sketchStructure == COMPACT_SINGLE) { - return serDe.deserializeFromMemorySegment(seg, DATA_START_ADR_SINGLE_ITEM, 1)[0]; - } - //sketchStructure == COMPACT_FULL - final int offset = DATA_START_ADR + (getNumLevels() * Integer.BYTES); - return serDe.deserializeFromMemorySegment(seg, offset, 1)[0]; - } - - @Override - String getMinItemAsString() { - if (isEmpty()) { return "Null"; } - return serDe.toString(getMinItem()); - } - - @Override - public long getN() { - if (sketchStructure == COMPACT_EMPTY) { return 0; } - if (sketchStructure == COMPACT_SINGLE) { return 1; } - return getMemorySegmentN(seg); - } - - //restricted - - private int getCompactDataOffset() { //Sketch cannot be empty - return sketchStructure == COMPACT_SINGLE - ? DATA_START_ADR_SINGLE_ITEM - : DATA_START_ADR + (getNumLevels() * Integer.BYTES) + getMinMaxSizeBytes(); - } - - @Override - int getM() { - return getMemorySegmentM(seg); - } - - @Override - int getMinK() { - if ((sketchStructure == COMPACT_EMPTY) || (sketchStructure == COMPACT_SINGLE)) { return getMemorySegmentK(seg); } - return getMemorySegmentMinK(seg); - } - - @Override - byte[] getMinMaxByteArr() { //this is only used by COMPACT_FULL - final int offset = DATA_START_ADR + (getNumLevels() * Integer.BYTES); - final int bytesMinMax = serDe.sizeOf(seg, offset, 2); - final byte[] byteArr = new byte[bytesMinMax]; - MemorySegment.copy(seg, JAVA_BYTE, offset, byteArr, 0, bytesMinMax); - return byteArr; - } - - @Override - int getMinMaxSizeBytes() { //this is only used by COMPACT_FULL - final int offset = DATA_START_ADR + (getNumLevels() * Integer.BYTES); - if (serDe instanceof ArrayOfBooleansSerDe) { return 2; } - return serDe.sizeOf(seg, offset, 2); - } - - @Override - T[] getRetainedItemsArray() { - final int numRet = getNumRetained(); - if ((sketchStructure == COMPACT_EMPTY) || (getN() == 0)) { - return (T[]) Array.newInstance(serDe.getClassOfT(), numRet); - } - final int offset = getCompactDataOffset(); //both single & full - return serDe.deserializeFromMemorySegment(seg, offset, numRet); - } - - @Override - byte[] getRetainedItemsByteArr() { - if ((sketchStructure == COMPACT_EMPTY) || (getN() == 0)) { return new byte[0]; } - final int offset = getCompactDataOffset(); //both single & full - final int bytes = serDe.sizeOf(seg, offset, getNumRetained()); - final byte[] byteArr = new byte[bytes]; - MemorySegment.copy(seg, JAVA_BYTE, offset, byteArr, 0, bytes); - return byteArr; - } - - @Override - int getRetainedItemsSizeBytes() { - if ((sketchStructure == COMPACT_EMPTY) || (getN() == 0)) { return 0; } - final int offset = getCompactDataOffset(); //both single & full - return serDe.sizeOf(seg, offset, getNumRetained()); - } - - @Override - T getSingleItem() { - if (getN() != 1) { throw new SketchesArgumentException(NOT_SINGLE_ITEM_MSG); } - final int offset = getCompactDataOffset(); //both single & full - return (serDe.deserializeFromMemorySegment(seg, offset, 1)[0]); - } - - @Override - byte[] getSingleItemByteArr() { - if (getN() != 1) { throw new SketchesArgumentException(NOT_SINGLE_ITEM_MSG); } - final int offset = getCompactDataOffset(); //both single & full - final int bytes = serDe.sizeOf(seg, offset, 1); - final byte[] byteArr = new byte[bytes]; - MemorySegment.copy(seg, JAVA_BYTE, offset, byteArr, 0, bytes); - return byteArr; - } - - @Override - int getSingleItemSizeBytes() { - if (getN() != 1) { throw new SketchesArgumentException(NOT_SINGLE_ITEM_MSG); } - final int offset = getCompactDataOffset(); //both single & full - return serDe.sizeOf(seg, offset, 1); - } - - @Override - T[] getTotalItemsArray() { - final int k = getK(); - if (getN() == 0) { return (T[]) Array.newInstance(serDe.getClassOfT(), k); } - if (getN() == 1) { - final T[] itemsArr = (T[]) Array.newInstance(serDe.getClassOfT(), k); - itemsArr[k - 1] = getSingleItem(); - return itemsArr; - } - final int offset = getCompactDataOffset(); - final int numRetItems = getNumRetained(); - final int numCapItems = levelsArr[getNumLevels()]; - final T[] retItems = serDe.deserializeFromMemorySegment(seg, offset, numRetItems); - final T[] capItems = (T[]) Array.newInstance(serDe.getClassOfT(), numCapItems); - System.arraycopy(retItems, 0, capItems, levelsArr[0], numRetItems); - return capItems; - } - - @Override - MemorySegment getMemorySegment() { - return seg; - } - - @Override - void incN(final int increment) { - throw new SketchesArgumentException(UNSUPPORTED_MSG); - } - - @Override - boolean isLevelZeroSorted() { - return getMemorySegmentLevelZeroSortedFlag(seg); - } - - @Override - void setItemsArray(final Object[] ItemsArr) { - throw new SketchesArgumentException(UNSUPPORTED_MSG); - } - - @Override - void setItemsArrayAt(final int index, final Object item) { - throw new SketchesArgumentException(UNSUPPORTED_MSG); - } - - @Override - void setLevelZeroSorted(final boolean sorted) { - throw new SketchesArgumentException(UNSUPPORTED_MSG); - } - - @Override - void setMaxItem(final Object item) { - throw new SketchesArgumentException(UNSUPPORTED_MSG); - } - - @Override - void setMinItem(final Object item) { - throw new SketchesArgumentException(UNSUPPORTED_MSG); - } - - @Override - void setMinK(final int minK) { - throw new SketchesArgumentException(UNSUPPORTED_MSG); - } - - @Override - void setN(final long n) { - throw new SketchesArgumentException(UNSUPPORTED_MSG); - } - - @Override - public boolean hasMemorySegment() { - return (seg != null) && seg.scope().isAlive(); - } - - @Override - public boolean isOffHeap() { - return hasMemorySegment() && seg.isNative(); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return MemorySegmentStatus.isSameResource(seg, that); - } - - @Override - MemorySegmentRequest getMemorySegmentRequest() { - return null; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllDirectDoublesSketch.java b/src/main/java/org/apache/datasketches/kll/KllDirectDoublesSketch.java deleted file mode 100644 index 0283c015b..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllDirectDoublesSketch.java +++ /dev/null @@ -1,398 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.common.ByteArrayUtil.copyBytes; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR_SINGLE_ITEM; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentK; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentLevelZeroSortedFlag; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentM; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentMinK; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentN; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentNumLevels; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentFamilyID; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentK; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentLevelZeroSortedFlag; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentM; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentMinK; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentN; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentNumLevels; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentPreInts; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentSerVer; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_DOUBLES_SKETCH; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ByteArrayUtil; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This class implements an off-heap, updatable KllDoublesSketch using MemorySegment. - * - *

Please refer to the documentation in the package-info:
- * {@link org.apache.datasketches.kll}

- * - * @author Lee Rhodes, Kevin Lang - */ -class KllDirectDoublesSketch extends KllDoublesSketch { - private MemorySegment wseg; - private final MemorySegmentRequest mSegReq; - - /** - * Constructs from MemorySegment or MemorySegment already initialized with a sketch image and validated. - * @param wseg the current MemorySegment - * @param segVal the MemorySegment Validate object - * @param mSegmentRequest the MemorySegmentRequest object. - */ - KllDirectDoublesSketch( - final MemorySegment wseg, - final KllMemorySegmentValidate segVal, - final MemorySegmentRequest mSegmentRequest) { - super(segVal); - this.wseg = wseg; - mSegReq = mSegmentRequest; - } - - /** - * Create a new updatable, direct instance of this sketch. - * @param k parameter that controls size of the sketch and accuracy of estimates - * @param m parameter that controls the minimum level width in items. - * @param dstSeg the given destination MemorySegment object for use by the sketch - * @param mSegReq the callback for the sketch to request a larger MemorySegment. - * @return a new instance of this sketch - */ - static KllDirectDoublesSketch newDirectUpdatableInstance( - final int k, - final int m, - final MemorySegment dstSeg, - final MemorySegmentRequest mSegmentRequest) { - setMemorySegmentPreInts(dstSeg, UPDATABLE.getPreInts()); - setMemorySegmentSerVer(dstSeg, UPDATABLE.getSerVer()); - setMemorySegmentFamilyID(dstSeg, Family.KLL.getID()); - setMemorySegmentK(dstSeg, k); - setMemorySegmentM(dstSeg, m); - setMemorySegmentN(dstSeg, 0); - setMemorySegmentMinK(dstSeg, k); - setMemorySegmentNumLevels(dstSeg, 1); - int offset = DATA_START_ADR; - //new Levels array - MemorySegment.copy(new int[] {k, k}, 0, dstSeg, JAVA_INT_UNALIGNED, offset, 2); - offset += 2 * Integer.BYTES; - //new min/max array - MemorySegment.copy(new double[] {Double.NaN, Double.NaN}, 0, dstSeg, JAVA_DOUBLE_UNALIGNED, offset, 2); - offset += 2 * ITEM_BYTES; - //new empty items array - MemorySegment.copy(new double[k], 0, dstSeg, JAVA_DOUBLE_UNALIGNED, offset, k); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(dstSeg, KLL_DOUBLES_SKETCH, null); - final MemorySegment wSeg = dstSeg; - return new KllDirectDoublesSketch(wSeg, segVal, mSegmentRequest); - } - - //End of constructors - - @Override - String getItemAsString(final int index) { - if (isEmpty()) { return "NaN"; } - return Double.toString(getDoubleItemsArray()[index]); - } - - @Override - public int getK() { - return getMemorySegmentK(wseg); - } - - //MinMax Methods - - @Override - public double getMaxItem() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - if (sketchStructure == COMPACT_SINGLE) { return getDoubleSingleItem(); } - //either compact-full or updatable - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ITEM_BYTES; - return wseg.get(JAVA_DOUBLE_UNALIGNED, offset); - } - - @Override - double getMaxItemInternal() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { return Double.NaN; } - if (sketchStructure == COMPACT_SINGLE) { return getDoubleSingleItem(); } - //either compact-full or updatable - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ITEM_BYTES; - return wseg.get(JAVA_DOUBLE_UNALIGNED, offset); - } - - @Override - String getMaxItemAsString() { - final double maxItem = getMaxItemInternal(); - return Double.toString(maxItem); - } - - @Override - public double getMinItem() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - if (sketchStructure == COMPACT_SINGLE) { return getDoubleSingleItem(); } - //either compact-full or updatable - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure); - return wseg.get(JAVA_DOUBLE_UNALIGNED, offset); - } - - @Override - double getMinItemInternal() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { return Double.NaN; } - if (sketchStructure == COMPACT_SINGLE) { return getDoubleSingleItem(); } - //either compact-full or updatable - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure); - return wseg.get(JAVA_DOUBLE_UNALIGNED, offset); - } - - @Override - String getMinItemAsString() { - final double minItem = getMinItemInternal(); - return Double.toString(minItem); - } - - @Override - void setMaxItem(final double item) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ITEM_BYTES; - wseg.set(JAVA_DOUBLE_UNALIGNED, offset, item); - } - - @Override - void setMinItem(final double item) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure); - wseg.set(JAVA_DOUBLE_UNALIGNED, offset, item); - } - - //END MinMax Methods - - @Override - public long getN() { - if (sketchStructure == COMPACT_EMPTY) { return 0; } - else if (sketchStructure == COMPACT_SINGLE) { return 1; } - else { return getMemorySegmentN(wseg); } - } - - //other restricted - - @Override //returns updatable, expanded array including free space at bottom - double[] getDoubleItemsArray() { - final int k = getK(); - if (sketchStructure == COMPACT_EMPTY) { return new double[k]; } - if (sketchStructure == COMPACT_SINGLE) { - final double[] itemsArr = new double[k]; - itemsArr[k - 1] = getDoubleSingleItem(); - return itemsArr; - } - final int capacityItems = KllHelper.computeTotalItemCapacity(k, getM(), getNumLevels()); - final double[] doubleItemsArr = new double[capacityItems]; - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (2 * ITEM_BYTES); - final int shift = (sketchStructure == COMPACT_FULL) ? levelsArr[0] : 0; - final int numItems = (sketchStructure == COMPACT_FULL) ? getNumRetained() : capacityItems; - MemorySegment.copy(wseg, JAVA_DOUBLE_UNALIGNED, offset, doubleItemsArr, shift, numItems); - return doubleItemsArr; - } - - @Override //returns compact items array of retained items, no free space. - double[] getDoubleRetainedItemsArray() { - if (sketchStructure == COMPACT_EMPTY) { return new double[0]; } - if (sketchStructure == COMPACT_SINGLE) { return new double[] { getDoubleSingleItem() }; } - final int numRetained = getNumRetained(); - final double[] doubleItemsArr = new double[numRetained]; - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (2 * ITEM_BYTES) - + (sketchStructure == COMPACT_FULL ? 0 : levelsArr[0] * ITEM_BYTES); - MemorySegment.copy(wseg, JAVA_DOUBLE_UNALIGNED, offset, doubleItemsArr, 0, numRetained); - return doubleItemsArr; - } - - @Override - double getDoubleSingleItem() { - if (!isSingleItem()) { throw new SketchesArgumentException(NOT_SINGLE_ITEM_MSG); } - if (sketchStructure == COMPACT_SINGLE) { - return wseg.get(JAVA_DOUBLE_UNALIGNED, DATA_START_ADR_SINGLE_ITEM); - } - final int offset; - if (sketchStructure == COMPACT_FULL) { - offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (2 * ITEM_BYTES); - } else { //sketchStructure == UPDATABLE - offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (((2 + getK()) - 1) * ITEM_BYTES); - } - return wseg.get(JAVA_DOUBLE_UNALIGNED, offset); - } - - @Override - int getM() { - return getMemorySegmentM(wseg); - } - - @Override - MemorySegmentRequest getMemorySegmentRequest() { - return mSegReq; - } - - @Override - int getMinK() { - if ((sketchStructure == COMPACT_FULL) || (sketchStructure == UPDATABLE)) { return getMemorySegmentMinK(wseg); } - return getK(); - } - - @Override - byte[] getMinMaxByteArr() { - final byte[] bytesOut = new byte[2 * ITEM_BYTES]; - if (sketchStructure == COMPACT_EMPTY) { - ByteArrayUtil.putDoubleLE(bytesOut, 0, Double.NaN); - ByteArrayUtil.putDoubleLE(bytesOut, ITEM_BYTES, Double.NaN); - return bytesOut; - } - final int offset; - if (sketchStructure == COMPACT_SINGLE) { - offset = DATA_START_ADR_SINGLE_ITEM; - MemorySegment.copy(wseg, JAVA_BYTE, offset, bytesOut, 0, ITEM_BYTES); - copyBytes(bytesOut, 0, bytesOut, ITEM_BYTES, ITEM_BYTES); - return bytesOut; - } - //sketchStructure == UPDATABLE OR COMPACT_FULL - offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure); - MemorySegment.copy(wseg, JAVA_BYTE, offset, bytesOut, 0, ITEM_BYTES); - MemorySegment.copy(wseg, JAVA_BYTE, offset + ITEM_BYTES, bytesOut, ITEM_BYTES, ITEM_BYTES); - return bytesOut; - } - - @Override - byte[] getRetainedItemsByteArr() { - if (sketchStructure == COMPACT_EMPTY) { return new byte[0]; } - final double[] dblArr = getDoubleRetainedItemsArray(); - final byte[] dblByteArr = new byte[dblArr.length * ITEM_BYTES]; - final MemorySegment wseg2 = MemorySegment.ofArray(dblByteArr); - MemorySegment.copy(dblArr, 0, wseg2, JAVA_DOUBLE_UNALIGNED, 0, dblArr.length); - return dblByteArr; - } - - @Override - byte[] getTotalItemsByteArr() { - final double[] dblArr = getDoubleItemsArray(); - final byte[] dblByteArr = new byte[dblArr.length * ITEM_BYTES]; - final MemorySegment wseg2 = MemorySegment.ofArray(dblByteArr); - MemorySegment.copy(dblArr, 0, wseg2, JAVA_DOUBLE_UNALIGNED, 0, dblArr.length); - return dblByteArr; - } - - @Override - MemorySegment getMemorySegment() { - return wseg; - } - - @Override - void incN(final int increment) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentN(wseg, getMemorySegmentN(wseg) + increment); - } - - @Override - void incNumLevels() { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - int numLevels = getMemorySegmentNumLevels(wseg); - setMemorySegmentNumLevels(wseg, ++numLevels); - } - - @Override - boolean isLevelZeroSorted() { - return getMemorySegmentLevelZeroSortedFlag(wseg); - } - - @Override - void setDoubleItemsArray(final double[] doubleItems) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (2 * ITEM_BYTES); - MemorySegment.copy(doubleItems, 0, wseg, JAVA_DOUBLE_UNALIGNED, offset, doubleItems.length); - } - - @Override - void setDoubleItemsArrayAt(final int index, final double item) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = - DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ((index + 2) * ITEM_BYTES); - wseg.set(JAVA_DOUBLE_UNALIGNED, offset, item); - } - - @Override - void setDoubleItemsArrayAt(final int index, final double[] items, final int srcOffset, final int length) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ((index + 2) * ITEM_BYTES); - MemorySegment.copy(items, srcOffset, wseg, JAVA_DOUBLE_UNALIGNED, offset, length); - } - - @Override - void setLevelZeroSorted(final boolean sorted) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentLevelZeroSortedFlag(wseg, sorted); - } - - @Override - void setMinK(final int minK) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentMinK(wseg, minK); - } - - @Override - void setN(final long n) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentN(wseg, n); - } - - @Override - void setNumLevels(final int numLevels) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentNumLevels(wseg, numLevels); - } - - @Override - public boolean hasMemorySegment() { - return (wseg != null) && wseg.scope().isAlive(); - } - - @Override - public boolean isOffHeap() { - return hasMemorySegment() && wseg.isNative(); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return MemorySegmentStatus.isSameResource(wseg, that); - } - - @Override - void setMemorySegment(final MemorySegment wseg) { - this.wseg = wseg; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllDirectFloatsSketch.java b/src/main/java/org/apache/datasketches/kll/KllDirectFloatsSketch.java deleted file mode 100644 index 552df0ffb..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllDirectFloatsSketch.java +++ /dev/null @@ -1,398 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.common.ByteArrayUtil.copyBytes; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR_SINGLE_ITEM; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentK; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentLevelZeroSortedFlag; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentM; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentMinK; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentN; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentNumLevels; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentFamilyID; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentK; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentLevelZeroSortedFlag; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentM; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentMinK; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentN; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentNumLevels; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentPreInts; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentSerVer; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_FLOATS_SKETCH; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ByteArrayUtil; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This class implements an off-heap, updatable KllFloatsSketch using MemorySegment. - * - *

Please refer to the documentation in the package-info:
- * {@link org.apache.datasketches.kll}

- * - * @author Lee Rhodes, Kevin Lang - */ -class KllDirectFloatsSketch extends KllFloatsSketch { - private MemorySegment wseg; - private final MemorySegmentRequest mSegReq; - - /** - * Constructs from MemorySegment or MemorySegment already initialized with a sketch image and validated. - * @param wseg the current writable MemorySegment - * @param segVal the MemorySegment Validate object - * @param mSegmentRequest the MemorySegmentRequest object - */ - KllDirectFloatsSketch( - final MemorySegment wseg, - final KllMemorySegmentValidate segVal, - final MemorySegmentRequest mSegmentRequest) { - super(segVal); - this.wseg = wseg; - mSegReq = mSegmentRequest; - } - - /** - * Create a new updatable, direct instance of this sketch. - * @param k parameter that controls size of the sketch and accuracy of estimates - * @param m parameter that controls the minimum level width in items. - * @param dstSeg the given destination MemorySegment object for use by the sketch - * @param mSegmentRequest the callback for the sketch to request a larger MemorySegment. - * @return a new instance of this sketch - */ - static KllDirectFloatsSketch newDirectUpdatableInstance( - final int k, - final int m, - final MemorySegment dstSeg, - final MemorySegmentRequest mSegmentRequest) { - setMemorySegmentPreInts(dstSeg, UPDATABLE.getPreInts()); - setMemorySegmentSerVer(dstSeg, UPDATABLE.getSerVer()); - setMemorySegmentFamilyID(dstSeg, Family.KLL.getID()); - setMemorySegmentK(dstSeg, k); - setMemorySegmentM(dstSeg, m); - setMemorySegmentN(dstSeg, 0); - setMemorySegmentMinK(dstSeg, k); - setMemorySegmentNumLevels(dstSeg, 1); - int offset = DATA_START_ADR; - //new Levels array - MemorySegment.copy(new int[] {k, k}, 0, dstSeg, JAVA_INT_UNALIGNED, offset, 2); - offset += 2 * Integer.BYTES; - //new min/max array - MemorySegment.copy(new float[] {Float.NaN, Float.NaN}, 0, dstSeg, JAVA_FLOAT_UNALIGNED, offset, 2); - offset += 2 * ITEM_BYTES; - //new empty items array - MemorySegment.copy(new float[k], 0, dstSeg, JAVA_FLOAT_UNALIGNED, offset, k); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(dstSeg, KLL_FLOATS_SKETCH, null); - final MemorySegment wSeg = dstSeg; - return new KllDirectFloatsSketch(wSeg, segVal, mSegmentRequest); - } - - //End of Constructors - - @Override - String getItemAsString(final int index) { - if (isEmpty()) { return "NaN"; } - return Float.toString(getFloatItemsArray()[index]); - } - - @Override - public int getK() { - return getMemorySegmentK(wseg); - } - - //MinMax Methods - - @Override - public float getMaxItem() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - if (sketchStructure == COMPACT_SINGLE) { return getFloatSingleItem(); } - //either compact-full or updatable - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ITEM_BYTES; - return wseg.get(JAVA_FLOAT_UNALIGNED, offset); - } - - @Override - float getMaxItemInternal() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { return Float.NaN; } - if (sketchStructure == COMPACT_SINGLE) { return getFloatSingleItem(); } - //either compact-full or updatable - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ITEM_BYTES; - return wseg.get(JAVA_FLOAT_UNALIGNED, offset); - } - - @Override - String getMaxItemAsString() { - final float maxItem = getMaxItemInternal(); - return Float.toString(maxItem); - } - - @Override - public float getMinItem() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - if (sketchStructure == COMPACT_SINGLE) { return getFloatSingleItem(); } - //either compact-full or updatable - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure); - return wseg.get(JAVA_FLOAT_UNALIGNED, offset); - } - - @Override - float getMinItemInternal() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { return Float.NaN; } - if (sketchStructure == COMPACT_SINGLE) { return getFloatSingleItem(); } - //either compact-full or updatable - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure); - return wseg.get(JAVA_FLOAT_UNALIGNED, offset); - } - - @Override - String getMinItemAsString() { - final float minItem = getMinItemInternal(); - return Float.toString(minItem); - } - - @Override - void setMaxItem(final float item) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ITEM_BYTES; - wseg.set(JAVA_FLOAT_UNALIGNED, offset, item); - } - - @Override - void setMinItem(final float item) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure); - wseg.set(JAVA_FLOAT_UNALIGNED, offset, item); - } - - //END MinMax Methods - - @Override - public long getN() { - if (sketchStructure == COMPACT_EMPTY) { return 0; } - else if (sketchStructure == COMPACT_SINGLE) { return 1; } - else { return getMemorySegmentN(wseg); } - } - - //other restricted - - @Override //returns updatable, expanded array including free space at bottom - float[] getFloatItemsArray() { - final int k = getK(); - if (sketchStructure == COMPACT_EMPTY) { return new float[k]; } - if (sketchStructure == COMPACT_SINGLE) { - final float[] itemsArr = new float[k]; - itemsArr[k - 1] = getFloatSingleItem(); - return itemsArr; - } - final int capacityItems = KllHelper.computeTotalItemCapacity(k, getM(), getNumLevels()); - final float[] floatItemsArr = new float[capacityItems]; - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (2 * ITEM_BYTES); - final int shift = (sketchStructure == COMPACT_FULL) ? levelsArr[0] : 0; - final int numItems = (sketchStructure == COMPACT_FULL) ? getNumRetained() : capacityItems; - MemorySegment.copy(wseg, JAVA_FLOAT_UNALIGNED, offset, floatItemsArr, shift, numItems); - return floatItemsArr; - } - - @Override //returns compact items array of retained items, no free space. - float[] getFloatRetainedItemsArray() { - if (sketchStructure == COMPACT_EMPTY) { return new float[0]; } - if (sketchStructure == COMPACT_SINGLE) { return new float[] { getFloatSingleItem() }; } - final int numRetained = getNumRetained(); - final float[] floatItemsArr = new float[numRetained]; - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (2 * ITEM_BYTES) - + (sketchStructure == COMPACT_FULL ? 0 : levelsArr[0] * ITEM_BYTES); - MemorySegment.copy(wseg, JAVA_FLOAT_UNALIGNED, offset, floatItemsArr, 0, numRetained); - return floatItemsArr; - } - - @Override - float getFloatSingleItem() { - if (!isSingleItem()) { throw new SketchesArgumentException(NOT_SINGLE_ITEM_MSG); } - if (sketchStructure == COMPACT_SINGLE) { - return wseg.get(JAVA_FLOAT_UNALIGNED, DATA_START_ADR_SINGLE_ITEM); - } - final int offset; - if (sketchStructure == COMPACT_FULL) { - offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (2 * ITEM_BYTES); - } else { //sketchStructure == UPDATABLE - offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (((2 + getK()) - 1) * ITEM_BYTES); - } - return wseg.get(JAVA_FLOAT_UNALIGNED, offset); - } - - @Override - int getM() { - return getMemorySegmentM(wseg); - } - - @Override - MemorySegmentRequest getMemorySegmentRequest() { - return mSegReq; - } - - @Override - int getMinK() { - if ((sketchStructure == COMPACT_FULL) || (sketchStructure == UPDATABLE)) { return getMemorySegmentMinK(wseg); } - return getK(); - } - - @Override - byte[] getMinMaxByteArr() { - final byte[] bytesOut = new byte[2 * ITEM_BYTES]; - if (sketchStructure == COMPACT_EMPTY) { - ByteArrayUtil.putFloatLE(bytesOut, 0, Float.NaN); - ByteArrayUtil.putFloatLE(bytesOut, ITEM_BYTES, Float.NaN); - return bytesOut; - } - final int offset; - if (sketchStructure == COMPACT_SINGLE) { - offset = DATA_START_ADR_SINGLE_ITEM; - MemorySegment.copy(wseg, JAVA_BYTE, offset, bytesOut, 0, ITEM_BYTES); - copyBytes(bytesOut, 0, bytesOut, ITEM_BYTES, ITEM_BYTES); - return bytesOut; - } - //sketchStructure == UPDATABLE OR COMPACT_FULL - offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure); - MemorySegment.copy(wseg, JAVA_BYTE, offset, bytesOut, 0, ITEM_BYTES); - MemorySegment.copy(wseg, JAVA_BYTE,offset + ITEM_BYTES, bytesOut, ITEM_BYTES, ITEM_BYTES); - return bytesOut; - } - - @Override - byte[] getRetainedItemsByteArr() { - if (sketchStructure == COMPACT_EMPTY) { return new byte[0]; } - final float[] fltArr = getFloatRetainedItemsArray(); - final byte[] fltByteArr = new byte[fltArr.length * ITEM_BYTES]; - final MemorySegment wseg2 = MemorySegment.ofArray(fltByteArr); - MemorySegment.copy(fltArr, 0, wseg2, JAVA_FLOAT_UNALIGNED, 0, fltArr.length); - return fltByteArr; - } - - @Override - byte[] getTotalItemsByteArr() { - final float[] fltArr = getFloatItemsArray(); - final byte[] fltByteArr = new byte[fltArr.length * ITEM_BYTES]; - final MemorySegment wseg2 = MemorySegment.ofArray(fltByteArr); - MemorySegment.copy(fltArr, 0, wseg2, JAVA_FLOAT_UNALIGNED, 0, fltArr.length); - return fltByteArr; - } - - @Override - MemorySegment getMemorySegment() { - return wseg; - } - - @Override - void incN(final int increment) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentN(wseg, getMemorySegmentN(wseg) + increment); - } - - @Override - void incNumLevels() { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - int numLevels = getMemorySegmentNumLevels(wseg); - setMemorySegmentNumLevels(wseg, ++numLevels); - } - - @Override - boolean isLevelZeroSorted() { - return getMemorySegmentLevelZeroSortedFlag(wseg); - } - - @Override - void setFloatItemsArray(final float[] floatItems) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (2 * ITEM_BYTES); - MemorySegment.copy(floatItems, 0, wseg, JAVA_FLOAT_UNALIGNED, offset, floatItems.length); - } - - @Override - void setFloatItemsArrayAt(final int index, final float item) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = - DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ((index + 2) * ITEM_BYTES); - wseg.set(JAVA_FLOAT_UNALIGNED, offset, item); - } - - @Override - void setFloatItemsArrayAt(final int index, final float[] items, final int srcOffset, final int length) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ((index + 2) * ITEM_BYTES); - MemorySegment.copy(items, srcOffset, wseg, JAVA_FLOAT_UNALIGNED, offset, length); - } - - @Override - void setLevelZeroSorted(final boolean sorted) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentLevelZeroSortedFlag(wseg, sorted); - } - - @Override - void setMinK(final int minK) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentMinK(wseg, minK); - } - - @Override - void setN(final long n) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentN(wseg, n); - } - - @Override - void setNumLevels(final int numLevels) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentNumLevels(wseg, numLevels); - } - - @Override - public boolean hasMemorySegment() { - return (wseg != null) && wseg.scope().isAlive(); - } - - @Override - public boolean isOffHeap() { - return hasMemorySegment() && wseg.isNative(); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return MemorySegmentStatus.isSameResource(wseg, that); - } - - @Override - void setMemorySegment(final MemorySegment wseg) { - this.wseg = wseg; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllDirectLongsSketch.java b/src/main/java/org/apache/datasketches/kll/KllDirectLongsSketch.java deleted file mode 100644 index 1de0b2ff1..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllDirectLongsSketch.java +++ /dev/null @@ -1,398 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.ByteArrayUtil.copyBytes; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR_SINGLE_ITEM; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentK; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentLevelZeroSortedFlag; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentM; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentMinK; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentN; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentNumLevels; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentFamilyID; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentK; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentLevelZeroSortedFlag; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentM; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentMinK; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentN; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentNumLevels; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentPreInts; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentSerVer; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_LONGS_SKETCH; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ByteArrayUtil; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This class implements an off-heap, updatable KllLongsSketch using MemorySegment. - * - *

Please refer to the documentation in the package-info:
- * {@link org.apache.datasketches.kll}

- * - * @author Lee Rhodes, Kevin Lang - */ -class KllDirectLongsSketch extends KllLongsSketch { - private MemorySegment wseg; - private final MemorySegmentRequest mSegReq; - - /** - * Constructs from MemorySegment already initialized with a sketch image and validated. - * @param wseg the current MemorySegment - * @param segVal the MemoryValadate object - * @param mSegmentRequest the MemorySegmentRequest object. - */ - KllDirectLongsSketch( - final MemorySegment wseg, - final KllMemorySegmentValidate segVal, - final MemorySegmentRequest mSegmentRequest) { - super(segVal); - this.wseg = wseg; - mSegReq = mSegmentRequest; - } - - /** - * Create a new updatable, direct instance of this sketch backed by a MemorySegment. - * @param k parameter that controls size of the sketch and accuracy of estimates - * @param m parameter that controls the minimum level width in items. - * @param dstSeg the given destination MemorySegment object for use by the sketch - * @param mSegReq the callback for the sketch to request a larger MemorySegment. - * @return a new instance of this sketch - */ - static KllDirectLongsSketch newDirectUpdatableInstance( - final int k, - final int m, - final MemorySegment dstSeg, - final MemorySegmentRequest mSegmentRequest) { - setMemorySegmentPreInts(dstSeg, UPDATABLE.getPreInts()); - setMemorySegmentSerVer(dstSeg, UPDATABLE.getSerVer()); - setMemorySegmentFamilyID(dstSeg, Family.KLL.getID()); - setMemorySegmentK(dstSeg, k); - setMemorySegmentM(dstSeg, m); - setMemorySegmentN(dstSeg, 0); - setMemorySegmentMinK(dstSeg, k); - setMemorySegmentNumLevels(dstSeg, 1); - int offset = DATA_START_ADR; - //new Levels array - MemorySegment.copy(new int[] {k, k}, 0, dstSeg, JAVA_INT_UNALIGNED, offset, 2); - offset += 2 * Integer.BYTES; - //new min/max array - MemorySegment.copy(new long[] {Long.MAX_VALUE, Long.MIN_VALUE}, 0, dstSeg, JAVA_LONG_UNALIGNED, offset, 2); - offset += 2 * ITEM_BYTES; - //new empty items array - MemorySegment.copy(new long[k], 0, dstSeg, JAVA_LONG_UNALIGNED, offset, k); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(dstSeg, KLL_LONGS_SKETCH, null); - final MemorySegment wSeg = dstSeg; - return new KllDirectLongsSketch(wSeg, segVal, mSegmentRequest); - } - - //End of Constructors - - @Override - String getItemAsString(final int index) { - if (isEmpty()) { return "Null"; } - return Long.toString(getLongItemsArray()[index]); - } - - @Override - public int getK() { - return getMemorySegmentK(wseg); - } - - //MinMax Methods - - @Override - public long getMaxItem() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - if (sketchStructure == COMPACT_SINGLE) { return getLongSingleItem(); } - //either compact-full or updatable - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ITEM_BYTES; - return wseg.get(JAVA_LONG_UNALIGNED, offset); - } - - @Override - long getMaxItemInternal() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { return Long.MAX_VALUE; } - if (sketchStructure == COMPACT_SINGLE) { return getLongSingleItem(); } - //either compact-full or updatable - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ITEM_BYTES; - return wseg.get(JAVA_LONG_UNALIGNED, offset); - } - - @Override - String getMaxItemAsString() { - final long maxItem = getMaxItemInternal(); - return Long.toString(maxItem); - } - - @Override - public long getMinItem() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - if (sketchStructure == COMPACT_SINGLE) { return getLongSingleItem(); } - //either compact-full or updatable - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure); - return wseg.get(JAVA_LONG_UNALIGNED, offset); - } - - @Override - long getMinItemInternal() { - if ((sketchStructure == COMPACT_EMPTY) || isEmpty()) { return Long.MAX_VALUE; } - if (sketchStructure == COMPACT_SINGLE) { return getLongSingleItem(); } - //either compact-full or updatable - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure); - return wseg.get(JAVA_LONG_UNALIGNED, offset); - } - - @Override - String getMinItemAsString() { - final long minItem = getMinItemInternal(); - return Long.toString(minItem); - } - - @Override - void setMaxItem(final long item) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ITEM_BYTES; - wseg.set(JAVA_LONG_UNALIGNED, offset, item); - } - - @Override - void setMinItem(final long item) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure); - wseg.set(JAVA_LONG_UNALIGNED, offset, item); - } - - //END MinMax Methods - - @Override - public long getN() { - if (sketchStructure == COMPACT_EMPTY) { return 0; } - else if (sketchStructure == COMPACT_SINGLE) { return 1; } - else { return getMemorySegmentN(wseg); } - } - - //other restricted - - @Override //returns updatable, expanded array including free space at bottom - long[] getLongItemsArray() { - final int k = getK(); - if (sketchStructure == COMPACT_EMPTY) { return new long[k]; } - if (sketchStructure == COMPACT_SINGLE) { - final long[] itemsArr = new long[k]; - itemsArr[k - 1] = getLongSingleItem(); - return itemsArr; - } - final int capacityItems = KllHelper.computeTotalItemCapacity(k, getM(), getNumLevels()); - final long[] longItemsArr = new long[capacityItems]; - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (2 * ITEM_BYTES); - final int shift = (sketchStructure == COMPACT_FULL) ? levelsArr[0] : 0; - final int numItems = (sketchStructure == COMPACT_FULL) ? getNumRetained() : capacityItems; - MemorySegment.copy(wseg, JAVA_LONG_UNALIGNED, offset, longItemsArr, shift, numItems); - return longItemsArr; - } - - @Override //returns compact items array of retained items, no free space. - long[] getLongRetainedItemsArray() { - if (sketchStructure == COMPACT_EMPTY) { return new long[0]; } - if (sketchStructure == COMPACT_SINGLE) { return new long[] { getLongSingleItem() }; } - final int numRetained = getNumRetained(); - final long[] longItemsArr = new long[numRetained]; - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (2 * ITEM_BYTES) - + (sketchStructure == COMPACT_FULL ? 0 : levelsArr[0] * ITEM_BYTES); - MemorySegment.copy(wseg, JAVA_LONG_UNALIGNED, offset, longItemsArr, 0, numRetained); - return longItemsArr; - } - - @Override - long getLongSingleItem() { - if (!isSingleItem()) { throw new SketchesArgumentException(NOT_SINGLE_ITEM_MSG); } - if (sketchStructure == COMPACT_SINGLE) { - return wseg.get(JAVA_LONG_UNALIGNED, DATA_START_ADR_SINGLE_ITEM); - } - final int offset; - if (sketchStructure == COMPACT_FULL) { - offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (2 * ITEM_BYTES); - } else { //sketchStructure == UPDATABLE - offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (((2 + getK()) - 1) * ITEM_BYTES); - } - return wseg.get(JAVA_LONG_UNALIGNED, offset); - } - - @Override - int getM() { - return getMemorySegmentM(wseg); - } - - @Override - MemorySegmentRequest getMemorySegmentRequest() { - return mSegReq; - } - - @Override - int getMinK() { - if ((sketchStructure == COMPACT_FULL) || (sketchStructure == UPDATABLE)) { return getMemorySegmentMinK(wseg); } - return getK(); - } - - @Override - byte[] getMinMaxByteArr() { - final byte[] bytesOut = new byte[2 * ITEM_BYTES]; - if (sketchStructure == COMPACT_EMPTY) { - ByteArrayUtil.putLongLE(bytesOut, 0, Long.MAX_VALUE); - ByteArrayUtil.putLongLE(bytesOut, ITEM_BYTES, Long.MIN_VALUE); - return bytesOut; - } - final int offset; - if (sketchStructure == COMPACT_SINGLE) { - offset = DATA_START_ADR_SINGLE_ITEM; - MemorySegment.copy(wseg, JAVA_BYTE, offset, bytesOut, 0, ITEM_BYTES); - copyBytes(bytesOut, 0, bytesOut, ITEM_BYTES, ITEM_BYTES); - return bytesOut; - } - //sketchStructure == UPDATABLE OR COMPACT_FULL - offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure); - MemorySegment.copy(wseg, JAVA_BYTE, offset, bytesOut, 0, ITEM_BYTES); - MemorySegment.copy(wseg, JAVA_BYTE, offset + ITEM_BYTES, bytesOut, ITEM_BYTES, ITEM_BYTES); - return bytesOut; - } - - @Override - byte[] getRetainedItemsByteArr() { - if (sketchStructure == COMPACT_EMPTY) { return new byte[0]; } - final long[] lngArr = getLongRetainedItemsArray(); - final byte[] lngByteArr = new byte[lngArr.length * ITEM_BYTES]; - final MemorySegment wseg2 = MemorySegment.ofArray(lngByteArr); - MemorySegment.copy(lngArr, 0, wseg2, JAVA_LONG_UNALIGNED, 0, lngArr.length); - return lngByteArr; - } - - @Override - byte[] getTotalItemsByteArr() { - final long[] lngArr = getLongItemsArray(); - final byte[] lngByteArr = new byte[lngArr.length * ITEM_BYTES]; - final MemorySegment wseg2 = MemorySegment.ofArray(lngByteArr); - MemorySegment.copy(lngArr, 0, wseg2, JAVA_LONG_UNALIGNED, 0, lngArr.length); - return lngByteArr; - } - - @Override - MemorySegment getMemorySegment() { - return wseg; - } - - @Override - void incN(final int increment) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentN(wseg, getMemorySegmentN(wseg) + increment); - } - - @Override - void incNumLevels() { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - int numLevels = getMemorySegmentNumLevels(wseg); - setMemorySegmentNumLevels(wseg, ++numLevels); - } - - @Override - boolean isLevelZeroSorted() { - return getMemorySegmentLevelZeroSortedFlag(wseg); - } - - @Override - void setLongItemsArray(final long[] longItems) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + (2 * ITEM_BYTES); - MemorySegment.copy(longItems, 0, wseg, JAVA_LONG_UNALIGNED, offset, longItems.length); - } - - @Override - void setLongItemsArrayAt(final int index, final long item) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = - DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ((index + 2) * ITEM_BYTES); - wseg.set(JAVA_LONG_UNALIGNED, offset, item); - } - - @Override - void setLongItemsArrayAt(final int index, final long[] items, final int srcOffset, final int length) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int offset = DATA_START_ADR + getLevelsArrSizeBytes(sketchStructure) + ((index + 2) * ITEM_BYTES); - MemorySegment.copy(items, srcOffset, wseg, JAVA_LONG_UNALIGNED, offset, length); - } - - @Override - void setLevelZeroSorted(final boolean sorted) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentLevelZeroSortedFlag(wseg, sorted); - } - - @Override - void setMinK(final int minK) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentMinK(wseg, minK); - } - - @Override - void setN(final long n) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentN(wseg, n); - } - - @Override - void setNumLevels(final int numLevels) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - setMemorySegmentNumLevels(wseg, numLevels); - } - - @Override - public boolean hasMemorySegment() { - return (wseg != null) && wseg.scope().isAlive(); - } - - @Override - public boolean isOffHeap() { - return hasMemorySegment() && wseg.isNative(); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return MemorySegmentStatus.isSameResource(wseg, that); - } - - @Override - void setMemorySegment(final MemorySegment wseg) { - this.wseg = wseg; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllDoublesHelper.java b/src/main/java/org/apache/datasketches/kll/KllDoublesHelper.java deleted file mode 100644 index 93b4ec007..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllDoublesHelper.java +++ /dev/null @@ -1,479 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.apache.datasketches.common.Util.isEven; -import static org.apache.datasketches.common.Util.isOdd; -import static org.apache.datasketches.kll.KllHelper.findLevelToCompact; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Random; - -/** - * Static methods to support KllDoublesSketch - * @author Kevin Lang - * @author Alexander Saydakov - */ -final class KllDoublesHelper { - - /** - * Create Items Array from given item and weight. - * Used with weighted update only. - * @param item the given item - * @param weight the given weight - * @return the Items Array. - */ - static double[] createItemsArray(final double item, final long weight) { - final int itemsArrLen = Long.bitCount(weight); - final double[] itemsArr = new double[itemsArrLen]; - Arrays.fill(itemsArr, item); - return itemsArr; - } - - /** - * The following code is only valid in the special case of exactly reaching capacity while updating. - * It cannot be used while merging, while reducing k, or anything else. - * @param dblSk the current KllDoublesSketch - */ - static void compressWhileUpdatingSketch(final KllDoublesSketch dblSk) { - final int level = - findLevelToCompact(dblSk.getK(), dblSk.getM(), dblSk.getNumLevels(), dblSk.levelsArr); - if (level == (dblSk.getNumLevels() - 1)) { - //The level to compact is the top level, thus we need to add a level. - //Be aware that this operation grows the items array, - //shifts the items data and the level boundaries of the data, - //and grows the levels array and increments numLevels_. - KllHelper.addEmptyTopLevelToCompletelyFullSketch(dblSk); - } - //after this point, the levelsArray will not be expanded, only modified. - final int[] myLevelsArr = dblSk.levelsArr; - final int rawBeg = myLevelsArr[level]; - final int rawEnd = myLevelsArr[level + 1]; - // +2 is OK because we already added a new top level if necessary - final int popAbove = myLevelsArr[level + 2] - rawEnd; - final int rawPop = rawEnd - rawBeg; - final boolean oddPop = isOdd(rawPop); - final int adjBeg = oddPop ? rawBeg + 1 : rawBeg; - final int adjPop = oddPop ? rawPop - 1 : rawPop; - final int halfAdjPop = adjPop / 2; - - //the following is specific to Doubles - final double[] myDoubleItemsArr = dblSk.getDoubleItemsArray(); - if (level == 0) { // level zero might not be sorted, so we must sort it if we wish to compact it - Arrays.sort(myDoubleItemsArr, adjBeg, adjBeg + adjPop); - } - if (popAbove == 0) { - KllDoublesHelper.randomlyHalveUpDoubles(myDoubleItemsArr, adjBeg, adjPop, KllSketch.random); - } else { - KllDoublesHelper.randomlyHalveDownDoubles(myDoubleItemsArr, adjBeg, adjPop, KllSketch.random); - KllDoublesHelper.mergeSortedDoubleArrays( - myDoubleItemsArr, adjBeg, halfAdjPop, - myDoubleItemsArr, rawEnd, popAbove, - myDoubleItemsArr, adjBeg + halfAdjPop); - } - - int newIndex = myLevelsArr[level + 1] - halfAdjPop; // adjust boundaries of the level above - dblSk.setLevelsArrayAt(level + 1, newIndex); - - if (oddPop) { - dblSk.setLevelsArrayAt(level, myLevelsArr[level + 1] - 1); // the current level now contains one item - myDoubleItemsArr[myLevelsArr[level]] = myDoubleItemsArr[rawBeg]; // namely this leftover guy - } else { - dblSk.setLevelsArrayAt(level, myLevelsArr[level + 1]); // the current level is now empty - } - - // verify that we freed up halfAdjPop array slots just below the current level - assert myLevelsArr[level] == (rawBeg + halfAdjPop); - - // finally, we need to shift up the data in the levels below - // so that the freed-up space can be used by level zero - if (level > 0) { - final int amount = rawBeg - myLevelsArr[0]; - System.arraycopy(myDoubleItemsArr, myLevelsArr[0], myDoubleItemsArr, myLevelsArr[0] + halfAdjPop, amount); - } - for (int lvl = 0; lvl < level; lvl++) { - newIndex = myLevelsArr[lvl] + halfAdjPop; //adjust boundary - dblSk.setLevelsArrayAt(lvl, newIndex); - } - dblSk.setDoubleItemsArray(myDoubleItemsArr); - } - - //assumes readOnly = false and UPDATABLE, called from KllDoublesSketch::merge - static void mergeDoubleImpl(final KllDoublesSketch mySketch, final KllDoublesSketch otherDblSk) { - if (otherDblSk.isEmpty()) { return; } - - //capture my key mutable fields before doing any merging - final boolean myEmpty = mySketch.isEmpty(); - final double myMin = mySketch.getMinItemInternal(); - final double myMax = mySketch.getMaxItemInternal(); - final int myMinK = mySketch.getMinK(); - final long finalN = Math.addExact(mySketch.getN(), otherDblSk.getN()); - - //buffers that are referenced multiple times - final int otherNumLevels = otherDblSk.getNumLevels(); - final int[] otherLevelsArr = otherDblSk.levelsArr; - final double[] otherDoubleItemsArr; - - //MERGE: update this sketch with level0 items from the other sketch - if (otherDblSk.isCompactSingleItem()) { - KllDoublesSketch.updateDouble(mySketch, otherDblSk.getDoubleSingleItem()); - otherDoubleItemsArr = new double[0]; - } else { - otherDoubleItemsArr = otherDblSk.getDoubleItemsArray(); - for (int i = otherLevelsArr[0]; i < otherLevelsArr[1]; i++) { - KllDoublesSketch.updateDouble(mySketch, otherDoubleItemsArr[i]); - } - } - - //After the level 0 update, we capture the intermediate state of my levels and items arrays... - final int myCurNumLevels = mySketch.getNumLevels(); - final int[] myCurLevelsArr = mySketch.levelsArr; - final double[] myCurDoubleItemsArr = mySketch.getDoubleItemsArray(); - - // create aliases in case there are no higher levels - int myNewNumLevels = myCurNumLevels; - int[] myNewLevelsArr = myCurLevelsArr; - double[] myNewDoubleItemsArr = myCurDoubleItemsArr; - - //merge higher levels if they exist - if ((otherNumLevels > 1) && !otherDblSk.isCompactSingleItem()) { - final int tmpSpaceNeeded = mySketch.getNumRetained() - + KllHelper.getNumRetainedAboveLevelZero(otherNumLevels, otherLevelsArr); - final double[] workbuf = new double[tmpSpaceNeeded]; - - final int provisionalNumLevels = max(myCurNumLevels, otherNumLevels); - - final int ub = max(KllHelper.ubOnNumLevels(finalN), provisionalNumLevels); - final int[] worklevels = new int[ub + 2]; // ub+1 does not work - final int[] outlevels = new int[ub + 2]; - - populateDoubleWorkArrays(workbuf, worklevels, provisionalNumLevels, - myCurNumLevels, myCurLevelsArr, myCurDoubleItemsArr, - otherNumLevels, otherLevelsArr, otherDoubleItemsArr); - - // notice that workbuf is being used as both the input and output - final int[] result = generalDoublesCompress(mySketch.getK(), mySketch.getM(), provisionalNumLevels, - workbuf, worklevels, workbuf, outlevels, mySketch.isLevelZeroSorted(), KllSketch.random); - final int targetItemCount = result[1]; //was finalCapacity. Max size given k, m, numLevels - final int curItemCount = result[2]; //was finalPop - - // now we need to finalize the results for mySketch - - //THE NEW NUM LEVELS - myNewNumLevels = result[0]; - assert myNewNumLevels <= ub; // ub may be much bigger - - // THE NEW ITEMS ARRAY - myNewDoubleItemsArr = (targetItemCount == myCurDoubleItemsArr.length) - ? myCurDoubleItemsArr - : new double[targetItemCount]; - final int freeSpaceAtBottom = targetItemCount - curItemCount; - - //shift the new items array create space at bottom - System.arraycopy(workbuf, outlevels[0], myNewDoubleItemsArr, freeSpaceAtBottom, curItemCount); - final int theShift = freeSpaceAtBottom - outlevels[0]; - - //calculate the new levels array length - final int finalLevelsArrLen; - if (myCurLevelsArr.length < (myNewNumLevels + 1)) { finalLevelsArrLen = myNewNumLevels + 1; } - else { finalLevelsArrLen = myCurLevelsArr.length; } - - //THE NEW LEVELS ARRAY - myNewLevelsArr = new int[finalLevelsArrLen]; - for (int lvl = 0; lvl < (myNewNumLevels + 1); lvl++) { // includes the "extra" index - myNewLevelsArr[lvl] = outlevels[lvl] + theShift; - } - - //MemorySegment SPACE MANAGEMENT - if (mySketch.getMemorySegment() != null) { - final MemorySegment wseg = KllHelper.memorySegmentSpaceMgmt(mySketch, myNewLevelsArr.length, myNewDoubleItemsArr.length); - mySketch.setMemorySegment(wseg); - } - } //end of updating levels above level 0 - - //Update Preamble: - mySketch.setN(finalN); - if (otherDblSk.isEstimationMode()) { //otherwise the merge brings over exact items. - mySketch.setMinK(min(myMinK, otherDblSk.getMinK())); - } - - //Update numLevels, levelsArray, items - mySketch.setNumLevels(myNewNumLevels); - mySketch.setLevelsArray(myNewLevelsArr); - mySketch.setDoubleItemsArray(myNewDoubleItemsArr); - - //Update min, max items - final double otherMin = otherDblSk.getMinItemInternal(); - final double otherMax = otherDblSk.getMaxItemInternal(); - if (Double.isNaN(myMin) || myEmpty) { - mySketch.setMinItem(otherMin); - mySketch.setMaxItem(otherMax); - } else { - mySketch.setMinItem(min(myMin, otherMin)); - mySketch.setMaxItem(max(myMax, otherMax)); - } - assert KllHelper.sumTheSampleWeights(mySketch.getNumLevels(), mySketch.levelsArr) == mySketch.getN(); - } - - private static void mergeSortedDoubleArrays( //only bufC is modified - final double[] bufA, final int startA, final int lenA, - final double[] bufB, final int startB, final int lenB, - final double[] bufC, final int startC) { - final int lenC = lenA + lenB; - final int limA = startA + lenA; - final int limB = startB + lenB; - final int limC = startC + lenC; - - int a = startA; - int b = startB; - - for (int c = startC; c < limC; c++) { - if (a == limA) { - bufC[c] = bufB[b]; - b++; - } else if ((b == limB) || (bufA[a] < bufB[b])) { - bufC[c] = bufA[a]; - a++; - } else { - bufC[c] = bufB[b]; - b++; - } - } - assert a == limA; - assert b == limB; - } - - /** - * Validation Method. This must be modified to use the validation test - * @param buf the items array - * @param start data start - * @param length items array length - * @param random instance of Random - */ - //NOTE For validation Method: Need to modify to run. - private static void randomlyHalveDownDoubles(final double[] buf, final int start, final int length, - final Random random) { - assert isEven(length); - final int half_length = length / 2; - final int offset = random.nextInt(2); // disable for validation - //final int offset = deterministicOffset(); // enable for validation - int j = start + offset; - for (int i = start; i < (start + half_length); i++) { - buf[i] = buf[j]; - j += 2; - } - } - - /** - * Validation Method. This must be modified to use the validation test - * @param buf the items array - * @param start data start - * @param length items array length - * @param random instance of Random - */ - //NOTE For validation Method: Need to modify to run. - private static void randomlyHalveUpDoubles(final double[] buf, final int start, final int length, - final Random random) { - assert isEven(length); - final int half_length = length / 2; - final int offset = random.nextInt(2); // disable for validation - //final int offset = deterministicOffset(); // enable for validation - int j = (start + length) - 1 - offset; - for (int i = (start + length) - 1; i >= (start + half_length); i--) { - buf[i] = buf[j]; - j -= 2; - } - } - - /** - * Compression algorithm used to merge higher levels. - * - *

Here is what we do for each level:

- *
  • If it does not need to be compacted, then simply copy it over.
  • - *
  • Otherwise, it does need to be compacted, so... - *
    • Copy zero or one guy over.
    • - *
    • If the level above is empty, halve up.
    • - *
    • Else the level above is nonempty, so halve down, then merge up.
    • - *
  • - *
  • Adjust the boundaries of the level above.
  • - *
- * - *

It can be proved that generalCompress returns a sketch that satisfies the space constraints - * no matter how much data is passed in. - * We are pretty sure that it works correctly when inBuf and outBuf are the same. - * All levels except for level zero must be sorted before calling this, and will still be - * sorted afterwards. - * Level zero is not required to be sorted before, and may not be sorted afterwards.

- * - *

This trashes inBuf and inLevels and modifies outBuf and outLevels.

- * - * @param k The sketch parameter k - * @param m The minimum level size - * @param numLevelsIn provisional number of number of levels = max(this.numLevels, other.numLevels) - * @param inBuf work buffer of size = this.getNumRetained() + other.getNumRetainedAboveLevelZero(). - * This contains the double[] of the other sketch - * @param inLevels work levels array size = ubOnNumLevels(this.n + other.n) + 2 - * @param outBuf the same array as inBuf - * @param outLevels the same size as inLevels - * @param isLevelZeroSorted true if this.level 0 is sorted - * @param random instance of java.util.Random - * @return int array of: {numLevels, targetItemCount, currentItemCount) - */ - // - private static int[] generalDoublesCompress( - final int k, - final int m, - final int numLevelsIn, - final double[] inBuf, - final int[] inLevels, - final double[] outBuf, - final int[] outLevels, - final boolean isLevelZeroSorted, - final Random random) { - assert numLevelsIn > 0; // things are too weird if zero levels are allowed - int numLevels = numLevelsIn; - int currentItemCount = inLevels[numLevels] - inLevels[0]; // decreases with each compaction - int targetItemCount = KllHelper.computeTotalItemCapacity(k, m, numLevels); // increases if we add levels - boolean doneYet = false; - outLevels[0] = 0; - int curLevel = -1; - while (!doneYet) { - curLevel++; // start out at level 0 - - // If we are at the current top level, add an empty level above it for convenience, - // but do not actually increment numLevels until later - if (curLevel == (numLevels - 1)) { - inLevels[curLevel + 2] = inLevels[curLevel + 1]; - } - - final int rawBeg = inLevels[curLevel]; - final int rawLim = inLevels[curLevel + 1]; - final int rawPop = rawLim - rawBeg; - - if ((currentItemCount < targetItemCount) || (rawPop < KllHelper.levelCapacity(k, numLevels, curLevel, m))) { - // copy level over as is - // because inBuf and outBuf could be the same, make sure we are not moving data upwards! - assert (rawBeg >= outLevels[curLevel]); - System.arraycopy(inBuf, rawBeg, outBuf, outLevels[curLevel], rawPop); - outLevels[curLevel + 1] = outLevels[curLevel] + rawPop; - } - else { - // The sketch is too full AND this level is too full, so we compact it - // Note: this can add a level and thus change the sketch's capacity - - final int popAbove = inLevels[curLevel + 2] - rawLim; - final boolean oddPop = isOdd(rawPop); - final int adjBeg = oddPop ? 1 + rawBeg : rawBeg; - final int adjPop = oddPop ? rawPop - 1 : rawPop; - final int halfAdjPop = adjPop / 2; - - if (oddPop) { // copy one guy over - outBuf[outLevels[curLevel]] = inBuf[rawBeg]; - outLevels[curLevel + 1] = outLevels[curLevel] + 1; - } else { // copy zero guys over - outLevels[curLevel + 1] = outLevels[curLevel]; - } - - // level zero might not be sorted, so we must sort it if we wish to compact it - if ((curLevel == 0) && !isLevelZeroSorted) { - Arrays.sort(inBuf, adjBeg, adjBeg + adjPop); - } - - if (popAbove == 0) { // Level above is empty, so halve up - randomlyHalveUpDoubles(inBuf, adjBeg, adjPop, random); - } else { // Level above is nonempty, so halve down, then merge up - randomlyHalveDownDoubles(inBuf, adjBeg, adjPop, random); - mergeSortedDoubleArrays(inBuf, adjBeg, halfAdjPop, inBuf, rawLim, popAbove, inBuf, adjBeg + halfAdjPop); - } - - // track the fact that we just eliminated some data - currentItemCount -= halfAdjPop; - - // Adjust the boundaries of the level above - inLevels[curLevel + 1] = inLevels[curLevel + 1] - halfAdjPop; - - // Increment numLevels if we just compacted the old top level - // This creates some more capacity (the size of the new bottom level) - if (curLevel == (numLevels - 1)) { - numLevels++; - targetItemCount += KllHelper.levelCapacity(k, numLevels, 0, m); - } - } // end of code for compacting a level - - // determine whether we have processed all levels yet (including any new levels that we created) - if (curLevel == (numLevels - 1)) { doneYet = true; } - } // end of loop over levels - - assert (outLevels[numLevels] - outLevels[0]) == currentItemCount; - return new int[] {numLevels, targetItemCount, currentItemCount}; - } - - private static void populateDoubleWorkArrays( //workBuf and workLevels are modified - final double[] workBuf, final int[] workLevels, final int provisionalNumLevels, - final int myCurNumLevels, final int[] myCurLevelsArr, final double[] myCurDoubleItemsArr, - final int otherNumLevels, final int[] otherLevelsArr, final double[] otherDoubleItemsArr) { - - workLevels[0] = 0; - - // Note: the level zero data from "other" was already inserted into "self". - // This copies into workbuf. - final int selfPopZero = KllHelper.currentLevelSizeItems(0, myCurNumLevels, myCurLevelsArr); - System.arraycopy(myCurDoubleItemsArr, myCurLevelsArr[0], workBuf, workLevels[0], selfPopZero); - workLevels[1] = workLevels[0] + selfPopZero; - - for (int lvl = 1; lvl < provisionalNumLevels; lvl++) { - final int selfPop = KllHelper.currentLevelSizeItems(lvl, myCurNumLevels, myCurLevelsArr); - final int otherPop = KllHelper.currentLevelSizeItems(lvl, otherNumLevels, otherLevelsArr); - workLevels[lvl + 1] = workLevels[lvl] + selfPop + otherPop; - assert (selfPop >= 0) && (otherPop >= 0); - if ((selfPop == 0) && (otherPop == 0)) { continue; } - if ((selfPop > 0) && (otherPop == 0)) { - System.arraycopy(myCurDoubleItemsArr, myCurLevelsArr[lvl], workBuf, workLevels[lvl], selfPop); - } - else if ((selfPop == 0) && (otherPop > 0)) { - System.arraycopy(otherDoubleItemsArr, otherLevelsArr[lvl], workBuf, workLevels[lvl], otherPop); - } - else if ((selfPop > 0) && (otherPop > 0)) { - mergeSortedDoubleArrays( //only workBuf is modified - myCurDoubleItemsArr, myCurLevelsArr[lvl], selfPop, - otherDoubleItemsArr, otherLevelsArr[lvl], otherPop, - workBuf, workLevels[lvl]); - } - } - } - - /* - * Validation Method. - * The following must be enabled for use with the KllDoublesValidationTest, - * which is only enabled for manual testing. In addition, two Validation Methods - * above need to be modified. - */ //NOTE Validation Method: Need to uncomment to use - // static int nextOffset = 0; - // - // private static int deterministicOffset() { - // final int result = nextOffset; - // nextOffset = 1 - nextOffset; - // return result; - // } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllDoublesSketch.java b/src/main/java/org/apache/datasketches/kll/KllDoublesSketch.java deleted file mode 100644 index 2981d3628..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllDoublesSketch.java +++ /dev/null @@ -1,673 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.apache.datasketches.common.ByteArrayUtil.putDoubleLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_DOUBLES_SKETCH; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Objects; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.DoublesSketchSortedView; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; -import org.apache.datasketches.quantilescommon.QuantilesDoublesAPI; -import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIteratorAPI; - -/** - * This variation of the KllSketch implements primitive doubles. - * - * @see org.apache.datasketches.kll.KllSketch - */ -public abstract class KllDoublesSketch extends KllSketch implements QuantilesDoublesAPI { - private DoublesSketchSortedView doublesSV = null; - final static int ITEM_BYTES = Double.BYTES; - - /** - * Constructor for on-heap. - * @param sketchStructure the current sketch structure - */ - KllDoublesSketch(final SketchStructure sketchStructure) { - super(SketchType.KLL_DOUBLES_SKETCH, sketchStructure); - } - - /** - * Constructor for MemorySegment based sketch - * @param segVal MemorySegment validator. - */ - KllDoublesSketch(final KllMemorySegmentValidate segVal) { - super(segVal); - } - - //Factories for new heap instances. - - /** - * Create a new heap instance of this sketch with the default k = 200. - * The default k = 200 results in a normalized rank error of about - * 1.65%. Larger K will have smaller error but the sketch will be larger (and slower). - * @return new KllDoublesSketch on the Java heap. - */ - public static KllDoublesSketch newHeapInstance() { - return newHeapInstance(DEFAULT_K); - } - - /** - * Create a new heap instance of this sketch with a given parameter k. - * k can be between 8, inclusive, and 65535, inclusive. - * The default k = 200 results in a normalized rank error of about - * 1.65%. Larger K will have smaller error but the sketch will be larger (and slower). - * @param k parameter that controls size of the sketch and accuracy of estimates. - * @return new KllDoublesSketch on the Java heap. - */ - public static KllDoublesSketch newHeapInstance(final int k) { - return new KllHeapDoublesSketch(k, DEFAULT_M); - } - - //Factories for new direct instances. - - /** - * Create a new direct updatable instance of this sketch with the default k. - * The default k = 200 results in a normalized rank error of about - * 1.65%. Larger k will have smaller error but the sketch will be larger (and slower). - * @param dstSeg the given destination MemorySegment object for use by the sketch - * @return a new direct instance of this sketch - */ - public static KllDoublesSketch newDirectInstance(final MemorySegment dstSeg) { - return newDirectInstance(DEFAULT_K, dstSeg, null); - } - - /** - * Create a new direct updatable instance of this sketch with a given k. - * @param k parameter that controls size of the sketch and accuracy of estimates. - * @param dstSeg the given destination MemorySegment object for use by the sketch - * @param mSegReq the callback for the sketch to request a larger MemorySegment. It may be null. - * @return a new direct instance of this sketch - */ - public static KllDoublesSketch newDirectInstance( - final int k, - final MemorySegment dstSeg, - final MemorySegmentRequest mSegReq) { - Objects.requireNonNull(dstSeg, "Parameter 'dstSeg' must not be null"); - return KllDirectDoublesSketch.newDirectUpdatableInstance(k, DEFAULT_M, dstSeg, mSegReq); - } - - //Factory to create an heap instance from a MemorySegment image - - /** - * Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch. - * The resulting sketch will not retain any link to the source MemorySegment. - * @param srcSeg a compact MemorySegment image of a sketch serialized by this sketch. - * @return a heap-based sketch based on the given MemorySegment. - */ - public static KllDoublesSketch heapify(final MemorySegment srcSeg) { - Objects.requireNonNull(srcSeg, "Parameter 'srcSeg' must not be null"); - return KllHeapDoublesSketch.heapifyImpl(srcSeg); - } - - //Factories to wrap a MemorySegment image - - /** - * Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch. - * - *

The given MemorySegment must be writable and it must contain a KllDoublesSketch in updatable form. - * The sketch will be updated and managed totally within the MemorySegment. If the given source - * MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

- * - *

NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch - * will request more capacity using the {@link MemorySegmentRequest MemorySegmentRequest} interface. The default of this interface will - * return a new MemorySegment on the heap.

- * - * @param srcSeg a MemorySegment that contains sketch data. - * @return an instance of this sketch that wraps the given MemorySegment. - */ - public static KllDoublesSketch wrap(final MemorySegment srcSeg) { - return wrap(srcSeg, null); - } - - /** - * Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch and including an - * optional, user defined {@link MemorySegmentRequest MemorySegmentRequest}. - * - *

The given MemorySegment must be writable and it must contain a KllDoublesSketch in updatable form. - * The sketch will be updated and managed totally within the MemorySegment. If the given source - * MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

- * - *

NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch - * will request more capacity using the {@link MemorySegmentRequest MemorySegmentRequest} interface. The default of this interface will - * return a new MemorySegment on the heap. It is up to the user to optionally extend this interface if more flexible - * handling of requests for more capacity is required.

- * - * @param srcSeg a MemorySegment that contains sketch data. - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return an instance of this sketch that wraps the given MemorySegment. - */ - public static KllDoublesSketch wrap(final MemorySegment srcSeg, final MemorySegmentRequest mSegReq) { - Objects.requireNonNull(srcSeg, "Parameter 'srcSeg' must not be null"); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(srcSeg, KLL_DOUBLES_SKETCH); - return new KllDirectDoublesSketch(srcSeg, segVal, mSegReq); - } - - //END of Constructors - - @Override - public double[] getCDF(final double[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return doublesSV.getCDF(splitPoints, searchCrit); - } - - @Override - public double[] getPMF(final double[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return doublesSV.getPMF(splitPoints, searchCrit); - } - - @Override - public double getQuantile(final double rank, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return doublesSV.getQuantile(rank, searchCrit); - } - - @Override - public double[] getQuantiles(final double[] ranks, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - final int len = ranks.length; - final double[] quantiles = new double[len]; - for (int i = 0; i < len; i++) { - quantiles[i] = doublesSV.getQuantile(ranks[i], searchCrit); - } - return quantiles; - } - - /** - * {@inheritDoc} - * The approximate probability that the true quantile is within the confidence interval - * specified by the upper and lower quantile bounds for this sketch is 0.99. - */ - @Override - public double getQuantileLowerBound(final double rank) { - return getQuantile(max(0, rank - KllHelper.getNormalizedRankError(getMinK(), false))); - } - - /** - * {@inheritDoc} - * The approximate probability that the true quantile is within the confidence interval - * specified by the upper and lower quantile bounds for this sketch is 0.99. - */ - @Override - public double getQuantileUpperBound(final double rank) { - return getQuantile(min(1.0, rank + KllHelper.getNormalizedRankError(getMinK(), false))); - } - - @Override - public double getRank(final double quantile, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return doublesSV.getRank(quantile, searchCrit); - } - - /** - * {@inheritDoc} - * The approximate probability that the true rank is within the confidence interval - * specified by the upper and lower rank bounds for this sketch is 0.99. - */ - @Override - public double getRankLowerBound(final double rank) { - return max(0.0, rank - KllHelper.getNormalizedRankError(getMinK(), false)); - } - - /** - * {@inheritDoc} - * The approximate probability that the true rank is within the confidence interval - * specified by the upper and lower rank bounds for this sketch is 0.99. - */ - @Override - public double getRankUpperBound(final double rank) { - return min(1.0, rank + KllHelper.getNormalizedRankError(getMinK(), false)); - } - - @Override - public double[] getRanks(final double[] quantiles, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - final int len = quantiles.length; - final double[] ranks = new double[len]; - for (int i = 0; i < len; i++) { - ranks[i] = doublesSV.getRank(quantiles[i], searchCrit); - } - return ranks; - } - - @Override - public QuantilesDoublesSketchIteratorAPI iterator() { - return new KllDoublesSketchIterator( - getDoubleItemsArray(), getLevelsArray(SketchStructure.UPDATABLE), getNumLevels()); - } - - @Override - public final void merge(final KllSketch other) { - if (readOnly || (sketchStructure != UPDATABLE)) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - if (this == other) { throw new SketchesArgumentException(SELF_MERGE_MSG); } - final KllDoublesSketch othDblSk = (KllDoublesSketch)other; - if (othDblSk.isEmpty()) { return; } - KllDoublesHelper.mergeDoubleImpl(this, othDblSk); - doublesSV = null; - } - - /** - * {@inheritDoc} - * - *

The parameter k will not change.

- */ - @Override - public final void reset() { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int k = getK(); - setN(0); - setMinK(k); - setNumLevels(1); - setLevelZeroSorted(false); - setLevelsArray(new int[] {k, k}); - setMinItem(Double.NaN); - setMaxItem(Double.NaN); - setDoubleItemsArray(new double[k]); - doublesSV = null; - } - - @Override - public byte[] toByteArray() { - return KllHelper.toByteArray(this, false); - } - - @Override - public String toString(final boolean withLevels, final boolean withLevelsAndItems) { - KllSketch sketch = this; - if (withLevelsAndItems && (sketchStructure != UPDATABLE)) { - final MemorySegment seg = getMemorySegment(); - assert seg != null; - sketch = KllDoublesSketch.heapify(getMemorySegment()); - } - return KllHelper.toStringImpl(sketch, withLevels, withLevelsAndItems); - } - - //SINGLE UPDATE - - @Override - public void update(final double item) { - if (Double.isNaN(item)) { return; } //ignore - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - updateDouble(this, item); - doublesSV = null; - } - - //Also Called from KllDoublesHelper::merge - static void updateDouble(final KllDoublesSketch dblSk, final double item) { - dblSk.updateMinMax(item); - int freeSpace = dblSk.levelsArr[0]; - assert (freeSpace >= 0); - if (freeSpace == 0) { - KllDoublesHelper.compressWhileUpdatingSketch(dblSk); - freeSpace = dblSk.levelsArr[0]; - assert (freeSpace > 0); - } - dblSk.incN(1); - dblSk.setLevelZeroSorted(false); - final int nextPos = freeSpace - 1; - dblSk.setLevelsArrayAt(0, nextPos); - dblSk.setDoubleItemsArrayAt(nextPos, item); - } - - /** - * Single update of min and max - * @param item the source item, it must not be a NaN. - */ - final void updateMinMax(final double item) { - if (isEmpty() || Double.isNaN(getMinItemInternal())) { - setMinItem(item); - setMaxItem(item); - } else { - setMinItem(min(getMinItemInternal(), item)); - setMaxItem(max(getMaxItemInternal(), item)); - } - } - - //WEIGHTED UPDATE - - /** - * Weighted update. Updates this sketch with the given item the number of times specified by the given integer weight. - * @param item the item to be repeated. NaNs are ignored. - * @param weight the number of times the update of item is to be repeated. It must be ≥ one. - */ - public void update(final double item, final long weight) { - if (Double.isNaN(item)) { return; } //ignore - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - if (weight < 1L) { throw new SketchesArgumentException("Weight is less than one."); } - if (weight == 1L) { updateDouble(this, item); } - else if (weight < levelsArr[0]) { - for (int i = 0; i < (int)weight; i++) { updateDouble(this, item); } - } else { - final KllHeapDoublesSketch tmpSk = new KllHeapDoublesSketch(getK(), DEFAULT_M, item, weight); - merge(tmpSk); - } - doublesSV = null; - } - - // VECTOR UPDATE - - /** - * Vector update. Updates this sketch with the given array (vector) of items, starting at the items - * offset for a length number of items. This is not supported for direct sketches. - *

Note: a single occurrence of a NaN in the array will force this method to use the conventional update path - * rather than the fast update path.

- * @param items the vector of items - * @param offset the starting index of the items[] array - * @param length the number of items - */ - public void update(final double[] items, final int offset, final int length) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - if (length == 0) { return; } - if (!hasNaN(items, offset, length)) { - updateDouble(items, offset, length); //fast path - doublesSV = null; - return; - } - //has at least one NaN - final int end = offset + length; - for (int i = offset; i < end; i++) { - final double v = items[i]; - if (!Double.isNaN(v)) { - updateDouble(this, v); //normal path - doublesSV = null; - } - } - } - - // No NaNs are allowed at this point - private void updateDouble(final double[] srcItems, final int srcOffset, final int length) { - if (isEmpty() || Double.isNaN(getMinItemInternal())) { - setMinItem(srcItems[srcOffset]); //initialize with a real value - setMaxItem(srcItems[srcOffset]); - } - - int count = 0; - while (count < length) { - if (levelsArr[0] == 0) { - KllDoublesHelper.compressWhileUpdatingSketch(this); - } - final int spaceNeeded = length - count; - final int freeSpace = levelsArr[0]; - assert (freeSpace > 0); - final int numItemsToCopy = min(spaceNeeded, freeSpace); - final int dstOffset = freeSpace - numItemsToCopy; - final int localSrcOffset = srcOffset + count; - setDoubleItemsArrayAt(dstOffset, srcItems, localSrcOffset, numItemsToCopy); - updateMinMax(srcItems, localSrcOffset, numItemsToCopy); - count += numItemsToCopy; - incN(numItemsToCopy); - setLevelsArrayAt(0, dstOffset); - } - setLevelZeroSorted(false); - } - - /** - * Vector update of min and max. - * @param srcItems the input source array of values, no NaNs allowed. - * @param srcOffset the starting offset in srcItems - * @param length the number of items to update min and max - */ - private void updateMinMax(final double[] srcItems, final int srcOffset, final int length) { - final int end = srcOffset + length; - for (int i = srcOffset; i < end; i++) { - setMinItem(min(getMinItemInternal(), srcItems[i])); - setMaxItem(max(getMaxItemInternal(), srcItems[i])); - } - } - - // this returns on the first detected NaN. - private static boolean hasNaN(final double[] items, final int offset, final int length) { - final int end = offset + length; - for (int i = offset; i < end; i++) { - if (Double.isNaN(items[i])) { return true; } - } - return false; - } - - // END ALL UPDATE METHODS - - /** - * @return full size of internal items array including empty space at bottom. - */ - abstract double[] getDoubleItemsArray(); - - /** - * @return items array of retained items. - */ - abstract double[] getDoubleRetainedItemsArray(); - - abstract double getDoubleSingleItem(); - - // Min & Max Methods - - abstract double getMaxItemInternal(); - - abstract void setMaxItem(double item); - - abstract double getMinItemInternal(); - - abstract void setMinItem(double item); - - @Override - abstract byte[] getMinMaxByteArr(); - - @Override - int getMinMaxSizeBytes() { - return Double.BYTES * 2; - } - - //END Min & Max Methods - - @Override - abstract byte[] getRetainedItemsByteArr(); - - @Override - int getRetainedItemsSizeBytes() { - return getNumRetained() * Double.BYTES; - } - - @Override - ArrayOfItemsSerDe getSerDe() { return null; } - - @Override - final byte[] getSingleItemByteArr() { - final byte[] bytes = new byte[ITEM_BYTES]; - putDoubleLE(bytes, 0, getDoubleSingleItem()); - return bytes; - } - - @Override - int getSingleItemSizeBytes() { - return Double.BYTES; - } - - @Override - abstract byte[] getTotalItemsByteArr(); - - @Override - int getTotalItemsNumBytes() { - return levelsArr[getNumLevels()] * Double.BYTES; - } - - abstract void setDoubleItemsArray(double[] doubleItems); - - abstract void setDoubleItemsArrayAt(int index, double item); - - abstract void setDoubleItemsArrayAt(int dstIndex, double[] srcItems, int srcOffset, int length); - - // SORTED VIEW - - @Override - public DoublesSketchSortedView getSortedView() { - refreshSortedView(); - return doublesSV; - } - - private final DoublesSketchSortedView refreshSortedView() { - if (doublesSV == null) { - final CreateSortedView csv = new CreateSortedView(); - doublesSV = csv.getSV(); - } - return doublesSV; - } - - private final class CreateSortedView { - double[] quantiles; - long[] cumWeights; - - DoublesSketchSortedView getSV() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - final double[] srcQuantiles = getDoubleItemsArray(); - final int[] srcLevels = levelsArr; - final int srcNumLevels = getNumLevels(); - - if (!isLevelZeroSorted()) { - Arrays.sort(srcQuantiles, srcLevels[0], srcLevels[1]); - if (!hasMemorySegment()) { setLevelZeroSorted(true); } - //we don't sort level0 in MemorySegment, only our copy. - } - final int numQuantiles = getNumRetained(); - quantiles = new double[numQuantiles]; - cumWeights = new long[numQuantiles]; - populateFromSketch(srcQuantiles, srcLevels, srcNumLevels, numQuantiles); - return new DoublesSketchSortedView(quantiles, cumWeights, KllDoublesSketch.this); - } - - private void populateFromSketch(final double[] srcQuantiles, final int[] srcLevels, - final int srcNumLevels, final int numItems) { - final int[] myLevels = new int[srcNumLevels + 1]; - final int offset = srcLevels[0]; - System.arraycopy(srcQuantiles, offset, quantiles, 0, numItems); - int srcLevel = 0; - int dstLevel = 0; - long weight = 1; - while (srcLevel < srcNumLevels) { - final int fromIndex = srcLevels[srcLevel] - offset; - final int toIndex = srcLevels[srcLevel + 1] - offset; // exclusive - if (fromIndex < toIndex) { // if equal, skip empty level - Arrays.fill(cumWeights, fromIndex, toIndex, weight); - myLevels[dstLevel] = fromIndex; - myLevels[dstLevel + 1] = toIndex; - dstLevel++; - } - srcLevel++; - weight *= 2; - } - final int numLevels = dstLevel; - blockyTandemMergeSort(quantiles, cumWeights, myLevels, numLevels); //create unit weights - KllHelper.convertToCumulative(cumWeights); - } - } //End of class CreateSortedView - - private static void blockyTandemMergeSort(final double[] quantiles, final long[] weights, - final int[] levels, final int numLevels) { - if (numLevels == 1) { return; } - - // duplicate the input in preparation for the "ping-pong" copy reduction strategy. - final double[] quantilesTmp = Arrays.copyOf(quantiles, quantiles.length); - final long[] weightsTmp = Arrays.copyOf(weights, quantiles.length); // don't need the extra one - - blockyTandemMergeSortRecursion(quantilesTmp, weightsTmp, quantiles, weights, levels, 0, numLevels); - } - - private static void blockyTandemMergeSortRecursion( - final double[] quantilesSrc, final long[] weightsSrc, - final double[] quantilesDst, final long[] weightsDst, - final int[] levels, final int startingLevel, final int numLevels) { - if (numLevels == 1) { return; } - final int numLevels1 = numLevels / 2; - final int numLevels2 = numLevels - numLevels1; - assert numLevels1 >= 1; - assert numLevels2 >= numLevels1; - final int startingLevel1 = startingLevel; - final int startingLevel2 = startingLevel + numLevels1; - // swap roles of src and dst - blockyTandemMergeSortRecursion( - quantilesDst, weightsDst, - quantilesSrc, weightsSrc, - levels, startingLevel1, numLevels1); - blockyTandemMergeSortRecursion( - quantilesDst, weightsDst, - quantilesSrc, weightsSrc, - levels, startingLevel2, numLevels2); - tandemMerge( - quantilesSrc, weightsSrc, - quantilesDst, weightsDst, - levels, - startingLevel1, numLevels1, - startingLevel2, numLevels2); - } - - private static void tandemMerge( - final double[] quantilesSrc, final long[] weightsSrc, - final double[] quantilesDst, final long[] weightsDst, - final int[] levelStarts, - final int startingLevel1, final int numLevels1, - final int startingLevel2, final int numLevels2) { - final int fromIndex1 = levelStarts[startingLevel1]; - final int toIndex1 = levelStarts[startingLevel1 + numLevels1]; // exclusive - final int fromIndex2 = levelStarts[startingLevel2]; - final int toIndex2 = levelStarts[startingLevel2 + numLevels2]; // exclusive - int iSrc1 = fromIndex1; - int iSrc2 = fromIndex2; - int iDst = fromIndex1; - - while ((iSrc1 < toIndex1) && (iSrc2 < toIndex2)) { - if (quantilesSrc[iSrc1] < quantilesSrc[iSrc2]) { - quantilesDst[iDst] = quantilesSrc[iSrc1]; - weightsDst[iDst] = weightsSrc[iSrc1]; - iSrc1++; - } else { - quantilesDst[iDst] = quantilesSrc[iSrc2]; - weightsDst[iDst] = weightsSrc[iSrc2]; - iSrc2++; - } - iDst++; - } - if (iSrc1 < toIndex1) { - System.arraycopy(quantilesSrc, iSrc1, quantilesDst, iDst, toIndex1 - iSrc1); - System.arraycopy(weightsSrc, iSrc1, weightsDst, iDst, toIndex1 - iSrc1); - } else if (iSrc2 < toIndex2) { - System.arraycopy(quantilesSrc, iSrc2, quantilesDst, iDst, toIndex2 - iSrc2); - System.arraycopy(weightsSrc, iSrc2, weightsDst, iDst, toIndex2 - iSrc2); - } - } - - // END SORTED VIEW - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllDoublesSketchIterator.java b/src/main/java/org/apache/datasketches/kll/KllDoublesSketchIterator.java deleted file mode 100644 index 9c7e4bd13..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllDoublesSketchIterator.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIteratorAPI; - -/** - * Iterator over KllDoublesSketch. The order is not defined. - */ -public final class KllDoublesSketchIterator extends KllSketchIterator implements QuantilesDoublesSketchIteratorAPI { - private final double[] quantiles; - - KllDoublesSketchIterator(final double[] quantiles, final int[] levelsArr, final int numLevels) { - super(levelsArr, numLevels); - this.quantiles = quantiles; - } - - @Override - public double getQuantile() { - return quantiles[index]; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllFloatsHelper.java b/src/main/java/org/apache/datasketches/kll/KllFloatsHelper.java deleted file mode 100644 index 7038e1b2f..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllFloatsHelper.java +++ /dev/null @@ -1,479 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.apache.datasketches.common.Util.isEven; -import static org.apache.datasketches.common.Util.isOdd; -import static org.apache.datasketches.kll.KllHelper.findLevelToCompact; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Random; - -/** - * Static methods to support KllFloatsSketch - * @author Kevin Lang - * @author Alexander Saydakov - */ -final class KllFloatsHelper { - - /** - * Create Items Array from given item and weight. - * Used with weighted update only. - * @param item the given item - * @param weight the given weight - * @return the Items Array. - */ - static float[] createItemsArray(final float item, final long weight) { - final int itemsArrLen = Long.bitCount(weight); - final float[] itemsArr = new float[itemsArrLen]; - Arrays.fill(itemsArr, item); - return itemsArr; - } - - /** - * The following code is only valid in the special case of exactly reaching capacity while updating. - * It cannot be used while merging, while reducing k, or anything else. - * @param fltSk the current KllFloatsSketch - */ - static void compressWhileUpdatingSketch(final KllFloatsSketch fltSk) { - final int level = - findLevelToCompact(fltSk.getK(), fltSk.getM(), fltSk.getNumLevels(), fltSk.levelsArr); - if (level == (fltSk.getNumLevels() - 1)) { - //The level to compact is the top level, thus we need to add a level. - //Be aware that this operation grows the items array, - //shifts the items data and the level boundaries of the data, - //and grows the levels array and increments numLevels_. - KllHelper.addEmptyTopLevelToCompletelyFullSketch(fltSk); - } - //after this point, the levelsArray will not be expanded, only modified. - final int[] myLevelsArr = fltSk.levelsArr; - final int rawBeg = myLevelsArr[level]; - final int rawEnd = myLevelsArr[level + 1]; - // +2 is OK because we already added a new top level if necessary - final int popAbove = myLevelsArr[level + 2] - rawEnd; - final int rawPop = rawEnd - rawBeg; - final boolean oddPop = isOdd(rawPop); - final int adjBeg = oddPop ? rawBeg + 1 : rawBeg; - final int adjPop = oddPop ? rawPop - 1 : rawPop; - final int halfAdjPop = adjPop / 2; - - //the following is specific to Floats - final float[] myFloatItemsArr = fltSk.getFloatItemsArray(); - if (level == 0) { // level zero might not be sorted, so we must sort it if we wish to compact it - Arrays.sort(myFloatItemsArr, adjBeg, adjBeg + adjPop); - } - if (popAbove == 0) { - KllFloatsHelper.randomlyHalveUpFloats(myFloatItemsArr, adjBeg, adjPop, KllSketch.random); - } else { - KllFloatsHelper.randomlyHalveDownFloats(myFloatItemsArr, adjBeg, adjPop, KllSketch.random); - KllFloatsHelper.mergeSortedFloatArrays( - myFloatItemsArr, adjBeg, halfAdjPop, - myFloatItemsArr, rawEnd, popAbove, - myFloatItemsArr, adjBeg + halfAdjPop); - } - - int newIndex = myLevelsArr[level + 1] - halfAdjPop; // adjust boundaries of the level above - fltSk.setLevelsArrayAt(level + 1, newIndex); - - if (oddPop) { - fltSk.setLevelsArrayAt(level, myLevelsArr[level + 1] - 1); // the current level now contains one item - myFloatItemsArr[myLevelsArr[level]] = myFloatItemsArr[rawBeg]; // namely this leftover guy - } else { - fltSk.setLevelsArrayAt(level, myLevelsArr[level + 1]); // the current level is now empty - } - - // verify that we freed up halfAdjPop array slots just below the current level - assert myLevelsArr[level] == (rawBeg + halfAdjPop); - - // finally, we need to shift up the data in the levels below - // so that the freed-up space can be used by level zero - if (level > 0) { - final int amount = rawBeg - myLevelsArr[0]; - System.arraycopy(myFloatItemsArr, myLevelsArr[0], myFloatItemsArr, myLevelsArr[0] + halfAdjPop, amount); - } - for (int lvl = 0; lvl < level; lvl++) { - newIndex = myLevelsArr[lvl] + halfAdjPop; //adjust boundary - fltSk.setLevelsArrayAt(lvl, newIndex); - } - fltSk.setFloatItemsArray(myFloatItemsArr); - } - - //assumes readOnly = false and UPDATABLE, called from KllFloatsSketch::merge - static void mergeFloatImpl(final KllFloatsSketch mySketch, final KllFloatsSketch otherFltSk) { - if (otherFltSk.isEmpty()) { return; } - - //capture my key mutable fields before doing any merging - final boolean myEmpty = mySketch.isEmpty(); - final float myMin = mySketch.getMinItemInternal(); - final float myMax = mySketch.getMaxItemInternal(); - final int myMinK = mySketch.getMinK(); - final long finalN = Math.addExact(mySketch.getN(), otherFltSk.getN()); - - //buffers that are referenced multiple times - final int otherNumLevels = otherFltSk.getNumLevels(); - final int[] otherLevelsArr = otherFltSk.levelsArr; - final float[] otherFloatItemsArr; - - //MERGE: update this sketch with level0 items from the other sketch - if (otherFltSk.isCompactSingleItem()) { - KllFloatsSketch.updateFloat(mySketch, otherFltSk.getFloatSingleItem()); - otherFloatItemsArr = new float[0]; - } else { - otherFloatItemsArr = otherFltSk.getFloatItemsArray(); - for (int i = otherLevelsArr[0]; i < otherLevelsArr[1]; i++) { - KllFloatsSketch.updateFloat(mySketch, otherFloatItemsArr[i]); - } - } - - //After the level 0 update, we capture the intermediate state of levels and items arrays... - final int myCurNumLevels = mySketch.getNumLevels(); - final int[] myCurLevelsArr = mySketch.levelsArr; - final float[] myCurFloatItemsArr = mySketch.getFloatItemsArray(); - - // create aliases in case there are no higher levels - int myNewNumLevels = myCurNumLevels; - int[] myNewLevelsArr = myCurLevelsArr; - float[] myNewFloatItemsArr = myCurFloatItemsArr; - - //merge higher levels if they exist - if ((otherNumLevels > 1) && !otherFltSk.isCompactSingleItem()) { - final int tmpSpaceNeeded = mySketch.getNumRetained() - + KllHelper.getNumRetainedAboveLevelZero(otherNumLevels, otherLevelsArr); - final float[] workbuf = new float[tmpSpaceNeeded]; - - final int provisionalNumLevels = max(myCurNumLevels, otherNumLevels); - - final int ub = max(KllHelper.ubOnNumLevels(finalN), provisionalNumLevels); - final int[] worklevels = new int[ub + 2]; // ub+1 does not work - final int[] outlevels = new int[ub + 2]; - - populateFloatWorkArrays(workbuf, worklevels, provisionalNumLevels, - myCurNumLevels, myCurLevelsArr, myCurFloatItemsArr, - otherNumLevels, otherLevelsArr, otherFloatItemsArr); - - // notice that workbuf is being used as both the input and output - final int[] result = generalFloatsCompress(mySketch.getK(), mySketch.getM(), provisionalNumLevels, - workbuf, worklevels, workbuf, outlevels, mySketch.isLevelZeroSorted(), KllSketch.random); - final int targetItemCount = result[1]; //was finalCapacity. Max size given k, m, numLevels - final int curItemCount = result[2]; //was finalPop - - // now we need to finalize the results for mySketch - - //THE NEW NUM LEVELS - myNewNumLevels = result[0]; - assert myNewNumLevels <= ub; // ub may be much bigger - - // THE NEW ITEMS ARRAY - myNewFloatItemsArr = (targetItemCount == myCurFloatItemsArr.length) - ? myCurFloatItemsArr - : new float[targetItemCount]; - final int freeSpaceAtBottom = targetItemCount - curItemCount; - - //shift the new items array create space at bottom - System.arraycopy(workbuf, outlevels[0], myNewFloatItemsArr, freeSpaceAtBottom, curItemCount); - final int theShift = freeSpaceAtBottom - outlevels[0]; - - //calculate the new levels array length - final int finalLevelsArrLen; - if (myCurLevelsArr.length < (myNewNumLevels + 1)) { finalLevelsArrLen = myNewNumLevels + 1; } - else { finalLevelsArrLen = myCurLevelsArr.length; } - - //THE NEW LEVELS ARRAY - myNewLevelsArr = new int[finalLevelsArrLen]; - for (int lvl = 0; lvl < (myNewNumLevels + 1); lvl++) { // includes the "extra" index - myNewLevelsArr[lvl] = outlevels[lvl] + theShift; - } - - //MemorySegment SPACE MANAGEMENT - if (mySketch.getMemorySegment() != null) { - final MemorySegment wseg = KllHelper.memorySegmentSpaceMgmt(mySketch, myNewLevelsArr.length, myNewFloatItemsArr.length); - mySketch.setMemorySegment(wseg); - } - } //end of updating levels above level 0 - - //Update Preamble: - mySketch.setN(finalN); - if (otherFltSk.isEstimationMode()) { //otherwise the merge brings over exact items. - mySketch.setMinK(min(myMinK, otherFltSk.getMinK())); - } - - //Update numLevels, levelsArray, items - mySketch.setNumLevels(myNewNumLevels); - mySketch.setLevelsArray(myNewLevelsArr); - mySketch.setFloatItemsArray(myNewFloatItemsArr); - - //Update min, max items - final float otherMin = otherFltSk.getMinItem(); - final float otherMax = otherFltSk.getMaxItem(); - if (myEmpty) { - mySketch.setMinItem(otherMin); - mySketch.setMaxItem(otherMax); - } else { - mySketch.setMinItem(min(myMin, otherMin)); - mySketch.setMaxItem(max(myMax, otherMax)); - } - assert KllHelper.sumTheSampleWeights(mySketch.getNumLevels(), mySketch.levelsArr) == mySketch.getN(); - } - - private static void mergeSortedFloatArrays( - final float[] bufA, final int startA, final int lenA, - final float[] bufB, final int startB, final int lenB, - final float[] bufC, final int startC) { - final int lenC = lenA + lenB; - final int limA = startA + lenA; - final int limB = startB + lenB; - final int limC = startC + lenC; - - int a = startA; - int b = startB; - - for (int c = startC; c < limC; c++) { - if (a == limA) { - bufC[c] = bufB[b]; - b++; - } else if ((b == limB) || (bufA[a] < bufB[b])) { - bufC[c] = bufA[a]; - a++; - } else { - bufC[c] = bufB[b]; - b++; - } - } - assert a == limA; - assert b == limB; - } - - /** - * Validation Method. This must be modified to use the validation test - * @param buf the items array - * @param start data start - * @param length items array length - * @param random instance of Random - */ - //NOTE For validation Method: Need to modify to run. - private static void randomlyHalveDownFloats(final float[] buf, final int start, final int length, - final Random random) { - assert isEven(length); - final int half_length = length / 2; - final int offset = random.nextInt(2); // disable for validation - //final int offset = deterministicOffset(); // enable for validation - int j = start + offset; - for (int i = start; i < (start + half_length); i++) { - buf[i] = buf[j]; - j += 2; - } - } - - /** - * Validation Method. This must be modified to use the validation test - * @param buf the items array - * @param start data start - * @param length items array length - * @param random instance of Random - */ - //NOTE For validation Method: Need to modify to run. - private static void randomlyHalveUpFloats(final float[] buf, final int start, final int length, - final Random random) { - assert isEven(length); - final int half_length = length / 2; - final int offset = random.nextInt(2); // disable for validation - //final int offset = deterministicOffset(); // enable for validation - int j = (start + length) - 1 - offset; - for (int i = (start + length) - 1; i >= (start + half_length); i--) { - buf[i] = buf[j]; - j -= 2; - } - } - - /** - * Compression algorithm used to merge higher levels. - * - *

Here is what we do for each level:

- *
  • If it does not need to be compacted, then simply copy it over.
  • - *
  • Otherwise, it does need to be compacted, so... - *
    • Copy zero or one guy over.
    • - *
    • If the level above is empty, halve up.
    • - *
    • Else the level above is nonempty, so halve down, then merge up.
    • - *
  • - *
  • Adjust the boundaries of the level above.
  • - *
- * - *

It can be proved that generalCompress returns a sketch that satisfies the space constraints - * no matter how much data is passed in. - * We are pretty sure that it works correctly when inBuf and outBuf are the same. - * All levels except for level zero must be sorted before calling this, and will still be - * sorted afterwards. - * Level zero is not required to be sorted before, and may not be sorted afterwards.

- * - *

This trashes inBuf and inLevels and modifies outBuf and outLevels.

- * - * @param k The sketch parameter k - * @param m The minimum level size - * @param numLevelsIn provisional number of number of levels = max(this.numLevels, other.numLevels) - * @param inBuf work buffer of size = this.getNumRetained() + other.getNumRetainedAboveLevelZero(). - * This contains the float[] of the other sketch - * @param inLevels work levels array size = ubOnNumLevels(this.n + other.n) + 2 - * @param outBuf the same array as inBuf - * @param outLevels the same size as inLevels - * @param isLevelZeroSorted true if this.level 0 is sorted - * @param random instance of java.util.Random - * @return int array of: {numLevels, targetItemCount, currentItemCount) - */ - // - private static int[] generalFloatsCompress( - final int k, - final int m, - final int numLevelsIn, - final float[] inBuf, - final int[] inLevels, - final float[] outBuf, - final int[] outLevels, - final boolean isLevelZeroSorted, - final Random random) { - assert numLevelsIn > 0; // things are too weird if zero levels are allowed - int numLevels = numLevelsIn; - int currentItemCount = inLevels[numLevels] - inLevels[0]; // decreases with each compaction - int targetItemCount = KllHelper.computeTotalItemCapacity(k, m, numLevels); // increases if we add levels - boolean doneYet = false; - outLevels[0] = 0; - int curLevel = -1; - while (!doneYet) { - curLevel++; // start out at level 0 - - // If we are at the current top level, add an empty level above it for convenience, - // but do not actually increment numLevels until later - if (curLevel == (numLevels - 1)) { - inLevels[curLevel + 2] = inLevels[curLevel + 1]; - } - - final int rawBeg = inLevels[curLevel]; - final int rawLim = inLevels[curLevel + 1]; - final int rawPop = rawLim - rawBeg; - - if ((currentItemCount < targetItemCount) || (rawPop < KllHelper.levelCapacity(k, numLevels, curLevel, m))) { - // copy level over as is - // because inBuf and outBuf could be the same, make sure we are not moving data upwards! - assert (rawBeg >= outLevels[curLevel]); - System.arraycopy(inBuf, rawBeg, outBuf, outLevels[curLevel], rawPop); - outLevels[curLevel + 1] = outLevels[curLevel] + rawPop; - } - else { - // The sketch is too full AND this level is too full, so we compact it - // Note: this can add a level and thus change the sketch's capacity - - final int popAbove = inLevels[curLevel + 2] - rawLim; - final boolean oddPop = isOdd(rawPop); - final int adjBeg = oddPop ? 1 + rawBeg : rawBeg; - final int adjPop = oddPop ? rawPop - 1 : rawPop; - final int halfAdjPop = adjPop / 2; - - if (oddPop) { // copy one guy over - outBuf[outLevels[curLevel]] = inBuf[rawBeg]; - outLevels[curLevel + 1] = outLevels[curLevel] + 1; - } else { // copy zero guys over - outLevels[curLevel + 1] = outLevels[curLevel]; - } - - // level zero might not be sorted, so we must sort it if we wish to compact it - if ((curLevel == 0) && !isLevelZeroSorted) { - Arrays.sort(inBuf, adjBeg, adjBeg + adjPop); - } - - if (popAbove == 0) { // Level above is empty, so halve up - randomlyHalveUpFloats(inBuf, adjBeg, adjPop, random); - } else { // Level above is nonempty, so halve down, then merge up - randomlyHalveDownFloats(inBuf, adjBeg, adjPop, random); - mergeSortedFloatArrays(inBuf, adjBeg, halfAdjPop, inBuf, rawLim, popAbove, inBuf, adjBeg + halfAdjPop); - } - - // track the fact that we just eliminated some data - currentItemCount -= halfAdjPop; - - // Adjust the boundaries of the level above - inLevels[curLevel + 1] = inLevels[curLevel + 1] - halfAdjPop; - - // Increment numLevels if we just compacted the old top level - // This creates some more capacity (the size of the new bottom level) - if (curLevel == (numLevels - 1)) { - numLevels++; - targetItemCount += KllHelper.levelCapacity(k, numLevels, 0, m); - } - } // end of code for compacting a level - - // determine whether we have processed all levels yet (including any new levels that we created) - if (curLevel == (numLevels - 1)) { doneYet = true; } - } // end of loop over levels - - assert (outLevels[numLevels] - outLevels[0]) == currentItemCount; - return new int[] {numLevels, targetItemCount, currentItemCount}; - } - - private static void populateFloatWorkArrays( //workBuf and workLevels are modified - final float[] workBuf, final int[] workLevels, final int provisionalNumLevels, - final int myCurNumLevels, final int[] myCurLevelsArr, final float[] myCurFloatItemsArr, - final int otherNumLevels, final int[] otherLevelsArr, final float[] otherFloatItemsArr) { - - workLevels[0] = 0; - - // Note: the level zero data from "other" was already inserted into "self". - // This copies into workbuf. - final int selfPopZero = KllHelper.currentLevelSizeItems(0, myCurNumLevels, myCurLevelsArr); - System.arraycopy( myCurFloatItemsArr, myCurLevelsArr[0], workBuf, workLevels[0], selfPopZero); - workLevels[1] = workLevels[0] + selfPopZero; - - for (int lvl = 1; lvl < provisionalNumLevels; lvl++) { - final int selfPop = KllHelper.currentLevelSizeItems(lvl, myCurNumLevels, myCurLevelsArr); - final int otherPop = KllHelper.currentLevelSizeItems(lvl, otherNumLevels, otherLevelsArr); - workLevels[lvl + 1] = workLevels[lvl] + selfPop + otherPop; - assert (selfPop >= 0) && (otherPop >= 0); - if ((selfPop == 0) && (otherPop == 0)) { continue; } - if ((selfPop > 0) && (otherPop == 0)) { - System.arraycopy(myCurFloatItemsArr, myCurLevelsArr[lvl], workBuf, workLevels[lvl], selfPop); - } - else if ((selfPop == 0) && (otherPop > 0)) { - System.arraycopy(otherFloatItemsArr, otherLevelsArr[lvl], workBuf, workLevels[lvl], otherPop); - } - else if ((selfPop > 0) && (otherPop > 0)) { - mergeSortedFloatArrays( //only workBuf is modified - myCurFloatItemsArr, myCurLevelsArr[lvl], selfPop, - otherFloatItemsArr, otherLevelsArr[lvl], otherPop, - workBuf, workLevels[lvl]); - } - } - } - - /* - * Validation Method. - * The following must be enabled for use with the KllFloatsValidationTest, - * which is only enabled for manual testing. In addition, two Validation Methods - * above need to be modified. - */ //NOTE Validation Method: Need to uncomment to use - // static int nextOffset = 0; - // - // private static int deterministicOffset() { - // final int result = nextOffset; - // nextOffset = 1 - nextOffset; - // return result; - // } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllFloatsSketch.java b/src/main/java/org/apache/datasketches/kll/KllFloatsSketch.java deleted file mode 100644 index b2741047c..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllFloatsSketch.java +++ /dev/null @@ -1,673 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.apache.datasketches.common.ByteArrayUtil.putFloatLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_FLOATS_SKETCH; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Objects; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.FloatsSketchSortedView; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; -import org.apache.datasketches.quantilescommon.QuantilesFloatsAPI; -import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator; - -/** - * This variation of the KllSketch implements primitive floats. - * - * @see org.apache.datasketches.kll.KllSketch - */ -public abstract class KllFloatsSketch extends KllSketch implements QuantilesFloatsAPI { - private FloatsSketchSortedView floatsSV = null; - final static int ITEM_BYTES = Float.BYTES; - - /** - * Constructor for on-heap. - * @param sketchStructure the current sketch structure - */ - KllFloatsSketch(final SketchStructure sketchStructure) { - super(SketchType.KLL_FLOATS_SKETCH, sketchStructure); - } - - /** - * Constructor for MemorySegment based sketch - * @param segVal MemorySegment validator. - */ - KllFloatsSketch(final KllMemorySegmentValidate segVal) { - super(segVal); - } - - //Factories for new heap instances. - - /** - * Create a new heap instance of this sketch with the default k = 200. - * The default k = 200 results in a normalized rank error of about - * 1.65%. Larger K will have smaller error but the sketch will be larger (and slower). - * @return new KllFloatsSketch on the Java heap. - */ - public static KllFloatsSketch newHeapInstance() { - return newHeapInstance(DEFAULT_K); - } - - /** - * Create a new heap instance of this sketch with a given parameter k. - * k can be between 8, inclusive, and 65535, inclusive. - * The default k = 200 results in a normalized rank error of about - * 1.65%. Larger K will have smaller error but the sketch will be larger (and slower). - * @param k parameter that controls size of the sketch and accuracy of estimates. - * @return new KllFloatsSketch on the Java heap. - */ - public static KllFloatsSketch newHeapInstance(final int k) { - return new KllHeapFloatsSketch(k, DEFAULT_M); - } - - //Factories for new direct instances. - - /** - * Create a new direct updatable instance of this sketch with the default k. - * The default k = 200 results in a normalized rank error of about - * 1.65%. Larger k will have smaller error but the sketch will be larger (and slower). - * @param dstSeg the given destination MemorySegment object for use by the sketch - * @return a new direct instance of this sketch - */ - public static KllFloatsSketch newDirectInstance(final MemorySegment dstSeg) { - return newDirectInstance(DEFAULT_K, dstSeg, null); - } - - /** - * Create a new direct updatable instance of this sketch with a given k. - * @param k parameter that controls size of the sketch and accuracy of estimates. - * @param dstSeg the given destination MemorySegment object for use by the sketch - * @param mSegReq the callback for the sketch to request a larger MemorySegment. It may be null. - * @return a new direct instance of this sketch - */ - public static KllFloatsSketch newDirectInstance( - final int k, - final MemorySegment dstSeg, - final MemorySegmentRequest mSegReq) { - Objects.requireNonNull(dstSeg, "Parameter 'dstSeg' must not be null"); - return KllDirectFloatsSketch.newDirectUpdatableInstance(k, DEFAULT_M, dstSeg, mSegReq); - } - - //Factory to create an heap instance from a MemorySegment image - - /** - * Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch. - * The resulting sketch will not retain any link to the source MemorySegment. - * @param srcSeg a compact MemorySegment image of a sketch serialized by this sketch. - * @return a heap-based sketch based on the given MemorySegment. - */ - public static KllFloatsSketch heapify(final MemorySegment srcSeg) { - Objects.requireNonNull(srcSeg, "Parameter 'srcSeg' must not be null"); - return KllHeapFloatsSketch.heapifyImpl(srcSeg); - } - - //Factories to wrap a MemorySegment image - - /** - * Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch. - * - *

The given MemorySegment must be writable and it must contain a KllFloatsSketch in updatable form. - * The sketch will be updated and managed totally within the MemorySegment. If the given source - * MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

- * - *

NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch - * will request more capacity using the {@link MemorySegmentRequest MemorySegmentRequest} interface. The default of this interface will - * return a new MemorySegment on the heap.

- * - * @param srcSeg a MemorySegment that contains sketch data. - * @return an instance of this sketch that wraps the given MemorySegment. - */ - public static KllFloatsSketch wrap(final MemorySegment srcSeg) { - return wrap(srcSeg, null); - } - - /** - * Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch and including an - * optional, user defined {@link MemorySegmentRequest MemorySegmentRequest}. - * - *

The given MemorySegment must be writable and it must contain a KllFloatsSketch in updatable form. - * The sketch will be updated and managed totally within the MemorySegment. If the given source - * MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

- * - *

NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch - * will request more capacity using the {@link MemorySegmentRequest MemorySegmentRequest} interface. The default of this interface will - * return a new MemorySegment on the heap. It is up to the user to optionally extend this interface if more flexible - * handling of requests for more capacity is required.

- * - * @param srcSeg a MemorySegment that contains sketch data. - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return an instance of this sketch that wraps the given MemorySegment. - */ - public static KllFloatsSketch wrap(final MemorySegment srcSeg, final MemorySegmentRequest mSegReq) { - Objects.requireNonNull(srcSeg, "Parameter 'srcSeg' must not be null"); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(srcSeg, KLL_FLOATS_SKETCH); - return new KllDirectFloatsSketch(srcSeg, segVal, mSegReq); - } - - //END of Constructors - - @Override - public double[] getCDF(final float[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return floatsSV.getCDF(splitPoints, searchCrit); - } - - @Override - public double[] getPMF(final float[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return floatsSV.getPMF(splitPoints, searchCrit); - } - - @Override - public float getQuantile(final double rank, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return floatsSV.getQuantile(rank, searchCrit); - } - - @Override - public float[] getQuantiles(final double[] ranks, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - final int len = ranks.length; - final float[] quantiles = new float[len]; - for (int i = 0; i < len; i++) { - quantiles[i] = floatsSV.getQuantile(ranks[i], searchCrit); - } - return quantiles; - } - - /** - * {@inheritDoc} - * The approximate probability that the true quantile is within the confidence interval - * specified by the upper and lower quantile bounds for this sketch is 0.99. - */ - @Override - public float getQuantileLowerBound(final double rank) { - return getQuantile(max(0, rank - KllHelper.getNormalizedRankError(getMinK(), false))); - } - - /** - * {@inheritDoc} - * The approximate probability that the true quantile is within the confidence interval - * specified by the upper and lower quantile bounds for this sketch is 0.99. - */ - @Override - public float getQuantileUpperBound(final double rank) { - return getQuantile(min(1.0, rank + KllHelper.getNormalizedRankError(getMinK(), false))); - } - - @Override - public double getRank(final float quantile, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return floatsSV.getRank(quantile, searchCrit); - } - - /** - * {@inheritDoc} - * The approximate probability that the true rank is within the confidence interval - * specified by the upper and lower rank bounds for this sketch is 0.99. - */ - @Override - public double getRankLowerBound(final double rank) { - return max(0.0, rank - KllHelper.getNormalizedRankError(getMinK(), false)); - } - - /** - * {@inheritDoc} - * The approximate probability that the true rank is within the confidence interval - * specified by the upper and lower rank bounds for this sketch is 0.99. - */ - @Override - public double getRankUpperBound(final double rank) { - return min(1.0, rank + KllHelper.getNormalizedRankError(getMinK(), false)); - } - - @Override - public double[] getRanks(final float[] quantiles, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - final int len = quantiles.length; - final double[] ranks = new double[len]; - for (int i = 0; i < len; i++) { - ranks[i] = floatsSV.getRank(quantiles[i], searchCrit); - } - return ranks; - } - - @Override - public QuantilesFloatsSketchIterator iterator() { - return new KllFloatsSketchIterator( - getFloatItemsArray(), getLevelsArray(SketchStructure.UPDATABLE), getNumLevels()); - } - - @Override - public final void merge(final KllSketch other) { - if (readOnly || (sketchStructure != UPDATABLE)) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - if (this == other) { throw new SketchesArgumentException(SELF_MERGE_MSG); } - final KllFloatsSketch othFltSk = (KllFloatsSketch)other; - if (othFltSk.isEmpty()) { return; } - KllFloatsHelper.mergeFloatImpl(this, othFltSk); - floatsSV = null; - } - - /** - * {@inheritDoc} - * - *

The parameter k will not change.

- */ - @Override - public final void reset() { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int k = getK(); - setN(0); - setMinK(k); - setNumLevels(1); - setLevelZeroSorted(false); - setLevelsArray(new int[] {k, k}); - setMinItem(Float.NaN); - setMaxItem(Float.NaN); - setFloatItemsArray(new float[k]); - floatsSV = null; - } - - @Override - public byte[] toByteArray() { - return KllHelper.toByteArray(this, false); - } - - @Override - public String toString(final boolean withLevels, final boolean withLevelsAndItems) { - KllSketch sketch = this; - if (withLevelsAndItems && (sketchStructure != UPDATABLE)) { - final MemorySegment seg = getMemorySegment(); - assert seg != null; - sketch = KllFloatsSketch.heapify(getMemorySegment()); - } - return KllHelper.toStringImpl(sketch, withLevels, withLevelsAndItems); - } - - //SINGLE UPDATE - - @Override - public void update(final float item) { - if (Float.isNaN(item)) { return; } //ignore - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - updateFloat(this, item); - floatsSV = null; - } - - //Also Called from KllFloatsHelper::merge - static void updateFloat(final KllFloatsSketch fltSk, final float item) { - fltSk.updateMinMax(item); - int freeSpace = fltSk.levelsArr[0]; - assert (freeSpace >= 0); - if (freeSpace == 0) { - KllFloatsHelper.compressWhileUpdatingSketch(fltSk); - freeSpace = fltSk.levelsArr[0]; - assert (freeSpace > 0); - } - fltSk.incN(1); - fltSk.setLevelZeroSorted(false); - final int nextPos = freeSpace - 1; - fltSk.setLevelsArrayAt(0, nextPos); - fltSk.setFloatItemsArrayAt(nextPos, item); - } - - /** - * Single update of min and max - * @param item the source item, it must not be a NaN. - */ - final void updateMinMax(final float item) { - if (isEmpty() || Float.isNaN(getMinItemInternal())) { - setMinItem(item); - setMaxItem(item); - } else { - setMinItem(min(getMinItemInternal(), item)); - setMaxItem(max(getMaxItemInternal(), item)); - } - } - - //WEIGHTED UPDATE - - /** - * Weighted update. Updates this sketch with the given item the number of times specified by the given integer weight. - * @param item the item to be repeated. NaNs are ignored. - * @param weight the number of times the update of item is to be repeated. It must be ≥ one. - */ - public void update(final float item, final long weight) { - if (Float.isNaN(item)) { return; } //ignore - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - if (weight < 1L) { throw new SketchesArgumentException("Weight is less than one."); } - if (weight == 1L) { updateFloat(this, item); } - else if (weight < levelsArr[0]) { - for (int i = 0; i < (int)weight; i++) { updateFloat(this, item); } - } else { - final KllHeapFloatsSketch tmpSk = new KllHeapFloatsSketch(getK(), DEFAULT_M, item, weight); - merge(tmpSk); - } - floatsSV = null; - } - - // VECTOR UPDATE - - /** - * Vector update. Updates this sketch with the given array (vector) of items, starting at the items - * offset for a length number of items. This is not supported for direct sketches. - *

Note: a single occurrence of a NaN in the array will force this method to use the conventional update path - * rather than the fast update path.

- * @param items the vector of items - * @param offset the starting index of the items[] array - * @param length the number of items - */ - public void update(final float[] items, final int offset, final int length) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - if (length == 0) { return; } - if (!hasNaN(items, offset, length)) { - updateFloat(items, offset, length); //fast path - floatsSV = null; - return; - } - //has at least one NaN - final int end = offset + length; - for (int i = offset; i < end; i++) { - final float v = items[i]; - if (!Float.isNaN(v)) { - updateFloat(this, v); //normal path - floatsSV = null; - } - } - } - - // No NaNs are allowed at this point - private void updateFloat(final float[] srcItems, final int srcOffset, final int length) { - if (isEmpty() || Float.isNaN(getMinItemInternal())) { - setMinItem(srcItems[srcOffset]); //initialize with a real value - setMaxItem(srcItems[srcOffset]); - } - - int count = 0; - while (count < length) { - if (levelsArr[0] == 0) { - KllFloatsHelper.compressWhileUpdatingSketch(this); - } - final int spaceNeeded = length - count; - final int freeSpace = levelsArr[0]; - assert (freeSpace > 0); - final int numItemsToCopy = min(spaceNeeded, freeSpace); - final int dstOffset = freeSpace - numItemsToCopy; - final int localSrcOffset = srcOffset + count; - setFloatItemsArrayAt(dstOffset, srcItems, localSrcOffset, numItemsToCopy); - updateMinMax(srcItems, localSrcOffset, numItemsToCopy); - count += numItemsToCopy; - incN(numItemsToCopy); - setLevelsArrayAt(0, dstOffset); - } - setLevelZeroSorted(false); - } - - /** - * Vector update of min and max. - * @param srcItems the input source array of values, no NaNs allowed. - * @param srcOffset the starting offset in srcItems - * @param length the number of items to update min and max - */ - private void updateMinMax(final float[] srcItems, final int srcOffset, final int length) { - final int end = srcOffset + length; - for (int i = srcOffset; i < end; i++) { - setMinItem(min(getMinItemInternal(), srcItems[i])); - setMaxItem(max(getMaxItemInternal(), srcItems[i])); - } - } - - // this returns on the first detected NaN. - private static boolean hasNaN(final float[] items, final int offset, final int length) { - final int end = offset + length; - for (int i = offset; i < end; i++) { - if (Float.isNaN(items[i])) { return true; } - } - return false; - } - - // END ALL UPDATE METHODS - - /** - * @return full size of internal items array including empty space at bottom. - */ - abstract float[] getFloatItemsArray(); - - /** - * @return items array of retained items. - */ - abstract float[] getFloatRetainedItemsArray(); - - abstract float getFloatSingleItem(); - - // Min & Max Methods - - abstract float getMaxItemInternal(); - - abstract void setMaxItem(float item); - - abstract float getMinItemInternal(); - - abstract void setMinItem(float item); - - @Override - abstract byte[] getMinMaxByteArr(); - - @Override - int getMinMaxSizeBytes() { - return Float.BYTES * 2; - } - - //END Min & Max Methods - - @Override - abstract byte[] getRetainedItemsByteArr(); - - @Override - int getRetainedItemsSizeBytes() { - return getNumRetained() * Float.BYTES; - } - - @Override - ArrayOfItemsSerDe getSerDe() { return null; } - - @Override - final byte[] getSingleItemByteArr() { - final byte[] bytes = new byte[ITEM_BYTES]; - putFloatLE(bytes, 0, getFloatSingleItem()); - return bytes; - } - - @Override - int getSingleItemSizeBytes() { - return Float.BYTES; - } - - @Override - abstract byte[] getTotalItemsByteArr(); - - @Override - int getTotalItemsNumBytes() { - return levelsArr[getNumLevels()] * Float.BYTES; - } - - abstract void setFloatItemsArray(float[] floatItems); - - abstract void setFloatItemsArrayAt(int index, float item); - - abstract void setFloatItemsArrayAt(int dstIndex, float[] srcItems, int srcOffset, int length); - - // SORTED VIEW - - @Override - public FloatsSketchSortedView getSortedView() { - refreshSortedView(); - return floatsSV; - } - - private final FloatsSketchSortedView refreshSortedView() { - if (floatsSV == null) { - final CreateSortedView csv = new CreateSortedView(); - floatsSV = csv.getSV(); - } - return floatsSV; - } - - private final class CreateSortedView { - float[] quantiles; - long[] cumWeights; - - FloatsSketchSortedView getSV() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - final float[] srcQuantiles = getFloatItemsArray(); - final int[] srcLevels = levelsArr; - final int srcNumLevels = getNumLevels(); - - if (!isLevelZeroSorted()) { - Arrays.sort(srcQuantiles, srcLevels[0], srcLevels[1]); - if (!hasMemorySegment()) { setLevelZeroSorted(true); } - //we don't sort level0 in MemorySegment, only our copy. - } - final int numQuantiles = getNumRetained(); - quantiles = new float[numQuantiles]; - cumWeights = new long[numQuantiles]; - populateFromSketch(srcQuantiles, srcLevels, srcNumLevels, numQuantiles); - return new FloatsSketchSortedView(quantiles, cumWeights, KllFloatsSketch.this); - } - - private void populateFromSketch(final float[] srcQuantiles, final int[] srcLevels, - final int srcNumLevels, final int numItems) { - final int[] myLevels = new int[srcNumLevels + 1]; - final int offset = srcLevels[0]; - System.arraycopy(srcQuantiles, offset, quantiles, 0, numItems); - int srcLevel = 0; - int dstLevel = 0; - long weight = 1; - while (srcLevel < srcNumLevels) { - final int fromIndex = srcLevels[srcLevel] - offset; - final int toIndex = srcLevels[srcLevel + 1] - offset; // exclusive - if (fromIndex < toIndex) { // if equal, skip empty level - Arrays.fill(cumWeights, fromIndex, toIndex, weight); - myLevels[dstLevel] = fromIndex; - myLevels[dstLevel + 1] = toIndex; - dstLevel++; - } - srcLevel++; - weight *= 2; - } - final int numLevels = dstLevel; - blockyTandemMergeSort(quantiles, cumWeights, myLevels, numLevels); //create unit weights - KllHelper.convertToCumulative(cumWeights); - } - } //End of class CreateSortedView - - private static void blockyTandemMergeSort(final float[] quantiles, final long[] weights, - final int[] levels, final int numLevels) { - if (numLevels == 1) { return; } - - // duplicate the input in preparation for the "ping-pong" copy reduction strategy. - final float[] quantilesTmp = Arrays.copyOf(quantiles, quantiles.length); - final long[] weightsTmp = Arrays.copyOf(weights, quantiles.length); // don't need the extra one - - blockyTandemMergeSortRecursion(quantilesTmp, weightsTmp, quantiles, weights, levels, 0, numLevels); - } - - private static void blockyTandemMergeSortRecursion( - final float[] quantilesSrc, final long[] weightsSrc, - final float[] quantilesDst, final long[] weightsDst, - final int[] levels, final int startingLevel, final int numLevels) { - if (numLevels == 1) { return; } - final int numLevels1 = numLevels / 2; - final int numLevels2 = numLevels - numLevels1; - assert numLevels1 >= 1; - assert numLevels2 >= numLevels1; - final int startingLevel1 = startingLevel; - final int startingLevel2 = startingLevel + numLevels1; - // swap roles of src and dst - blockyTandemMergeSortRecursion( - quantilesDst, weightsDst, - quantilesSrc, weightsSrc, - levels, startingLevel1, numLevels1); - blockyTandemMergeSortRecursion( - quantilesDst, weightsDst, - quantilesSrc, weightsSrc, - levels, startingLevel2, numLevels2); - tandemMerge( - quantilesSrc, weightsSrc, - quantilesDst, weightsDst, - levels, - startingLevel1, numLevels1, - startingLevel2, numLevels2); - } - - private static void tandemMerge( - final float[] quantilesSrc, final long[] weightsSrc, - final float[] quantilesDst, final long[] weightsDst, - final int[] levelStarts, - final int startingLevel1, final int numLevels1, - final int startingLevel2, final int numLevels2) { - final int fromIndex1 = levelStarts[startingLevel1]; - final int toIndex1 = levelStarts[startingLevel1 + numLevels1]; // exclusive - final int fromIndex2 = levelStarts[startingLevel2]; - final int toIndex2 = levelStarts[startingLevel2 + numLevels2]; // exclusive - int iSrc1 = fromIndex1; - int iSrc2 = fromIndex2; - int iDst = fromIndex1; - - while ((iSrc1 < toIndex1) && (iSrc2 < toIndex2)) { - if (quantilesSrc[iSrc1] < quantilesSrc[iSrc2]) { - quantilesDst[iDst] = quantilesSrc[iSrc1]; - weightsDst[iDst] = weightsSrc[iSrc1]; - iSrc1++; - } else { - quantilesDst[iDst] = quantilesSrc[iSrc2]; - weightsDst[iDst] = weightsSrc[iSrc2]; - iSrc2++; - } - iDst++; - } - if (iSrc1 < toIndex1) { - System.arraycopy(quantilesSrc, iSrc1, quantilesDst, iDst, toIndex1 - iSrc1); - System.arraycopy(weightsSrc, iSrc1, weightsDst, iDst, toIndex1 - iSrc1); - } else if (iSrc2 < toIndex2) { - System.arraycopy(quantilesSrc, iSrc2, quantilesDst, iDst, toIndex2 - iSrc2); - System.arraycopy(weightsSrc, iSrc2, weightsDst, iDst, toIndex2 - iSrc2); - } - } - - // END SORTED VIEW - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllFloatsSketchIterator.java b/src/main/java/org/apache/datasketches/kll/KllFloatsSketchIterator.java deleted file mode 100644 index accf039de..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllFloatsSketchIterator.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator; - -/** - * Iterator over KllFloatsSketch. The order is not defined. - */ -public final class KllFloatsSketchIterator extends KllSketchIterator implements QuantilesFloatsSketchIterator { - private final float[] quantiles; - - KllFloatsSketchIterator(final float[] quantiles, final int[] levelsArr, final int numLevels) { - super(levelsArr, numLevels); - this.quantiles = quantiles; - } - - @Override - public float getQuantile() { - return quantiles[index]; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllHeapDoublesSketch.java b/src/main/java/org/apache/datasketches/kll/KllHeapDoublesSketch.java deleted file mode 100644 index c6de1a5d8..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllHeapDoublesSketch.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static org.apache.datasketches.common.ByteArrayUtil.putDoubleLE; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR_SINGLE_ITEM; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_DOUBLES_SKETCH; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Objects; - -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This class implements an on-heap doubles KllSketch. - * - *

Please refer to the documentation in the package-info:
- * {@link org.apache.datasketches.kll}

- * - * @author Lee Rhodes, Kevin Lang - */ -final class KllHeapDoublesSketch extends KllDoublesSketch { - private final int k; // configured size of K. - private final int m; // configured size of M. - private long n; // number of items input into this sketch. - private int minK; // dynamic minK for error estimation after merging with different k. - private boolean isLevelZeroSorted; - private double minDoubleItem; - private double maxDoubleItem; - private double[] doubleItems; - - /** - * New instance heap constructor with a given parameters k and m. - * - * @param k parameter that controls size of the sketch and accuracy of estimates. - * k can be between m and 65535, inclusive. - * @param m parameter controls the minimum level width in items. It can be 2, 4, 6 or 8. - * The DEFAULT_M, which is 8 is recommended. Other sizes of m should be considered - * experimental as they have not been as well characterized. - */ - KllHeapDoublesSketch(final int k, final int m) { - super(UPDATABLE); - KllHelper.checkM(m); - KllHelper.checkK(k, m); - levelsArr = new int[] {k, k}; - readOnly = false; - this.k = k; - this.m = m; - n = 0; - minK = k; - isLevelZeroSorted = false; - minDoubleItem = Double.NaN; - maxDoubleItem = Double.NaN; - doubleItems = new double[k]; - } - - /** - * Used for creating a temporary sketch for use with weighted updates. - */ - KllHeapDoublesSketch(final int k, final int m, final double item, final long weight) { - super(UPDATABLE); - KllHelper.checkM(m); - KllHelper.checkK(k, m); - levelsArr = KllHelper.createLevelsArray(weight); - readOnly = false; - this.k = k; - this.m = m; - n = weight; - minK = k; - isLevelZeroSorted = false; - minDoubleItem = item; - maxDoubleItem = item; - doubleItems = KllDoublesHelper.createItemsArray(item, weight); - } - - /** - * Heapify constructor. - * @param srcSeg MemorySegment object that contains data serialized by this sketch. - * @param segValidate the MemoryValidate object - */ - private KllHeapDoublesSketch( - final MemorySegment srcSeg, - final KllMemorySegmentValidate segValidate) { - super(UPDATABLE); - final SketchStructure segStructure = segValidate.sketchStructure; - k = segValidate.k; - m = segValidate.m; - n = segValidate.n; - minK = segValidate.minK; - levelsArr = segValidate.levelsArr; //normalized to full - isLevelZeroSorted = segValidate.level0SortedFlag; - - if (segStructure == COMPACT_EMPTY) { - minDoubleItem = Double.NaN; - maxDoubleItem = Double.NaN; - doubleItems = new double[k]; - } - else if (segStructure == COMPACT_SINGLE) { - final double item = srcSeg.get(JAVA_DOUBLE_UNALIGNED, DATA_START_ADR_SINGLE_ITEM); - minDoubleItem = maxDoubleItem = item; - doubleItems = new double[k]; - doubleItems[k - 1] = item; - } - else if (segStructure == COMPACT_FULL) { - int offsetBytes = DATA_START_ADR; - offsetBytes += (levelsArr.length - 1) * Integer.BYTES; //shortened levelsArr - minDoubleItem = srcSeg.get(JAVA_DOUBLE_UNALIGNED, offsetBytes); - offsetBytes += Double.BYTES; - maxDoubleItem = srcSeg.get(JAVA_DOUBLE_UNALIGNED, offsetBytes); - offsetBytes += Double.BYTES; - final int capacityItems = levelsArr[getNumLevels()]; - final int freeSpace = levelsArr[0]; - final int retainedItems = capacityItems - freeSpace; - doubleItems = new double[capacityItems]; - MemorySegment.copy(srcSeg, JAVA_DOUBLE_UNALIGNED, offsetBytes, doubleItems, freeSpace, retainedItems); - } - else { //(segStructure == UPDATABLE) - int offsetBytes = DATA_START_ADR; - offsetBytes += levelsArr.length * Integer.BYTES; //full levelsArr - minDoubleItem = srcSeg.get(JAVA_DOUBLE_UNALIGNED, offsetBytes); - offsetBytes += Double.BYTES; - maxDoubleItem = srcSeg.get(JAVA_DOUBLE_UNALIGNED, offsetBytes); - offsetBytes += Double.BYTES; - final int capacityItems = levelsArr[getNumLevels()]; - doubleItems = new double[capacityItems]; - MemorySegment.copy(srcSeg, JAVA_DOUBLE_UNALIGNED, offsetBytes, doubleItems, 0, capacityItems); - } - } - - static KllHeapDoublesSketch heapifyImpl(final MemorySegment srcSeg) { - Objects.requireNonNull(srcSeg, "Parameter 'srcSeg' must not be null"); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(srcSeg, KLL_DOUBLES_SKETCH); - return new KllHeapDoublesSketch(srcSeg, segVal); - } - - //End of constructors - - @Override - String getItemAsString(final int index) { - if (isEmpty()) { return "NaN"; } - return Double.toString(doubleItems[index]); - } - - @Override - public int getK() { return k; } - - //MinMax Methods - - @Override - double getMaxItemInternal() { return maxDoubleItem; } - - @Override - public double getMaxItem() { - if (isEmpty() || Double.isNaN(maxDoubleItem)) { throw new SketchesArgumentException(EMPTY_MSG); } - return maxDoubleItem; - } - - @Override - String getMaxItemAsString() { - return Double.toString(maxDoubleItem); - } - - @Override - double getMinItemInternal() { return minDoubleItem; } - - @Override - public double getMinItem() { - if (isEmpty() || Double.isNaN(minDoubleItem)) { throw new SketchesArgumentException(EMPTY_MSG); } - return minDoubleItem; - } - - @Override - String getMinItemAsString() { - return Double.toString(minDoubleItem); - } - - @Override - byte[] getMinMaxByteArr() { - final byte[] bytesOut = new byte[2 * Double.BYTES]; - putDoubleLE(bytesOut, 0, minDoubleItem); - putDoubleLE(bytesOut, Double.BYTES, maxDoubleItem); - return bytesOut; - } - - @Override - void setMaxItem(final double item) { maxDoubleItem = item; } - - @Override - void setMinItem(final double item) { minDoubleItem = item; } - - //END MinMax Methods - - @Override - public long getN() { return n; } - - //other restricted - - @Override - double[] getDoubleItemsArray() { return doubleItems; } - - @Override - double getDoubleSingleItem() { - if (n != 1L) { throw new SketchesArgumentException(NOT_SINGLE_ITEM_MSG); } - return doubleItems[k - 1]; - } - - @Override - int getM() { return m; } - - @Override - int getMinK() { return minK; } - - @Override - byte[] getRetainedItemsByteArr() { - if (isEmpty()) { return new byte[0]; } - final byte[] bytesOut; - if (isSingleItem()) { - bytesOut = new byte[Double.BYTES]; - putDoubleLE(bytesOut, 0, getDoubleSingleItem()); - return bytesOut; - } - final int retained = getNumRetained(); - final int bytes = retained * Double.BYTES; - bytesOut = new byte[bytes]; - final MemorySegment wseg = MemorySegment.ofArray(bytesOut); - MemorySegment.copy(doubleItems, levelsArr[0], wseg, JAVA_DOUBLE_UNALIGNED, 0, retained); - return bytesOut; - } - - @Override - byte[] getTotalItemsByteArr() { - final byte[] byteArr = new byte[doubleItems.length * Double.BYTES]; - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - MemorySegment.copy(doubleItems, 0, wseg, JAVA_DOUBLE_UNALIGNED, 0, doubleItems.length); - return byteArr; - } - - @Override - MemorySegment getMemorySegment() { - return null; - } - - @Override - void incN(final int increment) { n += increment; } - - @Override - void incNumLevels() { - //the heap sketch computes num levels from the array itself, so this is not used on-heap - } - - @Override - boolean isLevelZeroSorted() { return isLevelZeroSorted; } - - @Override - void setDoubleItemsArray(final double[] doubleItems) { this.doubleItems = doubleItems; } - - @Override - void setDoubleItemsArrayAt(final int index, final double item) { doubleItems[index] = item; } - - @Override - void setDoubleItemsArrayAt(final int dstIndex, final double[] srcItems, final int srcOffset, final int length) { - System.arraycopy(srcItems, srcOffset, doubleItems, dstIndex, length); - } - - @Override - void setLevelZeroSorted(final boolean sorted) { isLevelZeroSorted = sorted; } - - @Override - void setMinK(final int minK) { this.minK = minK; } - - @Override - void setN(final long n) { this.n = n; } - - @Override - void setNumLevels(final int numLevels) { - //the heap sketch computes num levels from the array itself, so this is not used on-heap - } - - @Override - double[] getDoubleRetainedItemsArray() { - return Arrays.copyOfRange(doubleItems, levelsArr[0], levelsArr[getNumLevels()]); - } - - @Override - void setMemorySegment(final MemorySegment wseg) { /* heap does not have MemorySegment */ } - - @Override - public boolean hasMemorySegment() { - return false; - } - - @Override - public boolean isOffHeap() { - return false; - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return false; - } - - @Override - MemorySegmentRequest getMemorySegmentRequest() { - return null; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllHeapFloatsSketch.java b/src/main/java/org/apache/datasketches/kll/KllHeapFloatsSketch.java deleted file mode 100644 index 55b990d3c..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllHeapFloatsSketch.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static org.apache.datasketches.common.ByteArrayUtil.putFloatLE; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR_SINGLE_ITEM; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_FLOATS_SKETCH; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Objects; - -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This class implements an on-heap floats KllSketch. - * - *

Please refer to the documentation in the package-info:
- * {@link org.apache.datasketches.kll}

- * - * @author Lee Rhodes, Kevin Lang - */ -final class KllHeapFloatsSketch extends KllFloatsSketch { - private final int k; // configured size of K. - private final int m; // configured size of M. - private long n; // number of items input into this sketch. - private int minK; // dynamic minK for error estimation after merging with different k. - private boolean isLevelZeroSorted; - private float minFloatItem; - private float maxFloatItem; - private float[] floatItems; - - /** - * New instance heap constructor with a given parameters k and m. - * - * @param k parameter that controls size of the sketch and accuracy of estimates. - * k can be between m and 65535, inclusive. - * @param m parameter controls the minimum level width in items. It can be 2, 4, 6 or 8. - * The DEFAULT_M, which is 8 is recommended. Other sizes of m should be considered - * experimental as they have not been as well characterized. - */ - KllHeapFloatsSketch(final int k, final int m) { - super(UPDATABLE); - KllHelper.checkM(m); - KllHelper.checkK(k, m); - levelsArr = new int[] {k, k}; - readOnly = false; - this.k = k; - this.m = m; - n = 0; - minK = k; - isLevelZeroSorted = false; - minFloatItem = Float.NaN; - maxFloatItem = Float.NaN; - floatItems = new float[k]; - } - - /** - * Used for creating a temporary sketch for use with weighted updates. - */ - KllHeapFloatsSketch(final int k, final int m, final float item, final long weight) { - super(UPDATABLE); - KllHelper.checkM(m); - KllHelper.checkK(k, m); - levelsArr = KllHelper.createLevelsArray(weight); - readOnly = false; - this.k = k; - this.m = m; - n = weight; - minK = k; - isLevelZeroSorted = false; - minFloatItem = item; - maxFloatItem = item; - floatItems = KllFloatsHelper.createItemsArray(item, weight); - } - - /** - * Heapify constructor. - * @param srcSeg MemorySegment object that contains data serialized by this sketch. - * @param segValidate the MemoryValidate object - */ - private KllHeapFloatsSketch( - final MemorySegment srcSeg, - final KllMemorySegmentValidate segValidate) { - super(UPDATABLE); - final SketchStructure segStructure = segValidate.sketchStructure; - k = segValidate.k; - m = segValidate.m; - n = segValidate.n; - minK = segValidate.minK; - levelsArr = segValidate.levelsArr; //normalized to full - isLevelZeroSorted = segValidate.level0SortedFlag; - - if (segStructure == COMPACT_EMPTY) { - minFloatItem = Float.NaN; - maxFloatItem = Float.NaN; - floatItems = new float[k]; - } - else if (segStructure == COMPACT_SINGLE) { - final float item = srcSeg.get(JAVA_FLOAT_UNALIGNED, DATA_START_ADR_SINGLE_ITEM); - minFloatItem = maxFloatItem = item; - floatItems = new float[k]; - floatItems[k - 1] = item; - } - else if (segStructure == COMPACT_FULL) { - int offsetBytes = DATA_START_ADR; - offsetBytes += (levelsArr.length - 1) * Integer.BYTES; //shortened levelsArr - minFloatItem = srcSeg.get(JAVA_FLOAT_UNALIGNED, offsetBytes); - offsetBytes += Float.BYTES; - maxFloatItem = srcSeg.get(JAVA_FLOAT_UNALIGNED, offsetBytes); - offsetBytes += Float.BYTES; - final int capacityItems = levelsArr[getNumLevels()]; - final int freeSpace = levelsArr[0]; - final int retainedItems = capacityItems - freeSpace; - floatItems = new float[capacityItems]; - MemorySegment.copy(srcSeg, JAVA_FLOAT_UNALIGNED, offsetBytes, floatItems, freeSpace, retainedItems); - } - else { //(segStructure == UPDATABLE) - int offsetBytes = DATA_START_ADR; - offsetBytes += levelsArr.length * Integer.BYTES; //full levelsArr - minFloatItem = srcSeg.get(JAVA_FLOAT_UNALIGNED, offsetBytes); - offsetBytes += Float.BYTES; - maxFloatItem = srcSeg.get(JAVA_FLOAT_UNALIGNED, offsetBytes); - offsetBytes += Float.BYTES; - final int capacityItems = levelsArr[getNumLevels()]; - floatItems = new float[capacityItems]; - MemorySegment.copy(srcSeg, JAVA_FLOAT_UNALIGNED, offsetBytes, floatItems, 0, capacityItems); - } - } - - static KllHeapFloatsSketch heapifyImpl(final MemorySegment srcSeg) { - Objects.requireNonNull(srcSeg, "Parameter 'srcSeg' must not be null"); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(srcSeg, KLL_FLOATS_SKETCH); - return new KllHeapFloatsSketch(srcSeg, segVal); - } - - //End of constructors - - @Override - String getItemAsString(final int index) { - if (isEmpty()) { return "NaN"; } - return Float.toString(floatItems[index]); - } - - @Override - public int getK() { return k; } - - //MinMax Methods - - @Override - float getMaxItemInternal() { return maxFloatItem; } - - @Override - public float getMaxItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - return maxFloatItem; - } - - @Override - String getMaxItemAsString() { - return Float.toString(maxFloatItem); - } - - @Override - float getMinItemInternal() { return minFloatItem; } - - @Override - public float getMinItem() { - if (isEmpty() || Float.isNaN(minFloatItem)) { throw new SketchesArgumentException(EMPTY_MSG); } - return minFloatItem; - } - - @Override - String getMinItemAsString() { - return Float.toString(minFloatItem); - } - - @Override - byte[] getMinMaxByteArr() { - final byte[] bytesOut = new byte[2 * Float.BYTES]; - putFloatLE(bytesOut, 0, minFloatItem); - putFloatLE(bytesOut, Float.BYTES, maxFloatItem); - return bytesOut; - } - - @Override - void setMaxItem(final float item) { maxFloatItem = item; } - - @Override - void setMinItem(final float item) { minFloatItem = item; } - - //END MinMax Methods - - @Override - public long getN() { return n; } - - //other restricted - - @Override - float[] getFloatItemsArray() { return floatItems; } - - @Override - float getFloatSingleItem() { - if (n != 1L) { throw new SketchesArgumentException(NOT_SINGLE_ITEM_MSG); } - return floatItems[k - 1]; - } - - @Override - int getM() { return m; } - - @Override - int getMinK() { return minK; } - - @Override - byte[] getRetainedItemsByteArr() { - if (isEmpty()) { return new byte[0]; } - final byte[] bytesOut; - if (isSingleItem()) { - bytesOut = new byte[Float.BYTES]; - putFloatLE(bytesOut, 0, getFloatSingleItem()); - return bytesOut; - } - final int retained = getNumRetained(); - final int bytes = retained * Float.BYTES; - bytesOut = new byte[bytes]; - final MemorySegment wseg = MemorySegment.ofArray(bytesOut); - MemorySegment.copy(floatItems, levelsArr[0], wseg, JAVA_FLOAT_UNALIGNED, 0, retained); - return bytesOut; - } - - @Override - byte[] getTotalItemsByteArr() { - final byte[] byteArr = new byte[floatItems.length * Float.BYTES]; - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - MemorySegment.copy(floatItems, 0, wseg, JAVA_FLOAT_UNALIGNED, 0, floatItems.length); - return byteArr; - } - - @Override - MemorySegment getMemorySegment() { - return null; - } - - @Override - void incN(final int increment) { n += increment; } - - @Override - void incNumLevels() { - //the heap sketch computes num levels from the array itself, so this is not used on-heap - } - - @Override - boolean isLevelZeroSorted() { return isLevelZeroSorted; } - - @Override - void setFloatItemsArray(final float[] floatItems) { this.floatItems = floatItems; } - - @Override - void setFloatItemsArrayAt(final int index, final float item) { floatItems[index] = item; } - - @Override - void setFloatItemsArrayAt(final int dstIndex, final float[] srcItems, final int srcOffset, final int length) { - System.arraycopy(srcItems, srcOffset, floatItems, dstIndex, length); - } - - @Override - void setLevelZeroSorted(final boolean sorted) { isLevelZeroSorted = sorted; } - - @Override - void setMinK(final int minK) { this.minK = minK; } - - @Override - void setN(final long n) { this.n = n; } - - @Override - void setNumLevels(final int numLevels) { - //the heap sketch computes num levels from the array itself, so this is not used on-heap - } - - @Override - float[] getFloatRetainedItemsArray() { - return Arrays.copyOfRange(floatItems, levelsArr[0], levelsArr[getNumLevels()]); - } - - @Override - void setMemorySegment(final MemorySegment wseg) { /* heap does not have MemorySegment */ } - - @Override - public boolean hasMemorySegment() { - return false; - } - - @Override - public boolean isOffHeap() { - return false; - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return false; - } - - @Override - MemorySegmentRequest getMemorySegmentRequest() { - return null; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllHeapItemsSketch.java b/src/main/java/org/apache/datasketches/kll/KllHeapItemsSketch.java deleted file mode 100644 index 74640e902..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllHeapItemsSketch.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.common.ByteArrayUtil.copyBytes; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR; -import static org.apache.datasketches.kll.KllPreambleUtil.N_LONG_ADR; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; - -import java.lang.foreign.MemorySegment; -import java.lang.reflect.Array; -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This class implements an on-heap items KllSketch. - * - *

Please refer to the documentation in the package-info:
- * {@link org.apache.datasketches.kll}

- * - * @author Lee Rhodes, Kevin Lang - */ -@SuppressWarnings("unchecked") -final class KllHeapItemsSketch extends KllItemsSketch { - private final int k; // configured size of K. - private final int m; // configured size of M. - private long n; // number of items input into this sketch. - private int minK; // dynamic minK for error estimation after merging with different k. - private boolean isLevelZeroSorted; - private T minItem; - private T maxItem; - private Object[] itemsArr; - - /** - * New instance heap constructor. - * @param k parameter that controls size of the sketch and accuracy of estimates. - * @param m parameter controls the minimum level width in items. It can be 2, 4, 6 or 8. - * The DEFAULT_M, which is 8 is recommended. Other sizes of m should be considered - * experimental as they have not been as well characterized. - * @param comparator user specified comparator of type T. - * @param serDe serialization / deserialization class - */ - KllHeapItemsSketch(final int k, final int m, final Comparator comparator, - final ArrayOfItemsSerDe serDe) { - super(UPDATABLE, comparator, serDe); - KllHelper.checkM(m); - KllHelper.checkK(k, m); - levelsArr = new int[] {k, k}; - readOnly = false; - this.k = k; - this.m = m; - n = 0; - minK = k; - isLevelZeroSorted = false; - minItem = null; - maxItem = null; - itemsArr = new Object[k]; - } - - /** - * Used for creating a temporary sketch for use with weighted updates. - */ - KllHeapItemsSketch(final int k, final int m, final T item, final long weight, final Comparator comparator, - final ArrayOfItemsSerDe serDe) { - super(UPDATABLE, comparator, serDe); - KllHelper.checkM(m); - KllHelper.checkK(k, m); - levelsArr = KllHelper.createLevelsArray(weight); - readOnly = false; - this.k = k; - this.m = m; - n = weight; - minK = k; - isLevelZeroSorted = false; - minItem = item; - maxItem = item; - itemsArr = KllItemsHelper.createItemsArray(serDe.getClassOfT(), item, weight); - } - - /** - * The Heapify constructor - * @param srcSeg the Source MemorySegment image that contains data. - * @param comparator the comparator for this sketch and given MemorySegment. - * @param serDe the serializer / deserializer for this sketch and the given MemorySegment. - */ - KllHeapItemsSketch( - final MemorySegment srcSeg, - final Comparator comparator, - final ArrayOfItemsSerDe serDe) { - super(SketchStructure.UPDATABLE, comparator, serDe); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(srcSeg, SketchType.KLL_ITEMS_SKETCH, serDe); - k = segVal.k; - m = segVal.m; - levelsArr = segVal.levelsArr; - readOnly = false; - n = segVal.n; - minK = segVal.minK; - isLevelZeroSorted = segVal.level0SortedFlag; - itemsArr = new Object[levelsArr[segVal.numLevels]]; //updatable size - final SketchStructure segStruct = segVal.sketchStructure; - if (segStruct == COMPACT_EMPTY) { - minItem = null; - maxItem = null; - itemsArr = new Object[k]; - } else if (segStruct == COMPACT_SINGLE) { - final int offset = N_LONG_ADR; - final T item = serDe.deserializeFromMemorySegment(srcSeg, offset, 1)[0]; - minItem = item; - maxItem = item; - itemsArr[k - 1] = item; - } else if (segStruct == COMPACT_FULL) { - int offset = DATA_START_ADR + (segVal.numLevels * Integer.BYTES); - minItem = serDe.deserializeFromMemorySegment(srcSeg, offset, 1)[0]; - offset += serDe.sizeOf(minItem); - maxItem = serDe.deserializeFromMemorySegment(srcSeg, offset, 1)[0]; - offset += serDe.sizeOf(maxItem); - final int numRetained = levelsArr[segVal.numLevels] - levelsArr[0]; - final Object[] retItems = serDe.deserializeFromMemorySegment(srcSeg, offset, numRetained); - System.arraycopy(retItems, 0, itemsArr, levelsArr[0], numRetained); - } else { //segStruct == UPDATABLE - throw new SketchesArgumentException(UNSUPPORTED_MSG + "UPDATABLE"); - } - } - - //End of constructors - - @Override - String getItemAsString(final int index) { - if (isEmpty()) { return "Null"; } - return serDe.toString((T)(itemsArr[index])); - } - - @Override - public int getK() { - return k; - } - - @Override - public T getMaxItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - return maxItem; - } - - @Override - String getMaxItemAsString() { - if (isEmpty()) { return "Null"; } - return serDe.toString(maxItem); - } - - @Override - public T getMinItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - return minItem; - } - - @Override - String getMinItemAsString() { - if (isEmpty()) { return "Null"; } - return serDe.toString(minItem); - } - - @Override - public long getN() { - return n; - } - - //restricted - - @Override - int getM() { - return m; - } - - @Override - int getMinK() { - return minK; - } - - @Override - byte[] getMinMaxByteArr() { - final byte[] minBytes = serDe.serializeToByteArray(minItem); - final byte[] maxBytes = serDe.serializeToByteArray(maxItem); - final byte[] minMaxBytes = new byte[minBytes.length + maxBytes.length]; - copyBytes(minBytes, 0, minMaxBytes, 0, minBytes.length); - copyBytes(maxBytes, 0, minMaxBytes, minBytes.length, maxBytes.length); - return minMaxBytes; - } - - @Override - int getMinMaxSizeBytes() { - final int minBytes = serDe.sizeOf(minItem); - final int maxBytes = serDe.sizeOf(maxItem); - return minBytes + maxBytes; - } - - @Override - T[] getRetainedItemsArray() { - final int numRet = getNumRetained(); - final T[] outArr = (T[]) Array.newInstance(serDe.getClassOfT(), numRet); - System.arraycopy(itemsArr, levelsArr[0], outArr, 0 , numRet); - return outArr; - } - - @Override - byte[] getRetainedItemsByteArr() { - final T[] retArr = getRetainedItemsArray(); - return serDe.serializeToByteArray(retArr); - } - - @Override - int getRetainedItemsSizeBytes() { - return getRetainedItemsByteArr().length; - } - - @Override - T getSingleItem() { - if (n != 1L) { throw new SketchesArgumentException(NOT_SINGLE_ITEM_MSG); } - return (T) itemsArr[k - 1]; - } - - @Override - byte[] getSingleItemByteArr() { - return serDe.serializeToByteArray(getSingleItem()); - } - - @Override - int getSingleItemSizeBytes() { - return serDe.sizeOf(getSingleItem()); - } - - @Override - T[] getTotalItemsArray() { - if (n == 0) { return (T[]) Array.newInstance(serDe.getClassOfT(), k); } - final T[] outArr = (T[]) Array.newInstance(serDe.getClassOfT(), itemsArr.length); - System.arraycopy(itemsArr, 0, outArr, 0, itemsArr.length); - return outArr; - } - - @Override - MemorySegment getMemorySegment() { - return null; - } - - @Override - void incN(final int increment) { n += increment; } - - @Override - boolean isLevelZeroSorted() { - return isLevelZeroSorted; - } - - @Override - void setLevelZeroSorted(final boolean sorted) { - isLevelZeroSorted = sorted; - } - - @Override - void setMinK(final int minK) { - this.minK = minK; - } - - @Override - void setN(final long n) { - this.n = n; - } - - @Override - void setItemsArray(final Object[] itemsArr) { - this.itemsArr = itemsArr; - } - - @Override - void setItemsArrayAt(final int index, final Object item) { - itemsArr[index] = item; - } - - @Override - void setMaxItem(final Object item) { - maxItem = (T) item; - } - - @Override - void setMinItem(final Object item) { - minItem = (T) item; - } - - @Override - public boolean hasMemorySegment() { - return false; - } - - @Override - public boolean isOffHeap() { - return false; - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return false; - } - - @Override - MemorySegmentRequest getMemorySegmentRequest() { - return null; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllHeapLongsSketch.java b/src/main/java/org/apache/datasketches/kll/KllHeapLongsSketch.java deleted file mode 100644 index 21851b8b8..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllHeapLongsSketch.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.ByteArrayUtil.putLongLE; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR_SINGLE_ITEM; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_LONGS_SKETCH; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Objects; - -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This class implements an on-heap longs KllSketch. - * - *

Please refer to the documentation in the package-info:
- * {@link org.apache.datasketches.kll}

- * - * @author Lee Rhodes, Kevin Lang - */ -final class KllHeapLongsSketch extends KllLongsSketch { - private final int k; // configured size of K. - private final int m; // configured size of M. - private long n; // number of items input into this sketch. - private int minK; // dynamic minK for error estimation after merging with different k. - private boolean isLevelZeroSorted; - private long minLongItem; - private long maxLongItem; - private long[] longItems; - - /** - * New instance heap constructor with a given parameters k and m. - * - * @param k parameter that controls size of the sketch and accuracy of estimates. - * k can be between m and 65535, inclusive. - * @param m parameter controls the minimum level width in items. It can be 2, 4, 6 or 8. - * The DEFAULT_M, which is 8 is recommended. Other sizes of m should be considered - * experimental as they have not been as well characterized. - */ - KllHeapLongsSketch(final int k, final int m) { - super(UPDATABLE); - KllHelper.checkM(m); - KllHelper.checkK(k, m); - levelsArr = new int[] {k, k}; - readOnly = false; - this.k = k; - this.m = m; - n = 0; - minK = k; - isLevelZeroSorted = false; - minLongItem = Long.MAX_VALUE; - maxLongItem = Long.MIN_VALUE; - longItems = new long[k]; - } - - /** - * Internally used for creating a temporary sketch for use with weighted updates. - */ - KllHeapLongsSketch(final int k, final int m, final long item, final long weight) { - super(UPDATABLE); - KllHelper.checkM(m); - KllHelper.checkK(k, m); - levelsArr = KllHelper.createLevelsArray(weight); - readOnly = false; - this.k = k; - this.m = m; - n = weight; - minK = k; - isLevelZeroSorted = false; - minLongItem = item; - maxLongItem = item; - longItems = KllLongsHelper.createItemsArray(item, weight); - } - - /** - * Heapify constructor. - * @param srcSeg Memory object that contains data serialized by this sketch. - * @param segValidate the MemoryValidate object - */ - private KllHeapLongsSketch( - final MemorySegment srcSeg, - final KllMemorySegmentValidate segValidate) { - super(UPDATABLE); - final SketchStructure segStructure = segValidate.sketchStructure; - k = segValidate.k; - m = segValidate.m; - n = segValidate.n; - minK = segValidate.minK; - levelsArr = segValidate.levelsArr; //normalized to full - isLevelZeroSorted = segValidate.level0SortedFlag; - - if (segStructure == COMPACT_EMPTY) { - minLongItem = Long.MAX_VALUE; - maxLongItem = Long.MIN_VALUE; - longItems = new long[k]; - } - else if (segStructure == COMPACT_SINGLE) { - final long item = srcSeg.get(JAVA_LONG_UNALIGNED, DATA_START_ADR_SINGLE_ITEM); - minLongItem = maxLongItem = item; - longItems = new long[k]; - longItems[k - 1] = item; - } - else if (segStructure == COMPACT_FULL) { - int offsetBytes = DATA_START_ADR; - offsetBytes += (levelsArr.length - 1) * Integer.BYTES; //shortened levelsArr - minLongItem = srcSeg.get(JAVA_LONG_UNALIGNED, offsetBytes); - offsetBytes += Long.BYTES; - maxLongItem = srcSeg.get(JAVA_LONG_UNALIGNED, offsetBytes); - offsetBytes += Long.BYTES; - final int capacityItems = levelsArr[getNumLevels()]; - final int freeSpace = levelsArr[0]; - final int retainedItems = capacityItems - freeSpace; - longItems = new long[capacityItems]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, offsetBytes, longItems, freeSpace, retainedItems); - } - else { //(segStructure == UPDATABLE) - int offsetBytes = DATA_START_ADR; - offsetBytes += levelsArr.length * Integer.BYTES; //full levelsArr - minLongItem = srcSeg.get(JAVA_LONG_UNALIGNED, offsetBytes); - offsetBytes += Long.BYTES; - maxLongItem = srcSeg.get(JAVA_LONG_UNALIGNED, offsetBytes); - offsetBytes += Long.BYTES; - final int capacityItems = levelsArr[getNumLevels()]; - longItems = new long[capacityItems]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, offsetBytes, longItems, 0, capacityItems); - } - } - - static KllHeapLongsSketch heapifyImpl(final MemorySegment srcSeg) { - Objects.requireNonNull(srcSeg, "Parameter 'srcSeg' must not be null"); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(srcSeg, KLL_LONGS_SKETCH); - return new KllHeapLongsSketch(srcSeg, segVal); - } - - //End of constructors - - @Override - String getItemAsString(final int index) { - if (isEmpty()) { return "Null"; } - return Long.toString(longItems[index]); - } - - @Override - public int getK() { return k; } - - //MinMax Methods - - @Override - long getMaxItemInternal() { return maxLongItem; } - - @Override - public long getMaxItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - return maxLongItem; - } - - @Override - String getMaxItemAsString() { - return Long.toString(maxLongItem); - } - - @Override - long getMinItemInternal() { return minLongItem; } - - @Override - public long getMinItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - return minLongItem; - } - - @Override - String getMinItemAsString() { - return Long.toString(minLongItem); - } - - @Override - byte[] getMinMaxByteArr() { - final byte[] bytesOut = new byte[2 * Long.BYTES]; - putLongLE(bytesOut, 0, minLongItem); - putLongLE(bytesOut, Long.BYTES, maxLongItem); - return bytesOut; - } - - @Override - void setMaxItem(final long item) { maxLongItem = item; } - - @Override - void setMinItem(final long item) { minLongItem = item; } - - //END MinMax Methods - - @Override - public long getN() { return n; } - - //other restricted - - @Override - long[] getLongItemsArray() { return longItems; } - - @Override - long getLongSingleItem() { - if (n != 1L) { throw new SketchesArgumentException(NOT_SINGLE_ITEM_MSG); } - return longItems[k - 1]; - } - - @Override - int getM() { return m; } - - @Override - int getMinK() { return minK; } - - @Override - byte[] getRetainedItemsByteArr() { - if (isEmpty()) { return new byte[0]; } - final byte[] bytesOut; - if (isSingleItem()) { - bytesOut = new byte[Long.BYTES]; - putLongLE(bytesOut, 0, getLongSingleItem()); - return bytesOut; - } - final int retained = getNumRetained(); - final int bytes = retained * Long.BYTES; - bytesOut = new byte[bytes]; - final MemorySegment wseg = MemorySegment.ofArray(bytesOut); - MemorySegment.copy(longItems, levelsArr[0], wseg, JAVA_LONG_UNALIGNED, 0, retained); - return bytesOut; - } - - @Override - byte[] getTotalItemsByteArr() { - final byte[] byteArr = new byte[longItems.length * Long.BYTES]; - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - MemorySegment.copy(longItems, 0, wseg, JAVA_LONG_UNALIGNED, 0, longItems.length); - return byteArr; - } - - @Override - MemorySegment getMemorySegment() { - return null; - } - - @Override - void incN(final int increment) { n += increment; } - - @Override - void incNumLevels() { - //the heap sketch computes num levels from the array itself, so this is not used on-heap - } - - @Override - boolean isLevelZeroSorted() { return isLevelZeroSorted; } - - @Override - void setLongItemsArray(final long[] longItems) { this.longItems = longItems; } - - @Override - void setLongItemsArrayAt(final int index, final long item) { longItems[index] = item; } - - @Override - void setLongItemsArrayAt(final int dstIndex, final long[] srcItems, final int srcOffset, final int length) { - System.arraycopy(srcItems, srcOffset, longItems, dstIndex, length); - } - - @Override - void setLevelZeroSorted(final boolean sorted) { isLevelZeroSorted = sorted; } - - @Override - void setMinK(final int minK) { this.minK = minK; } - - @Override - void setN(final long n) { this.n = n; } - - @Override - void setNumLevels(final int numLevels) { - //the heap sketch computes num levels from the array itself, so this is not used on-heap - } - - @Override - long[] getLongRetainedItemsArray() { - return Arrays.copyOfRange(longItems, levelsArr[0], levelsArr[getNumLevels()]); - } - - @Override - void setMemorySegment(final MemorySegment wseg) { /* heap does not have MemorySegment */ } - - @Override - public boolean hasMemorySegment() { - return false; - } - - @Override - public boolean isOffHeap() { - return false; - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return false; - } - - @Override - MemorySegmentRequest getMemorySegmentRequest() { - return null; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllHelper.java b/src/main/java/org/apache/datasketches/kll/KllHelper.java deleted file mode 100644 index 4b6256cde..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllHelper.java +++ /dev/null @@ -1,790 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.Math.abs; -import static java.lang.Math.ceil; -import static java.lang.Math.exp; -import static java.lang.Math.log; -import static java.lang.Math.max; -import static java.lang.Math.min; -import static java.lang.Math.pow; -import static java.lang.Math.round; -import static org.apache.datasketches.common.Family.KLL; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.bitAt; -import static org.apache.datasketches.common.Util.floorPowerOf2; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR; -import static org.apache.datasketches.kll.KllPreambleUtil.EMPTY_BIT_MASK; -import static org.apache.datasketches.kll.KllPreambleUtil.LEVEL_ZERO_SORTED_BIT_MASK; -import static org.apache.datasketches.kll.KllPreambleUtil.SINGLE_ITEM_BIT_MASK; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_DOUBLES_SKETCH; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_FLOATS_SKETCH; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_ITEMS_SKETCH; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_LONGS_SKETCH; -import static org.apache.datasketches.quantilescommon.QuantilesAPI.UNSUPPORTED_MSG; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.positional.PositionalSegment; -import org.apache.datasketches.kll.KllSketch.SketchStructure; -import org.apache.datasketches.kll.KllSketch.SketchType; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This class provides some useful sketch analysis tools that are used internally. - * - * @author Lee Rhodes - */ -final class KllHelper { - static final double EPS_DELTA_THRESHOLD = 1E-6; - static final double MIN_EPS = 4.7634E-5; - static final double PMF_COEF = 2.446; - static final double PMF_EXP = 0.9433; - static final double CDF_COEF = 2.296; - static final double CDF_EXP = 0.9723; - - static class GrowthStats { - SketchType sketchType; - int k; - int m; - long givenN; - long maxN; - int numLevels; - int maxItems; - int compactBytes; - int updatableBytes; - } - - static class LevelStats { - long n; - public int numLevels; - int numItems; - - LevelStats(final long n, final int numLevels, final int numItems) { - this.n = n; - this.numLevels = numLevels; - this.numItems = numItems; - } - } - - /** - * This is the exact powers of 3 from 3^0 to 3^30 where the exponent is the index - */ - static long[] powersOfThree = - {1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, - 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467, - 3486784401L, 10460353203L, 31381059609L, 94143178827L, 282429536481L, - 847288609443L, 2541865828329L, 7625597484987L, 22876792454961L, 68630377364883L, - 205891132094649L}; - - /** - * Checks the validity of the given k - * @param k must be greater than 7 and less than 65536. - */ - static void checkK(final int k, final int m) { - if ((k < m) || (k > KllSketch.MAX_K)) { - throw new SketchesArgumentException( - "K must be >= " + m + " and <= " + KllSketch.MAX_K + ": " + k); - } - } - - static void checkM(final int m) { - if ((m < KllSketch.MIN_M) || (m > KllSketch.MAX_M) || ((m & 1) == 1)) { - throw new SketchesArgumentException( - "M must be >= 2, <= 8 and even: " + m); - } - } - - /** - * Returns the approximate maximum number of items that this sketch can handle - * @param k The sizing / accuracy parameter of the sketch in items. - * Note: this method actually works for k items up to k = 2^29 and 61 levels, - * however only k items up to (2^16 - 1) are currently used by the sketch. - * @param m the size of the smallest level in items. Default is 8. - * @param numLevels the upper bound number of levels based on n items. - * @return the total item capacity of the sketch. - */ - static int computeTotalItemCapacity(final int k, final int m, final int numLevels) { - long total = 0; - for (int level = 0; level < numLevels; level++) { - total += levelCapacity(k, numLevels, level, m); - } - return (int) total; - } - - /** - * Convert the individual weights into cumulative weights. - * An array of {1,1,1,1} becomes {1,2,3,4} - * @param array of actual weights from the sketch, where first element is not zero. - * @return total weight - */ - public static long convertToCumulative(final long[] array) { - long subtotal = 0; - for (int i = 0; i < array.length; i++) { - final long newSubtotal = subtotal + array[i]; - subtotal = array[i] = newSubtotal; - } - return subtotal; - } - - /** - * Create the Levels Array from given weight - * Used with weighted update only. - * @param weight the given weight - * @return the Levels Array - */ - static int[] createLevelsArray(final long weight) { - final int numLevels = 64 - Long.numberOfLeadingZeros(weight); - if (numLevels > 61) { - throw new SketchesArgumentException("The requested weight must not exceed 2^61"); - } - final int[] levelsArr = new int[numLevels + 1]; //always one more than numLevels - int itemsArrIndex = 0; - levelsArr[0] = itemsArrIndex; - for (int level = 0; level < numLevels; level++) { - levelsArr[level + 1] = itemsArrIndex += bitAt(weight, level); - } - return levelsArr; - } - - static int currentLevelSizeItems(final int level, final int numLevels, final int[] levels) { - if (level >= numLevels) { return 0; } - return levels[level + 1] - levels[level]; - } - - /** - * Given k, m, and numLevels, this computes and optionally prints the structure of the sketch when the given - * number of levels are completely filled. - * @param k the given user configured sketch parameter - * @param m the given user configured sketch parameter - * @param numLevels the given number of levels of the sketch - * @param printSketchStructure if true will print the details of the sketch structure at the given numLevels. - * @return LevelStats with the final summary of the sketch's cumulative N, - * and cumulative items at the given numLevels. - */ - static LevelStats getFinalSketchStatsAtNumLevels( - final int k, - final int m, - final int numLevels, - final boolean printSketchStructure) { - int cumItems = 0; - long cumN = 0; - if (printSketchStructure) { - println("SKETCH STRUCTURE:"); - println("Given K : " + k); - println("Given M : " + m); - println("Given NumLevels: " + numLevels); - printf("%6s %8s %12s %18s %18s" + LS, "Level", "Items", "CumItems", "N at Level", "CumN"); - } - for (int level = 0; level < numLevels; level++) { - final int items = KllHelper.levelCapacity(k, numLevels, level, m); - final long n = (long)items << level; - final LevelStats lvlStats = new LevelStats(n, numLevels, items); - cumItems += lvlStats.numItems; - cumN += lvlStats.n; - if (printSketchStructure) { - printf("%6d %,8d %,12d %,18d %,18d" + LS, level, lvlStats.numItems, cumItems, lvlStats.n, cumN); - } - } - return new LevelStats(cumN, numLevels, cumItems); - } - - /** - * This method is for direct Double and Float sketches only. - * Given k, m, n, and the sketch type, this computes (and optionally prints) the growth scheme for a sketch as it - * grows large enough to accommodate a stream length of n items. - * @param k the given user configured sketch parameter - * @param m the given user configured sketch parameter - * @param n the desired stream length - * @param sketchType the given sketch type: either DOUBLES_SKETCH or FLOATS_SKETCH. - * @param printGrowthScheme if true the entire growth scheme of the sketch will be printed. - * @return GrowthStats with the final numItems of the growth scheme - */ - static GrowthStats getGrowthSchemeForGivenN( - final int k, - final int m, - final long n, - final SketchType sketchType, - final boolean printGrowthScheme) { - if (sketchType == KLL_ITEMS_SKETCH) { throw new SketchesArgumentException(UNSUPPORTED_MSG); } - LevelStats lvlStats; - final GrowthStats gStats = new GrowthStats(); - gStats.numLevels = 0; - gStats.k = k; - gStats.m = m; - gStats.givenN = n; - gStats.sketchType = sketchType; - if (printGrowthScheme) { - println("GROWTH SCHEME:"); - println("Given SketchType: " + gStats.sketchType.toString()); - println("Given K : " + gStats.k); - println("Given M : " + gStats.m); - println("Given N : " + gStats.givenN); - printf("%10s %10s %20s %13s %15s" + LS, "NumLevels", "MaxItems", "MaxN", "CompactBytes", "UpdatableBytes"); - } - final int typeBytes = sketchType.getBytes(); - do { - gStats.numLevels++; // - lvlStats = getFinalSketchStatsAtNumLevels(gStats.k, gStats.m, gStats.numLevels, false); - gStats.maxItems = lvlStats.numItems; - gStats.maxN = lvlStats.n; // - gStats.compactBytes = - (gStats.maxItems * typeBytes) + (gStats.numLevels * Integer.BYTES) + (2 * typeBytes) + DATA_START_ADR; - gStats.updatableBytes = gStats.compactBytes + Integer.BYTES; - if (printGrowthScheme) { - printf("%10d %,10d %,20d %,13d %,15d" + LS, - gStats.numLevels, gStats.maxItems, gStats.maxN, gStats.compactBytes, gStats.updatableBytes); - } - } while (lvlStats.n < n); - - //gStats.numLevels = lvlStats.numLevels; // - //gStats.maxItems = lvlStats.numItems; // - return gStats; - } - - // constants were derived as the best fit to 99 percentile empirically measured max error in - // thousands of trials - static int getKFromEpsilon(final double epsilon, final boolean pmf) { - //Ensure that eps is >= than the lowest possible eps given MAX_K and pmf=false. - final double eps = max(epsilon, MIN_EPS); - final double kdbl = pmf - ? exp(log(PMF_COEF / eps) / PMF_EXP) - : exp(log(CDF_COEF / eps) / CDF_EXP); - final double krnd = round(kdbl); - final double del = abs(krnd - kdbl); - final int k = (int) (del < EPS_DELTA_THRESHOLD ? krnd : ceil(kdbl)); - return max(KllSketch.MIN_M, min(KllSketch.MAX_K, k)); - } - - /** - * Gets the normalized rank error given k and pmf. - * Static method version of the getNormalizedRankError(boolean). - * @param k the configuration parameter - * @param pmf if true, returns the "double-sided" normalized rank error for the getPMF() function. - * Otherwise, it is the "single-sided" normalized rank error for all the other queries. - * @return if pmf is true, the normalized rank error for the getPMF() function. - * Otherwise, it is the "single-sided" normalized rank error for all the other queries. - * @see KllHeapDoublesSketch - */ - // constants were derived as the best fit to 99 percentile empirically measured max error in - // thousands of trials - static double getNormalizedRankError(final int k, final boolean pmf) { - return pmf - ? PMF_COEF / pow(k, PMF_EXP) - : CDF_COEF / pow(k, CDF_EXP); - } - - static int getNumRetainedAboveLevelZero(final int numLevels, final int[] levels) { - return levels[numLevels] - levels[1]; - } - - /** - * Returns the item capacity of a specific level. - * @param k the accuracy parameter of the sketch. Because of the Java limits on array sizes, - * the theoretical maximum k is 2^29. However, this implementation of the KLL sketch - * limits k to 2^16 -1. - * @param numLevels the number of current levels in the sketch. Maximum is 61. - * @param level the zero-based index of a level. This varies from 0 to 60. - * @param m the minimum level width. Default is 8. - * @return the capacity of a specific level - */ - static int levelCapacity(final int k, final int numLevels, final int level, final int m) { - assert (k <= (1 << 29)) : "The given k is > 2^29."; - assert (numLevels >= 1) && (numLevels <= 61) : "The given numLevels is < 1 or > 61"; - assert (level >= 0) && (level < numLevels) : "The given level is < 0 or >= numLevels."; - final int depth = numLevels - level - 1; //depth is # levels from the top level (= 0) - return (int) Math.max(m, intCapAux(k, depth)); - } - - /** - * This method is only used by the direct Double, Float and Long sketches - * and does the following: - *
    - *
  • Determines if the required sketch bytes will fit in the current MemorySegment. - * If so, it will stretch the positioning of the arrays to fit. Otherwise: - *
  • Allocates a new heap MemorySegment of the required size
  • - *
  • Copies over the preamble as is (20 bytes)
  • - *
  • The caller is responsible for filling the remainder and updating the preamble.
  • - *
- * - * @param sketch The current sketch that needs to be expanded. - * @param newLevelsArrLen the element length of the new Levels array. - * @param newItemsArrLen the element length of the new Items array. - * @return the new expanded MemorySegment with preamble. - */ - static MemorySegment memorySegmentSpaceMgmt( - final KllSketch sketch, - final int newLevelsArrLen, - final int newItemsArrLen) { - final KllSketch.SketchType sketchType = sketch.sketchType; - if (sketchType == KLL_ITEMS_SKETCH) { throw new SketchesArgumentException(UNSUPPORTED_MSG); } - final MemorySegment oldWseg = sketch.getMemorySegment(); - if (oldWseg == null) { - return null; - } - final int typeBytes = sketchType.getBytes(); - final int requiredSketchBytes = DATA_START_ADR - + (newLevelsArrLen * Integer.BYTES) - + (2 * typeBytes) - + (newItemsArrLen * typeBytes); - - if (requiredSketchBytes > oldWseg.byteSize()) { //Acquire new larger MemorySegment - MemorySegmentRequest mSegReq = sketch.getMemorySegmentRequest(); - if (mSegReq == null) { - mSegReq = MemorySegmentRequest.DEFAULT; - } - final MemorySegment newSeg = mSegReq.request(requiredSketchBytes); - MemorySegment.copy(oldWseg, 0, newSeg, 0, DATA_START_ADR); //copy preamble (first 20 bytes) - mSegReq.requestClose(oldWseg); - return newSeg; - } - //Expand in current MemorySegment - return oldWseg; - } - - private static String outputDataDetail(final KllSketch sketch) { - final int[] levelsArr = sketch.getLevelsArray(SketchStructure.UPDATABLE); - final int numLevels = sketch.getNumLevels(); - final int k = sketch.getK(); - final int m = sketch.getM(); - final StringBuilder sb = new StringBuilder(); - sb.append(LS + "### KLL ItemsArray & LevelsArray Detail:").append(LS); - sb.append("Index, Value").append(LS); - if (levelsArr[0] > 0) { - final String gbg = " Free Space, Size = " + levelsArr[0]; - for (int i = 0; i < levelsArr[0]; i++) { - sb.append(" ").append(i + ", ").append(sketch.getItemAsString(i)); - if (i == 0) { sb.append(gbg); } - sb.append(LS); - } - } - int level = 0; - while (level < numLevels) { - final int fromIndex = levelsArr[level]; - final int toIndex = levelsArr[level + 1]; // exclusive - String lvlData = ""; - if (fromIndex < toIndex) { - lvlData = " Level[" + level + "]=" + levelsArr[level] - + ", Cap=" + KllHelper.levelCapacity(k, numLevels, level, m) - + ", Size=" + KllHelper.currentLevelSizeItems(level, numLevels, levelsArr) - + ", Wt=" + (1 << level) + LS; - } - - for (int i = fromIndex; i < toIndex; i++) { - sb.append(" ").append(i + ", ").append(sketch.getItemAsString(i)); - if (i == fromIndex) { sb.append(lvlData); } else { sb.append(LS); } - } - level++; - } - sb.append(" ----------Level[" + level + "]=" + levelsArr[level] + ": ItemsArray[].length"); - sb.append(LS); - sb.append("### End ItemsArray & LevelsArray Detail").append(LS); - return sb.toString(); - } - - private static String outputLevels(final int k, final int m, final int numLevels, final int[] levelsArr) { - final StringBuilder sb = new StringBuilder(); - sb.append(LS + "### KLL Levels Array:").append(LS) - .append(" Level, Offset: Nominal Capacity, Actual Capacity").append(LS); - int level = 0; - for ( ; level < numLevels; level++) { - sb.append(" ").append(level).append(", ").append(levelsArr[level]).append(": ") - .append(KllHelper.levelCapacity(k, numLevels, level, m)) - .append(", ").append(KllHelper.currentLevelSizeItems(level, numLevels, levelsArr)).append(LS); - } - sb.append(" ").append(level).append(", ").append(levelsArr[level]).append(": ----ItemsArray[].length") - .append(LS); - sb.append("### End Levels Array").append(LS); - return sb.toString(); - } - - static long sumTheSampleWeights(final int num_levels, final int[] levels) { - long total = 0; - long weight = 1; - for (int i = 0; i < num_levels; i++) { - total += weight * (levels[i + 1] - levels[i]); - weight *= 2; - } - return total; - } - - static byte[] toByteArray(final KllSketch srcSk, final boolean updatable) { - //ITEMS_SKETCH byte array is never updatable - final boolean myUpdatable = srcSk.sketchType == KLL_ITEMS_SKETCH ? false : updatable; - final long srcN = srcSk.getN(); - final SketchStructure tgtStructure; - if (myUpdatable) { tgtStructure = UPDATABLE; } - else if (srcN == 0) { tgtStructure = COMPACT_EMPTY; } - else if (srcN == 1) { tgtStructure = COMPACT_SINGLE; } - else { tgtStructure = COMPACT_FULL; } - final int totalBytes = srcSk.currentSerializedSizeBytes(myUpdatable); - final byte[] bytesOut = new byte[totalBytes]; - final PositionalSegment pSeg = PositionalSegment.wrap(MemorySegment.ofArray(bytesOut)); - - //ints 0,1 - final byte preInts = (byte)tgtStructure.getPreInts(); - final byte serVer = (byte)tgtStructure.getSerVer(); - final byte famId = (byte)(KLL.getID()); - final byte flags = (byte) ((srcSk.isEmpty() ? EMPTY_BIT_MASK : 0) - | (srcSk.isLevelZeroSorted() ? LEVEL_ZERO_SORTED_BIT_MASK : 0) - | (srcSk.getN() == 1 ? SINGLE_ITEM_BIT_MASK : 0)); - final short k = (short) srcSk.getK(); - final byte m = (byte) srcSk.getM(); - - //load first 8 bytes - pSeg.setByte(preInts); //byte 0 - pSeg.setByte(serVer); - pSeg.setByte(famId); - pSeg.setByte(flags); - pSeg.setShort(k); - pSeg.setByte(m); - pSeg.incrementPosition(1); //byte 7 is unused - - if (tgtStructure == COMPACT_EMPTY) { - return bytesOut; - } - - if (tgtStructure == COMPACT_SINGLE) { - final byte[] siByteArr = srcSk.getSingleItemByteArr(); - final int len = siByteArr.length; - pSeg.setByteArray(siByteArr, 0, len); - pSeg.incrementPosition(-len); - return bytesOut; - } - - // Tgt is either COMPACT_FULL or UPDATABLE - //ints 2,3 - final long n = srcSk.getN(); - //ints 4 - final short minK = (short) srcSk.getMinK(); - final byte numLevels = (byte) srcSk.getNumLevels(); - //end of full preamble - final int[] lvlsArr = srcSk.getLevelsArray(tgtStructure); - final byte[] minMaxByteArr = srcSk.getMinMaxByteArr(); - final byte[] itemsByteArr = tgtStructure == COMPACT_FULL - ? srcSk.getRetainedItemsByteArr() - : srcSk.getTotalItemsByteArr(); - - pSeg.setLong(n); - pSeg.setShort(minK); - pSeg.setByte(numLevels); - pSeg.incrementPosition(1); - pSeg.setIntArray(lvlsArr, 0, lvlsArr.length); - pSeg.setByteArray(minMaxByteArr, 0, minMaxByteArr.length); - pSeg.setByteArray(itemsByteArr, 0, itemsByteArr.length); - return bytesOut; - } - - static String toStringImpl(final KllSketch sketch, final boolean withLevels, final boolean withLevelsAndItems) { - final StringBuilder sb = new StringBuilder(); - final int k = sketch.getK(); - final int m = sketch.getM(); - final int numLevels = sketch.getNumLevels(); - final int[] fullLevelsArr = sketch.getLevelsArray(UPDATABLE); - - final SketchType sketchType = sketch.sketchType; - final boolean hasMSeg = sketch.hasMemorySegment(); - final long n = sketch.getN(); - final String epsPct = String.format("%.3f%%", sketch.getNormalizedRankError(false) * 100); - final String epsPMFPct = String.format("%.3f%%", sketch.getNormalizedRankError(true) * 100); - final boolean compact = sketch.isCompactMemorySegmentFormat(); - - final String directStr = hasMSeg ? "Direct" : ""; - final String compactStr = compact ? "Compact" : ""; - final String readOnlyStr = sketch.isReadOnly() ? "true" + ("(" + (compact ? "Format" : "MemorySegment") + ")") : "false"; - final String skTypeStr = sketchType.getName(); - final String className = "Kll" + directStr + compactStr + skTypeStr; - - sb.append(LS + "### ").append(className).append(" Summary:").append(LS); - sb.append(" K : ").append(k).append(LS); - sb.append(" Dynamic min K : ").append(sketch.getMinK()).append(LS); - sb.append(" M : ").append(m).append(LS); - sb.append(" N : ").append(n).append(LS); - sb.append(" Epsilon : ").append(epsPct).append(LS); - sb.append(" Epsilon PMF : ").append(epsPMFPct).append(LS); - sb.append(" Empty : ").append(sketch.isEmpty()).append(LS); - sb.append(" Estimation Mode : ").append(sketch.isEstimationMode()).append(LS); - sb.append(" Levels : ").append(numLevels).append(LS); - sb.append(" Level 0 Sorted : ").append(sketch.isLevelZeroSorted()).append(LS); - sb.append(" Capacity Items : ").append(fullLevelsArr[numLevels]).append(LS); - sb.append(" Retained Items : ").append(sketch.getNumRetained()).append(LS); - sb.append(" Free Space : ").append(sketch.levelsArr[0]).append(LS); - sb.append(" ReadOnly : ").append(readOnlyStr).append(LS); - if (sketchType != KLL_ITEMS_SKETCH) { - sb.append(" Updatable Storage Bytes: ").append(sketch.currentSerializedSizeBytes(true)).append(LS); - } - sb.append(" Compact Storage Bytes : ").append(sketch.currentSerializedSizeBytes(false)).append(LS); - - final String emptyStr = (sketchType == KLL_ITEMS_SKETCH) ? "Null" : "NaN"; - - sb.append(" Min Item : ").append(sketch.isEmpty() ? emptyStr : sketch.getMinItemAsString()) - .append(LS); - sb.append(" Max Item : ").append(sketch.isEmpty() ? emptyStr : sketch.getMaxItemAsString()) - .append(LS); - sb.append("### End sketch summary").append(LS); - - if (withLevels) { - sb.append(outputLevels(k, m, numLevels, fullLevelsArr)); - } - - if (withLevelsAndItems) { - sb.append(outputDataDetail(sketch)); - } - return sb.toString(); - } - - /** - * Returns very conservative upper bound of the number of levels based on n. - * @param n the length of the stream - * @return floor( log_2(n) ) - */ - static int ubOnNumLevels(final long n) { - return 1 + Long.numberOfTrailingZeros(floorPowerOf2(n)); - } - - /** - * This grows the levels arr by 1 (if needed) and increases the capacity of the items array - * at the bottom. Only numLevels, the levels array and the items array are affected. - * This assumes sketch is writable and UPDATABLE. - * @param sketch the current sketch - */ - static void addEmptyTopLevelToCompletelyFullSketch(final KllSketch sketch) { - final SketchType sketchType = sketch.sketchType; - - final int[] myCurLevelsArr = sketch.getLevelsArray(sketch.sketchStructure); - final int myCurNumLevels = sketch.getNumLevels(); - final int myCurTotalItemsCapacity = myCurLevelsArr[myCurNumLevels]; - - final int myNewNumLevels; - final int[] myNewLevelsArr; - final int myNewTotalItemsCapacity; - - - double[] myCurDoubleItemsArr = null; - double[] myNewDoubleItemsArr = null; - double minDouble = Double.NaN; - double maxDouble = Double.NaN; - - float[] myCurFloatItemsArr = null; - float[] myNewFloatItemsArr = null; - float minFloat = Float.NaN; - float maxFloat = Float.NaN; - - long[] myCurLongItemsArr = null; - long[] myNewLongItemsArr = null; - long minLong = Long.MAX_VALUE; - long maxLong = Long.MIN_VALUE; - - Object[] myCurItemsArr = null; - Object[] myNewItemsArr = null; - Object minItem = null; - Object maxItem = null; - - if (sketchType == KLL_DOUBLES_SKETCH) { - final KllDoublesSketch dblSk = (KllDoublesSketch) sketch; - myCurDoubleItemsArr = dblSk.getDoubleItemsArray(); - minDouble = dblSk.getMinItem(); - maxDouble = dblSk.getMaxItem(); - //assert we are following a certain growth scheme - assert myCurDoubleItemsArr.length == myCurTotalItemsCapacity; - } - else if (sketchType == KLL_FLOATS_SKETCH) { - final KllFloatsSketch fltSk = (KllFloatsSketch) sketch; - myCurFloatItemsArr = fltSk.getFloatItemsArray(); - minFloat = fltSk.getMinItem(); - maxFloat = fltSk.getMaxItem(); - //assert we are following a certain growth scheme - assert myCurFloatItemsArr.length == myCurTotalItemsCapacity; - } - else if (sketchType == KLL_LONGS_SKETCH) { - final KllLongsSketch lngSk = (KllLongsSketch) sketch; - myCurLongItemsArr = lngSk.getLongItemsArray(); - minLong = lngSk.getMinItem(); - maxLong = lngSk.getMaxItem(); - //assert we are following a certain growth scheme - assert myCurLongItemsArr.length == myCurTotalItemsCapacity; - } - else { //sketchType == ITEMS_SKETCH - final KllItemsSketch itmSk = (KllItemsSketch) sketch; - myCurItemsArr = itmSk.getTotalItemsArray(); - minItem = itmSk.getMinItem(); - maxItem = itmSk.getMaxItem(); - } - assert myCurLevelsArr[0] == 0; //definition of full is part of the growth scheme - - final int deltaItemsCap = levelCapacity(sketch.getK(), myCurNumLevels + 1, 0, sketch.getM()); - myNewTotalItemsCapacity = myCurTotalItemsCapacity + deltaItemsCap; - - // Check if growing the levels arr if required. - // Note that merging MIGHT over-grow levels_, in which case we might not have to grow it - final boolean growLevelsArr = myCurLevelsArr.length < (myCurNumLevels + 2); - - // GROW LEVELS ARRAY - if (growLevelsArr) { - //grow levels arr by one and copy the old data to the new array, extra space at the top. - myNewLevelsArr = Arrays.copyOf(myCurLevelsArr, myCurNumLevels + 2); - assert myNewLevelsArr.length == (myCurLevelsArr.length + 1); - myNewNumLevels = myCurNumLevels + 1; - sketch.incNumLevels(); //increment for off-heap - } else { - myNewLevelsArr = myCurLevelsArr; - myNewNumLevels = myCurNumLevels; - } - // This loop updates all level indices EXCLUDING the "extra" index at the top - for (int level = 0; level <= (myNewNumLevels - 1); level++) { - myNewLevelsArr[level] += deltaItemsCap; - } - myNewLevelsArr[myNewNumLevels] = myNewTotalItemsCapacity; // initialize the new "extra" index at the top - - // GROW items ARRAY - if (sketchType == KLL_DOUBLES_SKETCH) { - myNewDoubleItemsArr = new double[myNewTotalItemsCapacity]; - // copy and shift the current data into the new array - System.arraycopy(myCurDoubleItemsArr, 0, myNewDoubleItemsArr, deltaItemsCap, myCurTotalItemsCapacity); - } - else if (sketchType == KLL_FLOATS_SKETCH) { - myNewFloatItemsArr = new float[myNewTotalItemsCapacity]; - // copy and shift the current items data into the new array - System.arraycopy(myCurFloatItemsArr, 0, myNewFloatItemsArr, deltaItemsCap, myCurTotalItemsCapacity); - } - else if (sketchType == KLL_LONGS_SKETCH) { - myNewLongItemsArr = new long[myNewTotalItemsCapacity]; - // copy and shift the current items data into the new array - System.arraycopy(myCurLongItemsArr, 0, myNewLongItemsArr, deltaItemsCap, myCurTotalItemsCapacity); - } - else { //sketchType == ITEMS_SKETCH - myNewItemsArr = new Object[myNewTotalItemsCapacity]; - // copy and shift the current items data into the new array - System.arraycopy(myCurItemsArr, 0, myNewItemsArr, deltaItemsCap, myCurTotalItemsCapacity); - } - - //MemorySegment SPACE MANAGEMENT - if (sketch.getMemorySegment() != null) { - final MemorySegment wseg = memorySegmentSpaceMgmt(sketch, myNewLevelsArr.length, myNewTotalItemsCapacity); - sketch.setMemorySegment(wseg); - } - - //update our sketch with new expanded spaces - sketch.setNumLevels(myNewNumLevels); //for off-heap only - sketch.setLevelsArray(myNewLevelsArr); //the KllSketch copy - if (sketchType == KLL_DOUBLES_SKETCH) { - final KllDoublesSketch dblSk = (KllDoublesSketch) sketch; - dblSk.setMinItem(minDouble); - dblSk.setMaxItem(maxDouble); - dblSk.setDoubleItemsArray(myNewDoubleItemsArr); - } - else if (sketchType == KLL_FLOATS_SKETCH) { - final KllFloatsSketch fltSk = (KllFloatsSketch) sketch; - fltSk.setMinItem(minFloat); - fltSk.setMaxItem(maxFloat); - fltSk.setFloatItemsArray(myNewFloatItemsArr); - } - else if (sketchType == KLL_LONGS_SKETCH) { - final KllLongsSketch lngSk = (KllLongsSketch) sketch; - lngSk.setMinItem(minLong); - lngSk.setMaxItem(maxLong); - lngSk.setLongItemsArray(myNewLongItemsArr); - } - else { //sketchType == ITEMS_SKETCH - final KllItemsSketch itmSk = (KllItemsSketch) sketch; - itmSk.setMinItem(minItem); - itmSk.setMaxItem(maxItem); - itmSk.setItemsArray(myNewItemsArr); - } - - } //END of addEmptyTopLevelToCompletelyFullSketch(...) - - /** - * Finds the first level starting with level 0 that exceeds its nominal capacity - * @param k configured size of sketch. Range [m, 2^16] - * @param m minimum level size. Default is 8. - * @param numLevels one-based number of current levels - * @return level to compact - */ - static int findLevelToCompact(final int k, final int m, final int numLevels, final int[] levels) { - int level = 0; - while (true) { - assert level < numLevels; - final int pop = levels[level + 1] - levels[level]; - final int cap = KllHelper.levelCapacity(k, numLevels, level, m); - if (pop >= cap) { - return level; - } - level++; - } - } - - /** - * Computes the actual item capacity of a given level given its depth index. - * If the depth of levels exceeds 30, this uses a folding technique to accurately compute the - * actual level capacity up to a depth of 60 (or 61 levels). - * Without folding, the internal calculations would exceed the capacity of a long. - * This method just decides whether folding is required or not. - * @param k the configured k of the sketch - * @param depth the zero-based index of the level being computed. - * @return the actual capacity of a given level given its depth index. - */ - static long intCapAux(final int k, final int depth) { - if (depth <= 30) { return intCapAuxAux(k, depth); } - final int half = depth / 2; - final int rest = depth - half; - final long tmp = intCapAuxAux(k, half); - return intCapAuxAux(tmp, rest); - } - - /** - * Performs the integer based calculation of an individual level (or folded level). - * @param k the configured k of the sketch - * @param depth the zero-based index of the level being computed. The max depth is 30! - * @return the actual capacity of a given level given its depth index. - */ - static long intCapAuxAux(final long k, final int depth) { - final long twok = k << 1; // for rounding at the end, pre-multiply by 2 here, divide by 2 during rounding. - final long tmp = ((twok << depth) / powersOfThree[depth]); //2k* (2/3)^depth. 2k also keeps the fraction larger. - final long result = ((tmp + 1L) >>> 1); // (tmp + 1)/2. If odd, round up. This guarantees an integer. - assert (result <= k); - return result; - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ... args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllItemsHelper.java b/src/main/java/org/apache/datasketches/kll/KllItemsHelper.java deleted file mode 100644 index a066bf536..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllItemsHelper.java +++ /dev/null @@ -1,518 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static java.lang.reflect.Array.newInstance; -import static org.apache.datasketches.common.Util.isEven; -import static org.apache.datasketches.common.Util.isOdd; -import static org.apache.datasketches.kll.KllHelper.findLevelToCompact; -import static org.apache.datasketches.kll.KllSketch.DEFAULT_M; - -import java.util.Arrays; -import java.util.Comparator; -import java.util.Random; - -import org.apache.datasketches.common.Util; - -/** - * Static methods to support KllItemsSketch - * @author Kevin Lang - * @author Lee Rhodes - */ -@SuppressWarnings("unchecked") -final class KllItemsHelper { - - /** - * Create Items Array from given item and weight. - * Used with weighted update only. - * @param item the given item - * @param weight the given weight - * @return the Items Array. - */ - static T[] createItemsArray(final Class clazz, final T item, final long weight) { - final int itemsArrLen = Long.bitCount(weight); - final T[] itemsArr = (T[])newInstance(clazz, itemsArrLen); - Arrays.fill(itemsArr, item); - return itemsArr; - } - - /** - * The following code is only valid in the special case of exactly reaching capacity while updating. - * It cannot be used while merging, while reducing k, or anything else. - * @param itmSk the current KllItemsSketch - */ - private static void compressWhileUpdatingSketch(final KllItemsSketch itmSk) { - final int level = - findLevelToCompact(itmSk.getK(), itmSk.getM(), itmSk.getNumLevels(), itmSk.levelsArr); - if (level == (itmSk.getNumLevels() - 1)) { - //The level to compact is the top level, thus we need to add a level. - //Be aware that this operation grows the items array, - //shifts the items data and the level boundaries of the data, - //and grows the levels array and increments numLevels_. - KllHelper.addEmptyTopLevelToCompletelyFullSketch(itmSk); - } - //after this point, the levelsArray will not be expanded, only modified. - final int[] myLevelsArr = itmSk.levelsArr; - final int rawBeg = myLevelsArr[level]; - final int rawEnd = myLevelsArr[level + 1]; - // +2 is OK because we already added a new top level if necessary - final int popAbove = myLevelsArr[level + 2] - rawEnd; - final int rawPop = rawEnd - rawBeg; - final boolean oddPop = isOdd(rawPop); - final int adjBeg = oddPop ? rawBeg + 1 : rawBeg; - final int adjPop = oddPop ? rawPop - 1 : rawPop; - final int halfAdjPop = adjPop / 2; - - //the following is specific to generic Items - final Object[] myItemsArr = itmSk.getTotalItemsArray(); - if (level == 0) { // level zero might not be sorted, so we must sort it if we wish to compact it - Arrays.sort((T[])myItemsArr, adjBeg, adjBeg + adjPop, itmSk.comparator); - } - if (popAbove == 0) { - KllItemsHelper.randomlyHalveUpItems(myItemsArr, adjBeg, adjPop, KllSketch.random); - } else { - KllItemsHelper.randomlyHalveDownItems(myItemsArr, adjBeg, adjPop, KllSketch.random); - KllItemsHelper.mergeSortedItemsArrays( - myItemsArr, adjBeg, halfAdjPop, - myItemsArr, rawEnd, popAbove, - myItemsArr, adjBeg + halfAdjPop, itmSk.comparator); - } - - int newIndex = myLevelsArr[level + 1] - halfAdjPop; // adjust boundaries of the level above - itmSk.setLevelsArrayAt(level + 1, newIndex); - - if (oddPop) { - itmSk.setLevelsArrayAt(level, myLevelsArr[level + 1] - 1); // the current level now contains one item - myItemsArr[myLevelsArr[level]] = myItemsArr[rawBeg]; // namely this leftover guy - } else { - itmSk.setLevelsArrayAt(level, myLevelsArr[level + 1]); // the current level is now empty - } - - // verify that we freed up halfAdjPop array slots just below the current level - assert myLevelsArr[level] == (rawBeg + halfAdjPop); - - // finally, we need to shift up the data in the levels below - // so that the freed-up space can be used by level zero - if (level > 0) { - final int amount = rawBeg - myLevelsArr[0]; - System.arraycopy(myItemsArr, myLevelsArr[0], myItemsArr, myLevelsArr[0] + halfAdjPop, amount); - } - for (int lvl = 0; lvl < level; lvl++) { - newIndex = myLevelsArr[lvl] + halfAdjPop; //adjust boundary - itmSk.setLevelsArrayAt(lvl, newIndex); - } - itmSk.setItemsArray(myItemsArr); - } - - //assumes readOnly = false, and UPDATABLE, called from KllItemSketch::merge - static void mergeItemImpl(final KllItemsSketch mySketch, - final KllItemsSketch otherItmSk, final Comparator comp) { - if (otherItmSk.isEmpty()) { return; } - - //capture my key mutable fields before doing any merging - final boolean myEmpty = mySketch.isEmpty(); - final Object myMin = myEmpty ? null : mySketch.getMinItem(); - final Object myMax = myEmpty ? null : mySketch.getMaxItem(); - final int myMinK = mySketch.getMinK(); - final long finalN = Math.addExact(mySketch.getN(), otherItmSk.getN()); - - //buffers that are referenced multiple times - final int otherNumLevels = otherItmSk.getNumLevels(); - final int[] otherLevelsArr = otherItmSk.levelsArr; - final Object[] otherItemsArr; - - //MERGE: update this sketch with level0 items from the other sketch - if (otherItmSk.isCompactSingleItem()) { - updateItem(mySketch, otherItmSk.getSingleItem()); - otherItemsArr = new Object[0]; - } else { - otherItemsArr = otherItmSk.getTotalItemsArray(); - for (int i = otherLevelsArr[0]; i < otherLevelsArr[1]; i++) { - updateItem(mySketch, otherItemsArr[i]); - } - } - - //After the level 0 update, we capture the intermediate state of levels and items arrays... - final int myCurNumLevels = mySketch.getNumLevels(); - final int[] myCurLevelsArr = mySketch.levelsArr; - final Object[] myCurItemsArr = mySketch.getTotalItemsArray(); - - // then rename them and initialize in case there are no higher levels - int myNewNumLevels = myCurNumLevels; - int[] myNewLevelsArr = myCurLevelsArr; - Object[] myNewItemsArr = myCurItemsArr; - - //merge higher levels if they exist - if ((otherNumLevels > 1) && !otherItmSk.isCompactSingleItem()) { - final int tmpSpaceNeeded = mySketch.getNumRetained() - + KllHelper.getNumRetainedAboveLevelZero(otherNumLevels, otherLevelsArr); - final Object[] workbuf = new Object[tmpSpaceNeeded]; - - final int provisionalNumLevels = max(myCurNumLevels, otherNumLevels); - - final int ub = max(KllHelper.ubOnNumLevels(finalN), provisionalNumLevels); - final int[] worklevels = new int[ub + 2]; // ub+1 does not work - final int[] outlevels = new int[ub + 2]; - - populateItemWorkArrays(workbuf, worklevels, provisionalNumLevels, - myCurNumLevels, myCurLevelsArr, myCurItemsArr, - otherNumLevels, otherLevelsArr, otherItemsArr, comp); - - // notice that workbuf is being used as both the input and output - final int[] result = generalItemsCompress(mySketch.getK(), mySketch.getM(), provisionalNumLevels, - workbuf, worklevels, workbuf, outlevels, mySketch.isLevelZeroSorted(), KllSketch.random, comp); - final int targetItemCount = result[1]; //was finalCapacity. Max size given k, m, numLevels - final int curItemCount = result[2]; //was finalPop - - // now we need to finalize the results for mySketch - - //THE NEW NUM LEVELS - myNewNumLevels = result[0]; - assert myNewNumLevels <= ub; // ub may be much bigger - - // THE NEW ITEMS ARRAY - myNewItemsArr = (targetItemCount == myCurItemsArr.length) - ? myCurItemsArr - : new Object[targetItemCount]; - final int freeSpaceAtBottom = targetItemCount - curItemCount; - - //shift the new items array create space at bottom - System.arraycopy(workbuf, outlevels[0], myNewItemsArr, freeSpaceAtBottom, curItemCount); - final int theShift = freeSpaceAtBottom - outlevels[0]; - - //calculate the new levels array length - final int finalLevelsArrLen; - if (myCurLevelsArr.length < (myNewNumLevels + 1)) { finalLevelsArrLen = myNewNumLevels + 1; } - else { finalLevelsArrLen = myCurLevelsArr.length; } - - //THE NEW LEVELS ARRAY - myNewLevelsArr = new int[finalLevelsArrLen]; - for (int lvl = 0; lvl < (myNewNumLevels + 1); lvl++) { // includes the "extra" index - myNewLevelsArr[lvl] = outlevels[lvl] + theShift; - } - - //MEMORY SPACE MANAGEMENT - //not used - //extra spaces to make comparison with other helpers easier - // - // - // - } //end of updating levels above level 0 - - //Update Preamble: - mySketch.setN(finalN); - if (otherItmSk.isEstimationMode()) { //otherwise the merge brings over exact items. - mySketch.setMinK(min(myMinK, otherItmSk.getMinK())); - } - - //Update numLevels, levelsArray, items - mySketch.setNumLevels(myNewNumLevels); - mySketch.setLevelsArray(myNewLevelsArr); - mySketch.setItemsArray(myNewItemsArr); - - //Update min, max items - final Object otherMin = otherItmSk.getMinItem(); - final Object otherMax = otherItmSk.getMaxItem(); - if (myEmpty) { - mySketch.setMinItem(otherMin); - mySketch.setMaxItem(otherMax); - } else { - mySketch.setMinItem(Util.minT(myMin, otherMin, comp)); - mySketch.setMaxItem(Util.maxT(myMax, otherMax, comp)); - } - assert KllHelper.sumTheSampleWeights(mySketch.getNumLevels(), mySketch.levelsArr) == mySketch.getN(); - } - - private static void mergeSortedItemsArrays( //only bufC is modified - final Object[] bufA, final int startA, final int lenA, - final Object[] bufB, final int startB, final int lenB, - final Object[] bufC, final int startC, final Comparator comp) { - final int lenC = lenA + lenB; - final int limA = startA + lenA; - final int limB = startB + lenB; - final int limC = startC + lenC; - - int a = startA; - int b = startB; - - for (int c = startC; c < limC; c++) { - if (a == limA) { - bufC[c] = bufB[b]; - b++; - } else if (b == limB) { - bufC[c] = bufA[a]; - a++; - } else if ( Util.lt(bufA[a], bufB[b], comp)) { - bufC[c] = bufA[a]; - a++; - } else { - bufC[c] = bufB[b]; - b++; - } - } - assert a == limA; - assert b == limB; - } - - /** - * Validation Method. This must be modified to use the validation test - * @param buf the items array - * @param start data start - * @param length items array length - * @param random instance of Random - */ - //NOTE For validation Method: Need to modify to run. - private static void randomlyHalveDownItems(final Object[] buf, final int start, final int length, - final Random random) { - assert isEven(length); - final int half_length = length / 2; - final int offset = random.nextInt(2); // disable for validation - //final int offset = deterministicOffset(); // enable for validation - int j = start + offset; - for (int i = start; i < (start + half_length); i++) { - buf[i] = buf[j]; - j += 2; - } - } - - /** - * Validation Method. This must be modified to use the validation test - * @param buf the items array - * @param start data start - * @param length items array length - * @param random instance of Random - */ - //NOTE For validation Method: Need to modify to run. - private static void randomlyHalveUpItems(final Object[] buf, final int start, final int length, - final Random random) { - assert isEven(length); - final int half_length = length / 2; - final int offset = random.nextInt(2); // disable for validation - //final int offset = deterministicOffset(); // enable for validation - int j = (start + length) - 1 - offset; - for (int i = (start + length) - 1; i >= (start + half_length); i--) { - buf[i] = buf[j]; - j -= 2; - } - } - - //Called from KllItemsSketch::update and this - static void updateItem(final KllItemsSketch itmSk, final Object item) { - itmSk.updateMinMax((T)item); - int freeSpace = itmSk.levelsArr[0]; - assert freeSpace >= 0; - if (freeSpace == 0) { - compressWhileUpdatingSketch(itmSk); - freeSpace = itmSk.levelsArr[0]; - assert (freeSpace > 0); - } - itmSk.incN(1); - itmSk.setLevelZeroSorted(false); - final int nextPos = freeSpace - 1; - itmSk.setLevelsArrayAt(0, nextPos); - itmSk.setItemsArrayAt(nextPos, item); - } - - //Called from KllItemsSketch::update with weight - static void updateItem(final KllItemsSketch itmSk, final T item, final long weight) { - if (weight < itmSk.levelsArr[0]) { - for (int i = 0; i < (int)weight; i++) { updateItem(itmSk, item); } - } else { - itmSk.updateMinMax(item); - final KllHeapItemsSketch tmpSk = - new KllHeapItemsSketch<>(itmSk.getK(), DEFAULT_M, item, weight, itmSk.comparator, itmSk.serDe); - itmSk.merge(tmpSk); - } - } - - /** - * Compression algorithm used to merge higher levels. - * - *

Here is what we do for each level:

- *
  • If it does not need to be compacted, then simply copy it over.
  • - *
  • Otherwise, it does need to be compacted, so... - *
    • Copy zero or one guy over.
    • - *
    • If the level above is empty, halve up.
    • - *
    • Else the level above is nonempty, so halve down, then merge up.
    • - *
  • - *
  • Adjust the boundaries of the level above.
  • - *
- * - *

It can be proved that generalCompress returns a sketch that satisfies the space constraints - * no matter how much data is passed in. - * We are pretty sure that it works correctly when inBuf and outBuf are the same. - * All levels except for level zero must be sorted before calling this, and will still be - * sorted afterwards. - * Level zero is not required to be sorted before, and may not be sorted afterwards.

- * - *

This trashes inBuf and inLevels and modifies outBuf and outLevels.

- * - * @param k The sketch parameter k - * @param m The minimum level size - * @param numLevelsIn provisional number of number of levels = max(this.numLevels, other.numLevels) - * @param inBuf work buffer of size = this.getNumRetained() + other.getNumRetainedAboveLevelZero(). - * This contains the items array of the other sketch - * @param inLevels work levels array size = ubOnNumLevels(this.n + other.n) + 2 - * @param outBuf the same array as inBuf - * @param outLevels the same size as inLevels - * @param isLevelZeroSorted true if this.level 0 is sorted - * @param random instance of java.util.Random - * @param comp Comparator of T - * @return int array of: {numLevels, targetItemCount, currentItemCount) - */ - private static int[] generalItemsCompress( - final int k, - final int m, - final int numLevelsIn, - final Object[] inBuf, - final int[] inLevels, - final Object[] outBuf, - final int[] outLevels, - final boolean isLevelZeroSorted, - final Random random, final Comparator comp) { - assert numLevelsIn > 0; // things are too weird if zero levels are allowed - int numLevels = numLevelsIn; - int currentItemCount = inLevels[numLevels] - inLevels[0]; // decreases with each compaction - int targetItemCount = KllHelper.computeTotalItemCapacity(k, m, numLevels); // increases if we add levels - boolean doneYet = false; - outLevels[0] = 0; - int curLevel = -1; - while (!doneYet) { - curLevel++; // start out at level 0 - - // If we are at the current top level, add an empty level above it for convenience, - // but do not actually increment numLevels until later - if (curLevel == (numLevels - 1)) { - inLevels[curLevel + 2] = inLevels[curLevel + 1]; - } - - final int rawBeg = inLevels[curLevel]; - final int rawLim = inLevels[curLevel + 1]; - final int rawPop = rawLim - rawBeg; - - if ((currentItemCount < targetItemCount) || (rawPop < KllHelper.levelCapacity(k, numLevels, curLevel, m))) { - // copy level over as is - // because inBuf and outBuf could be the same, make sure we are not moving data upwards! - assert (rawBeg >= outLevels[curLevel]); - System.arraycopy(inBuf, rawBeg, outBuf, outLevels[curLevel], rawPop); - outLevels[curLevel + 1] = outLevels[curLevel] + rawPop; - } - else { - // The sketch is too full AND this level is too full, so we compact it - // Note: this can add a level and thus change the sketch's capacity - - final int popAbove = inLevels[curLevel + 2] - rawLim; - final boolean oddPop = isOdd(rawPop); - final int adjBeg = oddPop ? 1 + rawBeg : rawBeg; - final int adjPop = oddPop ? rawPop - 1 : rawPop; - final int halfAdjPop = adjPop / 2; - - if (oddPop) { // copy one guy over - outBuf[outLevels[curLevel]] = inBuf[rawBeg]; - outLevels[curLevel + 1] = outLevels[curLevel] + 1; - } else { // copy zero guys over - outLevels[curLevel + 1] = outLevels[curLevel]; - } - - // level zero might not be sorted, so we must sort it if we wish to compact it - if ((curLevel == 0) && !isLevelZeroSorted) { - Arrays.sort((T[])inBuf, adjBeg, adjBeg + adjPop, comp); - } - - if (popAbove == 0) { // Level above is empty, so halve up - randomlyHalveUpItems(inBuf, adjBeg, adjPop, random); - } else { // Level above is nonempty, so halve down, then merge up - randomlyHalveDownItems(inBuf, adjBeg, adjPop, random); - mergeSortedItemsArrays(inBuf, adjBeg, halfAdjPop, inBuf, rawLim, popAbove, inBuf, adjBeg + halfAdjPop, comp); - } - - // track the fact that we just eliminated some data - currentItemCount -= halfAdjPop; - - // Adjust the boundaries of the level above - inLevels[curLevel + 1] = inLevels[curLevel + 1] - halfAdjPop; - - // Increment numLevels if we just compacted the old top level - // This creates some more capacity (the size of the new bottom level) - if (curLevel == (numLevels - 1)) { - numLevels++; - targetItemCount += KllHelper.levelCapacity(k, numLevels, 0, m); - } - } // end of code for compacting a level - - // determine whether we have processed all levels yet (including any new levels that we created) - if (curLevel == (numLevels - 1)) { doneYet = true; } - } // end of loop over levels - - assert (outLevels[numLevels] - outLevels[0]) == currentItemCount; - return new int[] {numLevels, targetItemCount, currentItemCount}; - } - - private static void populateItemWorkArrays( //workBuf and workLevels are modified - final Object[] workbuf, final int[] worklevels, final int provisionalNumLevels, - final int myCurNumLevels, final int[] myCurLevelsArr, final Object[] myCurItemsArr, - final int otherNumLevels, final int[] otherLevelsArr, final Object[] otherItemsArr, - final Comparator comp) { - worklevels[0] = 0; - - // Note: the level zero data from "other" was already inserted into "self". - // This copies into workbuf. - final int selfPopZero = KllHelper.currentLevelSizeItems(0, myCurNumLevels, myCurLevelsArr); - System.arraycopy( myCurItemsArr, myCurLevelsArr[0], workbuf, worklevels[0], selfPopZero); - worklevels[1] = worklevels[0] + selfPopZero; - - for (int lvl = 1; lvl < provisionalNumLevels; lvl++) { - final int selfPop = KllHelper.currentLevelSizeItems(lvl, myCurNumLevels, myCurLevelsArr); - final int otherPop = KllHelper.currentLevelSizeItems(lvl, otherNumLevels, otherLevelsArr); - worklevels[lvl + 1] = worklevels[lvl] + selfPop + otherPop; - assert (selfPop >= 0) && (otherPop >= 0); - if ((selfPop == 0) && (otherPop == 0)) { /* do nothing for this case */ } - else if ((selfPop > 0) && (otherPop == 0)) { - System.arraycopy(myCurItemsArr, myCurLevelsArr[lvl], workbuf, worklevels[lvl], selfPop); - } - else if ((selfPop == 0) && (otherPop > 0)) { - System.arraycopy(otherItemsArr, otherLevelsArr[lvl], workbuf, worklevels[lvl], otherPop); - } - else if ((selfPop > 0) && (otherPop > 0)) { - mergeSortedItemsArrays( - myCurItemsArr, myCurLevelsArr[lvl], selfPop, - otherItemsArr, otherLevelsArr[lvl], otherPop, - workbuf, worklevels[lvl], comp); - } - } - } - - /* - * Validation Method. - * The following must be enabled for use with the KllItemsValidationTest, - * which is only enabled for manual testing. In addition, two Validation Methods - * above need to be modified. - */ //NOTE Validation Method: Need to uncomment to use - // static int nextOffset = 0; - // - // private static int deterministicOffset() { - // final int result = nextOffset; - // nextOffset = 1 - nextOffset; - // return result; - // } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllItemsSketch.java b/src/main/java/org/apache/datasketches/kll/KllItemsSketch.java deleted file mode 100644 index 89f277fb8..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllItemsSketch.java +++ /dev/null @@ -1,541 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_ITEMS_SKETCH; - -import java.lang.foreign.MemorySegment; -import java.lang.reflect.Array; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Objects; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.quantilescommon.GenericPartitionBoundaries; -import org.apache.datasketches.quantilescommon.ItemsSketchSortedView; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; -import org.apache.datasketches.quantilescommon.QuantilesGenericAPI; -import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI; - -/** - * This variation of the KllSketch implements generic data types. The user must provide - * a suitable implementation of the java.lang.Comparator as well as an implementation of - * the serializer / deserializer, org.apache.datasketches.common.ArrayOfItemsSerDe. - * @param The sketch data type. - * @see org.apache.datasketches.kll.KllSketch - */ -@SuppressWarnings("unchecked") -public abstract class KllItemsSketch extends KllSketch implements QuantilesGenericAPI { - private ItemsSketchSortedView itemsSV = null; - final Comparator comparator; - final ArrayOfItemsSerDe serDe; - - KllItemsSketch( //pass-through constructor - final SketchStructure skStructure, - final Comparator comparator, - final ArrayOfItemsSerDe serDe) { - super(KLL_ITEMS_SKETCH, skStructure); - Objects.requireNonNull(comparator, "Comparator must not be null."); - Objects.requireNonNull(serDe, "SerDe must not be null."); - this.comparator = comparator; - this.serDe = serDe; - } - - //Factories for new heap instances. - - /** - * Create a new heap instance of this sketch with the default k = 200. - * The default k = 200 results in a normalized rank error of about - * 1.65%. Larger K will have smaller error but the sketch will be larger (and slower). - * @param comparator to compare items - * @param serDe Serializer / deserializer for an array of items, T[]. - * @param The sketch data type. - * @return new KllItemsSketch on the Java heap. - */ - public static KllItemsSketch newHeapInstance( - final Comparator comparator, - final ArrayOfItemsSerDe serDe) { - return new KllHeapItemsSketch<>(DEFAULT_K, DEFAULT_M, comparator, serDe); - } - - /** - * Create a new heap instance of this sketch with a given parameter k. - * k can be between DEFAULT_M and 65535, inclusive. - * The default k = 200 results in a normalized rank error of about - * 1.65%. Larger K will have smaller error but the sketch will be larger (and slower). - * @param k parameter that controls size of the sketch and accuracy of estimates. - * @param comparator to compare items - * @param serDe Serializer / deserializer for items of type T and T[]. - * @param The sketch data type - * @return new KllItemsSketch on the heap. - */ - public static KllItemsSketch newHeapInstance( - final int k, - final Comparator comparator, - final ArrayOfItemsSerDe serDe) { - return new KllHeapItemsSketch<>(k, DEFAULT_M, comparator, serDe); - } - - // Factory to create an heap instance from a MemorySegment image - - /** - * Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch. - * The resulting sketch will not retain any link to the source MemorySegment. - * @param srcSeg a compact MemorySegment image of a sketch serialized by this sketch and of the same type of T. - * @param comparator to compare items - * @param serDe Serializer / deserializer for items of type T and T[]. - * @param The sketch data type - * @return a heap-based sketch based on the given MemorySegment. - */ - public static KllItemsSketch heapify( - final MemorySegment srcSeg, - final Comparator comparator, - final ArrayOfItemsSerDe serDe) { - return new KllHeapItemsSketch<>(srcSeg, comparator, serDe); - } - - //Factory to wrap a Read-Only MemorySegment - - /** - * Constructs a thin wrapper on the heap around a MemorySegment (or MemorySegment) already initialized with a - * validated sketch image of a type T consistent with the given comparator and serDe. - * A reference to the MemorySegment is kept in the sketch and must remain in scope consistent - * with the temporal scope of this sketch. The amount of data kept on the heap is very small. - * All of the item data originally collected by the given MemorySegment sketch object remains in the - * MemorySegment object. - * @param srcSeg the MemorySegment object that this sketch will wrap. It will not be modified. - * @param comparator to compare items - * @param serDe Serializer / deserializer for items of type T and T[]. - * @param The sketch data type - * @return a heap-base sketch that is a thin wrapper around the given srcSeg. - */ - public static KllItemsSketch wrap( - final MemorySegment srcSeg, - final Comparator comparator, - final ArrayOfItemsSerDe serDe) { - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(srcSeg, SketchType.KLL_ITEMS_SKETCH, serDe); - return new KllDirectCompactItemsSketch<>(segVal, comparator, serDe); - } - - //END of Constructors - - @Override - public double[] getCDF(final T[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return itemsSV.getCDF(splitPoints, searchCrit); - } - - @Override - public Class getClassOfT() { return serDe.getClassOfT(); } - - @Override - public Comparator getComparator() { - return comparator; - } - - @Override - public GenericPartitionBoundaries getPartitionBoundariesFromNumParts( - final int numEquallySizedParts, - final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(EMPTY_MSG); } - refreshSortedView(); - return itemsSV.getPartitionBoundariesFromNumParts(numEquallySizedParts, searchCrit); - } - - @Override - public GenericPartitionBoundaries getPartitionBoundariesFromPartSize( - final long nominalPartSizeItems, - final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(EMPTY_MSG); } - refreshSortedView(); - return itemsSV.getPartitionBoundariesFromPartSize(nominalPartSizeItems, searchCrit); - } - - @Override - public double[] getPMF(final T[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return itemsSV.getPMF(splitPoints, searchCrit); - } - - @Override - public T getQuantile(final double rank, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return itemsSV.getQuantile(rank, searchCrit); - } - - @Override - public T[] getQuantiles(final double[] ranks, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - final int len = ranks.length; - final T[] quantiles = (T[]) Array.newInstance(getMinItem().getClass(), len); - for (int i = 0; i < len; i++) { - quantiles[i] = itemsSV.getQuantile(ranks[i], searchCrit); - } - return quantiles; - } - - @Override - public T getQuantileLowerBound(final double rank) { - return getQuantile(max(0, rank - KllHelper.getNormalizedRankError(getMinK(), false))); - } - - @Override - public T getQuantileUpperBound(final double rank) { - return getQuantile(min(1.0, rank + KllHelper.getNormalizedRankError(getMinK(), false))); - } - - @Override - public double getRank(final T quantile, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return itemsSV.getRank(quantile, searchCrit); - } - - /** - * {@inheritDoc} - * The approximate probability that the true rank is within the confidence interval - * specified by the upper and lower rank bounds for this sketch is 0.99. - */ - @Override - public double getRankLowerBound(final double rank) { - return max(0.0, rank - KllHelper.getNormalizedRankError(getMinK(), false)); - } - - /** - * {@inheritDoc} - * The approximate probability that the true rank is within the confidence interval - * specified by the upper and lower rank bounds for this sketch is 0.99. - */ - @Override - public double getRankUpperBound(final double rank) { - return min(1.0, rank + KllHelper.getNormalizedRankError(getMinK(), false)); - } - - @Override - public double[] getRanks(final T[] quantiles, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - final int len = quantiles.length; - final double[] ranks = new double[len]; - for (int i = 0; i < len; i++) { - ranks[i] = itemsSV.getRank(quantiles[i], searchCrit); - } - return ranks; - } - - @Override - public final ItemsSketchSortedView getSortedView() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - return refreshSortedView(); - } - - @Override - public QuantilesGenericSketchIteratorAPI iterator() { - return new KllItemsSketchIterator<>( - getTotalItemsArray(), getLevelsArray(SketchStructure.UPDATABLE), getNumLevels()); - } - - @Override - public final void merge(final KllSketch other) { - if (readOnly || (sketchStructure != UPDATABLE)) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - if (this == other) { throw new SketchesArgumentException(SELF_MERGE_MSG); } - final KllItemsSketch othItmSk = (KllItemsSketch)other; - if (othItmSk.isEmpty()) { return; } - KllItemsHelper.mergeItemImpl(this, othItmSk, comparator); - itemsSV = null; - } - - @Override - public void reset() { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int k = getK(); - setN(0); - setMinK(k); - setNumLevels(1); - setLevelZeroSorted(false); - setLevelsArray(new int[] {k, k}); - setMinItem(null); - setMaxItem(null); - setItemsArray(new Object[k]); - itemsSV = null; - } - - /** - * Export the current sketch as a compact byte array. - * @return the current sketch as a compact byte array. - */ - public byte[] toByteArray() { - return KllHelper.toByteArray(this, false); - } - - @Override - public String toString(final boolean withLevels, final boolean withLevelsAndItems) { - KllSketch sketch = this; - if (hasMemorySegment()) { - final MemorySegment seg = getMemorySegment(); - assert seg != null; - sketch = KllItemsSketch.heapify(getMemorySegment(), comparator, serDe); - } - return KllHelper.toStringImpl(sketch, withLevels, withLevelsAndItems); - } - - @Override - public void update(final T item) { - if (item == null) { return; } //ignore - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - KllItemsHelper.updateItem(this, item); - itemsSV = null; - } - - /** - * Weighted update. Updates this sketch with the given item the number of times specified by the given integer weight. - * @param item the item to be repeated. NaNs are ignored. - * @param weight the number of times the update of item is to be repeated. It must be ≥ one. - */ - public void update(final T item, final long weight) { - if (item == null) { return; } //ignore - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - if (weight < 1L) { throw new SketchesArgumentException("Weight is less than one."); } - if (weight == 1L) { KllItemsHelper.updateItem(this, item); } - else { KllItemsHelper.updateItem(this, item, weight); } - itemsSV = null; - } - - //restricted - - @Override - abstract byte[] getMinMaxByteArr(); - - @Override - abstract int getMinMaxSizeBytes(); - - abstract T[] getRetainedItemsArray(); - - @Override - abstract byte[] getRetainedItemsByteArr(); - - @Override - abstract int getRetainedItemsSizeBytes(); - - //abstract Object[] getRetainedItemsArray(); - - @Override - ArrayOfItemsSerDe getSerDe() { return serDe; } - - abstract T getSingleItem(); - - @Override - abstract byte[] getSingleItemByteArr(); - - @Override - abstract int getSingleItemSizeBytes(); - - /** - * @return a full array of items as if the sketch was in COMPACT_FULL or UPDATABLE format. - * This will include zeros and possibly some free space. - */ - abstract T[] getTotalItemsArray(); - - @Override - byte[] getTotalItemsByteArr() { - throw new SketchesArgumentException(UNSUPPORTED_MSG); - } - - @Override - int getTotalItemsNumBytes() { - throw new SketchesArgumentException(UNSUPPORTED_MSG); - } - - @Override - void incNumLevels() { - //this is not used and must be a no-op. - } - - abstract void setItemsArray(Object[] ItemsArr); - - abstract void setItemsArrayAt(int index, Object item); - - abstract void setMaxItem(Object item); - - abstract void setMinItem(Object item); - - @Override - void setNumLevels(final int numLevels) { - // this is not used and must be a no-op. - } - - @Override - void setMemorySegment(final MemorySegment wseg) { - throw new SketchesArgumentException(UNSUPPORTED_MSG + "Sketch not writable."); - } - - void updateMinMax(final T item) { - if (isEmpty()) { - setMinItem(item); - setMaxItem(item); - } else { - setMinItem(Util.minT(getMinItem(), item, comparator)); - setMaxItem(Util.maxT(getMaxItem(), item, comparator)); - } - } - - private final ItemsSketchSortedView refreshSortedView() { - if (itemsSV == null) { - final CreateSortedView csv = new CreateSortedView(); - itemsSV = csv.getSV(); - } - return itemsSV; - } - - @SuppressWarnings({"rawtypes"}) - private final class CreateSortedView { - T[] quantiles; - long[] cumWeights; //The new cumWeights array - - ItemsSketchSortedView getSV() { - if (isEmpty() || (getN() == 0)) { throw new SketchesArgumentException(EMPTY_MSG); } - final T[] srcQuantiles = getTotalItemsArray(); - final int[] srcLevelsArr = levelsArr; - final int srcNumLevels = getNumLevels(); - - if (!isLevelZeroSorted()) { - Arrays.sort(srcQuantiles, srcLevelsArr[0], srcLevelsArr[1], comparator); - if (!hasMemorySegment()) { setLevelZeroSorted(true); } - } - final int numQuantiles = getNumRetained(); - quantiles = (T[]) Array.newInstance(serDe.getClassOfT(), numQuantiles); - cumWeights = new long[numQuantiles]; - populateFromSketch(srcQuantiles, srcLevelsArr, srcNumLevels, numQuantiles); - final QuantilesGenericAPI sk = KllItemsSketch.this; - return new ItemsSketchSortedView(quantiles, cumWeights, sk); - } - - private void populateFromSketch(final Object[] srcQuantiles, final int[] srcLevelsArr, - final int srcNumLevels, final int numItems) { - //Remove free space from both itemsArray and levels array - final int[] myLevelsArr = new int[srcLevelsArr.length]; - final int offset = srcLevelsArr[0]; - System.arraycopy(srcQuantiles, offset, quantiles, 0, numItems); //remove free space from quantiles arr - //fill the new cumWeights array with the correct weights and adjust the levels array to match. - int srcLevel = 0; - int dstLevel = 0; - long weight = 1; - while (srcLevel < srcNumLevels) { - final int fromIndex = srcLevelsArr[srcLevel] - offset; - final int toIndex = srcLevelsArr[srcLevel + 1] - offset; // exclusive - if (fromIndex < toIndex) { // if equal, skip empty level - Arrays.fill(cumWeights, fromIndex, toIndex, weight); - myLevelsArr[dstLevel] = fromIndex; - myLevelsArr[dstLevel + 1] = toIndex; - dstLevel++; - } - srcLevel++; - weight *= 2; - } - final int numLevels = dstLevel; - blockyTandemMergeSort(quantiles, cumWeights, myLevelsArr, numLevels, comparator); //create unit weights - KllHelper.convertToCumulative(cumWeights); - } - } //End of class CreateSortedView - - private static void blockyTandemMergeSort(final Object[] quantiles, final long[] weights, - final int[] levels, final int numLevels, final Comparator comp) { - if (numLevels == 1) { return; } - - // duplicate the input in preparation for the "ping-pong" copy reduction strategy. - final Object[] quantilesTmp = Arrays.copyOf(quantiles, quantiles.length); - final long[] weightsTmp = Arrays.copyOf(weights, quantiles.length); // don't need the extra one here - - blockyTandemMergeSortRecursion(quantilesTmp, weightsTmp, quantiles, weights, levels, 0, numLevels, comp); - } - - private static void blockyTandemMergeSortRecursion( - final Object[] quantilesSrc, final long[] weightsSrc, - final Object[] quantilesDst, final long[] weightsDst, - final int[] levels, final int startingLevel, final int numLevels, final Comparator comp) { - if (numLevels == 1) { return; } - final int numLevels1 = numLevels / 2; - final int numLevels2 = numLevels - numLevels1; - assert numLevels1 >= 1; - assert numLevels2 >= numLevels1; - final int startingLevel1 = startingLevel; - final int startingLevel2 = startingLevel + numLevels1; - // swap roles of src and dst - blockyTandemMergeSortRecursion( - quantilesDst, weightsDst, - quantilesSrc, weightsSrc, - levels, startingLevel1, numLevels1, comp); - blockyTandemMergeSortRecursion( - quantilesDst, weightsDst, - quantilesSrc, weightsSrc, - levels, startingLevel2, numLevels2, comp); - tandemMerge( - quantilesSrc, weightsSrc, - quantilesDst, weightsDst, - levels, - startingLevel1, numLevels1, - startingLevel2, numLevels2, comp); - } - - private static void tandemMerge( - final Object[] quantilesSrc, final long[] weightsSrc, - final Object[] quantilesDst, final long[] weightsDst, - final int[] levelStarts, - final int startingLevel1, final int numLevels1, - final int startingLevel2, final int numLevels2, final Comparator comp) { - final int fromIndex1 = levelStarts[startingLevel1]; - final int toIndex1 = levelStarts[startingLevel1 + numLevels1]; // exclusive - final int fromIndex2 = levelStarts[startingLevel2]; - final int toIndex2 = levelStarts[startingLevel2 + numLevels2]; // exclusive - int iSrc1 = fromIndex1; - int iSrc2 = fromIndex2; - int iDst = fromIndex1; - - while ((iSrc1 < toIndex1) && (iSrc2 < toIndex2)) { - if (Util.lt((T) quantilesSrc[iSrc1], (T) quantilesSrc[iSrc2], comp)) { - quantilesDst[iDst] = quantilesSrc[iSrc1]; - weightsDst[iDst] = weightsSrc[iSrc1]; - iSrc1++; - } else { - quantilesDst[iDst] = quantilesSrc[iSrc2]; - weightsDst[iDst] = weightsSrc[iSrc2]; - iSrc2++; - } - iDst++; - } - if (iSrc1 < toIndex1) { - System.arraycopy(quantilesSrc, iSrc1, quantilesDst, iDst, toIndex1 - iSrc1); - System.arraycopy(weightsSrc, iSrc1, weightsDst, iDst, toIndex1 - iSrc1); - } else if (iSrc2 < toIndex2) { - System.arraycopy(quantilesSrc, iSrc2, quantilesDst, iDst, toIndex2 - iSrc2); - System.arraycopy(weightsSrc, iSrc2, weightsDst, iDst, toIndex2 - iSrc2); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllItemsSketchIterator.java b/src/main/java/org/apache/datasketches/kll/KllItemsSketchIterator.java deleted file mode 100644 index 0e39c2c69..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllItemsSketchIterator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI; - -/** - * Iterator over KllItemsSketch. The order is not defined. - * @param the item class type - */ -public final class KllItemsSketchIterator extends KllSketchIterator implements QuantilesGenericSketchIteratorAPI { - private final Object[] quantiles; - - KllItemsSketchIterator(final Object[] quantiles, final int[] levelsArr, final int numLevels) { - super(levelsArr, numLevels); - this.quantiles = quantiles; - } - - @SuppressWarnings("unchecked") - @Override - public T getQuantile() { - return (T)quantiles[index]; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllLongsHelper.java b/src/main/java/org/apache/datasketches/kll/KllLongsHelper.java deleted file mode 100644 index 94638b047..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllLongsHelper.java +++ /dev/null @@ -1,479 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.apache.datasketches.common.Util.isEven; -import static org.apache.datasketches.common.Util.isOdd; -import static org.apache.datasketches.kll.KllHelper.findLevelToCompact; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Random; - -/** - * Static methods to support KllLongsSketch - * @author Lee Rhodes - * @author Zac Blanco - */ -final class KllLongsHelper { - - /** - * Create Items Array from given item and weight. - * Used with weighted update only. - * @param item the given item - * @param weight the given weight - * @return the Items Array. - */ - static long[] createItemsArray(final long item, final long weight) { - final int itemsArrLen = Long.bitCount(weight); - final long[] itemsArr = new long[itemsArrLen]; - Arrays.fill(itemsArr, item); - return itemsArr; - } - - /** - * The following code is only valid in the special case of exactly reaching capacity while updating. - * It cannot be used while merging, while reducing k, or anything else. - * @param lngSk the current KllLongsSketch - */ - static void compressWhileUpdatingSketch(final KllLongsSketch lngSk) { - final int level = - findLevelToCompact(lngSk.getK(), lngSk.getM(), lngSk.getNumLevels(), lngSk.levelsArr); - if (level == (lngSk.getNumLevels() - 1)) { - //The level to compact is the top level, thus we need to add a level. - //Be aware that this operation grows the items array, - //shifts the items data and the level boundaries of the data, - //and grows the levels array and increments numLevels_. - KllHelper.addEmptyTopLevelToCompletelyFullSketch(lngSk); - } - //after this point, the levelsArray will not be expanded, only modified. - final int[] myLevelsArr = lngSk.levelsArr; - final int rawBeg = myLevelsArr[level]; - final int rawEnd = myLevelsArr[level + 1]; - // +2 is OK because we already added a new top level if necessary - final int popAbove = myLevelsArr[level + 2] - rawEnd; - final int rawPop = rawEnd - rawBeg; - final boolean oddPop = isOdd(rawPop); - final int adjBeg = oddPop ? rawBeg + 1 : rawBeg; - final int adjPop = oddPop ? rawPop - 1 : rawPop; - final int halfAdjPop = adjPop / 2; - - //the following is specific to longs - final long[] myLongItemsArray = lngSk.getLongItemsArray(); - if (level == 0) { // level zero might not be sorted, so we must sort it if we wish to compact it - Arrays.sort(myLongItemsArray, adjBeg, adjBeg + adjPop); - } - if (popAbove == 0) { - KllLongsHelper.randomlyHalveUpLongs(myLongItemsArray, adjBeg, adjPop, KllSketch.random); - } else { - KllLongsHelper.randomlyHalveDownLongs(myLongItemsArray, adjBeg, adjPop, KllSketch.random); - KllLongsHelper.mergeSortedLongArrays( - myLongItemsArray, adjBeg, halfAdjPop, - myLongItemsArray, rawEnd, popAbove, - myLongItemsArray, adjBeg + halfAdjPop); - } - - int newIndex = myLevelsArr[level + 1] - halfAdjPop; // adjust boundaries of the level above - lngSk.setLevelsArrayAt(level + 1, newIndex); - - if (oddPop) { - lngSk.setLevelsArrayAt(level, myLevelsArr[level + 1] - 1); // the current level now contains one item - myLongItemsArray[myLevelsArr[level]] = myLongItemsArray[rawBeg]; // namely this leftover guy - } else { - lngSk.setLevelsArrayAt(level, myLevelsArr[level + 1]); // the current level is now empty - } - - // verify that we freed up halfAdjPop array slots just below the current level - assert myLevelsArr[level] == (rawBeg + halfAdjPop); - - // finally, we need to shift up the data in the levels below - // so that the freed-up space can be used by level zero - if (level > 0) { - final int amount = rawBeg - myLevelsArr[0]; - System.arraycopy(myLongItemsArray, myLevelsArr[0], myLongItemsArray, myLevelsArr[0] + halfAdjPop, amount); - } - for (int lvl = 0; lvl < level; lvl++) { - newIndex = myLevelsArr[lvl] + halfAdjPop; //adjust boundary - lngSk.setLevelsArrayAt(lvl, newIndex); - } - lngSk.setLongItemsArray(myLongItemsArray); - } - - //assumes readOnly = false and UPDATABLE, called from KllLongsSketch::merge - static void mergeLongsImpl(final KllLongsSketch mySketch, final KllLongsSketch otherLngSk) { - if (otherLngSk.isEmpty()) { return; } - - //capture my key mutable fields before doing any merging - final boolean myEmpty = mySketch.isEmpty(); - final long myMin = mySketch.getMinItemInternal(); - final long myMax = mySketch.getMaxItemInternal(); - final int myMinK = mySketch.getMinK(); - final long finalN = Math.addExact(mySketch.getN(), otherLngSk.getN()); - - //buffers that are referenced multiple times - final int otherNumLevels = otherLngSk.getNumLevels(); - final int[] otherLevelsArr = otherLngSk.levelsArr; - final long[] otherLongItemsArray; - - //MERGE: update this sketch with level0 items from the other sketch - if (otherLngSk.isCompactSingleItem()) { - KllLongsSketch.updateLong(mySketch, otherLngSk.getLongSingleItem()); - otherLongItemsArray = new long[0]; - } else { - otherLongItemsArray = otherLngSk.getLongItemsArray(); - for (int i = otherLevelsArr[0]; i < otherLevelsArr[1]; i++) { - KllLongsSketch.updateLong(mySketch, otherLongItemsArray[i]); - } - } - - //After the level 0 update, we capture the intermediate state of my levels and items arrays... - final int myCurNumLevels = mySketch.getNumLevels(); - final int[] myCurLevelsArr = mySketch.levelsArr; - final long[] myCurLongItemsArray = mySketch.getLongItemsArray(); - - // create aliases in case there are no higher levels - int myNewNumLevels = myCurNumLevels; - int[] myNewLevelsArr = myCurLevelsArr; - long[] myNewLongItemsArray = myCurLongItemsArray; - - //merge higher levels if they exist - if ((otherNumLevels > 1) && !otherLngSk.isCompactSingleItem()) { - final int tmpSpaceNeeded = mySketch.getNumRetained() - + KllHelper.getNumRetainedAboveLevelZero(otherNumLevels, otherLevelsArr); - final long[] workbuf = new long[tmpSpaceNeeded]; - - final int provisionalNumLevels = max(myCurNumLevels, otherNumLevels); - - final int ub = max(KllHelper.ubOnNumLevels(finalN), provisionalNumLevels); - final int[] worklevels = new int[ub + 2]; // ub+1 does not work - final int[] outlevels = new int[ub + 2]; - - populateLongWorkArrays(workbuf, worklevels, provisionalNumLevels, - myCurNumLevels, myCurLevelsArr, myCurLongItemsArray, - otherNumLevels, otherLevelsArr, otherLongItemsArray); - - // notice that workbuf is being used as both the input and output - final int[] result = generalLongsCompress(mySketch.getK(), mySketch.getM(), provisionalNumLevels, - workbuf, worklevels, workbuf, outlevels, mySketch.isLevelZeroSorted(), KllSketch.random); - final int targetItemCount = result[1]; //was finalCapacity. Max size given k, m, numLevels - final int curItemCount = result[2]; //was finalPop - - // now we need to finalize the results for mySketch - - //THE NEW NUM LEVELS - myNewNumLevels = result[0]; - assert myNewNumLevels <= ub; // ub may be much bigger - - // THE NEW ITEMS ARRAY - myNewLongItemsArray = (targetItemCount == myCurLongItemsArray.length) - ? myCurLongItemsArray - : new long[targetItemCount]; - final int freeSpaceAtBottom = targetItemCount - curItemCount; - - //shift the new items array create space at bottom - System.arraycopy(workbuf, outlevels[0], myNewLongItemsArray, freeSpaceAtBottom, curItemCount); - final int theShift = freeSpaceAtBottom - outlevels[0]; - - //calculate the new levels array length - final int finalLevelsArrLen; - if (myCurLevelsArr.length < (myNewNumLevels + 1)) { finalLevelsArrLen = myNewNumLevels + 1; } - else { finalLevelsArrLen = myCurLevelsArr.length; } - - //THE NEW LEVELS ARRAY - myNewLevelsArr = new int[finalLevelsArrLen]; - for (int lvl = 0; lvl < (myNewNumLevels + 1); lvl++) { // includes the "extra" index - myNewLevelsArr[lvl] = outlevels[lvl] + theShift; - } - - //MemorySegment SPACE MANAGEMENT - if (mySketch.getMemorySegment() != null) { - final MemorySegment wseg = KllHelper.memorySegmentSpaceMgmt(mySketch, myNewLevelsArr.length, myNewLongItemsArray.length); - mySketch.setMemorySegment(wseg); - } - } //end of updating levels above level 0 - - //Update Preamble: - mySketch.setN(finalN); - if (otherLngSk.isEstimationMode()) { //otherwise the merge brings over exact items. - mySketch.setMinK(min(myMinK, otherLngSk.getMinK())); - } - - //Update numLevels, levelsArray, items - mySketch.setNumLevels(myNewNumLevels); - mySketch.setLevelsArray(myNewLevelsArr); - mySketch.setLongItemsArray(myNewLongItemsArray); - - //Update min, max items - final long otherMin = otherLngSk.getMinItemInternal(); - final long otherMax = otherLngSk.getMaxItemInternal(); - if (myEmpty) { - mySketch.setMinItem(otherMin); - mySketch.setMaxItem(otherMax); - } else { - mySketch.setMinItem(min(myMin, otherMin)); - mySketch.setMaxItem(max(myMax, otherMax)); - } - assert KllHelper.sumTheSampleWeights(mySketch.getNumLevels(), mySketch.levelsArr) == mySketch.getN(); - } - - private static void mergeSortedLongArrays( //only bufC is modified - final long[] bufA, final int startA, final int lenA, - final long[] bufB, final int startB, final int lenB, - final long[] bufC, final int startC) { - final int lenC = lenA + lenB; - final int limA = startA + lenA; - final int limB = startB + lenB; - final int limC = startC + lenC; - - int a = startA; - int b = startB; - - for (int c = startC; c < limC; c++) { - if (a == limA) { - bufC[c] = bufB[b]; - b++; - } else if ((b == limB) || (bufA[a] < bufB[b])) { - bufC[c] = bufA[a]; - a++; - } else { - bufC[c] = bufB[b]; - b++; - } - } - assert a == limA; - assert b == limB; - } - - /** - * Validation Method. This must be modified to use the validation test - * @param buf the items array - * @param start data start - * @param length items array length - * @param random instance of Random - */ - //NOTE For validation Method: Need to modify to run. - private static void randomlyHalveDownLongs(final long[] buf, final int start, final int length, - final Random random) { - assert isEven(length); - final int half_length = length / 2; - final int offset = random.nextInt(2); // disable for validation - //final int offset = deterministicOffset(); // enable for validation - int j = start + offset; - for (int i = start; i < (start + half_length); i++) { - buf[i] = buf[j]; - j += 2; - } - } - - /** - * Validation Method. This must be modified to use the validation test - * @param buf the items array - * @param start data start - * @param length items array length - * @param random instance of Random - */ - //NOTE For validation Method: Need to modify to run. - private static void randomlyHalveUpLongs(final long[] buf, final int start, final int length, - final Random random) { - assert isEven(length); - final int half_length = length / 2; - final int offset = random.nextInt(2); // disable for validation - //final int offset = deterministicOffset(); // enable for validation - int j = (start + length) - 1 - offset; - for (int i = (start + length) - 1; i >= (start + half_length); i--) { - buf[i] = buf[j]; - j -= 2; - } - } - - /** - * Compression algorithm used to merge higher levels. - * - *

Here is what we do for each level:

- *
  • If it does not need to be compacted, then simply copy it over.
  • - *
  • Otherwise, it does need to be compacted, so... - *
    • Copy zero or one guy over.
    • - *
    • If the level above is empty, halve up.
    • - *
    • Else the level above is nonempty, so halve down, then merge up.
    • - *
  • - *
  • Adjust the boundaries of the level above.
  • - *
- * - *

It can be proved that generalCompress returns a sketch that satisfies the space constraints - * no matter how much data is passed in. - * We are pretty sure that it works correctly when inBuf and outBuf are the same. - * All levels except for level zero must be sorted before calling this, and will still be - * sorted afterwards. - * Level zero is not required to be sorted before, and may not be sorted afterwards.

- * - *

This trashes inBuf and inLevels and modifies outBuf and outLevels.

- * - * @param k The sketch parameter k - * @param m The minimum level size - * @param numLevelsIn provisional number of number of levels = max(this.numLevels, other.numLevels) - * @param inBuf work buffer of size = this.getNumRetained() + other.getNumRetainedAboveLevelZero(). - * This contains the long[] of the other sketch - * @param inLevels work levels array size = ubOnNumLevels(this.n + other.n) + 2 - * @param outBuf the same array as inBuf - * @param outLevels the same size as inLevels - * @param isLevelZeroSorted true if this.level 0 is sorted - * @param random instance of java.util.Random - * @return int array of: {numLevels, targetItemCount, currentItemCount) - */ - // - private static int[] generalLongsCompress( - final int k, - final int m, - final int numLevelsIn, - final long[] inBuf, - final int[] inLevels, - final long[] outBuf, - final int[] outLevels, - final boolean isLevelZeroSorted, - final Random random) { - assert numLevelsIn > 0; // things are too weird if zero levels are allowed - int numLevels = numLevelsIn; - int currentItemCount = inLevels[numLevels] - inLevels[0]; // decreases with each compaction - int targetItemCount = KllHelper.computeTotalItemCapacity(k, m, numLevels); // increases if we add levels - boolean doneYet = false; - outLevels[0] = 0; - int curLevel = -1; - while (!doneYet) { - curLevel++; // start out at level 0 - - // If we are at the current top level, add an empty level above it for convenience, - // but do not actually increment numLevels until later - if (curLevel == (numLevels - 1)) { - inLevels[curLevel + 2] = inLevels[curLevel + 1]; - } - - final int rawBeg = inLevels[curLevel]; - final int rawLim = inLevels[curLevel + 1]; - final int rawPop = rawLim - rawBeg; - - if ((currentItemCount < targetItemCount) || (rawPop < KllHelper.levelCapacity(k, numLevels, curLevel, m))) { - // copy level over as is - // because inBuf and outBuf could be the same, make sure we are not moving data upwards! - assert (rawBeg >= outLevels[curLevel]); - System.arraycopy(inBuf, rawBeg, outBuf, outLevels[curLevel], rawPop); - outLevels[curLevel + 1] = outLevels[curLevel] + rawPop; - } - else { - // The sketch is too full AND this level is too full, so we compact it - // Note: this can add a level and thus change the sketch's capacity - - final int popAbove = inLevels[curLevel + 2] - rawLim; - final boolean oddPop = isOdd(rawPop); - final int adjBeg = oddPop ? 1 + rawBeg : rawBeg; - final int adjPop = oddPop ? rawPop - 1 : rawPop; - final int halfAdjPop = adjPop / 2; - - if (oddPop) { // copy one guy over - outBuf[outLevels[curLevel]] = inBuf[rawBeg]; - outLevels[curLevel + 1] = outLevels[curLevel] + 1; - } else { // copy zero guys over - outLevels[curLevel + 1] = outLevels[curLevel]; - } - - // level zero might not be sorted, so we must sort it if we wish to compact it - if ((curLevel == 0) && !isLevelZeroSorted) { - Arrays.sort(inBuf, adjBeg, adjBeg + adjPop); - } - - if (popAbove == 0) { // Level above is empty, so halve up - randomlyHalveUpLongs(inBuf, adjBeg, adjPop, random); - } else { // Level above is nonempty, so halve down, then merge up - randomlyHalveDownLongs(inBuf, adjBeg, adjPop, random); - mergeSortedLongArrays(inBuf, adjBeg, halfAdjPop, inBuf, rawLim, popAbove, inBuf, adjBeg + halfAdjPop); - } - - // track the fact that we just eliminated some data - currentItemCount -= halfAdjPop; - - // Adjust the boundaries of the level above - inLevels[curLevel + 1] = inLevels[curLevel + 1] - halfAdjPop; - - // Increment numLevels if we just compacted the old top level - // This creates some more capacity (the size of the new bottom level) - if (curLevel == (numLevels - 1)) { - numLevels++; - targetItemCount += KllHelper.levelCapacity(k, numLevels, 0, m); - } - } // end of code for compacting a level - - // determine whether we have processed all levels yet (including any new levels that we created) - if (curLevel == (numLevels - 1)) { doneYet = true; } - } // end of loop over levels - - assert (outLevels[numLevels] - outLevels[0]) == currentItemCount; - return new int[] {numLevels, targetItemCount, currentItemCount}; - } - - private static void populateLongWorkArrays( //workBuf and workLevels are modified - final long[] workBuf, final int[] workLevels, final int provisionalNumLevels, - final int myCurNumLevels, final int[] myCurLevelsArr, final long[] myCurLongItemsArr, - final int otherNumLevels, final int[] otherLevelsArr, final long[] otherLongItemsArr) { - - workLevels[0] = 0; - - // Note: the level zero data from "other" was already inserted into "self". - // This copies into workbuf. - final int selfPopZero = KllHelper.currentLevelSizeItems(0, myCurNumLevels, myCurLevelsArr); - System.arraycopy(myCurLongItemsArr, myCurLevelsArr[0], workBuf, workLevels[0], selfPopZero); - workLevels[1] = workLevels[0] + selfPopZero; - - for (int lvl = 1; lvl < provisionalNumLevels; lvl++) { - final int selfPop = KllHelper.currentLevelSizeItems(lvl, myCurNumLevels, myCurLevelsArr); - final int otherPop = KllHelper.currentLevelSizeItems(lvl, otherNumLevels, otherLevelsArr); - workLevels[lvl + 1] = workLevels[lvl] + selfPop + otherPop; - assert (selfPop >= 0) && (otherPop >= 0); - if ((selfPop == 0) && (otherPop == 0)) { continue; } - if ((selfPop > 0) && (otherPop == 0)) { - System.arraycopy(myCurLongItemsArr, myCurLevelsArr[lvl], workBuf, workLevels[lvl], selfPop); - } - else if ((selfPop == 0) && (otherPop > 0)) { - System.arraycopy(otherLongItemsArr, otherLevelsArr[lvl], workBuf, workLevels[lvl], otherPop); - } - else if ((selfPop > 0) && (otherPop > 0)) { - mergeSortedLongArrays( //only workBuf is modified - myCurLongItemsArr, myCurLevelsArr[lvl], selfPop, - otherLongItemsArr, otherLevelsArr[lvl], otherPop, - workBuf, workLevels[lvl]); - } - } - } - - /* - * Validation Method. - * The following must be enabled for use with the KllDoublesValidationTest, - * which is only enabled for manual testing. In addition, two Validation Methods - * above need to be modified. - */ //NOTE Validation Method: Need to uncomment to use - // static int nextOffset = 0; - // - // private static int deterministicOffset() { - // final int result = nextOffset; - // nextOffset = 1 - nextOffset; - // return result; - // } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllLongsSketch.java b/src/main/java/org/apache/datasketches/kll/KllLongsSketch.java deleted file mode 100644 index 4826d8392..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllLongsSketch.java +++ /dev/null @@ -1,673 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.apache.datasketches.common.ByteArrayUtil.putLongLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_LONGS_SKETCH; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Objects; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.LongsSketchSortedView; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; -import org.apache.datasketches.quantilescommon.QuantilesLongsAPI; -import org.apache.datasketches.quantilescommon.QuantilesLongsSketchIterator; - -/** - * This variation of the KllSketch implements primitive longs. - * - * @see org.apache.datasketches.kll.KllSketch - */ -public abstract class KllLongsSketch extends KllSketch implements QuantilesLongsAPI { - private LongsSketchSortedView longsSV = null; - final static int ITEM_BYTES = Long.BYTES; - - /** - * Constructor for on-heap. - * @param sketchStructure the current sketch structure - */ - KllLongsSketch(final SketchStructure sketchStructure) { - super(SketchType.KLL_LONGS_SKETCH, sketchStructure); - } - - /** - * Constructor for MemorySegment based sketch - * @param segVal MemorySegment validator. - */ - KllLongsSketch(final KllMemorySegmentValidate segVal) { - super(segVal); - } - - //Factories for new heap instances. - - /** - * Create a new heap instance of this sketch with the default k = 200. - * The default k = 200 results in a normalized rank error of about - * 1.65%. Larger K will have smaller error but the sketch will be larger (and slower). - * @return new KllLongsSketch on the Java heap. - */ - public static KllLongsSketch newHeapInstance() { - return newHeapInstance(DEFAULT_K); - } - - /** - * Create a new heap instance of this sketch with a given parameter k. - * k can be between 8, inclusive, and 65535, inclusive. - * The default k = 200 results in a normalized rank error of about - * 1.65%. Larger K will have smaller error but the sketch will be larger (and slower). - * @param k parameter that controls size of the sketch and accuracy of estimates. - * @return new KllLongsSketch on the Java heap. - */ - public static KllLongsSketch newHeapInstance(final int k) { - return new KllHeapLongsSketch(k, DEFAULT_M); - } - - //Factories for new direct instances. - - /** - * Create a new direct updatable instance of this sketch with the default k. - * The default k = 200 results in a normalized rank error of about - * 1.65%. Larger k will have smaller error but the sketch will be larger (and slower). - * @param dstSeg the given destination MemorySegment object for use by the sketch - * @return a new direct instance of this sketch - */ - public static KllLongsSketch newDirectInstance(final MemorySegment dstSeg) { - return newDirectInstance(DEFAULT_K, dstSeg, null); - } - - /** - * Create a new direct updatable instance of this sketch with a given k. - * @param k parameter that controls size of the sketch and accuracy of estimates. - * @param dstSeg the given destination MemorySegment object for use by the sketch - * @param mSegReq the callback for the sketch to request a larger MemorySegment. It may be null. - * @return a new direct instance of this sketch - */ - public static KllLongsSketch newDirectInstance( - final int k, - final MemorySegment dstSeg, - final MemorySegmentRequest mSegReq) { - Objects.requireNonNull(dstSeg, "Parameter 'dstSeg' must not be null"); - return KllDirectLongsSketch.newDirectUpdatableInstance(k, DEFAULT_M, dstSeg, mSegReq); - } - - //Factory to create an heap instance from a MemorySegment image - - /** - * Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch. - * The resulting sketch will not retain any link to the source MemorySegment. - * @param srcSeg a compact MemorySegment image of a sketch serialized by this sketch. - * @return a heap-based sketch based on the given MemorySegment. - */ - public static KllLongsSketch heapify(final MemorySegment srcSeg) { - Objects.requireNonNull(srcSeg, "Parameter 'srcSeg' must not be null"); - return KllHeapLongsSketch.heapifyImpl(srcSeg); - } - - //Factories to wrap a MemorySegment image - - /** - * Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch. - * - *

The given MemorySegment must be writable and it must contain a KllLongsSketch in updatable form. - * The sketch will be updated and managed totally within the MemorySegment. If the given source - * MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

- * - *

NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch - * will request more capacity using the {@link MemorySegmentRequest MemorySegmentRequest} interface. The default of this interface will - * return a new MemorySegment on the heap.

- * - * @param srcSeg a MemorySegment that contains sketch data. - * @return an instance of this sketch that wraps the given MemorySegment. - */ - public static KllLongsSketch wrap(final MemorySegment srcSeg) { - return wrap(srcSeg, null); - } - - /** - * Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch and including an - * optional, user defined {@link MemorySegmentRequest MemorySegmentRequest}. - * - *

The given MemorySegment must be writable and it must contain a KllLongsSketch in updatable form. - * The sketch will be updated and managed totally within the MemorySegment. If the given source - * MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

- * - *

NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch - * will request more capacity using the {@link MemorySegmentRequest MemorySegmentRequest} interface. The default of this interface will - * return a new MemorySegment on the heap. It is up to the user to optionally extend this interface if more flexible - * handling of requests for more capacity is required.

- * - * @param srcSeg a MemorySegment that contains sketch data. - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return an instance of this sketch that wraps the given MemorySegment. - */ - public static KllLongsSketch wrap(final MemorySegment srcSeg, final MemorySegmentRequest mSegReq) { - Objects.requireNonNull(srcSeg, "Parameter 'srcSeg' must not be null"); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(srcSeg, KLL_LONGS_SKETCH); - return new KllDirectLongsSketch(srcSeg, segVal, mSegReq); - } - - //END of Constructors - - @Override - public double[] getCDF(final long[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return longsSV.getCDF(splitPoints, searchCrit); - } - - @Override - public double[] getPMF(final long[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return longsSV.getPMF(splitPoints, searchCrit); - } - - @Override - public long getQuantile(final double rank, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return longsSV.getQuantile(rank, searchCrit); - } - - @Override - public long[] getQuantiles(final double[] ranks, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - final int len = ranks.length; - final long[] quantiles = new long[len]; - for (int i = 0; i < len; i++) { - quantiles[i] = longsSV.getQuantile(ranks[i], searchCrit); - } - return quantiles; - } - - /** - * {@inheritDoc} - * The approximate probability that the true quantile is within the confidence interval - * specified by the upper and lower quantile bounds for this sketch is 0.99. - */ - @Override - public long getQuantileLowerBound(final double rank) { - return getQuantile(max(0, rank - KllHelper.getNormalizedRankError(getMinK(), false))); - } - - /** - * {@inheritDoc} - * The approximate probability that the true quantile is within the confidence interval - * specified by the upper and lower quantile bounds for this sketch is 0.99. - */ - @Override - public long getQuantileUpperBound(final double rank) { - return getQuantile(min(1.0, rank + KllHelper.getNormalizedRankError(getMinK(), false))); - } - - @Override - public double getRank(final long quantile, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - return longsSV.getRank(quantile, searchCrit); - } - - /** - * {@inheritDoc} - * The approximate probability that the true rank is within the confidence interval - * specified by the upper and lower rank bounds for this sketch is 0.99. - */ - @Override - public double getRankLowerBound(final double rank) { - return max(0.0, rank - KllHelper.getNormalizedRankError(getMinK(), false)); - } - - /** - * {@inheritDoc} - * The approximate probability that the true rank is within the confidence interval - * specified by the upper and lower rank bounds for this sketch is 0.99. - */ - @Override - public double getRankUpperBound(final double rank) { - return min(1.0, rank + KllHelper.getNormalizedRankError(getMinK(), false)); - } - - @Override - public double[] getRanks(final long[] quantiles, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - refreshSortedView(); - final int len = quantiles.length; - final double[] ranks = new double[len]; - for (int i = 0; i < len; i++) { - ranks[i] = longsSV.getRank(quantiles[i], searchCrit); - } - return ranks; - } - - @Override - public QuantilesLongsSketchIterator iterator() { - return new KllLongsSketchIterator( - getLongItemsArray(), getLevelsArray(SketchStructure.UPDATABLE), getNumLevels()); - } - - @Override - public final void merge(final KllSketch other) { - if (readOnly || (sketchStructure != UPDATABLE)) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - if (this == other) { throw new SketchesArgumentException(SELF_MERGE_MSG); } - final KllLongsSketch otherLngSk = (KllLongsSketch)other; - if (otherLngSk.isEmpty()) { return; } - KllLongsHelper.mergeLongsImpl(this, otherLngSk); - longsSV = null; - } - - /** - * {@inheritDoc} - * - *

The parameter k will not change.

- */ - @Override - public final void reset() { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - final int k = getK(); - setN(0); - setMinK(k); - setNumLevels(1); - setLevelZeroSorted(false); - setLevelsArray(new int[] {k, k}); - setMinItem(Long.MAX_VALUE); - setMaxItem(Long.MIN_VALUE); - setLongItemsArray(new long[k]); - longsSV = null; - } - - @Override - public byte[] toByteArray() { - return KllHelper.toByteArray(this, false); - } - - @Override - public String toString(final boolean withLevels, final boolean withLevelsAndItems) { - KllSketch sketch = this; - if (withLevelsAndItems && (sketchStructure != UPDATABLE)) { - final MemorySegment seg = getMemorySegment(); - assert seg != null; - sketch = KllLongsSketch.heapify(getMemorySegment()); - } - return KllHelper.toStringImpl(sketch, withLevels, withLevelsAndItems); - } - - //SINGLE UPDATE - - @Override - public void update(final long item) { - // Align with KllDoublesSketch - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - updateLong(this, item); - longsSV = null; - } - - //Also Called from KllLongsHelper::merge - static void updateLong(final KllLongsSketch lngSk, final long item) { - lngSk.updateMinMax(item); - int freeSpace = lngSk.levelsArr[0]; - assert (freeSpace >= 0); - if (freeSpace == 0) { - KllLongsHelper.compressWhileUpdatingSketch(lngSk); - freeSpace = lngSk.levelsArr[0]; - assert (freeSpace > 0); - } - lngSk.incN(1); - lngSk.setLevelZeroSorted(false); - final int nextPos = freeSpace - 1; - lngSk.setLevelsArrayAt(0, nextPos); - lngSk.setLongItemsArrayAt(nextPos, item); - } - - /** - * Single update of min and max - * @param item the source item, it must not be a NaN. - */ - final void updateMinMax(final long item) { - if (isEmpty()) { - setMinItem(item); - setMaxItem(item); - } else { - setMinItem(min(getMinItemInternal(), item)); - setMaxItem(max(getMaxItemInternal(), item)); - } - } - - //WEIGHTED UPDATE - - /** - * Weighted update. Updates this sketch with the given item the number of times specified by the given integer weight. - * @param item the item to be repeated. - * @param weight the number of times the update of item is to be repeated. It must be ≥ one. - */ - public void update(final long item, final long weight) { - // - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - if (weight < 1L) { throw new SketchesArgumentException("Weight is less than one."); } - if (weight == 1L) { updateLong(this, item); } - else if (weight < levelsArr[0]) { - for (int i = 0; i < (int)weight; i++) { updateLong(this, item); } - } else { - final KllHeapLongsSketch tmpSk = new KllHeapLongsSketch(getK(), DEFAULT_M, item, weight); - merge(tmpSk); - } - longsSV = null; - } - - // VECTOR UPDATE - - /** - * Vector update. Updates this sketch with the given array (vector) of items, starting at the items - * offset for a length number of items. This is not supported for direct sketches. - * @param items the vector of items - * @param offset the starting index of the items[] array - * @param length the number of items - */ - public void update(final long[] items, final int offset, final int length) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - if (length == 0) { return; } - updateLong(items, offset, length); - longsSV = null; - } - /* Align with KllDoublesSketch & KllFloatsSketch - - - - - - - - - - - - - - - */ - private void updateLong(final long[] srcItems, final int srcOffset, final int length) { - if (isEmpty()) { - setMinItem(srcItems[srcOffset]); //initialize with a real value - setMaxItem(srcItems[srcOffset]); - } - - int count = 0; - while (count < length) { - if (levelsArr[0] == 0) { - KllLongsHelper.compressWhileUpdatingSketch(this); - } - final int spaceNeeded = length - count; - final int freeSpace = levelsArr[0]; - assert (freeSpace > 0); - final int numItemsToCopy = min(spaceNeeded, freeSpace); - final int dstOffset = freeSpace - numItemsToCopy; - final int localSrcOffset = srcOffset + count; - setLongItemsArrayAt(dstOffset, srcItems, localSrcOffset, numItemsToCopy); - updateMinMax(srcItems, localSrcOffset, numItemsToCopy); - count += numItemsToCopy; - incN(numItemsToCopy); - setLevelsArrayAt(0, dstOffset); - } - setLevelZeroSorted(false); - } - - /** - * Vector update of min and max. - * @param srcItems the input source array of values, no NaNs allowed. - * @param srcOffset the starting offset in srcItems - * @param length the number of items to update min and max - */ - private void updateMinMax(final long[] srcItems, final int srcOffset, final int length) { - final int end = srcOffset + length; - for (int i = srcOffset; i < end; i++) { - setMinItem(min(getMinItemInternal(), srcItems[i])); - setMaxItem(max(getMaxItemInternal(), srcItems[i])); - } - } - /* Align with KllDoublesSketch & KllFloatsSketch - - - - - - - - - */ - // END ALL UPDATE METHODS - - /** - * @return full size of internal items array including empty space at bottom. - */ - abstract long[] getLongItemsArray(); - - /** - * @return items array of retained items. - */ - abstract long[] getLongRetainedItemsArray(); - - abstract long getLongSingleItem(); - - // Min & Max Methods - - abstract long getMaxItemInternal(); - - abstract void setMaxItem(long item); - - abstract long getMinItemInternal(); - - abstract void setMinItem(long item); - - @Override - abstract byte[] getMinMaxByteArr(); - - @Override - int getMinMaxSizeBytes() { - return Long.BYTES * 2; - } - - //END Min & Max Methods - - @Override - abstract byte[] getRetainedItemsByteArr(); - - @Override - int getRetainedItemsSizeBytes() { - return getNumRetained() * Long.BYTES; - } - - @Override - ArrayOfItemsSerDe getSerDe() { return null; } - - @Override - final byte[] getSingleItemByteArr() { - final byte[] bytes = new byte[ITEM_BYTES]; - putLongLE(bytes, 0, getLongSingleItem()); - return bytes; - } - - @Override - int getSingleItemSizeBytes() { - return Long.BYTES; - } - - @Override - abstract byte[] getTotalItemsByteArr(); - - @Override - int getTotalItemsNumBytes() { - return levelsArr[getNumLevels()] * Long.BYTES; - } - - abstract void setLongItemsArray(long[] longItems); - - abstract void setLongItemsArrayAt(int index, long item); - - abstract void setLongItemsArrayAt(int dstIndex, long[] srcItems, int srcOffset, int length); - - // SORTED VIEW - - @Override - public LongsSketchSortedView getSortedView() { - refreshSortedView(); - return longsSV; - } - - private final LongsSketchSortedView refreshSortedView() { - if (longsSV == null) { - final CreateSortedView csv = new CreateSortedView(); - longsSV = csv.getSV(); - } - return longsSV; - } - - private final class CreateSortedView { - long[] quantiles; - long[] cumWeights; - - LongsSketchSortedView getSV() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - final long[] srcQuantiles = getLongItemsArray(); - final int[] srcLevels = levelsArr; - final int srcNumLevels = getNumLevels(); - - if (!isLevelZeroSorted()) { - Arrays.sort(srcQuantiles, srcLevels[0], srcLevels[1]); - if (!hasMemorySegment()) { setLevelZeroSorted(true); } - //we don't sort level0 in MemorySegment, only our copy. - } - final int numQuantiles = getNumRetained(); - quantiles = new long[numQuantiles]; - cumWeights = new long[numQuantiles]; - populateFromSketch(srcQuantiles, srcLevels, srcNumLevels, numQuantiles); - return new LongsSketchSortedView(quantiles, cumWeights, KllLongsSketch.this); - } - - private void populateFromSketch(final long[] srcQuantiles, final int[] srcLevels, - final int srcNumLevels, final int numItems) { - final int[] myLevels = new int[srcNumLevels + 1]; - final int offset = srcLevels[0]; - System.arraycopy(srcQuantiles, offset, quantiles, 0, numItems); - int srcLevel = 0; - int dstLevel = 0; - long weight = 1; - while (srcLevel < srcNumLevels) { - final int fromIndex = srcLevels[srcLevel] - offset; - final int toIndex = srcLevels[srcLevel + 1] - offset; // exclusive - if (fromIndex < toIndex) { // if equal, skip empty level - Arrays.fill(cumWeights, fromIndex, toIndex, weight); - myLevels[dstLevel] = fromIndex; - myLevels[dstLevel + 1] = toIndex; - dstLevel++; - } - srcLevel++; - weight *= 2; - } - final int numLevels = dstLevel; - blockyTandemMergeSort(quantiles, cumWeights, myLevels, numLevels); //create unit weights - KllHelper.convertToCumulative(cumWeights); - } - } //End of class CreateSortedView - - private static void blockyTandemMergeSort(final long[] quantiles, final long[] weights, - final int[] levels, final int numLevels) { - if (numLevels == 1) { return; } - - // duplicate the input in preparation for the "ping-pong" copy reduction strategy. - final long[] quantilesTmp = Arrays.copyOf(quantiles, quantiles.length); - final long[] weightsTmp = Arrays.copyOf(weights, quantiles.length); // don't need the extra one - - blockyTandemMergeSortRecursion(quantilesTmp, weightsTmp, quantiles, weights, levels, 0, numLevels); - } - - private static void blockyTandemMergeSortRecursion( - final long[] quantilesSrc, final long[] weightsSrc, - final long[] quantilesDst, final long[] weightsDst, - final int[] levels, final int startingLevel, final int numLevels) { - if (numLevels == 1) { return; } - final int numLevels1 = numLevels / 2; - final int numLevels2 = numLevels - numLevels1; - assert numLevels1 >= 1; - assert numLevels2 >= numLevels1; - final int startingLevel1 = startingLevel; - final int startingLevel2 = startingLevel + numLevels1; - // swap roles of src and dst - blockyTandemMergeSortRecursion( - quantilesDst, weightsDst, - quantilesSrc, weightsSrc, - levels, startingLevel1, numLevels1); - blockyTandemMergeSortRecursion( - quantilesDst, weightsDst, - quantilesSrc, weightsSrc, - levels, startingLevel2, numLevels2); - tandemMerge( - quantilesSrc, weightsSrc, - quantilesDst, weightsDst, - levels, - startingLevel1, numLevels1, - startingLevel2, numLevels2); - } - - private static void tandemMerge( - final long[] quantilesSrc, final long[] weightsSrc, - final long[] quantilesDst, final long[] weightsDst, - final int[] levelStarts, - final int startingLevel1, final int numLevels1, - final int startingLevel2, final int numLevels2) { - final int fromIndex1 = levelStarts[startingLevel1]; - final int toIndex1 = levelStarts[startingLevel1 + numLevels1]; // exclusive - final int fromIndex2 = levelStarts[startingLevel2]; - final int toIndex2 = levelStarts[startingLevel2 + numLevels2]; // exclusive - int iSrc1 = fromIndex1; - int iSrc2 = fromIndex2; - int iDst = fromIndex1; - - while ((iSrc1 < toIndex1) && (iSrc2 < toIndex2)) { - if (quantilesSrc[iSrc1] < quantilesSrc[iSrc2]) { - quantilesDst[iDst] = quantilesSrc[iSrc1]; - weightsDst[iDst] = weightsSrc[iSrc1]; - iSrc1++; - } else { - quantilesDst[iDst] = quantilesSrc[iSrc2]; - weightsDst[iDst] = weightsSrc[iSrc2]; - iSrc2++; - } - iDst++; - } - if (iSrc1 < toIndex1) { - System.arraycopy(quantilesSrc, iSrc1, quantilesDst, iDst, toIndex1 - iSrc1); - System.arraycopy(weightsSrc, iSrc1, weightsDst, iDst, toIndex1 - iSrc1); - } else if (iSrc2 < toIndex2) { - System.arraycopy(quantilesSrc, iSrc2, quantilesDst, iDst, toIndex2 - iSrc2); - System.arraycopy(weightsSrc, iSrc2, weightsDst, iDst, toIndex2 - iSrc2); - } - } - - // END SORTED VIEW - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllLongsSketchIterator.java b/src/main/java/org/apache/datasketches/kll/KllLongsSketchIterator.java deleted file mode 100644 index 8922ec70e..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllLongsSketchIterator.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import org.apache.datasketches.quantilescommon.QuantilesLongsSketchIterator; - -/** - * Iterator over KllLongsSketch. The order is not defined. - */ -public final class KllLongsSketchIterator extends KllSketchIterator implements QuantilesLongsSketchIterator { - private final long[] quantiles; - - KllLongsSketchIterator(final long[] quantiles, final int[] levelsArr, final int numLevels) { - super(levelsArr, numLevels); - this.quantiles = quantiles; - } - - @Override - public long getQuantile() { - return quantiles[index]; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllMemorySegmentValidate.java b/src/main/java/org/apache/datasketches/kll/KllMemorySegmentValidate.java deleted file mode 100644 index 33f6904ec..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllMemorySegmentValidate.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR_SINGLE_ITEM; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentEmptyFlag; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentFamilyID; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentFlags; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentK; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentLevelZeroSortedFlag; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentM; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentMinK; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentN; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentNumLevels; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentPreInts; -import static org.apache.datasketches.kll.KllPreambleUtil.getMemorySegmentSerVer; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_DOUBLES_SKETCH; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_FLOATS_SKETCH; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_ITEMS_SKETCH; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ArrayOfBooleansSerDe; -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllSketch.SketchStructure; -import org.apache.datasketches.kll.KllSketch.SketchType; - -/** - * This class performs all the error checking of an incoming MemorySegment object and extracts the key fields in the process. - * This is used by all KLL sketches that read or import MemorySegment objects. - * @author lrhodes - * - */ -final class KllMemorySegmentValidate { - final MemorySegment srcSeg; - final ArrayOfItemsSerDe serDe; - final SketchType sketchType; - final SketchStructure sketchStructure; - - // first 8 bytes of preamble - final int preInts; //used by KllPreambleUtil - final int serVer; //used by KllPreambleUtil - final int familyID; //used by KllPreambleUtil - final int flags; //used by KllPreambleUtil - final int k; //used multiple places - final int m; //used multiple places - //byte 7 is unused - - //Flag bits: - final boolean emptyFlag; //used multiple places - final boolean level0SortedFlag; //used multiple places - - // depending on the layout, the next 8-16 bytes of the preamble, may be derived by assumption. - // For example, if the layout is compact & empty, n = 0, if compact and single, n = 1. - long n; //8 bytes (if present), used multiple places - int minK; //2 bytes (if present), used multiple places - int numLevels; //1 byte (if present), used by KllPreambleUtil - //skip unused byte - int[] levelsArr; //starts at byte 20, adjusted to include top index here, used multiple places - - // derived. - int sketchBytes = 0; //used by KllPreambleUtil - private int typeBytes = 0; //always 0 for generic - - KllMemorySegmentValidate(final MemorySegment srcSeg, final SketchType sketchType) { - this(srcSeg, sketchType, null); - } - - KllMemorySegmentValidate(final MemorySegment srcSeg, final SketchType sketchType, final ArrayOfItemsSerDe serDe) { - final long segCapBytes = srcSeg.byteSize(); - if (segCapBytes < 8) { throw new SketchesArgumentException(MEMORY_TOO_SMALL + segCapBytes); } - this.srcSeg = srcSeg; - this.sketchType = sketchType; - this.serDe = serDe; - preInts = getMemorySegmentPreInts(srcSeg); - serVer = getMemorySegmentSerVer(srcSeg); - sketchStructure = SketchStructure.getSketchStructure(preInts, serVer); - familyID = getMemorySegmentFamilyID(srcSeg); - if (familyID != Family.KLL.getID()) { throw new SketchesArgumentException(SRC_NOT_KLL + familyID); } - flags = getMemorySegmentFlags(srcSeg); - k = getMemorySegmentK(srcSeg); - m = getMemorySegmentM(srcSeg); - KllHelper.checkM(m); - KllHelper.checkK(k, m); - //flags - emptyFlag = getMemorySegmentEmptyFlag(srcSeg); - level0SortedFlag = getMemorySegmentLevelZeroSortedFlag(srcSeg); - if (sketchType == KLL_DOUBLES_SKETCH) { typeBytes = Double.BYTES; } - else if (sketchType == KLL_FLOATS_SKETCH) { typeBytes = Float.BYTES; } - else { typeBytes = 0; } - validate(); - } - - private void validate() { - - switch (sketchStructure) { - case COMPACT_FULL: { - if (emptyFlag) { throw new SketchesArgumentException(EMPTY_FLAG_AND_COMPACT_FULL); } - n = getMemorySegmentN(srcSeg); - minK = getMemorySegmentMinK(srcSeg); - numLevels = getMemorySegmentNumLevels(srcSeg); - // Get Levels Arr and add the last element - levelsArr = new int[numLevels + 1]; - MemorySegment.copy(srcSeg, JAVA_INT_UNALIGNED, DATA_START_ADR, levelsArr, 0, numLevels); //copies all except the last one - final int capacityItems = KllHelper.computeTotalItemCapacity(k, m, numLevels); - levelsArr[numLevels] = capacityItems; //load the last one - sketchBytes = computeSketchBytes(srcSeg, sketchType, levelsArr, false, serDe); - break; - } - case COMPACT_EMPTY: { - if (!emptyFlag) { throw new SketchesArgumentException(EMPTY_FLAG_AND_COMPACT_EMPTY); } - n = 0; //assumed - minK = k; //assumed - numLevels = 1; //assumed - levelsArr = new int[] {k, k}; - sketchBytes = DATA_START_ADR_SINGLE_ITEM; - break; - } - case COMPACT_SINGLE: { - if (emptyFlag) { throw new SketchesArgumentException(EMPTY_FLAG_AND_COMPACT_SINGLE); } - n = 1; //assumed - minK = k; //assumed - numLevels = 1; //assumed - levelsArr = new int[] {k - 1, k}; - if (sketchType == KLL_ITEMS_SKETCH) { - sketchBytes = DATA_START_ADR_SINGLE_ITEM + serDe.sizeOf(srcSeg, DATA_START_ADR_SINGLE_ITEM, 1); - } else { - sketchBytes = DATA_START_ADR_SINGLE_ITEM + typeBytes; - } - break; - } - case UPDATABLE: { - n = getMemorySegmentN(srcSeg); - minK = getMemorySegmentMinK(srcSeg); - numLevels = getMemorySegmentNumLevels(srcSeg); - levelsArr = new int[numLevels + 1]; - MemorySegment.copy(srcSeg, JAVA_INT_UNALIGNED, DATA_START_ADR, levelsArr, 0, numLevels + 1); - - - sketchBytes = computeSketchBytes(srcSeg, sketchType, levelsArr, true, serDe); - break; - } - default: break; //can not happen - } - } - - static int computeSketchBytes( //for COMPACT_FULL or UPDATABLE only - final MemorySegment srcSeg, - final SketchType sketchType, - final int[] levelsArr, //full levels array - final boolean updatable, - final ArrayOfItemsSerDe serDe) { //serDe only valid for ITEMS_SKETCH - final int numLevels = levelsArr.length - 1; - final int capacityItems = levelsArr[numLevels]; - final int retainedItems = (levelsArr[numLevels] - levelsArr[0]); - final int levelsLen = updatable ? levelsArr.length : levelsArr.length - 1; - final int numItems = updatable ? capacityItems : retainedItems; - - int offsetBytes = DATA_START_ADR + (levelsLen * Integer.BYTES); //levels array - if (sketchType == KLL_ITEMS_SKETCH) { - if (serDe instanceof ArrayOfBooleansSerDe) { - offsetBytes += serDe.sizeOf(srcSeg, offsetBytes, numItems) + 2; //2 for min & max - } else { - offsetBytes += serDe.sizeOf(srcSeg, offsetBytes, numItems + 2); //2 for min & max - } - } else { - final int typeBytes = sketchType.getBytes(); - offsetBytes += (numItems + 2) * typeBytes; //2 for min & max - } - return offsetBytes; - } - - static final String EMPTY_FLAG_AND_COMPACT_EMPTY = "A compact empty sketch should have empty flag set. "; - static final String EMPTY_FLAG_AND_COMPACT_FULL = "A compact full sketch should not have empty flag set. "; - static final String EMPTY_FLAG_AND_COMPACT_SINGLE = "A single item sketch should not have empty flag set. "; - //static final String N_AND_COMPACT_FULL = "A compact full sketch should have n > 1. "; - static final String SRC_NOT_KLL = "FamilyID Field must be: " + Family.KLL.getID() + ", NOT: "; - static final String MEMORY_TOO_SMALL = "A sketch MemorySegment image must be at least 8 bytes. "; - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllPreambleUtil.java b/src/main/java/org/apache/datasketches/kll/KllPreambleUtil.java deleted file mode 100644 index e7df5cfd6..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllPreambleUtil.java +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.common.Family.idToFamily; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.zeroPad; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_DOUBLES_SKETCH; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_FLOATS_SKETCH; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_ITEMS_SKETCH; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_LONGS_SKETCH; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.kll.KllSketch.SketchStructure; -import org.apache.datasketches.kll.KllSketch.SketchType; - -/** - * This class defines the serialized data structure and provides access methods for the preamble fields. - * - *

The intent of the design of this class was to isolate the detailed knowledge of the bit and - * byte layout of the serialized form of the sketches derived from the base sketch classes into one place. - * This allows the possibility of the introduction of different serialization - * schemes with minimal impact on the rest of the library.

- * - *

Visual Layout

- * The low significance bytes of the visual data structure below are on the left. - * The multi-byte primitives are stored in native byte order. - * The numeric byte and short fields are treated as unsigned. - * The numeric int and long fields are treated as signed. - * - *

Preamble Formats

- * The preamble has four formats: - * - *
    - *
  • The serialized empty compact structure requires 8 bytes of preamble. It is not updatable. - * It is identified by the enum SketchStructure.COMPACT_EMPTY.
  • - * - *
  • The serialized, single-item compact structure requires 8 bytes of preamble, followed by the one item. - * The size of this structure is 8 + itemSize bytes. It is not updatable. - * It is identified by the enum SketchStructure.COMPACT_SINGLE.
  • - * - *
  • A serialized, n > 1 compact structure requires 20 bytes of preamble (5 ints) followed by - * four variable-sized fields. The details of these fields can be found in the code and are illustrated - * in the table below. - * The 5 int preamble is followed by the levelsArr int[numLevels] as bytes, - * followed by the min and max values as bytes, - * followed by a packed items data array as bytes. There is no free space in this structure. - * It is not updatable. - * It is identified by the enum SketchStructure.COMPACT_FULL.
  • - * - *
  • A serialized, n > 1 non-compact, updatable structure requires 20 bytes of preamble (5 ints). - * This is followed by the LevelsArr int[NumLevels + 1], followed by the min and max values, and then - * followed by an items data array that may include free space. It is updatable. - * The details of these fields can be found in the code.. - * It is identified by the enum SketchStructure.UPDATABLE. This structure may not be implemented by - * some sketches.
  • - *
- * - *

Visual Layout

- * The fields in braces are those that can be variable in size. - * - *
{@code
- * Serialized COMPACT_EMPTY sketch structure, Empty (8 bytes)
- * and COMPACT_SINGLE sketch structure, (single item) (8 + itemSize):
- * Int Adr:   Byte Adr ->
- *    0     ||       0      |   1    |   2   |   3    |
- *          | PreambleInts  | SerVer | FamID | Flags  |
- *
- *    1     ||       4      |   5    |   6   |   7    |
- *          ||-----------K-----------|   M   | unused |
- *
- *    2     ||       8      |
- *          ||{Single Item} ->
- *
- * Serialized COMPACT_FULL sketch structure, more than one item:
- * Int Adr:   Byte Adr ->
- *    0     ||       0      |   1    |   2   |   3    |
- *          || PreambleInts | SerVer | FamID | Flags  |
- *
- *    1     ||       4      |   5    |   6   |   7    |
- *          ||-----------K-----------|   M   | unused |
- *
- *   2,3    || 8  | 9  | 10 | 11 | 12 | 13 | 14 | 15  |
- *          ||-----------------N_LONG-----------------|
- *
- *    4     ||      16      |   17   |  18   |  19    |
- *          ||------Min K------------|NumLvls| unused |
- *
- *    5     ||     20       |
- *            { Levels Array }
- *            {   Min Item   }
- *            {   Max Item   }
- *            { Items Array  }
- *
- * Serialization Combinations for SerVer and PreambleInts
- * | Sketch Structure | SerVer         | PreInts          |
- * |------------------|----------------|------------------|
- * | Compact Empty    | Empty/Full (1) | Empty/Single (2) | ReadOnly, 8 byte Preamble, nothing else
- * | Compact Single   | Single (2)     | Empty/Single (2) | ReadOnly, 8 byte Preamble + Single Item
- * | Compact Full     | Empty/Full (1) | Full (5)         | ReadOnly, 20 Byte Preamble, Short LevelsArr, Retained Items
- * | Updatable        | Updatable (3)  | Full (5)         | Updatable, 20 Byte Preamble, Full LevelsArr, All Items
- * | ERROR            | Single (2)     | Full (5)         |
- * | ERROR            | Updatable (3)  | Empty/Single (2) |
- * }
- * - * @author Lee Rhodes - */ -final class KllPreambleUtil { - - private KllPreambleUtil() {} - - // Preamble byte addresses - static final int PREAMBLE_INTS_BYTE_ADR = 0; - static final int SER_VER_BYTE_ADR = 1; - static final int FAMILY_BYTE_ADR = 2; - static final int FLAGS_BYTE_ADR = 3; - static final int K_SHORT_ADR = 4; // to 5 - static final int M_BYTE_ADR = 6; - // 7 is reserved for future use - // SINGLE ITEM ONLY - static final int DATA_START_ADR_SINGLE_ITEM = 8; //also ok for empty - - // MULTI-ITEM - static final int N_LONG_ADR = 8; // to 15 - static final int MIN_K_SHORT_ADR = 16; // to 17 - static final int NUM_LEVELS_BYTE_ADR = 18; - - // 19 is reserved for future use - static final int DATA_START_ADR = 20; // Full Sketch, not single item - - // Other static members - static final byte SERIAL_VERSION_EMPTY_FULL = 1; // Empty or full preamble, NOT single item format, NOT updatable - static final byte SERIAL_VERSION_SINGLE = 2; // only single-item format, NOT updatable - static final byte SERIAL_VERSION_UPDATABLE = 3; // PreInts=5, Full preamble + LevelsArr + min, max + empty space - static final byte PREAMBLE_INTS_EMPTY_SINGLE = 2; // for empty or single item - static final byte PREAMBLE_INTS_FULL = 5; // Full preamble, not empty nor single item. - static final byte KLL_FAMILY = 15; - - // Flag bit masks - static final int EMPTY_BIT_MASK = 1; - static final int LEVEL_ZERO_SORTED_BIT_MASK = 2; - static final int SINGLE_ITEM_BIT_MASK = 4; - - /** - * Returns a human readable string summary of the internal state of the given sketch byte array. - * Used primarily in testing. - * - * @param byteArr the given sketch byte array. - * @param includeData if true, includes detail of retained data. - * @return the summary string. - */ - static String toString(final byte[] byteArr, final SketchType sketchType, final boolean includeData) { - final MemorySegment seg = MemorySegment.ofArray(byteArr); - return toString(seg, sketchType, includeData, null); - } - - /** - * Returns a human readable string summary of the internal state of the given sketch byte array. - * Used primarily in testing. - * - * @param byteArr the given sketch byte array. - * @param includeData if true, includes detail of retained data. - * @param serDe the serialization/deserialization class, required for KllItemsSketch. - * @return the summary string. - */ - static String toString(final byte[] byteArr, final SketchType sketchType, final boolean includeData, - final ArrayOfItemsSerDe serDe) { - final MemorySegment seg = MemorySegment.ofArray(byteArr); - return toString(seg, sketchType, includeData, serDe); - } - - /** - * Returns a human readable string summary of the internal state of the given MemorySegment. - * Used primarily in testing. - * - * @param seg the given MemorySegment - * @param includeData if true, includes detail of retained data. - * @return the summary string. - */ - static String toString(final MemorySegment seg, final SketchType sketchType, final boolean includeData) { - return toString(seg, sketchType, includeData, null); - } - - /** - * Returns a human readable string summary of the internal state of the given MemorySegment. - * Used primarily in testing. - * - * @param seg the given MemorySegment - * @param sketchType the sketch type: FLOATS_SKETCH, DOUBLES_SKETCH, LONGS_SKETCH, or ITEMS_SKETCH. - * @param includeData if true, includes detail of retained data. - * @param serDe must be supplied for KllItemsSketch, otherwise can be null. - * @return the summary string. - */ - static String toString(final MemorySegment seg, final SketchType sketchType, final boolean includeData, - final ArrayOfItemsSerDe serDe) { - if (sketchType == KLL_ITEMS_SKETCH) { - Objects.requireNonNull(serDe, "SerDe parameter must not be null for ITEMS_SKETCH."); - } - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(seg, sketchType, serDe); - final SketchStructure myStructure = segVal.sketchStructure; - final int flags = segVal.flags & 0XFF; - final String flagsStr = (flags) + ", 0x" + (Integer.toHexString(flags)) + ", " - + zeroPad(Integer.toBinaryString(flags), 8); - final int preInts = segVal.preInts; //?? - final boolean emptyFlag = segVal.emptyFlag; - final int sketchBytes = segVal.sketchBytes; - final int typeBytes = sketchType.getBytes(); - final int familyID = getMemorySegmentFamilyID(seg); - final String famName = idToFamily(familyID).toString(); - - final StringBuilder sb = new StringBuilder(); - sb.append(Util.LS).append("### KLL SKETCH MEMORY SUMMARY:").append(LS); - sb.append("Sketch Type : ").append(sketchType.toString()).append(LS); - sb.append("SketchStructure : ").append(myStructure.toString()).append(LS); - sb.append("Byte 0 : Preamble Ints : ").append(preInts).append(LS); - sb.append("Byte 1 : SerVer : ").append(segVal.serVer).append(LS); - sb.append("Byte 2 : FamilyID : ").append(segVal.familyID).append(LS); - sb.append(" : FamilyName : ").append(famName).append(LS); - sb.append("Byte 3 : Flags Field : ").append(flagsStr).append(LS); - sb.append(" Bit: Flag Name : ").append(LS); - sb.append(" 0: EMPTY : ").append(emptyFlag).append(LS); - sb.append(" 1: LEVEL_ZERO_SORTED : ").append(segVal.level0SortedFlag).append(LS); - sb.append("Bytes 4-5 : K : ").append(segVal.k).append(LS); - sb.append("Byte 6 : Min Level Cap, M : ").append(segVal.m).append(LS); - sb.append("Byte 7 : (Reserved) : ").append(LS); - - final long n = segVal.n; - final int minK = segVal.minK; - final int numLevels = segVal.numLevels; - final int[] levelsArr = segVal.levelsArr; //the full levels array - final int retainedItems = levelsArr[numLevels] - levelsArr[0]; - - if ((myStructure == COMPACT_FULL) || (myStructure == UPDATABLE)) { - sb.append("Bytes 8-15 : N : ").append(n).append(LS); - sb.append("Bytes 16-17 : MinK : ").append(minK).append(LS); - sb.append("Byte 18 : NumLevels : ").append(numLevels).append(LS); - } - else { //COMPACT_EMPTY OR COMPACT_SINGLE - sb.append("Assumed : N : ").append(n).append(LS); - sb.append("Assumed : MinK : ").append(minK).append(LS); - sb.append("Assumed : NumLevels : ").append(numLevels).append(LS); - } - sb.append("PreambleBytes : ").append(preInts * Integer.BYTES).append(LS); - sb.append("Sketch Bytes : ").append(sketchBytes).append(LS); - sb.append("MemorySegment Capacity Bytes : ").append(seg.byteSize()).append(LS); - sb.append("### END KLL Sketch MemorySegment Summary").append(LS); - - if (includeData) { - sb.append(LS); - sb.append("### START KLL DATA:").append(LS); - int offsetBytes = 0; - - if (myStructure == UPDATABLE) { - - sb.append("LEVELS ARR:").append(LS); - offsetBytes = DATA_START_ADR; - for (int i = 0; i < (numLevels + 1); i++) { - sb.append(i + ", " + seg.get(JAVA_INT_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += Integer.BYTES; - } - - sb.append("MIN/MAX:").append(LS); - if (sketchType == KLL_DOUBLES_SKETCH) { - sb.append(seg.get(JAVA_DOUBLE_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - sb.append(seg.get(JAVA_DOUBLE_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - } else if (sketchType == KLL_FLOATS_SKETCH) { - sb.append(seg.get(JAVA_FLOAT_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - sb.append(seg.get(JAVA_FLOAT_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - } else if (sketchType == KLL_LONGS_SKETCH) { - sb.append(seg.get(JAVA_LONG_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - sb.append(seg.get(JAVA_LONG_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - } else { //ITEMS_SKETCH - sb.append("<<>>").append(LS); - } - - sb.append("ALL DATA (including free space)").append(LS); - final int itemsSpace = (sketchBytes - offsetBytes) / typeBytes; - if (sketchType == KLL_DOUBLES_SKETCH) { - for (int i = 0; i < itemsSpace; i++) { - sb.append(i + ", " + seg.get(JAVA_DOUBLE_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - } - } else if (sketchType == KLL_FLOATS_SKETCH) { - for (int i = 0; i < itemsSpace; i++) { - sb.append(seg.get(JAVA_FLOAT_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - } - } else if (sketchType == KLL_LONGS_SKETCH) { - for (int i = 0; i < itemsSpace; i++) { - sb.append(seg.get(JAVA_LONG_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - } - } else { //ITEMS_SKETCH - sb.append("<<>>").append(LS); - } - - } else if (myStructure == COMPACT_FULL) { - - sb.append("LEVELS ARR:").append(LS); - offsetBytes = DATA_START_ADR; - int j; - for (j = 0; j < numLevels; j++) { - sb.append(j + ", " + seg.get(JAVA_INT_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += Integer.BYTES; - } - sb.append(j + ", " + levelsArr[numLevels]); - sb.append(" (Top level of Levels Array is absent in MemorySegment)").append(LS); - - sb.append("MIN/MAX:").append(LS); - if (sketchType == KLL_DOUBLES_SKETCH) { - sb.append(seg.get(JAVA_DOUBLE_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - sb.append(seg.get(JAVA_DOUBLE_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - } else if (sketchType == KLL_FLOATS_SKETCH) { - sb.append(seg.get(JAVA_FLOAT_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - sb.append(seg.get(JAVA_FLOAT_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - } else if (sketchType == KLL_LONGS_SKETCH) { - sb.append(seg.get(JAVA_LONG_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - sb.append(seg.get(JAVA_LONG_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - } else { //ITEMS_SKETCH - sb.append(serDe.deserializeFromMemorySegment(seg, offsetBytes, 1)[0]).append(LS); - offsetBytes += serDe.sizeOf(seg, offsetBytes, 1); - sb.append(serDe.deserializeFromMemorySegment(seg, offsetBytes, 1)[0]).append(LS); - offsetBytes += serDe.sizeOf(seg, offsetBytes, 1); - } - - sb.append("RETAINED DATA").append(LS); - final int itemSpace = (sketchBytes - offsetBytes) / (typeBytes == 0 ? 1 : typeBytes); - if (sketchType == KLL_DOUBLES_SKETCH) { - for (int i = 0; i < itemSpace; i++) { - sb.append(i + ", " + seg.get(JAVA_DOUBLE_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - } - } else if (sketchType == KLL_FLOATS_SKETCH) { - for (int i = 0; i < itemSpace; i++) { - sb.append(i + ", " + seg.get(JAVA_FLOAT_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - } - } else if (sketchType == KLL_LONGS_SKETCH) { - for (int i = 0; i < itemSpace; i++) { - sb.append(i + ", " + seg.get(JAVA_LONG_UNALIGNED, offsetBytes)).append(LS); - offsetBytes += typeBytes; - } - } else { //ITEMS_SKETCH - final T[] itemsArr = serDe.deserializeFromMemorySegment(seg, offsetBytes, retainedItems); - for (int i = 0; i < itemsArr.length; i++) { - sb.append(i + ", " + serDe.toString(itemsArr[i])).append(LS); - } - } - - } else if (myStructure == COMPACT_SINGLE) { - - sb.append("SINGLE ITEM DATUM: "); //no LS - if (sketchType == KLL_DOUBLES_SKETCH) { - sb.append(seg.get(JAVA_DOUBLE_UNALIGNED, DATA_START_ADR_SINGLE_ITEM)).append(LS); - } else if (sketchType == KLL_FLOATS_SKETCH) { - sb.append(seg.get(JAVA_FLOAT_UNALIGNED, DATA_START_ADR_SINGLE_ITEM)).append(LS); - } else if (sketchType == KLL_LONGS_SKETCH) { - sb.append(seg.get(JAVA_LONG_UNALIGNED, DATA_START_ADR_SINGLE_ITEM)).append(LS); - } else { //ITEMS_SKETCH - sb.append(serDe.deserializeFromMemorySegment(seg, DATA_START_ADR_SINGLE_ITEM, 1)[0]).append(LS); - } - - } else { //COMPACT_EMPTY - sb.append("EMPTY, NO DATA").append(LS); - } - sb.append("### END KLL DATA:").append(LS); - } - return sb.toString(); - } - - static int getMemorySegmentPreInts(final MemorySegment seg) { - return seg.get(JAVA_BYTE, PREAMBLE_INTS_BYTE_ADR) & 0XFF; - } - - static int getMemorySegmentSerVer(final MemorySegment seg) { - return seg.get(JAVA_BYTE, SER_VER_BYTE_ADR) & 0XFF; - } - - static SketchStructure getMemorySegmentSketchStructure(final MemorySegment seg) { - final int preInts = getMemorySegmentPreInts(seg); - final int serVer = getMemorySegmentSerVer(seg); - return KllSketch.SketchStructure.getSketchStructure(preInts, serVer); - } - - static int getMemorySegmentFamilyID(final MemorySegment seg) { - return seg.get(JAVA_BYTE, FAMILY_BYTE_ADR) & 0XFF; - } - - static int getMemorySegmentFlags(final MemorySegment seg) { - return seg.get(JAVA_BYTE, FLAGS_BYTE_ADR) & 0XFF; - } - - static boolean getMemorySegmentEmptyFlag(final MemorySegment seg) { - return (getMemorySegmentFlags(seg) & EMPTY_BIT_MASK) != 0; - } - - static boolean getMemorySegmentLevelZeroSortedFlag(final MemorySegment seg) { - return (getMemorySegmentFlags(seg) & LEVEL_ZERO_SORTED_BIT_MASK) != 0; - } - - static int getMemorySegmentK(final MemorySegment seg) { - return seg.get(JAVA_SHORT_UNALIGNED, K_SHORT_ADR) & 0XFFFF; - } - - static int getMemorySegmentM(final MemorySegment seg) { - return seg.get(JAVA_BYTE, M_BYTE_ADR) & 0XFF; - } - - static long getMemorySegmentN(final MemorySegment seg) { - return seg.get(JAVA_LONG_UNALIGNED, N_LONG_ADR); - } - - static int getMemorySegmentMinK(final MemorySegment seg) { - return seg.get(JAVA_SHORT_UNALIGNED, MIN_K_SHORT_ADR) & 0XFFFF; - } - - static int getMemorySegmentNumLevels(final MemorySegment seg) { - return seg.get(JAVA_BYTE, NUM_LEVELS_BYTE_ADR) & 0XFF; - } - - static void setMemorySegmentPreInts(final MemorySegment wseg, final int numPreInts) { - wseg.set(JAVA_BYTE, PREAMBLE_INTS_BYTE_ADR, (byte) numPreInts); - } - - static void setMemorySegmentSerVer(final MemorySegment wseg, final int serVer) { - wseg.set(JAVA_BYTE, SER_VER_BYTE_ADR, (byte) serVer); - } - - static void setMemorySegmentFamilyID(final MemorySegment wseg, final int famId) { - wseg.set(JAVA_BYTE, FAMILY_BYTE_ADR, (byte) famId); - } - - static void setMemorySegmentFlags(final MemorySegment wseg, final int flags) { - wseg.set(JAVA_BYTE, FLAGS_BYTE_ADR, (byte) flags); - } - - static void setMemorySegmentEmptyFlag(final MemorySegment wseg, final boolean empty) { - final int flags = getMemorySegmentFlags(wseg); - setMemorySegmentFlags(wseg, empty ? flags | EMPTY_BIT_MASK : flags & ~EMPTY_BIT_MASK); - } - - static void setMemorySegmentLevelZeroSortedFlag(final MemorySegment wseg, final boolean levelZeroSorted) { - final int flags = getMemorySegmentFlags(wseg); - setMemorySegmentFlags(wseg, levelZeroSorted ? flags | LEVEL_ZERO_SORTED_BIT_MASK : flags & ~LEVEL_ZERO_SORTED_BIT_MASK); - } - - static void setMemorySegmentK(final MemorySegment wseg, final int segK) { - wseg.set(JAVA_SHORT_UNALIGNED, K_SHORT_ADR, (short) segK); - } - - static void setMemorySegmentM(final MemorySegment wseg, final int segM) { - wseg.set(JAVA_BYTE, M_BYTE_ADR, (byte) segM); - } - - static void setMemorySegmentN(final MemorySegment wseg, final long segN) { - wseg.set(JAVA_LONG_UNALIGNED, N_LONG_ADR, segN); - } - - static void setMemorySegmentMinK(final MemorySegment wseg, final int segMinK) { - wseg.set(JAVA_SHORT_UNALIGNED, MIN_K_SHORT_ADR, (short) segMinK); - } - - static void setMemorySegmentNumLevels(final MemorySegment wseg, final int segNumLevels) { - wseg.set(JAVA_BYTE, NUM_LEVELS_BYTE_ADR, (byte) segNumLevels); - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllSketch.java b/src/main/java/org/apache/datasketches/kll/KllSketch.java deleted file mode 100644 index 2a3f992dd..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllSketch.java +++ /dev/null @@ -1,580 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR; -import static org.apache.datasketches.kll.KllPreambleUtil.DATA_START_ADR_SINGLE_ITEM; -import static org.apache.datasketches.kll.KllPreambleUtil.N_LONG_ADR; -import static org.apache.datasketches.kll.KllPreambleUtil.PREAMBLE_INTS_EMPTY_SINGLE; -import static org.apache.datasketches.kll.KllPreambleUtil.PREAMBLE_INTS_FULL; -import static org.apache.datasketches.kll.KllPreambleUtil.SERIAL_VERSION_EMPTY_FULL; -import static org.apache.datasketches.kll.KllPreambleUtil.SERIAL_VERSION_SINGLE; -import static org.apache.datasketches.kll.KllPreambleUtil.SERIAL_VERSION_UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_DOUBLES_SKETCH; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_FLOATS_SKETCH; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_ITEMS_SKETCH; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_LONGS_SKETCH; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Random; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.QuantilesAPI; - -/* - * Sampled stream data (floats, doubles, or items) is stored as a heap array called itemsArr or as part of a - * MemorySegment object. - * This array is partitioned into sections called levels and the indices into the array of items - * are tracked by a small integer array called levelsArr. - * The data for level i lies in positions levelsArr[i] through levelsArr[i + 1] - 1 inclusive. - * Hence, the levelsArr must contain (numLevels + 1) elements. - * The valid portion of the itemsArr is completely packed and sorted, except for level 0, - * which is filled from the top down. Any items below the index levelsArr[0] is free space and will be - * overwritten by subsequent updates. - * - * Invariants: - * 1) After a compaction, update, or a merge, every level is sorted except for level zero. - * 2) After a compaction, (sum of level capacities) - (number of valid items) >= 1, - * so there is room for least 1 more quantile in level zero. - * 3) There are no gaps except at the bottom, so if levelsArr[0] = 0, - * the sketch is exactly filled to capacity and must be compacted or the itemsArr and levelsArr - * must be expanded to include more levels. - * 4) Sum of weights of all retained, valid items = N. - * 5) Current total item capacity = itemsArr.length = levelsArr[numLevels]. - */ - -/** - * This class is the root of the KLL sketch class hierarchy. It includes the public API that is independent - * of either sketch type (e.g., float, double, long or generic item) and independent of whether the sketch is targeted - * for use on the Java heap or off-heap. - * - *

KLL is an implementation of a very compact quantiles sketch with lazy compaction scheme - * and nearly optimal accuracy per retained quantile.

- * - *

Reference Optimal Quantile Approximation in Streams.

- * - *

The default k of 200 yields a "single-sided" epsilon of about 1.33% and a - * "double-sided" (PMF) epsilon of about 1.65%, with a confidence of 99%.

- * - * @see KLL Sketch - * @see QuantilesAPI - * - * @author Lee Rhodes - * @author Kevin Lang - * @author Alexander Saydakov - */ -public abstract class KllSketch implements QuantilesAPI, MemorySegmentStatus { - - /** - * The default K - */ - public static final int DEFAULT_K = 200; - - /** - * The maximum K - */ - public static final int MAX_K = (1 << 16) - 1; // serialized as an unsigned short - - /** - * The default M. The parameter m is the minimum level size in number of quantiles. - * Currently, the public default is 8, but this can be overridden using Package Private methods to - * 2, 4, 6 or 8, and the sketch works just fine. The number 8 was chosen as a compromise between speed and size. - * Choosing an m smaller than 8 will make the sketch slower. - */ - static final int DEFAULT_M = 8; - static final int MAX_M = 8; //The maximum M - static final int MIN_M = 2; //The minimum M - static final Random random = new Random(); - - final SketchType sketchType; - final SketchStructure sketchStructure; - boolean readOnly; - int[] levelsArr; //Always updatable form - - /** - * Constructor for on-heap. - * @param sketchType either DOUBLES_SKETCH, FLOATS_SKETCH or ITEMS_SKETCH - * @param sketchStructure the current sketch structure - */ - KllSketch( - final SketchType sketchType, - final SketchStructure sketchStructure) { - this.sketchType = sketchType; - this.sketchStructure = sketchStructure; - } - - /** - * Constructor for MemorySegment based sketch - * @param segVal MemorySegment validator. - */ - KllSketch(final KllMemorySegmentValidate segVal) { - sketchType = segVal.sketchType; - sketchStructure = segVal.sketchStructure; - levelsArr = segVal.levelsArr; //always converted to writable form. - readOnly = segVal.srcSeg.isReadOnly() || (segVal.sketchStructure != UPDATABLE); - } - - /** - * Gets the string value of the item at the given index. - * @param index the index of the value - * @return the string value of the item at the given index. - */ - abstract String getItemAsString(int index); - - /** - * Gets the approximate k to use given epsilon, the normalized rank error. - * @param epsilon the normalized rank error between zero and one. - * @param pmf if true, this function returns the k assuming the input epsilon - * is the desired "double-sided" epsilon for the getPMF() function. Otherwise, this function - * returns k assuming the input epsilon is the desired "single-sided" - * epsilon for all the other queries. - * @return k given epsilon. - */ - public static int getKFromEpsilon(final double epsilon, final boolean pmf) { - return KllHelper.getKFromEpsilon(epsilon, pmf); - } - - /** - * Returns upper bound on the serialized size of a KllSketch given the following parameters. - * @param k parameter that controls size of the sketch and accuracy of estimates - * @param n stream length - * @param sketchType Only DOUBLES_SKETCH, LONGS_SKETCH and FLOATS_SKETCH are supported for this operation. - * @param updatableFormat true if updatable MemorySegment format, otherwise the standard compact format. - * @return upper bound on the serialized size of a KllSketch. - */ - public static int getMaxSerializedSizeBytes(final int k, final long n, - final SketchType sketchType, final boolean updatableFormat) { - if (sketchType == KLL_ITEMS_SKETCH) { throw new SketchesArgumentException(UNSUPPORTED_MSG); } - final KllHelper.GrowthStats gStats = - KllHelper.getGrowthSchemeForGivenN(k, DEFAULT_M, n, sketchType, false); - return updatableFormat ? gStats.updatableBytes : gStats.compactBytes; - } - - /** - * Gets the string value of the max item - * @return the string value of the max item - */ - abstract String getMaxItemAsString(); - - /** - * Gets the string value of the min item - * @return the string value of the min item - */ - abstract String getMinItemAsString(); - - /** - * Gets the normalized rank error given k and pmf. - * Static method version of the getNormalizedRankError(boolean). - * The epsilon returned is a best fit to 99 percent confidence empirically measured max error - * in thousands of trials. - * @param k the configuration parameter - * @param pmf if true, returns the "double-sided" normalized rank error for the getPMF() function. - * Otherwise, it is the "single-sided" normalized rank error for all the other queries. - * @return if pmf is true, the normalized rank error for the getPMF() function. - * Otherwise, it is the "single-sided" normalized rank error for all the other queries. - */ - public static double getNormalizedRankError(final int k, final boolean pmf) { - return KllHelper.getNormalizedRankError(k, pmf); - } - - @Override - public final double getNormalizedRankError(final boolean pmf) { - return getNormalizedRankError(getMinK(), pmf); - } - - @Override - public final int getNumRetained() { - return levelsArr[getNumLevels()] - levelsArr[0]; - } - - /** - * Returns the current number of bytes this Sketch would require if serialized in compact form. - * @return the number of bytes this sketch would require if serialized. - */ - public int getSerializedSizeBytes() { - //current policy is that public method cannot return Updatable structure: - return currentSerializedSizeBytes(false); - } - - @Override - public abstract boolean hasMemorySegment(); - - /** - * Returns true if this sketch is in a Compact MemorySegment Format. - * @return true if this sketch is in a Compact MemorySegment Format. - */ - public boolean isCompactMemorySegmentFormat() { - return hasMemorySegment() && (sketchStructure != UPDATABLE); - } - - @Override - public abstract boolean isOffHeap(); - - @Override - public final boolean isEmpty() { - return getN() == 0; - } - - @Override - public final boolean isEstimationMode() { - return getNumLevels() > 1; - } - - /** - * Returns true if the backing MemorySegment is in updatable format. - * @return true if the backing MemorySegment is in updatable format. - */ - public final boolean isMemorySegmentUpdatableFormat() { - return hasMemorySegment() && (sketchStructure == UPDATABLE); - } - - @Override - public final boolean isReadOnly() { - return readOnly; - } - - @Override - public abstract boolean isSameResource(MemorySegment that); - - /** - * Merges another sketch into this one. - * Attempting to merge a sketch of the wrong type will throw an exception. - * @param other sketch to merge into this one - */ - public abstract void merge(KllSketch other); - - @Override - public final String toString() { - return toString(false, false); - } - - /** - * Returns human readable summary information about this sketch. - * Used for debugging. - * @param withLevels if true includes sketch levels array summary information - * @param withLevelsAndItems if true include detail of levels array and items array together - * @return human readable summary information about this sketch. - */ - public abstract String toString(final boolean withLevels, final boolean withLevelsAndItems); - - //restricted - - /** - * Compute serialized size in bytes independent of the current sketch. - * For KllItemsSketch the result is always in non-updatable, compact form. - * @param updatable true if the desired result is for updatable structure. - * @return serialized size in bytes given a SketchStructure. - */ - final int currentSerializedSizeBytes(final boolean updatable) { - final boolean myUpdatable = sketchType == KLL_ITEMS_SKETCH ? false : updatable; - final long srcN = getN(); - final SketchStructure tgtStructure; - if (myUpdatable) { tgtStructure = UPDATABLE; } - else if (srcN == 0) { tgtStructure = COMPACT_EMPTY; } - else if (srcN == 1) { tgtStructure = COMPACT_SINGLE; } - else { tgtStructure = COMPACT_FULL; } - final int totalBytes; - if (tgtStructure == COMPACT_EMPTY) { - totalBytes = N_LONG_ADR; - } - else if (tgtStructure == COMPACT_SINGLE) { - totalBytes = DATA_START_ADR_SINGLE_ITEM - + getSingleItemSizeBytes(); - } - else if (tgtStructure == COMPACT_FULL) { - totalBytes = DATA_START_ADR - + getLevelsArrSizeBytes(tgtStructure) - + getMinMaxSizeBytes() - + getRetainedItemsSizeBytes(); - } - else { //structure = UPDATABLE - totalBytes = DATA_START_ADR - + getLevelsArrSizeBytes(tgtStructure) - + getMinMaxSizeBytes() - + getTotalItemsNumBytes(); - } - return totalBytes; - } - - int[] getLevelsArray(final SketchStructure structure) { - if (structure == UPDATABLE) { return levelsArr.clone(); } - else if (structure == COMPACT_FULL) { return Arrays.copyOf(levelsArr, levelsArr.length - 1); } - else { return new int[0]; } - } - - final int getLevelsArrSizeBytes(final SketchStructure structure) { - if (structure == UPDATABLE) { return levelsArr.length * Integer.BYTES; } - else if (structure == COMPACT_FULL) { return (levelsArr.length - 1) * Integer.BYTES; } - else { return 0; } - } - - /** - * Returns the configured parameter m, which is the minimum level size in number of items. - * Currently, the public default is 8, but this can be overridden using Package Private methods to - * 2, 4, 6 or 8, and the sketch works just fine. The number 8 was chosen as a compromise between speed and size. - * Choosing smaller m will make the sketch much slower. - * @return the configured parameter m - */ - abstract int getM(); - - /** - * Gets the MemorySegmentRequest object or null. - * @return the MemorySegmentRequest or null. - */ - abstract MemorySegmentRequest getMemorySegmentRequest(); - - /** - * MinK is the K that results from a merge with a sketch configured with a K lower than - * the K of this sketch. This is then used in computing the estimated upper and lower bounds of error. - * @return The minimum K as a result of merging sketches with lower k. - */ - abstract int getMinK(); - - /** - * Gets the combined minItem and maxItem in a serialized byte array. - * @return the combined minItem and maxItem in a serialized byte array. - */ - abstract byte[] getMinMaxByteArr(); - - /** - * Gets the size in bytes of the combined minItem and maxItem serialized byte array. - * @return the size in bytes of the combined minItem and maxItem serialized byte array. - */ - abstract int getMinMaxSizeBytes(); - - /** - * Gets the current number of levels - * @return the current number of levels - */ - final int getNumLevels() { - if ((sketchStructure == UPDATABLE) || (sketchStructure == COMPACT_FULL)) { return levelsArr.length - 1; } - return 1; - } - - /** - * Gets the serialized byte array of the valid retained items as a byte array. - * It does not include the preamble, the levels array, minimum or maximum items, or free space. - * @return the serialized bytes of the retained data. - */ - abstract byte[] getRetainedItemsByteArr(); - - /** - * Gets the size in bytes of the valid retained items. - * It does not include the preamble, the levels array, minimum or maximum items, or free space. - * @return the size of the retained data in bytes. - */ - abstract int getRetainedItemsSizeBytes(); - - /** - * Gets the serializer / deserializer or null. - * @return the serializer / deserializer or null. - */ - abstract ArrayOfItemsSerDe getSerDe(); - - /** - * Gets the serialized byte array of the Single Item that corresponds to the Single Item Flag being true. - * @return the serialized byte array of the Single Item. - */ - abstract byte[] getSingleItemByteArr(); - - /** - * Gets the size in bytes of the serialized Single Item that corresponds to the Single Item Flag being true. - * @return the size in bytes of the serialized Single Item. - */ - abstract int getSingleItemSizeBytes(); - - /** - * Gets the serialized byte array of the entire internal items hypothetical structure. - * It does not include the preamble, the levels array, or minimum or maximum items. - * It may include empty or free space. - * @return the serialized bytes of the retained data. - */ - abstract byte[] getTotalItemsByteArr(); - - /** - * Gets the size in bytes of the entire internal items hypothetical structure. - * It does not include the preamble, the levels array, or minimum or maximum items. - * It may include empty or free space. - * @return the size of the retained data in bytes. - */ - abstract int getTotalItemsNumBytes(); - - /** - * This returns the MemorySegment for Direct type sketches, - * otherwise returns null. - * @return the MemorySegment for Direct type sketches, otherwise null. - */ - abstract MemorySegment getMemorySegment(); - - abstract void incN(int increment); - - abstract void incNumLevels(); - - final boolean isCompactSingleItem() { - return hasMemorySegment() && (sketchStructure == COMPACT_SINGLE) && (getN() == 1); - } - - boolean isKllDoublesSketch() { return sketchType == KLL_DOUBLES_SKETCH; } - - boolean isKllFloatsSketch() { return sketchType == KLL_FLOATS_SKETCH; } - - boolean isKllLongsSketch() { return sketchType == KLL_LONGS_SKETCH; } - - boolean isKllItemsSketch() { return sketchType == KLL_ITEMS_SKETCH; } - - abstract boolean isLevelZeroSorted(); - - /** - * @return true if N == 1. - */ - boolean isSingleItem() { return getN() == 1; } - - final void setLevelsArray(final int[] levelsArr) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - this.levelsArr = levelsArr; - final MemorySegment wseg = getMemorySegment(); - if (wseg != null) { - MemorySegment.copy(this.levelsArr, 0, wseg, JAVA_INT_UNALIGNED, DATA_START_ADR, levelsArr.length); - } - } - - final void setLevelsArrayAt(final int index, final int idxVal) { - if (readOnly) { throw new SketchesArgumentException(TGT_IS_READ_ONLY_MSG); } - levelsArr[index] = idxVal; - final MemorySegment wseg = getMemorySegment(); - if (wseg != null) { - final int offset = DATA_START_ADR + (index * Integer.BYTES); - wseg.set(JAVA_INT_UNALIGNED, offset, idxVal); - } - } - - abstract void setLevelZeroSorted(boolean sorted); - - abstract void setMinK(int minK); - - abstract void setN(long n); - - abstract void setNumLevels(int numLevels); - - abstract void setMemorySegment(final MemorySegment wseg); - - /** - * Used to define the variable type of the current instance of this class. - */ - public enum SketchType { - /** - * KllDoublesSketch - */ - KLL_DOUBLES_SKETCH(Double.BYTES, "KllDoublesSketch"), - /** - * KllFloatsSketch - */ - KLL_FLOATS_SKETCH(Float.BYTES, "KllFloatsSketch"), - /** - * KllItemsSketch - */ - KLL_ITEMS_SKETCH(0, "KllItemsSketch"), - /** - * KllDoublesSketch - */ - KLL_LONGS_SKETCH(Long.BYTES, "KllLongsSketch"); - - private final int typeBytes; - private final String name; - - SketchType(final int typeBytes, final String name) { - this.typeBytes = typeBytes; - this.name = name; - } - - /** - * Gets the item size in bytes. If the item is generic, this returns zero. - * @return the item size in bytes - */ - public int getBytes() { return typeBytes; } - - /** - * Get the name of the associated sketch - * @return the name of the associated sketch - */ - public String getName() { return name; } - } - - /** - * Used primarily to define the structure of the serialized sketch. Also used by the Heap Sketch. - */ - public enum SketchStructure { - /** Compact Empty Structure */ - COMPACT_EMPTY(PREAMBLE_INTS_EMPTY_SINGLE, SERIAL_VERSION_EMPTY_FULL), - /** Compact Single Item Structure */ - COMPACT_SINGLE(PREAMBLE_INTS_EMPTY_SINGLE, SERIAL_VERSION_SINGLE), - /** Compact Full Preamble Structure */ - COMPACT_FULL(PREAMBLE_INTS_FULL, SERIAL_VERSION_EMPTY_FULL), - /** Updatable Preamble Structure */ - UPDATABLE(PREAMBLE_INTS_FULL, SERIAL_VERSION_UPDATABLE); //also used by the heap sketch. - - private final int preInts; - private final int serVer; - - SketchStructure(final int preInts, final int serVer) { - this.preInts = preInts; - this.serVer = serVer; - } - - /** - * gets the Preamble Integers for this Structure. - * @return the Preamble Integers for this Structure - */ - public int getPreInts() { return preInts; } - - /** - * gets the Serialization Version for this Structure. - * @return the Serialization Version for this Structure. - */ - public int getSerVer() { return serVer; } - - /** - * gets the SketchStructure given preInts and serVer. - * @param preInts the given preamble size in integers - * @param serVer the given Serialization Version - * @return the SketchStructure given preInts and serVer. - */ - public static SketchStructure getSketchStructure(final int preInts, final int serVer) { - final SketchStructure[] ssArr = SketchStructure.values(); - for (int i = 0; i < ssArr.length; i++) { - if ((ssArr[i].preInts == preInts) && (ssArr[i].serVer == serVer)) { - return ssArr[i]; - } - } - throw new SketchesArgumentException("Error combination of PreInts and SerVer: " - + "PreInts: " + preInts + ", SerVer: " + serVer); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/KllSketchIterator.java b/src/main/java/org/apache/datasketches/kll/KllSketchIterator.java deleted file mode 100644 index 3e16fbc11..000000000 --- a/src/main/java/org/apache/datasketches/kll/KllSketchIterator.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import org.apache.datasketches.quantilescommon.QuantilesSketchIteratorAPI; - -/** - * The base implementation for the KLL sketch iterator hierarchy used for viewing the - * non-ordered quantiles retained by a sketch. - * - *

Prototype example of the recommended iteration loop:

- *
{@code
- *   SketchIterator itr = sketch.iterator();
- *   while (itr.next()) {
- *     ...get*();
- *   }
- * }
- * - * @author Lee Rhodes - */ -public class KllSketchIterator implements QuantilesSketchIteratorAPI { - protected final int[] levelsArr; - protected final int numLevels; - protected int level; - protected int index; - protected long weight; - protected boolean isInitialized_; - - KllSketchIterator(final int[] levelsArr, final int numLevels) { - this.levelsArr = levelsArr; - this.numLevels = numLevels; - this.isInitialized_ = false; - } - - @Override - public long getWeight() { - return weight; - } - - @Override - public boolean next() { - if (!isInitialized_) { - level = 0; - index = levelsArr[level]; - weight = 1; - isInitialized_ = true; - } else { - index++; - } - if (index < levelsArr[level + 1]) { - return true; - } - // go to the next non-empty level - do { - level++; - if (level == numLevels) { - return false; // run out of levels - } - weight *= 2; - } while (levelsArr[level] == levelsArr[level + 1]); - index = levelsArr[level]; - return true; - } - -} diff --git a/src/main/java/org/apache/datasketches/kll/package-info.java b/src/main/java/org/apache/datasketches/kll/package-info.java deleted file mode 100644 index 6da3c26dd..000000000 --- a/src/main/java/org/apache/datasketches/kll/package-info.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, - * and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names. - */ - -package org.apache.datasketches.kll; diff --git a/src/main/java/org/apache/datasketches/package-info.java b/src/main/java/org/apache/datasketches/package-info.java deleted file mode 100644 index 3683a3543..000000000 --- a/src/main/java/org/apache/datasketches/package-info.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package is the parent package for all sketch families and common code areas. - * - * @author Lee Rhodes - */ -package org.apache.datasketches; diff --git a/src/main/java/org/apache/datasketches/partitions/BoundsRule.java b/src/main/java/org/apache/datasketches/partitions/BoundsRule.java deleted file mode 100644 index 3cd38996b..000000000 --- a/src/main/java/org/apache/datasketches/partitions/BoundsRule.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.partitions; - -/** - * This instructs the user about which of the upper and lower bounds of a partition definition row - * should be included with the returned data. - */ -public enum BoundsRule { - - /** - * Include both the upper and lower bounds - */ - INCLUDE_BOTH, - - /** - * Include only the upper bound but not the lower bound - */ - INCLUDE_UPPER, - - /** - * Include only the lower bound but not the upper bound - */ - INCLUDE_LOWER, - - /** - * Include none - */ - INCLUDE_NEITHER; - -} diff --git a/src/main/java/org/apache/datasketches/partitions/Partitioner.java b/src/main/java/org/apache/datasketches/partitions/Partitioner.java deleted file mode 100644 index dd69f1ec2..000000000 --- a/src/main/java/org/apache/datasketches/partitions/Partitioner.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.partitions; - -import static java.lang.Math.ceil; -import static java.lang.Math.log; -import static java.lang.Math.max; -import static java.lang.Math.min; -import static java.lang.Math.pow; -import static java.lang.Math.round; -import static java.util.Collections.unmodifiableList; -import static org.apache.datasketches.partitions.BoundsRule.INCLUDE_BOTH; -import static org.apache.datasketches.partitions.BoundsRule.INCLUDE_LOWER; -import static org.apache.datasketches.partitions.BoundsRule.INCLUDE_NEITHER; -import static org.apache.datasketches.partitions.BoundsRule.INCLUDE_UPPER; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantilesAPI.EMPTY_MSG; - -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.List; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.GenericPartitionBoundaries; -import org.apache.datasketches.quantilescommon.PartitioningFeature; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; -import org.apache.datasketches.quantilescommon.QuantilesGenericAPI; - -/** - * A partitioning process that can partition very large data sets into thousands - * of partitions of approximately the same size. - * - *

The code included here does work fine for moderate sized partitioning tasks. - * As an example, using the test code in the test branch with the partitioning task of splitting - * a data set of 1 billion items into 324 partitions of size 3M items completed in under 3 minutes, which was - * performed on a single CPU. For much larger partitioning tasks, it is recommended that this code be leveraged into a - * parallelized systems environment.

- * @param the data type - * @param the quantiles sketch that implements both QuantilesGenericAPI and PartitioningFeature. - */ -public class Partitioner & PartitioningFeature> { - private static final QuantileSearchCriteria defaultCriteria = INCLUSIVE; - private final long tgtPartitionSize; - private final int maxPartsPerSk; - private final SketchFillRequest fillReq; - private final QuantileSearchCriteria criteria; - private final ArrayDeque> stack = new ArrayDeque<>(); - - //computed once at the beginning - private int numLevels; - private int partitionsPerSk; - //output - private final List> finalPartitionList = new ArrayList<>(); - - /** - * This constructor assumes a QuantileSearchCriteria of INCLUSIVE. - * @param tgtPartitionSize the target size of the resulting partitions in number of items. - * @param maxPartsPerPass The maximum number of partitions to request from the sketch. The smaller this number is - * the smaller the variance will be of the resulting partitions, but this will increase the number of passes of the - * source data set. - * @param fillReq The is an implementation of the SketchFillRequest call-back supplied by the user and implements - * the SketchFillRequest interface. - */ - public Partitioner( - final long tgtPartitionSize, - final int maxPartsPerPass, - final SketchFillRequest fillReq) { - this(tgtPartitionSize, maxPartsPerPass, fillReq, defaultCriteria); - } - - /** - * This constructor includes the QuantileSearchCriteria criteria as a parameter. - * @param tgtPartitionSize the target size of the resulting partitions in number of items. - * @param maxPartsPerSk The maximum number of partitions to request from the sketch. The smaller this number is - * the smaller the variance will be of the resulting partitions, but this will increase the number of passes of the - * source data set. - * @param fillReq The is an implementation of the SketchFillRequest call-back supplied by the user. - * @param criteria This is the desired QuantileSearchCriteria to be used. - */ - public Partitioner( - final long tgtPartitionSize, - final int maxPartsPerSk, - final SketchFillRequest fillReq, - final QuantileSearchCriteria criteria) { - this.tgtPartitionSize = tgtPartitionSize; - this.maxPartsPerSk = maxPartsPerSk; - this.fillReq = fillReq; - this.criteria = criteria; - } - - /** - * This initiates the partitioning process - * @param sk A sketch of the entire data set. - * @return the final partitioning list - */ - public List> partition(final S sk) { - if (sk.isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - final long inputN = sk.getN(); - final double guessNumParts = max(1.0, ceil((double)inputN / tgtPartitionSize)); - this.numLevels = (int)max(1, ceil(log(guessNumParts) / log(maxPartsPerSk))); - final int partsPerSk = (int)round(pow(guessNumParts, 1.0 / numLevels)); - this.partitionsPerSk = min(partsPerSk, maxPartsPerSk); - final GenericPartitionBoundaries gpb = sk.getPartitionBoundariesFromNumParts(partitionsPerSk, criteria); - final StackElement se = new StackElement<>(gpb, 0, "1"); - stack.push(se); - partitionSearch(stack); - return unmodifiableList(finalPartitionList); - } - - private void partitionSearch(final ArrayDeque> stack) { - if (stack.isEmpty()) { - return; - } - final StackElement se = stack.peek(); - final GenericPartitionBoundaries gpb = se.gpb; - final int numParts = gpb.getNumPartitions(); - - if (stack.size() == numLevels) { //at max level - while (++se.part <= numParts) { //add rows to final partition list - final PartitionBoundsRow row = new PartitionBoundsRow<>(se); - finalPartitionList.add(row); - } - stack.pop(); - partitionSearch(stack); - } - else { //not at max level - if (++se.part <= numParts) { - final PartitionBoundsRow row = new PartitionBoundsRow<>(se); - final S sk = fillReq.getRange(row.lowerBound, row.upperBound, row.rule); - final GenericPartitionBoundaries gpb2 = sk.getPartitionBoundariesFromNumParts(this.partitionsPerSk, criteria); - final int level = stack.size() + 1; - final String partId = se.levelPartId + "." + se.part + "," + level; - final StackElement se2 = new StackElement<>(gpb2, 0, partId); - stack.push(se2); - partitionSearch(stack); - } - //done with all parts at this level - if (stack.isEmpty()) { - return; - } - stack.pop(); - partitionSearch(stack); - } - } - - /** - * Holds data for a Stack element - * @param the item class type - */ - public static class StackElement { - /** A reference to the relevant GenericPartitionBoundaries class */ - public final GenericPartitionBoundaries gpb; - /** The partition index */ - public int part; - /** A brief string description of the partition and its hierarchy */ - public String levelPartId; - - /** - * Constructs this StackElement - * @param gpb the given GenericPartitionBoundarie reference - * @param part The partition index - * @param levelPartId A brief string description of the partition and its hierarchy - */ - public StackElement(final GenericPartitionBoundaries gpb, final int part, final String levelPartId) { - this.gpb = gpb; - this.part = part; - this.levelPartId = levelPartId; - } - } - - /** - * Defines a row for List of PartitionBounds. - * @param the item class type - */ - public static class PartitionBoundsRow { - /** The partition index */ - public int part; - /** A brief string description of the partition and its hierarchy */ - public String levelPartId; - /** The approximate number of items represented by this partition description row. */ - public long approxNumDeltaItems; - /** The BoundsRule for this partition description row. */ - public BoundsRule rule; - /** The lower bound value */ - public T lowerBound; - /** The upper bound value */ - public T upperBound; - - /** - * The constructor for the StackElement class. - * @param se the given stack element. - */ - public PartitionBoundsRow(final StackElement se) { - final GenericPartitionBoundaries gpb = se.gpb; - final QuantileSearchCriteria searchCrit = gpb.getSearchCriteria(); - final T[] boundaries = gpb.getBoundaries(); - final int numParts = gpb.getNumPartitions(); - this.part = se.part; - this.levelPartId = se.levelPartId + "." + part; - final long num; - this.approxNumDeltaItems = num = gpb.getNumDeltaItems()[part]; - if (searchCrit == INCLUSIVE) { - if (part == 1) { - lowerBound = gpb.getMinItem(); - upperBound = boundaries[part]; - rule = (num == 0) ? INCLUDE_NEITHER : (lowerBound == upperBound) ? INCLUDE_UPPER : INCLUDE_BOTH; - } else { - lowerBound = boundaries[part - 1]; - upperBound = boundaries[part]; - rule = (num == 0) ? INCLUDE_NEITHER : INCLUDE_UPPER; - } - } - else { //EXCLUSIVE - if (part == numParts) { - lowerBound = boundaries[part - 1]; - upperBound = gpb.getMaxItem(); - rule = (num == 0) ? INCLUDE_NEITHER : (lowerBound == upperBound) ? INCLUDE_LOWER : INCLUDE_BOTH; - } else { - lowerBound = boundaries[part - 1]; - upperBound = boundaries[part]; - rule = (num == 0) ? INCLUDE_NEITHER : INCLUDE_LOWER; - } - } - } - } - -} diff --git a/src/main/java/org/apache/datasketches/partitions/SketchFillRequest.java b/src/main/java/org/apache/datasketches/partitions/SketchFillRequest.java deleted file mode 100644 index 76e9d7454..000000000 --- a/src/main/java/org/apache/datasketches/partitions/SketchFillRequest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.partitions; - -import org.apache.datasketches.quantilescommon.PartitioningFeature; -import org.apache.datasketches.quantilescommon.QuantilesGenericAPI; - -/** - * This is a callback request to the data source to fill a quantiles sketch, - * which is returned to the caller. - * @param the item class type - * @param the sketch type - * @author Lee Rhodes - */ -public interface SketchFillRequest & PartitioningFeature> { - - /** - * This is a callback request to the data source to fill a quantiles sketch - * with a range of data between upper and lower bounds. Which of these bounds are to be included is determined by - * the BoundsRule. - * - *

This range of data may or may not be subsequently further partitioned.

- * @param lowerQuantile the lowest quantile of a range - * @param upperQuantile the highest quantile of a range - * @param boundsRule determines which quantile bounds to include - * @return a quantiles sketch filled from the given upper and lower bounds. - */ - public S getRange(final T lowerQuantile, final T upperQuantile, final BoundsRule boundsRule); - -} diff --git a/src/main/java/org/apache/datasketches/partitions/package-info.java b/src/main/java/org/apache/datasketches/partitions/package-info.java deleted file mode 100644 index 58bd126b3..000000000 --- a/src/main/java/org/apache/datasketches/partitions/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package is for classes that simplify the task of partitioning large data into many approximately equal-sized - * partitions. - */ -package org.apache.datasketches.partitions; diff --git a/src/main/java/org/apache/datasketches/quantiles/ClassicUtil.java b/src/main/java/org/apache/datasketches/quantiles/ClassicUtil.java deleted file mode 100644 index d86a0f487..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/ClassicUtil.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.Math.abs; -import static java.lang.Math.ceil; -import static java.lang.Math.exp; -import static java.lang.Math.log; -import static java.lang.Math.max; -import static java.lang.Math.min; -import static java.lang.Math.pow; -import static java.lang.Math.round; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.common.Util.isPowerOf2; -import static org.apache.datasketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.ORDERED_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.READ_ONLY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFlags; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Utilities for the classic quantiles sketches and independent of the type. - * - * @author Lee Rhodes - */ -public final class ClassicUtil { - static final int DOUBLES_SER_VER = 3; - static final int MAX_PRELONGS = Family.QUANTILES.getMaxPreLongs(); - static final int MIN_K = 2; - static final int MAX_K = 1 << 15; - - private ClassicUtil() {} - - static final char TAB = '\t'; - - /** - * Used by Classic Quantiles. - * Gets the normalized rank error given k and pmf for the QuantilesDoubleSketch and QuantilesItemsSketch. - * @param k the configuration parameter - * @param pmf if true, returns the "double-sided" normalized rank error for the getPMF() function. - * Otherwise, it is the "single-sided" normalized rank error for all the other queries. - * @return if pmf is true, the normalized rank error for the getPMF() function. - * Otherwise, it is the "single-sided" normalized rank error for all the other queries. - */ - // constants were derived as the best fit to 99 percentile empirically measured max error in - // thousands of trials - public static double getNormalizedRankError(final int k, final boolean pmf) { - return pmf - ? 1.854 / pow(k, 0.9657) - : 1.576 / pow(k, 0.9726); - } - - /** - * Used by Classic Quantiles. - * Gets the approximate k to use given epsilon, the normalized rank error - * for the QuantilesDoubleSketch and QuantilesItemsSketch. - * @param epsilon the normalized rank error between zero and one. - * @param pmf if true, this function returns k assuming the input epsilon - * is the desired "double-sided" epsilon for the getPMF() function. Otherwise, this function - * returns k assuming the input epsilon is the desired "single-sided" - * epsilon for all the other queries. - * @return k given epsilon. - */ - // constants were derived as the best fit to 99 percentile empirically measured max error in - // thousands of trials - public static int getKFromEpsilon(final double epsilon, final boolean pmf) { - //Ensure that eps is >= than the lowest possible eps given MAX_K and pmf=false. - final double eps = max(epsilon, 6.395E-5); - final double kdbl = pmf - ? exp(log(1.854 / eps) / 0.9657) - : exp(log(1.576 / eps) / 0.9726); - final double krnd = round(kdbl); - final double del = abs(krnd - kdbl); - //round to closest int if within 1 ppm of the int, otherwise use the ceiling. - final int k = (int) ((del < 1E-6) ? krnd : ceil(kdbl)); - return max(MIN_K, min(MAX_K, k)); - } - - /** - * Computes the new size of a growing base buffer. - * It doubles whatever the current size is until it reaches 2 * k items. - * This assumes all items are the same size and the combinedBuffer has no levels above the base buffer. - * @param k the given k of the sketch - * @param curCombinedBufCap the current capacity of the combined buffer in items. - * @return the new size of the base buffer in items. - */ - static int computeGrowingBaseBufferCap(final int k, final int curCombinedBufCap) { - if (curCombinedBufCap < (2 * k)) { - return 2 * Math.max(Math.min(k, curCombinedBufCap), MIN_K); - } - return 2 * k; - } - - /** - * Used by Classic Quantiles. - * Checks the validity of the given k - * @param k must be greater than 1 and less than 65536 and a power of 2. - */ - static void checkK(final int k) { - if ((k < MIN_K) || (k > MAX_K) || !isPowerOf2(k)) { - throw new SketchesArgumentException( - "K must be >= " + MIN_K + " and <= " + MAX_K + " and a power of 2: " + k); - } - } - - /** - * Used by Classic Quantiles. - * Checks the validity of the given family ID - * @param familyID the given family ID - */ - static void checkFamilyID(final int familyID) { - final Family family = Family.idToFamily(familyID); - if (!family.equals(Family.QUANTILES)) { - throw new SketchesArgumentException( - "Possible corruption: Invalid Family: " + family.toString()); - } - } - - /** - * Used by Classic Quantiles. - * Checks the consistency of the flag bits and the state of preambleLong and the MemorySegment - * capacity and returns the empty state. - * @param preambleLongs the size of preamble in longs - * @param flags the flags field - * @param segCapBytes the MemorySegment capacity - * @return the empty state - */ - static boolean checkPreLongsFlagsCap(final int preambleLongs, final int flags, final long segCapBytes) { - final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; //Preamble flags empty state - final int minPre = Family.QUANTILES.getMinPreLongs(); //1 - final int maxPre = Family.QUANTILES.getMaxPreLongs(); //2 - final boolean valid = ((preambleLongs == minPre) && empty) || ((preambleLongs == maxPre) && !empty); - if (!valid) { - throw new SketchesArgumentException( - "Possible corruption: PreambleLongs inconsistent with empty state: " + preambleLongs); - } - checkHeapFlags(flags); - if (segCapBytes < (preambleLongs << 3)) { - throw new SketchesArgumentException( - "Possible corruption: Insufficient capacity for preamble: " + segCapBytes); - } - return empty; - } - - /** - * Used by Classic Quantiles. - * Checks just the flags field of the preamble. Allowed flags are Read Only, Empty, Compact, and - * ordered. - * @param flags the flags field - */ - static void checkHeapFlags(final int flags) { //only used by checkPreLongsFlagsCap and test - final int allowedFlags = - READ_ONLY_FLAG_MASK | EMPTY_FLAG_MASK | COMPACT_FLAG_MASK | ORDERED_FLAG_MASK; - final int flagsMask = ~allowedFlags; - if ((flags & flagsMask) > 0) { - throw new SketchesArgumentException( - "Possible corruption: Invalid flags field: " + Integer.toBinaryString(flags)); - } - } - - /** - * Used by Classic Quantiles. - * Checks just the flags field of an input MemorySegment object. Returns true for a compact or readOnly - * sketch, false for an update sketch. Does not perform additional checks, including sketch - * family. - * @param srcSeg the source MemorySegment containing a sketch - * @return true if flags indicate a compact sketch, otherwise false - */ - static boolean checkIsMemorySegmentCompact(final MemorySegment srcSeg) { - final int flags = extractFlags(srcSeg); - final int compactFlags = COMPACT_FLAG_MASK; - return ((flags & compactFlags) > 0); - } - - /** - * Used by Classic Quantiles. - * Returns the number of retained valid items in the sketch given k and n. - * @param k the given configured k of the sketch - * @param n the current number of items seen by the sketch - * @return the number of retained items in the sketch given k and n. - */ - static int computeRetainedItems(final int k, final long n) { - final int bbCnt = computeBaseBufferItems(k, n); - final long bitPattern = computeBitPattern(k, n); - final int validLevels = computeValidLevels(bitPattern); - return bbCnt + (validLevels * k); - } - - /** - * Used by Classic Quantiles. - * Returns the total item capacity of an updatable, non-compact combined buffer - * given k and n. If total levels = 0, this returns the ceiling power of 2 - * size for the base buffer or the MIN_BASE_BUF_SIZE, whichever is larger. - * - * @param k sketch parameter. This determines the accuracy of the sketch and the - * size of the updatable data structure, which is a function of k and n. - * - * @param n The number of items in the input stream - * @return the current item capacity of the combined buffer - */ - static int computeCombinedBufferItemCapacity(final int k, final long n) { - final int totLevels = computeNumLevelsNeeded(k, n); - if (totLevels == 0) { - final int bbItems = computeBaseBufferItems(k, n); - return Math.max(2 * MIN_K, ceilingPowerOf2(bbItems)); - } - return (2 + totLevels) * k; - } - - /** - * Used by Classic Quantiles. - * Computes the number of valid levels above the base buffer - * @param bitPattern the bit pattern - * @return the number of valid levels above the base buffer - */ - static int computeValidLevels(final long bitPattern) { - return Long.bitCount(bitPattern); - } - - /** - * Used by Classic Quantiles. - * Computes the total number of logarithmic levels above the base buffer given the bitPattern. - * @param bitPattern the given bit pattern - * @return the total number of logarithmic levels above the base buffer - */ - static int computeTotalLevels(final long bitPattern) { - return hiBitPos(bitPattern) + 1; - } - - /** - * Used by Classic Quantiles. - * Computes the total number of logarithmic levels above the base buffer given k and n. - * This is equivalent to max(floor(lg(n/k), 0). - * Returns zero if n is less than 2 * k. - * @param k the configured size of the sketch - * @param n the total number presented to the sketch. - * @return the total number of levels needed. - */ - static int computeNumLevelsNeeded(final int k, final long n) { - return 1 + hiBitPos(n / (2L * k)); - } - - /** - * Used by Classic Quantiles. - * Computes the number of base buffer items given k, n - * @param k the configured size of the sketch - * @param n the total number presented to the sketch - * @return the number of base buffer items - */ - static int computeBaseBufferItems(final int k, final long n) { - return (int) (n % (2L * k)); - } - - /** - * Used by Classic Quantiles. - * Computes the levels bit pattern given k, n. - * This is computed as n / (2*k). - * @param k the configured size of the sketch - * @param n the total number presented to the sketch. - * @return the levels bit pattern - */ - static long computeBitPattern(final int k, final long n) { - return n / (2L * k); - } - - /** - * Used by Classic Quantiles. - * Zero-based position of the highest one-bit of the given long. - * Returns minus one if num is zero. - * @param num the given long - * @return Zero-based position of the highest one-bit of the given long - */ - static int hiBitPos(final long num) { - return 63 - Long.numberOfLeadingZeros(num); - } - - /** - * Used by Classic Quantiles. - * Returns the zero-based bit position of the lowest zero bit of bits starting at - * startingBit. If input is all ones, this returns 64. - * @param bits the input bits as a long - * @param startingBit the zero-based starting bit position. Only the low 6 bits are used. - * @return the zero-based bit position of the lowest zero bit starting at startingBit. - */ - static int lowestZeroBitStartingAt(final long bits, final int startingBit) { - int pos = startingBit & 0X3F; - long myBits = bits >>> pos; - - while ((myBits & 1L) != 0) { - myBits = myBits >>> 1; - pos++; - } - return pos; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/CompactQuantilesDoublesSketch.java b/src/main/java/org/apache/datasketches/quantiles/CompactQuantilesDoublesSketch.java deleted file mode 100644 index 490ac35eb..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/CompactQuantilesDoublesSketch.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * Compact sketches are inherently read only. - * @author Jon Malkin - */ -public abstract class CompactQuantilesDoublesSketch extends QuantilesDoublesSketch { - CompactQuantilesDoublesSketch(final int k) { - super(k); - } - - @Override - boolean isCompact() { - return true; - } - - @Override - public boolean isReadOnly() { - return false; - } - - @Override - public void reset() { - throw new SketchesStateException("Cannot reset a compact sketch, which is read-only."); - } - - @Override - public void update(final double quantile) { - throw new SketchesStateException("Cannot update a compact sketch, which is read-only."); - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/DirectCompactDoublesSketch.java b/src/main/java/org/apache/datasketches/quantiles/DirectCompactDoublesSketch.java deleted file mode 100644 index baf03736a..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/DirectCompactDoublesSketch.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.quantiles.ClassicUtil.DOUBLES_SER_VER; -import static org.apache.datasketches.quantiles.ClassicUtil.checkFamilyID; -import static org.apache.datasketches.quantiles.ClassicUtil.checkK; -import static org.apache.datasketches.quantiles.ClassicUtil.computeBaseBufferItems; -import static org.apache.datasketches.quantiles.ClassicUtil.computeBitPattern; -import static org.apache.datasketches.quantiles.ClassicUtil.computeRetainedItems; -import static org.apache.datasketches.quantiles.PreambleUtil.COMBINED_BUFFER; -import static org.apache.datasketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.MAX_DOUBLE; -import static org.apache.datasketches.quantiles.PreambleUtil.MIN_DOUBLE; -import static org.apache.datasketches.quantiles.PreambleUtil.N_LONG; -import static org.apache.datasketches.quantiles.PreambleUtil.ORDERED_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.READ_ONLY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFlags; -import static org.apache.datasketches.quantiles.PreambleUtil.extractK; -import static org.apache.datasketches.quantiles.PreambleUtil.extractN; -import static org.apache.datasketches.quantiles.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.quantiles.PreambleUtil.extractSerVer; -import static org.apache.datasketches.quantiles.PreambleUtil.insertFamilyID; -import static org.apache.datasketches.quantiles.PreambleUtil.insertFlags; -import static org.apache.datasketches.quantiles.PreambleUtil.insertK; -import static org.apache.datasketches.quantiles.PreambleUtil.insertMaxDouble; -import static org.apache.datasketches.quantiles.PreambleUtil.insertMinDouble; -import static org.apache.datasketches.quantiles.PreambleUtil.insertN; -import static org.apache.datasketches.quantiles.PreambleUtil.insertPreLongs; -import static org.apache.datasketches.quantiles.PreambleUtil.insertSerVer; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.QuantilesAPI; - -/** - * Implements the QuantilesDoublesSketch off-heap. - * - * @author Kevin Lang - * @author Lee Rhodes - * @author Jon Malkin - */ -final class DirectCompactDoublesSketch extends CompactQuantilesDoublesSketch { - private static final int MIN_DIRECT_DOUBLES_SER_VER = 3; - private final MemorySegment seg_; - - //**CONSTRUCTORS********************************************************** - private DirectCompactDoublesSketch(final int k, final MemorySegment seg) { - super(k); //Checks k - seg_ = seg.asReadOnly(); - } - - /** - * Converts the given UpdatableQuantilesDoublesSketch to this compact form. - * - * @param sketch the sketch to convert - * @param dstSeg the MemorySegment to use for the destination - * @return a DirectCompactDoublesSketch created from an UpdatableQuantilesDoublesSketch - */ - static DirectCompactDoublesSketch createFromUpdateSketch(final UpdatableQuantilesDoublesSketch sketch, - final MemorySegment dstSeg) { - final long segCap = dstSeg.byteSize(); - final int k = sketch.getK(); - final long n = sketch.getN(); - checkDirectSegCapacity(k, n, segCap); - - //initialize dstSeg - dstSeg.set(JAVA_LONG_UNALIGNED, 0, 0L); //clear pre0 - insertPreLongs(dstSeg, 2); - insertSerVer(dstSeg, DOUBLES_SER_VER); - insertFamilyID(dstSeg, Family.QUANTILES.getID()); - insertK(dstSeg, k); - - final int flags = COMPACT_FLAG_MASK | READ_ONLY_FLAG_MASK; // both true for all compact sketches - - if (sketch.isEmpty()) { - insertFlags(dstSeg, flags | EMPTY_FLAG_MASK); - } else { - insertFlags(dstSeg, flags); - insertN(dstSeg, n); - insertMinDouble(dstSeg, sketch.getMinItem()); - insertMaxDouble(dstSeg, sketch.getMaxItem()); - - final int bbCount = computeBaseBufferItems(k, n); - - final DoublesSketchAccessor inputAccessor = DoublesSketchAccessor.wrap(sketch, false); - assert bbCount == inputAccessor.numItems(); - - long dstSegOffset = COMBINED_BUFFER; - - // copy and sort base buffer - final double[] bbArray = inputAccessor.getArray(0, bbCount); - Arrays.sort(bbArray); - MemorySegment.copy(bbArray, 0, dstSeg, JAVA_DOUBLE_UNALIGNED, dstSegOffset, bbCount); - dstSegOffset += bbCount << 3; - - long bitPattern = computeBitPattern(k, n); - for (int lvl = 0; bitPattern > 0; ++lvl, bitPattern >>>= 1) { - if ((bitPattern & 1L) > 0L) { - inputAccessor.setLevel(lvl); - MemorySegment.copy(inputAccessor.getArray(0, k), 0, dstSeg, JAVA_DOUBLE_UNALIGNED, dstSegOffset, k); - dstSegOffset += k << 3; - } - } - } - - return new DirectCompactDoublesSketch(k, dstSeg); - } - - /** - * Wrap this sketch around the given compact MemorySegment image of a QuantilesDoublesSketch. - * - * @param srcSeg the given compact MemorySegment image of a QuantilesDoublesSketch, - * @return a sketch that wraps the given srcSeg. - */ - static DirectCompactDoublesSketch wrapInstance(final MemorySegment srcSeg) { - final long segCap = srcSeg.byteSize(); - - final int preLongs = extractPreLongs(srcSeg); - final int serVer = extractSerVer(srcSeg); - final int familyID = extractFamilyID(srcSeg); - final int flags = extractFlags(srcSeg); - final int k = extractK(srcSeg); - - final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; - final long n = empty ? 0 : extractN(srcSeg); - - //VALIDITY CHECKS - DirectUpdateDoublesSketch.checkPreLongs(preLongs); - checkFamilyID(familyID); - DoublesUtil.checkDoublesSerVer(serVer, MIN_DIRECT_DOUBLES_SER_VER); - checkCompact(serVer, flags); - checkK(k); - checkDirectSegCapacity(k, n, segCap); - DirectUpdateDoublesSketch.checkEmptyAndN(empty, n); - - return new DirectCompactDoublesSketch(k, srcSeg); - } - - @Override - public double getMaxItem() { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return seg_.get(JAVA_DOUBLE_UNALIGNED, MAX_DOUBLE); - } - - @Override - public double getMinItem() { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return seg_.get(JAVA_DOUBLE_UNALIGNED, MIN_DOUBLE); - } - - @Override - public long getN() { - return (seg_.byteSize() < COMBINED_BUFFER) ? 0 : seg_.get(JAVA_LONG_UNALIGNED, N_LONG); - } - - @Override - public boolean hasMemorySegment() { - return (seg_ != null); - } - - @Override - public boolean isOffHeap() { - return (seg_ != null) ? seg_.isNative() : false; - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return MemorySegmentStatus.isSameResource(seg_, that); - } - - //Restricted overrides - //Gets - - @Override - int getBaseBufferCount() { - return computeBaseBufferItems(getK(), getN()); - } - - @Override - int getCombinedBufferItemCapacity() { - return ((int)seg_.byteSize() - COMBINED_BUFFER) / 8; - } - - @Override - double[] getCombinedBuffer() { - final int k = getK(); - if (isEmpty()) { return new double[k << 1]; } //2K - final long n = getN(); - final int itemCap = computeRetainedItems(k, n); - final double[] combinedBuffer = new double[itemCap]; - MemorySegment.copy(seg_, JAVA_DOUBLE_UNALIGNED, COMBINED_BUFFER, combinedBuffer, 0, itemCap); - return combinedBuffer; - } - - @Override - long getBitPattern() { - final int k = getK(); - final long n = getN(); - return computeBitPattern(k, n); - } - - @Override - MemorySegment getMemorySegment() { - return seg_; - } - - //Checks - - /** - * Checks the validity of the direct MemorySegment capacity assuming n, k. - * @param k the given k - * @param n the given n - * @param segCapBytes the current MemorySegment capacity in bytes - */ - static void checkDirectSegCapacity(final int k, final long n, final long segCapBytes) { - final int reqBufBytes = getCompactSerialiedSizeBytes(k, n); - - if (segCapBytes < reqBufBytes) { - throw new SketchesArgumentException("Possible corruption: MemorySegment capacity too small: " - + segCapBytes + " < " + reqBufBytes); - } - } - - /** - * Checks a sketch's serial version and flags to see if the sketch can be wrapped as a - * DirectCompactDoubleSketch. Throws an exception if the sketch is neither empty nor compact - * and ordered, unless the sketch uses serialization version 2. - * @param serVer the serialization version - * @param flags Flags from the sketch to evaluate - */ - static void checkCompact(final int serVer, final int flags) { - final int compactFlagMask = COMPACT_FLAG_MASK | ORDERED_FLAG_MASK; - if ((serVer != 2) - && ((flags & EMPTY_FLAG_MASK) == 0) - && ((flags & compactFlagMask) != compactFlagMask)) { - throw new SketchesArgumentException( - "Possible corruption: Must be v2, empty, or compact and ordered. Flags field: " - + Integer.toBinaryString(flags) + ", SerVer: " + serVer); - } - } -} diff --git a/src/main/java/org/apache/datasketches/quantiles/DirectDoublesSketchAccessor.java b/src/main/java/org/apache/datasketches/quantiles/DirectDoublesSketchAccessor.java deleted file mode 100644 index 4452645b2..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/DirectDoublesSketchAccessor.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -/** - * @author Jon Malkin - */ -final class DirectDoublesSketchAccessor extends DoublesSketchAccessor { - - DirectDoublesSketchAccessor(final QuantilesDoublesSketch ds, - final boolean forceSize, - final int level) { - super(ds, forceSize, level); - assert ds.hasMemorySegment(); - } - - @Override - DoublesSketchAccessor copyAndSetLevel(final int level) { - return new DirectDoublesSketchAccessor(ds_, forceSize_, level); - } - - @Override - double get(final int index) { - assert (index >= 0) && (index < numItems_); - assert n_ == ds_.getN(); - - final int byteOffset = offset_ + (index << 3); - return ds_.getMemorySegment().get(JAVA_DOUBLE_UNALIGNED, byteOffset); - } - - @Override - double set(final int index, final double quantile) { - assert (index >= 0) && (index < numItems_); - assert n_ == ds_.getN(); - assert !ds_.isCompact(); // can't write to a compact sketch - - final int byteOffset = offset_ + (index << 3); - final MemorySegment seg = ds_.getMemorySegment(); - final double oldVal = seg.get(JAVA_DOUBLE_UNALIGNED, byteOffset); - seg.set(JAVA_DOUBLE_UNALIGNED, byteOffset, quantile); - return oldVal; - } - - @Override - double[] getArray(final int fromIdx, final int numItems) { - final int byteOffset = offset_ + (fromIdx << 3); - final MemorySegment seg = ds_.getMemorySegment(); - return seg.asSlice(byteOffset, numItems << 3).toArray(JAVA_DOUBLE_UNALIGNED); - } - - @Override - void putArray(final double[] srcArray, final int srcIndex, final int dstIndex, final int numItems) { - assert !ds_.isCompact(); // can't write to compact sketch - - final int byteOffset = offset_ + (dstIndex << 3); - MemorySegment.copy(srcArray, srcIndex, ds_.getMemorySegment(), JAVA_DOUBLE_UNALIGNED, byteOffset, numItems); - } - - @Override - void sort() { - assert currLvl_ == BB_LVL_IDX; - - final double[] tmpBuffer = new double[numItems_]; - final MemorySegment seg = ds_.getMemorySegment(); - MemorySegment.copy(seg, JAVA_DOUBLE_UNALIGNED, offset_, tmpBuffer, 0, numItems_); - Arrays.sort(tmpBuffer, 0, numItems_); - MemorySegment.copy(tmpBuffer, 0, seg, JAVA_DOUBLE_UNALIGNED, offset_, numItems_); - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/DirectUpdateDoublesSketch.java b/src/main/java/org/apache/datasketches/quantiles/DirectUpdateDoublesSketch.java deleted file mode 100644 index a3b717beb..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/DirectUpdateDoublesSketch.java +++ /dev/null @@ -1,415 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.quantiles.ClassicUtil.DOUBLES_SER_VER; -import static org.apache.datasketches.quantiles.ClassicUtil.checkFamilyID; -import static org.apache.datasketches.quantiles.ClassicUtil.checkK; -import static org.apache.datasketches.quantiles.ClassicUtil.computeBitPattern; -import static org.apache.datasketches.quantiles.DoublesUtil.checkDoublesSerVer; -import static org.apache.datasketches.quantiles.PreambleUtil.COMBINED_BUFFER; -import static org.apache.datasketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.FLAGS_BYTE; -import static org.apache.datasketches.quantiles.PreambleUtil.MAX_DOUBLE; -import static org.apache.datasketches.quantiles.PreambleUtil.MIN_DOUBLE; -import static org.apache.datasketches.quantiles.PreambleUtil.N_LONG; -import static org.apache.datasketches.quantiles.PreambleUtil.ORDERED_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.READ_ONLY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFlags; -import static org.apache.datasketches.quantiles.PreambleUtil.extractK; -import static org.apache.datasketches.quantiles.PreambleUtil.extractN; -import static org.apache.datasketches.quantiles.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.quantiles.PreambleUtil.extractSerVer; -import static org.apache.datasketches.quantiles.PreambleUtil.insertFamilyID; -import static org.apache.datasketches.quantiles.PreambleUtil.insertFlags; -import static org.apache.datasketches.quantiles.PreambleUtil.insertK; -import static org.apache.datasketches.quantiles.PreambleUtil.insertMaxDouble; -import static org.apache.datasketches.quantiles.PreambleUtil.insertMinDouble; -import static org.apache.datasketches.quantiles.PreambleUtil.insertN; -import static org.apache.datasketches.quantiles.PreambleUtil.insertPreLongs; -import static org.apache.datasketches.quantiles.PreambleUtil.insertSerVer; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesReadOnlyException; -import org.apache.datasketches.quantilescommon.QuantilesAPI; - -/** - * Implements the QuantilesDoublesSketch in a MemorySegment. - * - * @author Kevin Lang - * @author Lee Rhodes - */ -final class DirectUpdateDoublesSketch extends UpdatableQuantilesDoublesSketch { - private static final int MIN_DIRECT_DOUBLES_SER_VER = 3; - private MemorySegmentRequest mSegReq_ = null; - private MemorySegment seg_; - - //**CONSTRUCTORS** - private DirectUpdateDoublesSketch(final int k, final MemorySegment seg, final MemorySegmentRequest mSegReq) { - super(k); //Checks k - mSegReq_ = mSegReq; - seg_ = seg; - } - - /** - * Creates a new instance of a QuantilesDoublesSketch in a MemorySegment. - * - * @param k Parameter that controls space usage of sketch and accuracy of estimates. - * Must be greater than 1 and less than 65536 and a power of 2. - * @param dstSeg the non-null destination MemorySegment that will be initialized to hold the data for this sketch. - * It must initially be at least (16 * MIN_K + 32) bytes, where MIN_K defaults to 2. As it grows - * it will request more MemorySegment using the MemorySegmentRequest callback. - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return a DirectUpdateDoublesSketch - */ - static DirectUpdateDoublesSketch newInstance(final int k, final MemorySegment dstSeg, final MemorySegmentRequest mSegReq) { - Objects.requireNonNull(dstSeg, "The MemorySegment dstSeg must not be null"); - final long segCap = dstSeg.byteSize(); - checkDirectSegCapacity(k, 0, segCap); - - //initialize dstSeg - dstSeg.set(JAVA_LONG_UNALIGNED, 0, 0L); //clear pre0 - insertPreLongs(dstSeg, 2); - insertSerVer(dstSeg, DOUBLES_SER_VER); - insertFamilyID(dstSeg, Family.QUANTILES.getID()); - insertFlags(dstSeg, EMPTY_FLAG_MASK); - insertK(dstSeg, k); - - if (segCap >= COMBINED_BUFFER) { - insertN(dstSeg, 0L); - insertMinDouble(dstSeg, Double.NaN); - insertMaxDouble(dstSeg, Double.NaN); - } - - return new DirectUpdateDoublesSketch(k, dstSeg, mSegReq); - } - - /** - * Wrap this sketch around the given updatable MemorySegment image of a QuantilesDoublesSketch. - * - * @param srcSeg the given MemorySegment image of an UpdatableQuantilesDoublesSketch and must not be null. - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return a sketch that wraps the given srcSeg - */ - static DirectUpdateDoublesSketch wrapInstance(final MemorySegment srcSeg, final MemorySegmentRequest mSegReq) { - Objects.requireNonNull(srcSeg, "The source MemorySegment must not be null"); - final long segCap = srcSeg.byteSize(); - - final int preLongs = extractPreLongs(srcSeg); - final int serVer = extractSerVer(srcSeg); - final int familyID = extractFamilyID(srcSeg); - final int flags = extractFlags(srcSeg); - final int k = extractK(srcSeg); - - final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; //Preamble flags empty state - final long n = empty ? 0 : extractN(srcSeg); - - //VALIDITY CHECKS - checkPreLongs(preLongs); - checkFamilyID(familyID); - checkDoublesSerVer(serVer, MIN_DIRECT_DOUBLES_SER_VER); - checkDirectFlags(flags); //Cannot be compact - checkK(k); - checkCompact(serVer, flags); - checkDirectSegCapacity(k, n, segCap); - checkEmptyAndN(empty, n); - - return new DirectUpdateDoublesSketch(k, srcSeg, mSegReq); - } - - //**END CONSTRUCTORS** - - @Override - public double getMaxItem() { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return seg_.get(JAVA_DOUBLE_UNALIGNED, MAX_DOUBLE); - } - - @Override - public double getMinItem() { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return seg_.get(JAVA_DOUBLE_UNALIGNED, MIN_DOUBLE); - } - - @Override - public long getN() { - return (seg_.byteSize() < COMBINED_BUFFER) ? 0 : seg_.get(JAVA_LONG_UNALIGNED, N_LONG); - } - - @Override - public boolean hasMemorySegment() { - return (seg_ != null); - } - - @Override - public boolean isOffHeap() { - return (seg_ != null) ? seg_.isNative() : false; - } - - @Override - public boolean isReadOnly() { - return seg_.isReadOnly(); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return MemorySegmentStatus.isSameResource(seg_, that); - } - - @Override - public void update(final double dataItem) { - if (Double.isNaN(dataItem)) { return; } - if (seg_.isReadOnly()) { throw new SketchesReadOnlyException("This sketch is read only."); } - final int curBBCount = getBaseBufferCount(); - final int newBBCount = curBBCount + 1; //derived, not stored - - //must check MemorySegment capacity before we put anything in it - final int combBufItemCap = getCombinedBufferItemCapacity(); - if (newBBCount > combBufItemCap) { //newBBCount can never exceed 2 * k. - //unlike the heap sketch, this will grow the base buffer immediately to full size. - seg_ = growCombinedSegBuffer(2 * getK()); - } - - final long curN = getN(); - final long newN = curN + 1; - - if (curN == 0) { //set min and max quantiles - putMaxItem(dataItem); - putMinItem(dataItem); - } else { - if (dataItem > getMaxItem()) { putMaxItem(dataItem); } - if (dataItem < getMinItem()) { putMinItem(dataItem); } - } - - seg_.set(JAVA_DOUBLE_UNALIGNED, COMBINED_BUFFER + ((long) curBBCount * Double.BYTES), dataItem); //put the item - seg_.set(JAVA_BYTE, FLAGS_BYTE, (byte) 0); //not compact, not ordered, not empty - - if (newBBCount == (2 * k_)) { //Propagate - // make sure there will be enough levels for the propagation - final int curSegItemCap = getCombinedBufferItemCapacity(); - final int itemSpaceNeeded = DoublesUpdateImpl.getRequiredItemCapacity(k_, newN); - - //check seg has capacity to accommodate new level - if (itemSpaceNeeded > curSegItemCap) { - // copies base buffer plus old levels, adds space for new level - seg_ = growCombinedSegBuffer(itemSpaceNeeded); - } - - // sort base buffer via accessor which modifies the underlying base buffer, - // then use as one of the inputs to propagate-carry - final DoublesSketchAccessor bbAccessor = DoublesSketchAccessor.wrap(this, true); - bbAccessor.sort(); - - final long newBitPattern = DoublesUpdateImpl.inPlacePropagateCarry( - 0, // starting level - null, - bbAccessor, - true, - k_, - DoublesSketchAccessor.wrap(this, true), - getBitPattern() - ); - - assert newBitPattern == computeBitPattern(k_, newN); // internal consistency check - //bit pattern on direct is always derived, no need to save it. - } - putN(newN); - doublesSV = null; - } - - @Override - public void reset() { - if (seg_.isReadOnly()) { throw new SketchesReadOnlyException("This sketch is read only."); } - if (seg_.byteSize() >= COMBINED_BUFFER) { - seg_.set(JAVA_BYTE, FLAGS_BYTE, (byte) EMPTY_FLAG_MASK); //not compact, not ordered - seg_.set(JAVA_LONG_UNALIGNED, N_LONG, 0L); - seg_.set(JAVA_DOUBLE_UNALIGNED, MIN_DOUBLE, Double.NaN); - seg_.set(JAVA_DOUBLE_UNALIGNED, MAX_DOUBLE, Double.NaN); - } - } - - //Restricted overrides - - @Override - int getBaseBufferCount() { - return ClassicUtil.computeBaseBufferItems(getK(), getN()); - } - - @Override - long getBitPattern() { - final int k = getK(); - final long n = getN(); - return ClassicUtil.computeBitPattern(k, n); - } - - @Override - double[] getCombinedBuffer() { - final int k = getK(); - if (isEmpty()) { return new double[k << 1]; } //2K - final long n = getN(); - final int itemCap = ClassicUtil.computeCombinedBufferItemCapacity(k, n); - final double[] combinedBuffer = new double[itemCap]; - MemorySegment.copy(seg_, JAVA_DOUBLE_UNALIGNED, COMBINED_BUFFER, combinedBuffer, 0, itemCap); - return combinedBuffer; - } - - @Override - int getCombinedBufferItemCapacity() { - return Math.max(0, (int)seg_.byteSize() - COMBINED_BUFFER) / Double.BYTES; - } - - @Override - MemorySegment getMemorySegment() { - return seg_; - } - - @Override - UpdatableQuantilesDoublesSketch getSketchAndReset() { - final HeapUpdateDoublesSketch skCopy = HeapUpdateDoublesSketch.heapifyInstance(seg_); - reset(); - return skCopy; - } - - @Override - double[] growCombinedBuffer(final int curCombBufItemCap, final int itemSpaceNeeded) { - if (seg_.isReadOnly()) { throw new SketchesReadOnlyException("This sketch is read only."); } - seg_ = growCombinedSegBuffer(itemSpaceNeeded); - // copy out any data that was there - final double[] newCombBuf = new double[itemSpaceNeeded]; - MemorySegment.copy(seg_, JAVA_DOUBLE_UNALIGNED, COMBINED_BUFFER, newCombBuf, 0, curCombBufItemCap); - return newCombBuf; - } - - //Puts - - @Override - void putMinItem(final double minQuantile) { - if (seg_.isReadOnly()) { throw new SketchesReadOnlyException("This sketch is read only."); } - assert (seg_.byteSize() >= COMBINED_BUFFER); - seg_.set(JAVA_DOUBLE_UNALIGNED, MIN_DOUBLE, minQuantile); - } - - @Override - void putMaxItem(final double maxQuantile) { - if (seg_.isReadOnly()) { throw new SketchesReadOnlyException("This sketch is read only."); } - assert (seg_.byteSize() >= COMBINED_BUFFER); - seg_.set(JAVA_DOUBLE_UNALIGNED, MAX_DOUBLE, maxQuantile); - } - - @Override - void putN(final long n) { - if (seg_.isReadOnly()) { throw new SketchesReadOnlyException("This sketch is read only."); } - assert (seg_.byteSize() >= COMBINED_BUFFER); - seg_.set(JAVA_LONG_UNALIGNED, N_LONG, n); - } - - @Override - void putCombinedBuffer(final double[] combinedBuffer) { - if (seg_.isReadOnly()) { throw new SketchesReadOnlyException("This sketch is read only."); } - MemorySegment.copy(combinedBuffer, 0, seg_, JAVA_DOUBLE_UNALIGNED, COMBINED_BUFFER, combinedBuffer.length); - } - - @Override - void putBaseBufferCount(final int baseBufferCount) { - if (seg_.isReadOnly()) { throw new SketchesReadOnlyException("This sketch is read only."); } - } - - @Override - void putBitPattern(final long bitPattern) { - if (seg_.isReadOnly()) { throw new SketchesReadOnlyException("This sketch is read only."); } - } - - //Direct supporting methods - - private MemorySegment growCombinedSegBuffer(final int itemSpaceNeeded) { - final long segBytes = seg_.byteSize(); - final int needBytes = (itemSpaceNeeded << 3) + COMBINED_BUFFER; //+ preamble + min & max - assert needBytes > segBytes; - - mSegReq_ = (mSegReq_ == null) ? MemorySegmentRequest.DEFAULT : mSegReq_; - - final MemorySegment newSeg = mSegReq_.request(needBytes); - MemorySegment.copy(seg_, 0, newSeg, 0, segBytes); - mSegReq_.requestClose(seg_); - return newSeg; - } - - //Checks - - /** - * Checks the validity of the direct MemorySegment capacity assuming n, k. - * @param k the given k - * @param n the given n - * @param segCapBytes the current MemorySegment capacity in bytes - */ - static void checkDirectSegCapacity(final int k, final long n, final long segCapBytes) { - final int reqBufBytes = getUpdatableStorageBytes(k, n); - - if (segCapBytes < reqBufBytes) { - throw new SketchesArgumentException("Possible corruption: MemorySegment capacity too small: " - + segCapBytes + " < " + reqBufBytes); - } - } - - static void checkCompact(final int serVer, final int flags) { - final boolean compact = (serVer == 2) || ((flags & COMPACT_FLAG_MASK) > 0); - if (compact) { - throw new SketchesArgumentException("MemorySegment is in compact form and is not supported for this writableWrap Instance."); - } - } - - static void checkPreLongs(final int preLongs) { - if ((preLongs < 1) || (preLongs > 2)) { - throw new SketchesArgumentException( - "Possible corruption: PreLongs must be 1 or 2: " + preLongs); - } - } - - static void checkDirectFlags(final int flags) { - final int allowedFlags = //Cannot be compact! - READ_ONLY_FLAG_MASK | EMPTY_FLAG_MASK | ORDERED_FLAG_MASK; - final int flagsMask = ~allowedFlags; - if ((flags & flagsMask) > 0) { - throw new SketchesArgumentException( - "Possible corruption: Invalid flags field: Cannot be compact! " - + Integer.toBinaryString(flags)); - } - } - - static void checkEmptyAndN(final boolean empty, final long n) { - if (empty && (n > 0)) { - throw new SketchesArgumentException( - "Possible corruption: Empty Flag = true and N > 0: " + n); - } - } -} diff --git a/src/main/java/org/apache/datasketches/quantiles/DoublesArrayAccessor.java b/src/main/java/org/apache/datasketches/quantiles/DoublesArrayAccessor.java deleted file mode 100644 index 7fcf38a2d..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/DoublesArrayAccessor.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import java.util.Arrays; - -/** - * @author Jon Malkin - */ -final class DoublesArrayAccessor extends DoublesBufferAccessor { - private int numItems_; - private double[] buffer_; - - private DoublesArrayAccessor(final double[] buffer) { - numItems_ = buffer.length; - buffer_ = buffer; - } - - static DoublesArrayAccessor wrap(final double[] buffer) { - return new DoublesArrayAccessor(buffer); - } - - static DoublesArrayAccessor initialize(final int numItems) { - return new DoublesArrayAccessor(new double[numItems]); - } - - @Override - double get(final int index) { - assert index >= 0 && index < numItems_; - return buffer_[index]; - } - - @Override - double set(final int index, final double quantile) { - assert index >= 0 && index < numItems_; - - final double retVal = buffer_[index]; - buffer_[index] = quantile; - return retVal; - } - - @Override - int numItems() { - return numItems_; - } - - @Override - double[] getArray(final int fromIdx, final int numItems) { - return Arrays.copyOfRange(buffer_, fromIdx, fromIdx + numItems); - } - - @Override - void putArray(final double[] srcArray, final int srcIndex, final int dstIndex, final int numItems) { - System.arraycopy(srcArray, srcIndex, buffer_, dstIndex, numItems); - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/DoublesBufferAccessor.java b/src/main/java/org/apache/datasketches/quantiles/DoublesBufferAccessor.java deleted file mode 100644 index fecc96d56..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/DoublesBufferAccessor.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -/** - * The hierarchy of Accessors enable easy access to the data structure of the Classic Quantiles sketches. - * - * @author Jon Malkin - */ -abstract class DoublesBufferAccessor { - - abstract double get(final int index); - - abstract double set(final int index, final double quantile); - - abstract int numItems(); - - abstract double[] getArray(int fromIdx, int numItems); - - abstract void putArray(double[] srcArray, int srcIndex, int dstIndex, int numItems); -} diff --git a/src/main/java/org/apache/datasketches/quantiles/DoublesByteArrayImpl.java b/src/main/java/org/apache/datasketches/quantiles/DoublesByteArrayImpl.java deleted file mode 100644 index 0deea1d9b..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/DoublesByteArrayImpl.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static org.apache.datasketches.quantiles.ClassicUtil.DOUBLES_SER_VER; -import static org.apache.datasketches.quantiles.ClassicUtil.computeBaseBufferItems; -import static org.apache.datasketches.quantiles.ClassicUtil.computeTotalLevels; -import static org.apache.datasketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.ORDERED_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.READ_ONLY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.insertFamilyID; -import static org.apache.datasketches.quantiles.PreambleUtil.insertFlags; -import static org.apache.datasketches.quantiles.PreambleUtil.insertK; -import static org.apache.datasketches.quantiles.PreambleUtil.insertMaxDouble; -import static org.apache.datasketches.quantiles.PreambleUtil.insertMinDouble; -import static org.apache.datasketches.quantiles.PreambleUtil.insertN; -import static org.apache.datasketches.quantiles.PreambleUtil.insertPreLongs; -import static org.apache.datasketches.quantiles.PreambleUtil.insertSerVer; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.Family; - -/** - * The doubles to byte array algorithms. - * - * @author Lee Rhodes - * @author Jon Malkin - */ -final class DoublesByteArrayImpl { - - private DoublesByteArrayImpl() {} - - static byte[] toByteArray(final QuantilesDoublesSketch sketch, final boolean ordered, final boolean compact) { - final boolean empty = sketch.isEmpty(); - - //create the flags byte - final int flags = (empty ? EMPTY_FLAG_MASK : 0) - | (ordered ? ORDERED_FLAG_MASK : 0) - | (compact ? (COMPACT_FLAG_MASK | READ_ONLY_FLAG_MASK) : 0); - - if (empty && !sketch.hasMemorySegment()) { //empty & !has MemorySegment - final byte[] outByteArr = new byte[Long.BYTES]; - final MemorySegment segOut = MemorySegment.ofArray(outByteArr); - final int preLongs = 1; - insertPre0(segOut, preLongs, flags, sketch.getK()); - return outByteArr; - } - //not empty || direct; flags passed for convenience - return convertToByteArray(sketch, flags, ordered, compact); - } - - /** - * Returns a byte array, including preamble, min, max and data extracted from the sketch. - * @param sketch the given QuantilesDoublesSketch - * @param flags the Flags field - * @param ordered true if the desired form of the resulting array has the base buffer sorted. - * @param compact true if the desired form of the resulting array is in compact form. - * @return a byte array, including preamble, min, max and data extracted from the Combined Buffer. - */ - private static byte[] convertToByteArray(final QuantilesDoublesSketch sketch, final int flags, - final boolean ordered, final boolean compact) { - final int preLongs = sketch.isEmpty() ? 1 : 2; - - final int outBytes = (compact ? sketch.getCurrentCompactSerializedSizeBytes() - : sketch.getCurrentUpdatableSerializedSizeBytes()); - - final byte[] outByteArr = new byte[outBytes]; - final MemorySegment segOut = MemorySegment.ofArray(outByteArr); - - //insert pre0 - final int k = sketch.getK(); - insertPre0(segOut, preLongs, flags, k); - if (sketch.isEmpty()) { return outByteArr; } - - //insert N, min, max - final long n = sketch.getN(); - insertN(segOut, n); - insertMinDouble(segOut, sketch.isEmpty() ? Double.NaN : sketch.getMinItem()); - insertMaxDouble(segOut, sketch.isEmpty() ? Double.NaN : sketch.getMaxItem()); - - // If not-compact, have accessor always report full levels. Then use level size to determine - // whether to copy data out. - final DoublesSketchAccessor dsa = DoublesSketchAccessor.wrap(sketch, !compact); - - final int minAndMax = 2; // extra space for min and max quantiles - long segOffsetBytes = (preLongs + minAndMax) << 3; - - // might need to sort base buffer but don't want to change input sketch - final int bbCnt = computeBaseBufferItems(k, n); - if (bbCnt > 0) { //Base buffer items only - final double[] bbItemsArr = dsa.getArray(0, bbCnt); - if (ordered) { Arrays.sort(bbItemsArr); } - MemorySegment.copy(bbItemsArr, 0, segOut, JAVA_DOUBLE_UNALIGNED, segOffsetBytes, bbCnt); - } - // If n < 2k, totalLevels == 0 so ok to overshoot the offset update - segOffsetBytes += (compact ? bbCnt : 2 * k) << 3; - - // If serializing from a compact sketch to a non-compact form, we may end up copying data for a - // higher level one or more times into an unused level. A bit wasteful, but not incorrect. - final int totalLevels = computeTotalLevels(sketch.getBitPattern()); - for (int lvl = 0; lvl < totalLevels; ++lvl) { - dsa.setLevel(lvl); - if (dsa.numItems() > 0) { - assert dsa.numItems() == k; - MemorySegment.copy(dsa.getArray(0, k), 0, segOut, JAVA_DOUBLE_UNALIGNED, segOffsetBytes, k); - segOffsetBytes += (k << 3); - } - } - - return outByteArr; - } - - private static void insertPre0(final MemorySegment wseg, - final int preLongs, final int flags, final int k) { - insertPreLongs(wseg, preLongs); - insertSerVer(wseg, DOUBLES_SER_VER); - insertFamilyID(wseg, Family.QUANTILES.getID()); - insertFlags(wseg, flags); - insertK(wseg, k); - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/DoublesMergeImpl.java b/src/main/java/org/apache/datasketches/quantiles/DoublesMergeImpl.java deleted file mode 100644 index c8ae7de0a..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/DoublesMergeImpl.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.Util.checkIfPowerOf2; -import static org.apache.datasketches.common.Util.clearBits; -import static org.apache.datasketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.FLAGS_BYTE; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Down-sampling and merge algorithms for doubles quantiles. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -final class DoublesMergeImpl { - - private DoublesMergeImpl() {} - - /** - * Merges the source sketch into the target sketch that can have a smaller K parameter. - * However, it is required that the ratio of the two K parameters be a power of 2. - * I.e., source.getK() = target.getK() * 2^(nonnegative integer). - * The source is not modified. - * - *

Note: It is easy to prove that the following simplified code which launches multiple waves of - * carry propagation does exactly the same amount of merging work (including the work of - * allocating fresh buffers) as the more complicated and seemingly more efficient approach that - * tracks a single carry propagation wave through both sketches. - * - *

This simplified code probably does do slightly more "outer loop" work, but I am pretty - * sure that even that is within a constant factor of the more complicated code, plus the - * total amount of "outer loop" work is at least a factor of K smaller than the total amount of - * merging work, which is identical in the two approaches. - * - *

Note: a two-way merge that doesn't modify either of its two inputs could be implemented - * by making a deep copy of the larger sketch and then merging the smaller one into it. - * However, it was decided not to do this. - * - * @param src The source sketch - * @param tgt The target sketch - */ - static void mergeInto(final QuantilesDoublesSketch src, final UpdatableQuantilesDoublesSketch tgt) { - final int srcK = src.getK(); - final int tgtK = tgt.getK(); - final long srcN = src.getN(); - final long tgtN = tgt.getN(); - - if (srcK != tgtK) { - downSamplingMergeInto(src, tgt); - return; - } - //The remainder of this code is for the case where the k's are equal - - final DoublesSketchAccessor srcSketchBuf = DoublesSketchAccessor.wrap(src, false); - final long nFinal = tgtN + srcN; - - for (int i = 0; i < srcSketchBuf.numItems(); i++) { // update only the base buffer - tgt.update(srcSketchBuf.get(i)); - } - - final int spaceNeeded = DoublesUpdateImpl.getRequiredItemCapacity(tgtK, nFinal); - final int tgtCombBufItemCap = tgt.getCombinedBufferItemCapacity(); - if (spaceNeeded > tgtCombBufItemCap) { //copies base buffer plus current levels - tgt.growCombinedBuffer(tgtCombBufItemCap, spaceNeeded); - } - - final DoublesArrayAccessor scratch2KAcc = DoublesArrayAccessor.initialize(2 * tgtK); - - long srcBitPattern = src.getBitPattern(); - assert srcBitPattern == (srcN / (2L * srcK)); - - final DoublesSketchAccessor tgtSketchBuf = DoublesSketchAccessor.wrap(tgt, true); - long newTgtBitPattern = tgt.getBitPattern(); - - for (int srcLvl = 0; srcBitPattern != 0L; srcLvl++, srcBitPattern >>>= 1) { - if ((srcBitPattern & 1L) > 0L) { - newTgtBitPattern = DoublesUpdateImpl.inPlacePropagateCarry( - srcLvl, - srcSketchBuf.setLevel(srcLvl), - scratch2KAcc, - false, - tgtK, - tgtSketchBuf, - newTgtBitPattern - ); - } - } - - if (tgt.hasMemorySegment() && (nFinal > 0)) { - final MemorySegment seg = tgt.getMemorySegment(); - clearBits(seg, FLAGS_BYTE, (byte) EMPTY_FLAG_MASK); - } - - tgt.putN(nFinal); - tgt.putBitPattern(newTgtBitPattern); // no-op if direct - - assert (tgt.getN() / (2L * tgtK)) == tgt.getBitPattern(); // internal consistency check - - double srcMax = src.getMaxItem(); - srcMax = Double.isNaN(srcMax) ? Double.NEGATIVE_INFINITY : srcMax; - double srcMin = src.getMinItem(); - srcMin = Double.isNaN(srcMin) ? Double.POSITIVE_INFINITY : srcMin; - - double tgtMax = tgt.getMaxItem(); - tgtMax = Double.isNaN(tgtMax) ? Double.NEGATIVE_INFINITY : tgtMax; - double tgtMin = tgt.getMinItem(); - tgtMin = Double.isNaN(tgtMin) ? Double.POSITIVE_INFINITY : tgtMin; - - tgt.putMaxItem(Math.max(srcMax, tgtMax)); - tgt.putMinItem(Math.min(srcMin, tgtMin)); - } - - /** - * Merges the source sketch into the target sketch that can have a smaller K. - * However, it is required that the ratio of the two K's be a power of 2. - * I.e., source.getK() = target.getK() * 2^(nonnegative integer). - * The source is not modified. - * - * @param src The source sketch - * @param tgt The target sketch - */ - //also used by QuantilesDoublesSketch, QuantilesDoublesUnionImpl and HeapDoublesSketchTest - static void downSamplingMergeInto(final QuantilesDoublesSketch src, final UpdatableQuantilesDoublesSketch tgt) { - final int sourceK = src.getK(); - final int targetK = tgt.getK(); - final long tgtN = tgt.getN(); - - if ((sourceK % targetK) != 0) { - throw new SketchesArgumentException( - "source.getK() must equal target.getK() * 2^(nonnegative integer)."); - } - - final int downFactor = sourceK / targetK; - checkIfPowerOf2(downFactor, "source.getK()/target.getK() ratio"); - final int lgDownFactor = Integer.numberOfTrailingZeros(downFactor); - - if (src.isEmpty()) { return; } - - final DoublesSketchAccessor srcSketchBuf = DoublesSketchAccessor.wrap(src, false); - final long nFinal = tgtN + src.getN(); - - for (int i = 0; i < srcSketchBuf.numItems(); i++) { // update only the base buffer - tgt.update(srcSketchBuf.get(i)); - } - - final int spaceNeeded = DoublesUpdateImpl.getRequiredItemCapacity(targetK, nFinal); - final int curCombBufCap = tgt.getCombinedBufferItemCapacity(); - if (spaceNeeded > curCombBufCap) { //copies base buffer plus current levels - tgt.growCombinedBuffer(curCombBufCap, spaceNeeded); - } - - //working scratch buffers - final DoublesArrayAccessor scratch2KAcc = DoublesArrayAccessor.initialize(2 * targetK); - final DoublesArrayAccessor downScratchKAcc = DoublesArrayAccessor.initialize(targetK); - - final DoublesSketchAccessor tgtSketchBuf = DoublesSketchAccessor.wrap(tgt, true); - - long srcBitPattern = src.getBitPattern(); - long newTgtBitPattern = tgt.getBitPattern(); - for (int srcLvl = 0; srcBitPattern != 0L; srcLvl++, srcBitPattern >>>= 1) { - if ((srcBitPattern & 1L) > 0L) { - justZipWithStride( - srcSketchBuf.setLevel(srcLvl), - downScratchKAcc, - targetK, - downFactor - ); - newTgtBitPattern = DoublesUpdateImpl.inPlacePropagateCarry( - srcLvl + lgDownFactor, //starting level - downScratchKAcc, //optSrcKBuf, - scratch2KAcc, //size2KBuf, - false, //do mergeInto version - targetK, - tgtSketchBuf, - newTgtBitPattern - ); - - tgt.putBitPattern(newTgtBitPattern); //off-heap is a no-op - } - } - if (tgt.hasMemorySegment() && (nFinal > 0)) { - final MemorySegment seg = tgt.getMemorySegment(); - clearBits(seg, FLAGS_BYTE, (byte) EMPTY_FLAG_MASK); - } - tgt.putN(nFinal); - - assert (tgt.getN() / (2L * targetK)) == newTgtBitPattern; // internal consistency check - - double srcMax = src.getMaxItem(); - srcMax = Double.isNaN(srcMax) ? Double.NEGATIVE_INFINITY : srcMax; - double srcMin = src.getMinItem(); - srcMin = Double.isNaN(srcMin) ? Double.POSITIVE_INFINITY : srcMin; - - double tgtMax = tgt.getMaxItem(); - tgtMax = Double.isNaN(tgtMax) ? Double.NEGATIVE_INFINITY : tgtMax; - double tgtMin = tgt.getMinItem(); - tgtMin = Double.isNaN(tgtMin) ? Double.POSITIVE_INFINITY : tgtMin; - - if (srcMax > tgtMax) { tgt.putMaxItem(srcMax); } - if (srcMin < tgtMin) { tgt.putMinItem(srcMin); } - } - - private static void justZipWithStride( - final DoublesBufferAccessor bufA, // input - final DoublesBufferAccessor bufC, // output - final int kC, // number of items that should be in the output - final int stride) { - final int randomOffset = QuantilesDoublesSketch.rand.nextInt(stride); - for (int a = randomOffset, c = 0; c < kC; a += stride, c++ ) { - bufC.set(c, bufA.get(a)); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/DoublesSketchAccessor.java b/src/main/java/org/apache/datasketches/quantiles/DoublesSketchAccessor.java deleted file mode 100644 index 4c4bdd5cd..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/DoublesSketchAccessor.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.quantiles.PreambleUtil.COMBINED_BUFFER; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This allows access to package-private levels and data in whatever doubles quantiles sketch you give - * it: on-heap, off-heap; compact and non-compact - * @author Jon Malkin - */ -abstract class DoublesSketchAccessor extends DoublesBufferAccessor { - static final int BB_LVL_IDX = -1; - - final QuantilesDoublesSketch ds_; - final boolean forceSize_; - - long n_; - int currLvl_; - int numItems_; - int offset_; //bytes for Direct, doubles for heap - - DoublesSketchAccessor( - final QuantilesDoublesSketch ds, - final boolean forceSize, - final int level) { - checkLvl(level); - ds_ = ds; - forceSize_ = forceSize; - setLevel(level); - } - - private static final void checkLvl(final int level) { - if ((level != BB_LVL_IDX) && (level < 0)) { - throw new SketchesArgumentException("Parameter level is < 0."); - } - } - - /** - * Wrap the given QuantilesDoublesSketch - * @param ds the given QuantilesDoublesSketch - * @param forceSize Generally, this must be true if modeling an updatable sketch, i.e., not compact. - * See {@link #setLevel(int) setLevel(int)} below. - * - * @return this - */ - static DoublesSketchAccessor wrap(final QuantilesDoublesSketch ds, final boolean forceSize) { - if (ds.hasMemorySegment()) { - return new DirectDoublesSketchAccessor(ds, forceSize, BB_LVL_IDX); - } - return new HeapDoublesSketchAccessor(ds, forceSize, BB_LVL_IDX); - } - - abstract DoublesSketchAccessor copyAndSetLevel(final int level); - - /* - * This initializes the following internal member variables: - *

    - *
  • n_ The local copy of QuantilesDoublesSketch.getN().
  • - *
  • currLvl_ The current level being processed.
  • - *
  • numItems_ The number of items in this level.
  • - *
  • offset_ If accessing a MemorySegment sketch, this is bytes offset from the start of the segment. - * If the sketch is on-heap, this is the item offset within the given level in item units.
  • - *
- * - *

If the constructor parameter forceSize is true and accessing the BaseBuffer, - * it forces the numItems_ to be 2K independent of the actual getBaseBufferCount().

- * - *

If forceSize is false and accessing the BaseBuffer, numItems_ is set to getBaseBufferCount(). - * - *

If forceSize is true and accessing a higher level, the numItems_ is always K.

- * - *

If forceSize is false and accessing a higher level, numItems_ is K - * only if the level is valid (i.e., a corresponding bit in bitPattern is one), otherwise it is zero.

- * - * @param lvl the given level to process. - */ - DoublesSketchAccessor setLevel(final int lvl) { - currLvl_ = lvl; - if (lvl == BB_LVL_IDX) { - numItems_ = (forceSize_ ? ds_.getK() * 2 : ds_.getBaseBufferCount()); - offset_ = (ds_.hasMemorySegment() ? COMBINED_BUFFER : 0); - } else { - //compact only keeps valid levels, updatable retains all levels even if not valid. - if (((ds_.getBitPattern() & (1L << lvl)) > 0) || forceSize_) { - numItems_ = ds_.getK(); - } else { - numItems_ = 0; - } - - // determine offset in two parts - // 1. index into combined buffer (compact vs update) - // 2. adjust if byte offset (direct) instead of doubles array index (heap) - final int levelStart; - if (ds_.isCompact()) { - levelStart = ds_.getBaseBufferCount() + (countValidLevelsBelow(lvl) * ds_.getK()); - } else { - levelStart = (2 + currLvl_) * ds_.getK(); - } - - if (ds_.hasMemorySegment()) { - final int preLongsAndExtra = Family.QUANTILES.getMaxPreLongs() + 2; // +2 for min, max - offset_ = (preLongsAndExtra + levelStart) << 3; //bytes relative to MemorySegment start - } else { - offset_ = levelStart; //double array index - } - } - - n_ = ds_.getN(); - - return this; - } - - // getters/queries - - @Override - int numItems() { - return numItems_; - } - - @Override - abstract double get(final int index); - - @Override - abstract double[] getArray(final int fromIdx, final int numItems); - - // setters/modifying methods - - @Override - abstract double set(final int index, final double quantile); - - @Override - abstract void putArray(final double[] srcArray, final int srcIndex, - final int dstIndex, final int numItems); - - abstract void sort(); - - /** - * Counts number of full levels in the sketch below tgtLvl. Useful for computing the level - * offset in a compact sketch. - * @param tgtLvl Target level in the sketch - * @return Number of full levels in the sketch below tgtLvl - */ - private int countValidLevelsBelow(final int tgtLvl) { - int count = 0; - long bitPattern = ds_.getBitPattern(); - for (int i = 0; (i < tgtLvl) && (bitPattern > 0); ++i, bitPattern >>>= 1) { - if ((bitPattern & 1L) > 0L) { - ++count; - } - } - return count; - - // shorter implementation, testing suggests a tiny bit slower - //final long mask = (1 << tgtLvl) - 1; - //return Long.bitCount(ds_.getBitPattern() & mask); - } -} diff --git a/src/main/java/org/apache/datasketches/quantiles/DoublesUpdateImpl.java b/src/main/java/org/apache/datasketches/quantiles/DoublesUpdateImpl.java deleted file mode 100644 index f76ddebad..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/DoublesUpdateImpl.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -/** - * The doubles update algorithms for quantiles. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -final class DoublesUpdateImpl { - - private DoublesUpdateImpl() {} - - /** - * Returns item capacity needed based on n and k, which may or may not be larger than - * current space allocated. - * @param k current k - * @param newN the new n - * @return item capacity based on n and k. It may or may not be different. - */ - //important: newN might not equal n_ - // This only increases the size and does not touch or move any data. - static int getRequiredItemCapacity(final int k, final long newN) { - final int numLevelsNeeded = ClassicUtil.computeNumLevelsNeeded(k, newN); - if (numLevelsNeeded == 0) { - // don't need any levels yet, and might have small base buffer; this can happen during a merge - return 2 * k; - } - // from here on we need a full-size base buffer and at least one level - assert newN >= (2L * k); - assert numLevelsNeeded > 0; - final int spaceNeeded = (2 + numLevelsNeeded) * k; - return spaceNeeded; - } - - /** - * This is used to propagate-carry (ripple-carry) an update that will cause the full, sorted - * base buffer to empty into the levels hierarchy, thus creating a ripple effect up - * through the higher levels. It is also used during merge operations with the only difference - * is the base buffer(s) could have valid data and is less than full. - * This distinction is determined by the doUpdateVersion flag. - * - *

Prior to this method being called, any extra space for the combined buffer required - * by either the update or merge operations must already be allocated.

- * - *

Update Version: The base buffer is initially full, and after it has been sorted and - * zipped, will be used as a size2KBuf scratch buffer for the remaining recursive carries. - * The lowest non-valid level, determined by the bit-pattern, will used internally as a - * size K scratch buffer and the ultimate target. - * Thus no additional buffer storage is required outside the combined buffer.

- * - *

Merge Version: During merging, each level from the source sketch that must be - * merged is entered into this method and is assigned to the optional source size K buffer - * (optSrcKBuf). Because the base buffer may have data, a separate size2K - * scratch buffer must be provided. The next-lowest. non-valid level, determined by the - * bit-pattern, will used as a sizeKBuf scratch buffer.

- * - *

Downsample Merge Version: This is a variant of the above Merge Version, except at - * each level the downsampling is performed and the target level is computed for the target merge. - * In this case the optSrcKBuf is the result of the downsample process and needs to be allocated - * for that purpose. - * - *

Recursive carry: This starts with a given sorted, size 2K buffer, which is zipped - * into a size K buffer. If the next level is not valid, the size K buffer is already in position, - * the bit pattern is updated and returned.

- * - *

If the next level is valid, it is merged with the size K buffer into the size 2K buffer. - * Continue the recursion until a non-valid level becomes filled by the size K buffer, - * the bit pattern is updated and returned.

- * - * @param startingLevel 0-based starting level - * @param optSrcKBuf optional, size k source, read only buffer - * @param size2KBuf size 2k scratch buffer - * @param doUpdateVersion true if update version - * @param k the target k - * @param tgtSketchBuf the given DoublesSketchAccessor - * @param bitPattern the current bitPattern, prior to this call - * @return The updated bit pattern. The updated combined buffer is output as a side effect. - */ - static long inPlacePropagateCarry( - final int startingLevel, - final DoublesBufferAccessor optSrcKBuf, - final DoublesBufferAccessor size2KBuf, - final boolean doUpdateVersion, - final int k, - final DoublesSketchAccessor tgtSketchBuf, - final long bitPattern) { - final int endingLevel = ClassicUtil.lowestZeroBitStartingAt(bitPattern, startingLevel); - tgtSketchBuf.setLevel(endingLevel); - if (doUpdateVersion) { // update version of computation - // its is okay for optSrcKBuf to be null in this case - zipSize2KBuffer(size2KBuf, tgtSketchBuf); - } else { // mergeInto version of computation - assert (optSrcKBuf != null); - tgtSketchBuf.putArray(optSrcKBuf.getArray(0, k), 0, 0, k); - } - - for (int lvl = startingLevel; lvl < endingLevel; lvl++) { - assert (bitPattern & (1L << lvl)) > 0; // internal consistency check - final DoublesSketchAccessor currLevelBuf = tgtSketchBuf.copyAndSetLevel(lvl); - mergeTwoSizeKBuffers( - currLevelBuf, // target level: lvl - tgtSketchBuf, // target level: endingLevel - size2KBuf); - zipSize2KBuffer(size2KBuf, tgtSketchBuf); - } // end of loop over lower levels - - // update bit pattern with binary-arithmetic ripple carry - return bitPattern + (1L << startingLevel); - } - - private static void zipSize2KBuffer( - final DoublesBufferAccessor bufIn, - final DoublesBufferAccessor bufOut) { - final int randomOffset = QuantilesDoublesSketch.rand.nextBoolean() ? 1 : 0; - final int limOut = bufOut.numItems(); - for (int idxIn = randomOffset, idxOut = 0; idxOut < limOut; idxIn += 2, idxOut++) { - bufOut.set(idxOut, bufIn.get(idxIn)); - } - } - - private static void mergeTwoSizeKBuffers( - final DoublesBufferAccessor src1, - final DoublesBufferAccessor src2, - final DoublesBufferAccessor dst) { - assert src1.numItems() == src2.numItems(); - - final int k = src1.numItems(); - int i1 = 0; - int i2 = 0; - int iDst = 0; - while ((i1 < k) && (i2 < k)) { - if (src2.get(i2) < src1.get(i1)) { - dst.set(iDst++, src2.get(i2++)); - } else { - dst.set(iDst++, src1.get(i1++)); - } - } - - if (i1 < k) { - final int numItems = k - i1; - dst.putArray(src1.getArray(i1, numItems), 0, iDst, numItems); - } else { - final int numItems = k - i2; - dst.putArray(src2.getArray(i2, numItems), 0, iDst, numItems); - } - } -} diff --git a/src/main/java/org/apache/datasketches/quantiles/DoublesUtil.java b/src/main/java/org/apache/datasketches/quantiles/DoublesUtil.java deleted file mode 100644 index da6b89579..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/DoublesUtil.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.quantiles.ClassicUtil.DOUBLES_SER_VER; -import static org.apache.datasketches.quantiles.ClassicUtil.computeCombinedBufferItemCapacity; -import static org.apache.datasketches.quantiles.ClassicUtil.computeNumLevelsNeeded; -import static org.apache.datasketches.quantiles.ClassicUtil.computeTotalLevels; -import static org.apache.datasketches.quantiles.ClassicUtil.computeValidLevels; -import static org.apache.datasketches.quantiles.ClassicUtil.getNormalizedRankError; - -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Utilities that support the doubles quantiles algorithms. - * - *

This class contains a highly specialized sort called blockyTandemMergeSort(). - * It also contains methods that are used while building histograms and other common - * functions.

- * - * @author Lee Rhodes - */ -final class DoublesUtil { - - private DoublesUtil() {} - - /** - * Returns an on-heap copy of the given sketch - * @param sketch the given sketch - * @return a copy of the given sketch - */ - static HeapUpdateDoublesSketch copyToHeap(final QuantilesDoublesSketch sketch) { - final HeapUpdateDoublesSketch qsCopy; - qsCopy = HeapUpdateDoublesSketch.newInstance(sketch.getK()); - qsCopy.putN(sketch.getN()); - qsCopy.putMinItem(sketch.isEmpty() ? Double.NaN : sketch.getMinItem()); - qsCopy.putMaxItem(sketch.isEmpty() ? Double.NaN : sketch.getMaxItem()); - qsCopy.putBaseBufferCount(sketch.getBaseBufferCount()); - qsCopy.putBitPattern(sketch.getBitPattern()); - - if (sketch.isCompact()) { - final int combBufItems = computeCombinedBufferItemCapacity(sketch.getK(), sketch.getN()); - final double[] combBuf = new double[combBufItems]; - qsCopy.putCombinedBuffer(combBuf); - final DoublesSketchAccessor sketchAccessor = DoublesSketchAccessor.wrap(sketch, false); - final DoublesSketchAccessor copyAccessor = DoublesSketchAccessor.wrap(qsCopy, false); - // start with BB - copyAccessor.putArray(sketchAccessor.getArray(0, sketchAccessor.numItems()), - 0, 0, sketchAccessor.numItems()); - - long bitPattern = sketch.getBitPattern(); - for (int lvl = 0; bitPattern != 0L; ++lvl, bitPattern >>>= 1) { - if ((bitPattern & 1L) > 0L) { - sketchAccessor.setLevel(lvl); - copyAccessor.setLevel(lvl); - copyAccessor.putArray(sketchAccessor.getArray(0, sketchAccessor.numItems()), - 0, 0, sketchAccessor.numItems()); - } - } - } else { - final double[] combBuf = sketch.getCombinedBuffer(); - qsCopy.putCombinedBuffer(Arrays.copyOf(combBuf, combBuf.length)); - } - return qsCopy; - } - - /** - * Check the validity of the given serialization version - * @param serVer the given serialization version - * @param minSupportedSerVer the oldest serialization version supported - */ - static void checkDoublesSerVer(final int serVer, final int minSupportedSerVer) { - final int max = DOUBLES_SER_VER; - if ((serVer > max) || (serVer < minSupportedSerVer)) { - throw new SketchesArgumentException( - "Possible corruption: Unsupported Serialization Version: " + serVer); - } - } - - static String toString(final boolean withLevels, final boolean withLevelsAndItems, final QuantilesDoublesSketch sk) { - final StringBuilder sb = new StringBuilder(); - sb.append(getSummary(sk)); - if (withLevels) { - sb.append(outputLevels(sk)); - } - if (withLevelsAndItems) { - sb.append(outputDataDetail(sk)); - } - return sb.toString(); - } - - private static String getSummary(final QuantilesDoublesSketch sk) { - final StringBuilder sb = new StringBuilder(); - final String thisSimpleName = sk.getClass().getSimpleName(); - final int k = sk.getK(); - final String kStr = String.format("%,d", k); - final long n = sk.getN(); - final String nStr = String.format("%,d", n); - final String bbCntStr = String.format("%,d", sk.getBaseBufferCount()); - final String combBufCapStr = String.format("%,d", sk.getCombinedBufferItemCapacity()); - final long bitPattern = sk.getBitPattern(); - final int neededLevels = computeNumLevelsNeeded(k, n); - final int totalLevels = computeTotalLevels(bitPattern); - final int validLevels = computeValidLevels(bitPattern); - final String retItemsStr = String.format("%,d", sk.getNumRetained()); - final int preBytes = sk.isEmpty() ? Long.BYTES : 2 * Long.BYTES; - final String cmptBytesStr = String.format("%,d", sk.getCurrentCompactSerializedSizeBytes()); - final String updtBytesStr = String.format("%,d", sk.getCurrentUpdatableSerializedSizeBytes()); - final double epsPmf = getNormalizedRankError(k, true); - final String epsPmfPctStr = String.format("%.3f%%", epsPmf * 100.0); - final double eps = getNormalizedRankError(k, false); - final String epsPctStr = String.format("%.3f%%", eps * 100.0); - final String segCap = sk.hasMemorySegment() ? Long.toString(sk.getMemorySegment().byteSize()) : ""; - final double minItem = sk.isEmpty() ? Double.NaN : sk.getMinItem(); - final double maxItem = sk.isEmpty() ? Double.NaN : sk.getMaxItem(); - - sb.append(LS).append("### Classic Quantiles ").append(thisSimpleName).append(" SUMMARY: ").append(LS); - sb.append(" Empty : ").append(sk.isEmpty()).append(LS); - sb.append(" Segment, Capacity bytes : ").append(sk.hasMemorySegment()).append(", ").append(segCap).append(LS); - sb.append(" Segment, ReadOnly : ").append(sk.hasMemorySegment() && sk.getMemorySegment().isReadOnly()).append(LS); - sb.append(" Estimation Mode : ").append(sk.isEstimationMode()).append(LS); - sb.append(" K : ").append(kStr).append(LS); - sb.append(" N : ").append(nStr).append(LS); - sb.append(" Levels (Needed, Total, Valid): ").append(neededLevels + ", " + totalLevels + ", " + validLevels).append(LS); - sb.append(" Level Bit Pattern : ").append(Long.toBinaryString(bitPattern)).append(LS); - sb.append(" Base Buffer Count : ").append(bbCntStr).append(LS); - sb.append(" Combined Buffer Capacity : ").append(combBufCapStr).append(LS); - sb.append(" Retained Items : ").append(retItemsStr).append(LS); - sb.append(" Preamble Bytes : ").append(preBytes).append(LS); - sb.append(" Compact Storage Bytes : ").append(cmptBytesStr).append(LS); - sb.append(" Updatable Storage Bytes : ").append(updtBytesStr).append(LS); - sb.append(" Normalized Rank Error : ").append(epsPctStr).append(LS); - sb.append(" Normalized Rank Error (PMF) : ").append(epsPmfPctStr).append(LS); - sb.append(" Min Item : ").append(String.format("%12.6e", minItem)).append(LS); - sb.append(" Max Item : ").append(String.format("%12.6e", maxItem)).append(LS); - sb.append("### END SKETCH SUMMARY").append(LS); - return sb.toString(); - } - - private static String outputLevels(final QuantilesDoublesSketch sk) { - final String name = sk.getClass().getSimpleName(); - final int k = sk.getK(); - final long n = sk.getN(); - final int totNumLevels = computeNumLevelsNeeded(k, n); - final long bitPattern = sk.getBitPattern(); - final StringBuilder sb = new StringBuilder(); - sb.append(LS).append("### ").append(name).append(" LEVELS ABOVE BASE BUF:").append(LS); - if (totNumLevels == 0) { - sb.append(" ").append(LS); - } else { - sb.append(" Level | Valid | Weight").append(LS); - for (int i = 0; i < totNumLevels; i++) { - final String wt = "" + (1L << (i + 1)); - final String valid = getValidFromLevel(i, bitPattern) ? "T" : "F"; - final String row = String.format(" %7s %8s %9s", i, valid, wt); - sb.append(row).append(LS); - } - } - sb.append("### END LEVELS ABOVE BASE BUF").append(LS); - return sb.toString(); - } - - private static String outputDataDetail(final QuantilesDoublesSketch sk) { - final String name = sk.getClass().getSimpleName(); - final int k = sk.getK(); - final long n = sk.getN(); - final long bitPattern = sk.getBitPattern(); - final int bbCount = sk.getBaseBufferCount(); - final int combBufCap = sk.getCombinedBufferItemCapacity(); - final StringBuilder sb = new StringBuilder(); - - sb.append(LS).append("### ").append(name).append(" DATA DETAIL: ").append(LS); - final double[] items = sk.getCombinedBuffer(); - if (n == 0) { - sb.append(" ").append(LS); - } else { - sb.append(" Index | Level | Valid | Item").append(LS); - final int limit = Math.min(items.length, combBufCap); - for (int i = 0; i < limit; i++) { - final int levelNum = getLevelNum(k, i); - final String lvlStr = (levelNum == -1) ? "BB" : ("" + levelNum); - final String validLvl = getValidFromIndex(levelNum, bitPattern, i, bbCount) ? "T" : "F"; - final String row = String.format("%7s %7s %7s %s", i, lvlStr, validLvl, items[i]); - sb.append(row).append(LS); - } - } - sb.append("### END DATA DETAIL").append(LS); - return sb.toString(); - } - - private static boolean getValidFromIndex(final int levelNum, final long bitPattern, final int index, final int bbCount) { - return ((levelNum == -1) && (index < bbCount)) || getValidFromLevel(levelNum, bitPattern); - } - - private static boolean getValidFromLevel(final int levelNum, final long bitPattern) { - return ((1L << levelNum) & bitPattern) > 0; - } - - private static int getLevelNum(final int k, final int index) { - final int twoK = 2 * k; - return index < twoK ? - 1 : (index - twoK) / k; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/HeapCompactDoublesSketch.java b/src/main/java/org/apache/datasketches/quantiles/HeapCompactDoublesSketch.java deleted file mode 100644 index f4b45fc54..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/HeapCompactDoublesSketch.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static org.apache.datasketches.quantiles.ClassicUtil.computeBaseBufferItems; -import static org.apache.datasketches.quantiles.ClassicUtil.computeBitPattern; -import static org.apache.datasketches.quantiles.ClassicUtil.computeRetainedItems; -import static org.apache.datasketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.MAX_DOUBLE; -import static org.apache.datasketches.quantiles.PreambleUtil.MIN_DOUBLE; -import static org.apache.datasketches.quantiles.PreambleUtil.READ_ONLY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFlags; -import static org.apache.datasketches.quantiles.PreambleUtil.extractK; -import static org.apache.datasketches.quantiles.PreambleUtil.extractN; -import static org.apache.datasketches.quantiles.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.quantiles.PreambleUtil.extractSerVer; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.QuantilesAPI; - -/** - * Implements the QuantilesDoublesSketch on the Java heap. - * - * @author Lee Rhodes - * @author Jon Malkin - */ -final class HeapCompactDoublesSketch extends CompactQuantilesDoublesSketch { - static final int MIN_HEAP_DOUBLES_SER_VER = 1; - - /** - * The smallest item ever seen in the stream. - */ - private double minItem_; - - /** - * The largest item ever seen in the stream. - */ - private double maxItem_; - - /** - * The total count of items seen. - */ - private long n_; - - /** - * Number of items currently in base buffer. - * - *

Count = N % (2*K) - */ - private int baseBufferCount_; - - /** - * Active levels expressed as a bit pattern. - * - *

Pattern = N / (2 * K) - */ - private long bitPattern_; - - /** - * This single array contains the base buffer plus all used levels. - * A level is of size K and is either full and sorted. - * Whether a level buffer is present is indicated by the bitPattern_. - * The base buffer is sorted and has max length 2*K but uses only baseBufferCount_ items. - * The base buffer precedes the level buffers. This buffer does not include the min, max items. - * - *

The levels arrays require quite a bit of explanation, which we defer until later.

- */ - private double[] combinedBuffer_; - - //**CONSTRUCTORS********************************************************** - private HeapCompactDoublesSketch(final int k) { - super(k); //Checks k - } - - /** - * Converts the given UpdatableQuantilesDoublesSketch to this compact form. - * - * @param sketch the sketch to convert - * @return a HeapCompactDoublesSketch created from an UpdatableQuantilesDoublesSketch - */ - static HeapCompactDoublesSketch createFromUpdateSketch(final UpdatableQuantilesDoublesSketch sketch) { - final int k = sketch.getK(); - final long n = sketch.getN(); - - final HeapCompactDoublesSketch hcds = new HeapCompactDoublesSketch(k); // checks k - - hcds.n_ = n; - hcds.bitPattern_ = computeBitPattern(k, n); - assert hcds.bitPattern_ == sketch.getBitPattern(); - - hcds.minItem_ = sketch.isEmpty() ? Double.NaN : sketch.getMinItem(); - hcds.maxItem_ = sketch.isEmpty() ? Double.NaN : sketch.getMaxItem(); - hcds.baseBufferCount_ = computeBaseBufferItems(k, n); - assert hcds.baseBufferCount_ == sketch.getBaseBufferCount(); - - //if (sketch.isEmpty()) { - // hcds.combinedBuffer_ = null; - // return hcds; - //} - - final int retainedItems = computeRetainedItems(k, n); - final double[] combinedBuffer = new double[retainedItems]; - - final DoublesSketchAccessor accessor = DoublesSketchAccessor.wrap(sketch, false); - assert hcds.baseBufferCount_ == accessor.numItems(); - - // copy and sort base buffer - System.arraycopy(accessor.getArray(0, hcds.baseBufferCount_), 0, - combinedBuffer, 0, - hcds.baseBufferCount_); - Arrays.sort(combinedBuffer, 0, hcds.baseBufferCount_); - - int combinedBufferOffset = hcds.baseBufferCount_; - long bitPattern = hcds.bitPattern_; - for (int lvl = 0; bitPattern > 0; ++lvl, bitPattern >>>= 1) { - if ((bitPattern & 1L) > 0L) { - accessor.setLevel(lvl); - System.arraycopy(accessor.getArray(0, k), 0, - combinedBuffer, combinedBufferOffset, k); - combinedBufferOffset += k; - } - } - hcds.combinedBuffer_ = combinedBuffer; - - return hcds; - } - - /** - * Heapifies the given srcSeg, which must be a MemorySegment image of a QuantilesDoublesSketch and may have data. - * - * @param srcSeg a MemorySegment image of a sketch, which may be in compact or not compact form. - * @return a QuantilesDoublesSketch on the Java heap. - */ - static HeapCompactDoublesSketch heapifyInstance(final MemorySegment srcSeg) { - final long segCapBytes = srcSeg.byteSize(); - if (segCapBytes < Long.BYTES) { - throw new SketchesArgumentException("Source MemorySegment too small: " + segCapBytes + " < 8"); - } - - final int preLongs = extractPreLongs(srcSeg); - final int serVer = extractSerVer(srcSeg); - final int familyID = extractFamilyID(srcSeg); - final int flags = extractFlags(srcSeg); - final int k = extractK(srcSeg); - - final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; //Preamble flags empty state - final long n = empty ? 0 : extractN(srcSeg); - - //VALIDITY CHECKS - DoublesUtil.checkDoublesSerVer(serVer, MIN_HEAP_DOUBLES_SER_VER); - ClassicUtil.checkHeapFlags(flags); - HeapUpdateDoublesSketch.checkPreLongsFlagsSerVer(flags, serVer, preLongs); - ClassicUtil.checkFamilyID(familyID); - - final HeapCompactDoublesSketch hcds = new HeapCompactDoublesSketch(k); //checks k - if (empty) { - hcds.n_ = 0; - hcds.combinedBuffer_ = null; - hcds.baseBufferCount_ = 0; - hcds.bitPattern_ = 0; - hcds.minItem_ = Double.NaN; - hcds.maxItem_ = Double.NaN; - return hcds; - } - - //Not empty, must have valid preamble + min, max, n. - //Forward compatibility from SerVer = 1 : - final boolean srcIsCompact = (serVer == 2) || ((flags & (COMPACT_FLAG_MASK | READ_ONLY_FLAG_MASK)) > 0); - - HeapUpdateDoublesSketch.checkHeapSegCapacity(k, n, srcIsCompact, serVer, segCapBytes); - - //set class members by computing them - hcds.n_ = n; - hcds.baseBufferCount_ = computeBaseBufferItems(k, n); - hcds.bitPattern_ = computeBitPattern(k, n); - hcds.minItem_ = srcSeg.get(JAVA_DOUBLE_UNALIGNED, MIN_DOUBLE); - hcds.maxItem_ = srcSeg.get(JAVA_DOUBLE_UNALIGNED, MAX_DOUBLE); - - final int totItems = ClassicUtil.computeRetainedItems(k, n); - hcds.srcMemorySegmentToCombinedBuffer(srcSeg, serVer, srcIsCompact, totItems); - - return hcds; - } - - @Override - public long getN() { - return n_; - } - - @Override - public boolean hasMemorySegment() { - return false; - } - - @Override - public boolean isOffHeap() { - return false; - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return false; - } - - @Override - public double getMinItem() { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return minItem_; - } - - @Override - public double getMaxItem() { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return maxItem_; - } - - /** - * Loads the Combined Buffer from the given source MemorySegment. - * The resulting Combined Buffer is allocated in this method and is always in compact form. - * @param srcSeg the given source MemorySegment - * @param serVer the serialization version of the source - * @param srcIsCompact true if the given source MemorySegment is in compact form - * @param combBufCap total items for the combined buffer (size in doubles) - */ - private void srcMemorySegmentToCombinedBuffer(final MemorySegment srcSeg, final int serVer, - final boolean srcIsCompact, final int combBufCap) { - final int preLongs = 2; - final int extra = (serVer == 1) ? 3 : 2; // space for min and max quantiles, buf alloc (SerVer 1) - final int preBytes = (preLongs + extra) << 3; - - final int k = getK(); - combinedBuffer_ = new double[combBufCap]; - - if (srcIsCompact) { - // just load the array, sort base buffer if serVer 2 - MemorySegment.copy(srcSeg, JAVA_DOUBLE_UNALIGNED, preBytes, combinedBuffer_, 0, combBufCap); - if (serVer == 2) { - Arrays.sort(combinedBuffer_, 0, baseBufferCount_); - } - } else { - // non-compact source - // load base buffer and ensure it's sorted - MemorySegment.copy(srcSeg, JAVA_DOUBLE_UNALIGNED, preBytes, combinedBuffer_, 0, baseBufferCount_); - Arrays.sort(combinedBuffer_, 0, baseBufferCount_); - - // iterate through levels - int srcOffset = preBytes + ((2 * k) << 3); - int dstOffset = baseBufferCount_; - long bitPattern = bitPattern_; - for (; bitPattern != 0; srcOffset += (k << 3), bitPattern >>>= 1) { - if ((bitPattern & 1L) > 0L) { - MemorySegment.copy(srcSeg, JAVA_DOUBLE_UNALIGNED, srcOffset, combinedBuffer_, dstOffset, k); - dstOffset += k; - } - } - } - } - - //Restricted overrides - //Gets - - @Override - int getBaseBufferCount() { - return baseBufferCount_; - } - - @Override - int getCombinedBufferItemCapacity() { - return combinedBuffer_.length; - } - - @Override - double[] getCombinedBuffer() { - return combinedBuffer_; - } - - @Override - long getBitPattern() { - return bitPattern_; - } - - @Override - MemorySegment getMemorySegment() { - return null; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/HeapDoublesSketchAccessor.java b/src/main/java/org/apache/datasketches/quantiles/HeapDoublesSketchAccessor.java deleted file mode 100644 index 66585d070..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/HeapDoublesSketchAccessor.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import java.util.Arrays; - -/** - * @author Jon Malkin - */ -final class HeapDoublesSketchAccessor extends DoublesSketchAccessor { - - HeapDoublesSketchAccessor(final QuantilesDoublesSketch ds, - final boolean forceSize, - final int level) { - super(ds, forceSize, level); - assert !ds.hasMemorySegment(); - } - - @Override - DoublesSketchAccessor copyAndSetLevel(final int level) { - return new HeapDoublesSketchAccessor(ds_, forceSize_, level); - } - - @Override - double get(final int index) { - assert (index >= 0) && (index < numItems_); - assert n_ == ds_.getN(); - - return ds_.getCombinedBuffer()[offset_ + index]; - } - - @Override - double set(final int index, final double quantile) { - assert (index >= 0) && (index < numItems_); - assert n_ == ds_.getN(); - - final int idxOffset = offset_ + index; - final double oldVal = ds_.getCombinedBuffer()[idxOffset]; - ds_.getCombinedBuffer()[idxOffset] = quantile; - - return oldVal; - } - - @Override - double[] getArray(final int fromIdx, final int numItems) { - final int srcIdx = offset_ + fromIdx; - return Arrays.copyOfRange(ds_.getCombinedBuffer(), srcIdx, srcIdx + numItems); - } - - @Override - void putArray(final double[] srcArray, final int srcIndex, final int dstIndex, final int numItems) { - final int tgtIdx = offset_ + dstIndex; - System.arraycopy(srcArray, srcIndex, ds_.getCombinedBuffer(), tgtIdx, numItems); - } - - @Override - void sort() { - assert currLvl_ == BB_LVL_IDX; - - if (!ds_.isCompact()) { // compact sketch is already sorted; not an error but a no-op - Arrays.sort(ds_.getCombinedBuffer(), offset_, offset_ + numItems_); - } - } -} diff --git a/src/main/java/org/apache/datasketches/quantiles/HeapUpdateDoublesSketch.java b/src/main/java/org/apache/datasketches/quantiles/HeapUpdateDoublesSketch.java deleted file mode 100644 index 144e94fb7..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/HeapUpdateDoublesSketch.java +++ /dev/null @@ -1,475 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static org.apache.datasketches.quantiles.ClassicUtil.MIN_K; -import static org.apache.datasketches.quantiles.ClassicUtil.checkFamilyID; -import static org.apache.datasketches.quantiles.ClassicUtil.checkHeapFlags; -import static org.apache.datasketches.quantiles.ClassicUtil.computeBaseBufferItems; -import static org.apache.datasketches.quantiles.ClassicUtil.computeBitPattern; -import static org.apache.datasketches.quantiles.ClassicUtil.computeCombinedBufferItemCapacity; -import static org.apache.datasketches.quantiles.ClassicUtil.computeGrowingBaseBufferCap; -import static org.apache.datasketches.quantiles.ClassicUtil.computeNumLevelsNeeded; -import static org.apache.datasketches.quantiles.ClassicUtil.computeRetainedItems; -import static org.apache.datasketches.quantiles.DoublesUtil.copyToHeap; -import static org.apache.datasketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.MAX_DOUBLE; -import static org.apache.datasketches.quantiles.PreambleUtil.MIN_DOUBLE; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFlags; -import static org.apache.datasketches.quantiles.PreambleUtil.extractK; -import static org.apache.datasketches.quantiles.PreambleUtil.extractN; -import static org.apache.datasketches.quantiles.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.quantiles.PreambleUtil.extractSerVer; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.QuantilesAPI; - -/** - * Implements the QuantilesDoublesSketch on the Java heap. - * - * @author Lee Rhodes - * @author Jon Malkin - */ -final class HeapUpdateDoublesSketch extends UpdatableQuantilesDoublesSketch { - static final int MIN_HEAP_DOUBLES_SER_VER = 1; - - /** - * The smallest item ever seen in the stream. - */ - private double minItem_; - - /** - * The largest item ever seen in the stream. - */ - private double maxItem_; - - /** - * The total count of items seen. - */ - private long n_; - - /** - * Number of items currently in base buffer. - * - *

Count = N % (2*K)

- */ - private int baseBufferCount_; - - /** - * Active levels expressed as a bit pattern. - * - *

Pattern = N / (2 * K)

- */ - private long bitPattern_; - - /** - * This single array contains the base buffer plus all levels some of which may not be used, - * i.e, is in non-compact form. - * A level is of size K and is either full and sorted, or not used. A "not used" buffer may have - * garbage. Whether a level buffer used or not is indicated by the bitPattern_. - * The base buffer has length 2*K but might not be full and isn't necessarily sorted. - * The base buffer precedes the level buffers. This buffer does not include the min, max items. - * - *

The levels arrays require quite a bit of explanation, which we defer until later.

- */ - private double[] combinedBuffer_; - - //**CONSTRUCTORS** - private HeapUpdateDoublesSketch(final int k) { - super(k); //Checks k - } - - /** - * Obtains a new on-heap instance of a QuantilesDoublesSketch. - * - * @param k Parameter that controls space usage of sketch and accuracy of estimates. - * Must be greater than 1 and less than 65536 and a power of 2. - * @return a HeapUpdateDoublesSketch - */ - static HeapUpdateDoublesSketch newInstance(final int k) { - final HeapUpdateDoublesSketch huds = new HeapUpdateDoublesSketch(k); - final int baseBufAlloc = 2 * Math.min(MIN_K, k); //the min is important - huds.n_ = 0; - huds.combinedBuffer_ = new double[baseBufAlloc]; - huds.baseBufferCount_ = 0; - huds.bitPattern_ = 0; - huds.minItem_ = Double.NaN; - huds.maxItem_ = Double.NaN; - return huds; - } - - /** - * Heapifies the given srcSeg, which must be a MemorySegment image of a QuantilesDoublesSketch and may have data. - * - * @param srcSeg a MemorySegment image of a sketch, which may be in compact or updatable form. - * @return a QuantilesDoublesSketch on the Java heap. - */ - static HeapUpdateDoublesSketch heapifyInstance(final MemorySegment srcSeg) { - final long segCapBytes = srcSeg.byteSize(); - if ((segCapBytes < 8) || (segCapBytes > Integer.MAX_VALUE)) { - throw new SketchesArgumentException("Source MemorySegment byteSize must be >= 8 and <= Integer.MAX_VALUE: " + segCapBytes); - } - - final int preLongs = extractPreLongs(srcSeg); - final int serVer = extractSerVer(srcSeg); - final int familyID = extractFamilyID(srcSeg); - final int flags = extractFlags(srcSeg); - final int k = extractK(srcSeg); - - final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; //Preamble flags empty state - final long n = empty ? 0 : extractN(srcSeg); - - //VALIDITY CHECKS - DoublesUtil.checkDoublesSerVer(serVer, MIN_HEAP_DOUBLES_SER_VER); - checkHeapFlags(flags); - checkPreLongsFlagsSerVer(flags, serVer, preLongs); - checkFamilyID(familyID); - - final HeapUpdateDoublesSketch huds = newInstance(k); //checks k - if (empty) { return huds; } - - //Not empty, must have valid preamble + min, max, n. - //Forward compatibility from SerVer = 1 : - final boolean srcIsCompact = (serVer == 2) || ((flags & COMPACT_FLAG_MASK) > 0); - - checkHeapSegCapacity(k, n, srcIsCompact, serVer, segCapBytes); - - //set class members by computing them - huds.n_ = n; - final int combBufCap = computeCombinedBufferItemCapacity(k, n); - huds.baseBufferCount_ = computeBaseBufferItems(k, n); - huds.bitPattern_ = computeBitPattern(k, n); - //Extract min, max, data from srcSeg into Combined Buffer - huds.srcMemorySegmentToCombinedBuffer(srcSeg, serVer, srcIsCompact, combBufCap); - return huds; - } - - //**END CONSTRUCTORS** - - @Override - public double getMaxItem() { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return maxItem_; - } - - @Override - public double getMinItem() { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return minItem_; - } - - @Override - public long getN() { - return n_; - } - - @Override - public boolean hasMemorySegment() { - return false; - } - - @Override - public boolean isOffHeap() { - return false; - } - - @Override - public boolean isReadOnly() { - return false; - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return false; - } - - @Override - public void reset() { - n_ = 0; - final int combinedBufferItemCapacity = 2 * Math.min(MIN_K, k_); //min is important - combinedBuffer_ = new double[combinedBufferItemCapacity]; - baseBufferCount_ = 0; - bitPattern_ = 0; - minItem_ = Double.NaN; - maxItem_ = Double.NaN; - } - - @Override - public void update(final double dataItem) { - if (Double.isNaN(dataItem)) { return; } - - if (n_ == 0) { - putMaxItem(dataItem); - putMinItem(dataItem); - } else { - if (dataItem > getMaxItem()) { putMaxItem(dataItem); } - if (dataItem < getMinItem()) { putMinItem(dataItem); } - } - - //don't increment n_ and baseBufferCount_ yet - final int curBBCount = baseBufferCount_; - final int newBBCount = curBBCount + 1; - final long newN = n_ + 1; - - final int combBufItemCap = combinedBuffer_.length; - if (newBBCount > combBufItemCap) { //newBBCount can never be > 2 * k - growBaseBuffer(); //this only changes combinedBuffer when it is only a base buffer - } - - //put the new item in the base buffer - combinedBuffer_[curBBCount] = dataItem; - - if (newBBCount == (k_ << 1)) { //Propagate - - // make sure there will be enough space (levels) for the propagation - final int spaceNeeded = DoublesUpdateImpl.getRequiredItemCapacity(k_, newN); - - if (spaceNeeded > combBufItemCap) { - // copies base buffer plus old levels, adds space for new level - growCombinedBuffer(combBufItemCap, spaceNeeded); - } - - // sort only the (full) base buffer via accessor which modifies the underlying base buffer, - // then use as one of the inputs to propagate-carry - final DoublesSketchAccessor bbAccessor = DoublesSketchAccessor.wrap(this, true); - bbAccessor.sort(); - - final long newBitPattern = DoublesUpdateImpl.inPlacePropagateCarry( - 0, // starting level - null, - bbAccessor, - true, - k_, - DoublesSketchAccessor.wrap(this, true), - bitPattern_ - ); - - assert newBitPattern == computeBitPattern(k_, newN); // internal consistency check - assert newBitPattern == (bitPattern_ + 1); - - bitPattern_ = newBitPattern; - baseBufferCount_ = 0; - } else { - //bitPattern unchanged - baseBufferCount_ = newBBCount; - } - n_ = newN; - doublesSV = null; - } - - /** - * Loads the Combined Buffer, min and max from the given source MemorySegment. - * The resulting Combined Buffer is always in non-compact form and must be pre-allocated. - * @param srcSeg the given source MemorySegment - * @param serVer the serialization version of the source - * @param srcIsCompact true if the given source MemorySegment is in compact form - * @param combBufCap total items for the combined buffer (size in doubles) - */ - private void srcMemorySegmentToCombinedBuffer(final MemorySegment srcSeg, final int serVer, - final boolean srcIsCompact, final int combBufCap) { - final int preLongs = 2; - final int extra = (serVer == 1) ? 3 : 2; // space for min and max quantiles, buf alloc (SerVer 1) - final int preBytes = (preLongs + extra) << 3; - final int bbCnt = baseBufferCount_; - final int k = getK(); - final long n = getN(); - final double[] combinedBuffer = new double[combBufCap]; //always non-compact - //Load min, max - putMinItem(srcSeg.get(JAVA_DOUBLE_UNALIGNED, MIN_DOUBLE)); - putMaxItem(srcSeg.get(JAVA_DOUBLE_UNALIGNED, MAX_DOUBLE)); - - if (srcIsCompact) { - //Load base buffer - MemorySegment.copy(srcSeg, JAVA_DOUBLE_UNALIGNED, preBytes, combinedBuffer, 0, bbCnt); - - //Load levels from compact srcSeg - long bitPattern = bitPattern_; - if (bitPattern != 0) { - long segOffset = preBytes + (bbCnt << 3); - int combBufOffset = 2 * k; - while (bitPattern != 0L) { - if ((bitPattern & 1L) > 0L) { - MemorySegment.copy(srcSeg, JAVA_DOUBLE_UNALIGNED, segOffset, combinedBuffer, combBufOffset, k); - segOffset += (k << 3); //bytes, increment compactly - } - combBufOffset += k; //doubles, increment every level - bitPattern >>>= 1; - } - - } - } else { //srcSeg not compact - final int levels = computeNumLevelsNeeded(k, n); - final int totItems = (levels == 0) ? bbCnt : (2 + levels) * k; - MemorySegment.copy(srcSeg, JAVA_DOUBLE_UNALIGNED, preBytes, combinedBuffer, 0, totItems); - } - putCombinedBuffer(combinedBuffer); - } - - //Restricted overrides - //Gets - - @Override - int getBaseBufferCount() { - return baseBufferCount_; - } - - @Override - long getBitPattern() { - return bitPattern_; - } - - @Override - double[] getCombinedBuffer() { - return combinedBuffer_; - } - - @Override - int getCombinedBufferItemCapacity() { - return combinedBuffer_.length; - } - - @Override - MemorySegment getMemorySegment() { - return null; - } - - @Override - HeapUpdateDoublesSketch getSketchAndReset() { - final HeapUpdateDoublesSketch skCopy = copyToHeap(this); - reset(); - return skCopy; - } - - @Override //the returned array is not always used - double[] growCombinedBuffer(final int currentSpace, final int spaceNeeded) { - combinedBuffer_ = Arrays.copyOf(combinedBuffer_, spaceNeeded); - return combinedBuffer_; - } - - //Puts - - @Override - void putBaseBufferCount(final int baseBufferCount) { - baseBufferCount_ = baseBufferCount; - } - - @Override - void putBitPattern(final long bitPattern) { - bitPattern_ = bitPattern; - } - - @Override - void putCombinedBuffer(final double[] combinedBuffer) { - combinedBuffer_ = combinedBuffer; - } - - @Override - void putMaxItem(final double maxItem) { - maxItem_ = maxItem; - } - - @Override - void putMinItem(final double minItem) { - minItem_ = minItem; - } - - @Override - void putN(final long n) { - n_ = n; - } - - /** - * This is only used for on-heap sketches, and grows the Base Buffer by factors of 2 until it - * reaches the maximum size of 2 * k. It is only called when there are no levels above the - * Base Buffer. - */ - //important: n has not been incremented yet - private void growBaseBuffer() { - final int oldSize = combinedBuffer_.length; - assert oldSize < (2 * k_); - final double[] baseBuffer = combinedBuffer_; - final int newSize = computeGrowingBaseBufferCap(k_, oldSize); - combinedBuffer_ = Arrays.copyOf(baseBuffer, newSize); - } - - static void checkPreLongsFlagsSerVer(final int flags, final int serVer, final int preLongs) { - final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; - final boolean compact = (flags & COMPACT_FLAG_MASK) > 0; - - final int sw = (compact ? 1 : 0) + (2 * (empty ? 1 : 0)) + (4 * (serVer & 0xF)) - + (32 * (preLongs & 0x3F)); - boolean valid = true; - switch (sw) { //These are the valid cases. - case 38 : break; //!compact, empty, serVer = 1, preLongs = 1; always stored as not compact - case 164 : break; //!compact, !empty, serVer = 1, preLongs = 5; always stored as not compact - case 42 : break; //!compact, empty, serVer = 2, preLongs = 1; always stored as compact - case 72 : break; //!compact, !empty, serVer = 2, preLongs = 2; always stored as compact - case 47 : break; // compact, empty, serVer = 3, preLongs = 1; - case 46 : break; //!compact, empty, serVer = 3, preLongs = 1; - case 79 : break; // compact, empty, serVer = 3, preLongs = 2; - case 78 : break; //!compact, empty, serVer = 3, preLongs = 2; - case 77 : break; // compact, !empty, serVer = 3, preLongs = 2; - case 76 : break; //!compact, !empty, serVer = 3, preLongs = 2; - default : //all other cases are invalid - valid = false; - } - - if (!valid) { - throw new SketchesArgumentException("Possible corruption. Inconsistent state: " - + "PreambleLongs = " + preLongs + ", empty = " + empty + ", SerVer = " + serVer - + ", Compact = " + compact); - } - } - - /** - * Checks the validity of the heap MemorySegment capacity assuming n, k and the compact state. - * @param k the given k - * @param n the given n - * @param compact true if MemorySegment is in compact form - * @param serVer serialization version of the source - * @param segCapBytes the current MemorySegment capacity in bytes - */ - static void checkHeapSegCapacity(final int k, final long n, final boolean compact, - final int serVer, final long segCapBytes) { - final int metaPre = Family.QUANTILES.getMaxPreLongs() + ((serVer == 1) ? 3 : 2); - final int retainedItems = computeRetainedItems(k, n); - final int reqBufBytes; - if (compact) { - reqBufBytes = (metaPre + retainedItems) << 3; - } else { //not compact - final int totLevels = computeNumLevelsNeeded(k, n); - reqBufBytes = (totLevels == 0) - ? (metaPre + retainedItems) << 3 - : (metaPre + ((2 + totLevels) * k)) << 3; - } - if (segCapBytes < reqBufBytes) { - throw new SketchesArgumentException("Possible corruption: MemorySegment capacity too small: " - + segCapBytes + " < " + reqBufBytes); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/ItemsByteArrayImpl.java b/src/main/java/org/apache/datasketches/quantiles/ItemsByteArrayImpl.java deleted file mode 100644 index 9c78268d4..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/ItemsByteArrayImpl.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.ORDERED_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.insertFamilyID; -import static org.apache.datasketches.quantiles.PreambleUtil.insertFlags; -import static org.apache.datasketches.quantiles.PreambleUtil.insertK; -import static org.apache.datasketches.quantiles.PreambleUtil.insertN; -import static org.apache.datasketches.quantiles.PreambleUtil.insertPreLongs; -import static org.apache.datasketches.quantiles.PreambleUtil.insertSerVer; - -import java.lang.foreign.MemorySegment; -import java.lang.reflect.Array; -import java.util.Arrays; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.Family; - -/** - * The items to byte array algorithms. - * - * @author Lee Rhodes - * @author Alexander Saydakov - */ -final class ItemsByteArrayImpl { - - private ItemsByteArrayImpl() {} - - static byte[] toByteArray(final QuantilesItemsSketch sketch, final boolean ordered, final ArrayOfItemsSerDe serDe) { - final boolean empty = sketch.isEmpty(); - - final int flags = (empty ? EMPTY_FLAG_MASK : 0) - | (ordered ? ORDERED_FLAG_MASK : 0) - | COMPACT_FLAG_MASK; //always compact - - if (empty) { - final byte[] outByteArr = new byte[Long.BYTES]; - final MemorySegment segOut = MemorySegment.ofArray(outByteArr); - final int preLongs = 1; - insertPre0(segOut, preLongs, flags, sketch.getK()); - return outByteArr; - } - - //not empty - final T[] dataArr = combinedBufferToItemsArray(sketch, ordered); //includes min and max - - final int preLongs = 2; - final byte[] itemsByteArr = serDe.serializeToByteArray(dataArr); - final int numOutBytes = (preLongs << 3) + itemsByteArr.length; - final byte[] outByteArr = new byte[numOutBytes]; - final MemorySegment segOut = MemorySegment.ofArray(outByteArr); - - //insert preamble - insertPre0(segOut, preLongs, flags, sketch.getK()); - insertN(segOut, sketch.getN()); - - //insert data - MemorySegment.copy(itemsByteArr, 0, segOut, JAVA_BYTE, preLongs << 3, itemsByteArr.length); - return outByteArr; - } - - /** - * Returns an array of items in compact form, including min and max extracted from the - * Combined Buffer. - * @param the data type - * @param sketch a type of QuantilesItemsSketch - * @param ordered true if the desired form of the resulting array has the base buffer sorted. - * @return an array of items, including min and max extracted from the Combined Buffer. - */ - @SuppressWarnings("unchecked") - private static T[] combinedBufferToItemsArray(final QuantilesItemsSketch sketch, - final boolean ordered) { - final int extra = 2; // extra space for min and max items - final int outArrCap = sketch.getNumRetained(); - final T minItem = sketch.getMinItem(); - final T[] outArr = (T[]) Array.newInstance(minItem.getClass(), outArrCap + extra); - - //Load min, max - outArr[0] = minItem; - outArr[1] = sketch.getMaxItem(); - final int baseBufferCount = sketch.getBaseBufferCount(); - final Object[] combinedBuffer = sketch.getCombinedBuffer(); - - //Load base buffer - System.arraycopy(combinedBuffer, 0, outArr, extra, baseBufferCount); - - //Load levels - long bitPattern = sketch.getBitPattern(); - if (bitPattern > 0) { - final int k = sketch.getK(); - int index = extra + baseBufferCount; - for (int level = 0; bitPattern != 0L; level++, bitPattern >>>= 1) { - if ((bitPattern & 1L) > 0L) { - System.arraycopy(combinedBuffer, (2 + level) * k, outArr, index, k); - index += k; - } - } - } - if (ordered) { - Arrays.sort(outArr, extra, baseBufferCount + extra, sketch.getComparator()); - } - return outArr; - } - - private static void insertPre0(final MemorySegment wseg, - final int preLongs, final int flags, final int k) { - insertPreLongs(wseg, preLongs); - insertSerVer(wseg, ItemsUtil.ITEMS_SER_VER); - insertFamilyID(wseg, Family.QUANTILES.getID()); - insertFlags(wseg, flags); - insertK(wseg, k); - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/ItemsMergeImpl.java b/src/main/java/org/apache/datasketches/quantiles/ItemsMergeImpl.java deleted file mode 100644 index 5105abe8a..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/ItemsMergeImpl.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.System.arraycopy; -import static org.apache.datasketches.common.Util.checkIfPowerOf2; - -import java.util.Arrays; -import java.util.Comparator; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Down-sampling and merge algorithms - * - * @author Lee Rhodes - * @author Alexander Saydakov - * @author Kevin Lang - */ -final class ItemsMergeImpl { - - private ItemsMergeImpl() {} - - /** - * Merges the source sketch into the target sketch that can have a smaller K parameter. - * However, it is required that the ratio of the two K parameters be a power of 2. - * I.e., source.getK() = target.getK() * 2^(nonnegative integer). - * The source is not modified. - * - *

Note: It is easy to prove that the following simplified code which launches multiple waves of - * carry propagation does exactly the same amount of merging work (including the work of - * allocating fresh buffers) as the more complicated and seemingly more efficient approach that - * tracks a single carry propagation wave through both sketches. - * - *

This simplified code probably does do slightly more "outer loop" work, but I am pretty - * sure that even that is within a constant factor of the more complicated code, plus the - * total amount of "outer loop" work is at least a factor of K smaller than the total amount of - * merging work, which is identical in the two approaches. - * - *

Note: a two-way merge that doesn't modify either of its two inputs could be implemented - * by making a deep copy of the larger sketch and then merging the smaller one into it. - * However, it was decided not to do this. - * - * @param the data type - * @param src The source sketch - * @param tgt The target sketch - */ - @SuppressWarnings("unchecked") - static void mergeInto(final QuantilesItemsSketch src, final QuantilesItemsSketch tgt) { - final int srcK = src.getK(); - final int tgtK = tgt.getK(); - final long srcN = src.getN(); - final long tgtN = tgt.getN(); - - if (srcK != tgtK) { - downSamplingMergeInto(src, tgt); - return; - } - //The remainder of this code is for the case where the k's are equal - - final Object[] srcCombBuf = src.getCombinedBuffer(); - final long nFinal = tgtN + srcN; - - for (int i = 0; i < src.getBaseBufferCount(); i++) { //update only the base buffer - tgt.update((T) srcCombBuf[i]); - } - - ItemsUpdateImpl.maybeGrowLevels(tgt, nFinal); - - final Object[] scratchBuf = new Object[2 * tgtK]; - - long srcBitPattern = src.getBitPattern(); - assert srcBitPattern == (srcN / (2L * srcK)); - - for (int srcLvl = 0; srcBitPattern != 0L; srcLvl++, srcBitPattern >>>= 1) { - if ((srcBitPattern & 1L) > 0L) { //only one level above base buffer - ItemsUpdateImpl.inPlacePropagateCarry( - srcLvl, - (T[]) srcCombBuf, (2 + srcLvl) * tgtK, - (T[]) scratchBuf, 0, - false, - tgt); - // won't update tgt.n_ until the very end - } - } - tgt.n_ = nFinal; - - assert (tgt.getN() / (2L * tgtK)) == tgt.getBitPattern(); // internal consistency check - - final T srcMax = src.isEmpty() ? null : src.getMaxItem(); - final T srcMin = src.isEmpty() ? null : src.getMinItem(); - final T tgtMax = tgt.isEmpty() ? null : tgt.getMaxItem(); - final T tgtMin = tgt.isEmpty() ? null : tgt.getMinItem(); - - if ((srcMax != null) && (tgtMax != null)) { - tgt.maxItem_ = (src.getComparator().compare(srcMax, tgtMax) > 0) ? srcMax : tgtMax; - } //only one could be null - else if (tgtMax == null) { //if srcMax were null we would leave tgt alone - tgt.maxItem_ = srcMax; - } - - if ((srcMin != null) && (tgtMin != null)) { - tgt.minItem_ = (src.getComparator().compare(srcMin, tgtMin) > 0) ? tgtMin : srcMin; - } //only one could be null - else if (tgtMin == null) { //if srcMin were null we would leave tgt alone - tgt.minItem_ = srcMin; - } - } - - /** - * Merges the source sketch into the target sketch that can have a smaller parameter K. - * However, it is required that the ratio of the two K parameters be a power of 2. - * I.e., source.getK() = target.getK() * 2^(nonnegative integer). - * The source is not modified. - * @param the data type - * @param src The source sketch - * @param tgt The target sketch - */ - @SuppressWarnings("unchecked") //also used by QuantilesItemsSketch and QuantilesItemsUnion - static void downSamplingMergeInto(final QuantilesItemsSketch src, final QuantilesItemsSketch tgt) { - final int sourceK = src.getK(); - final int targetK = tgt.getK(); - - if ((sourceK % targetK) != 0) { - throw new SketchesArgumentException( - "source.getK() must equal target.getK() * 2^(nonnegative integer)."); - } - - final int downFactor = sourceK / targetK; - checkIfPowerOf2(downFactor, "source.getK()/target.getK() ratio"); - final int lgDownFactor = Integer.numberOfTrailingZeros(downFactor); - - final Object[] sourceLevels = src.getCombinedBuffer(); // aliasing is a bit dangerous - final Object[] sourceBaseBuffer = src.getCombinedBuffer(); // aliasing is a bit dangerous - - final long nFinal = tgt.getN() + src.getN(); - - for (int i = 0; i < src.getBaseBufferCount(); i++) { - tgt.update((T) sourceBaseBuffer[i]); - } - - ItemsUpdateImpl.maybeGrowLevels(tgt, nFinal); - - final Object[] scratchBuf = new Object[2 * targetK]; - final Object[] downBuf = new Object[targetK]; - - long srcBitPattern = src.getBitPattern(); - for (int srcLvl = 0; srcBitPattern != 0L; srcLvl++, srcBitPattern >>>= 1) { - if ((srcBitPattern & 1L) > 0L) { - ItemsMergeImpl.justZipWithStride( - sourceLevels, (2 + srcLvl) * sourceK, - downBuf, 0, - targetK, - downFactor - ); - ItemsUpdateImpl.inPlacePropagateCarry( - srcLvl + lgDownFactor, - (T[]) downBuf, 0, - (T[]) scratchBuf, 0, - false, tgt - ); - // won't update target.n_ until the very end - } - } - tgt.n_ = nFinal; - - assert (tgt.getN() / (2L * targetK)) == tgt.getBitPattern(); // internal consistency check - - final T srcMax = src.isEmpty() ? null : src.getMaxItem(); - final T srcMin = src.isEmpty() ? null : src.getMinItem(); - final T tgtMax = tgt.isEmpty() ? null : tgt.getMaxItem(); - final T tgtMin = tgt.isEmpty() ? null : tgt.getMinItem(); - - if ((srcMax != null) && (tgtMax != null)) { - tgt.maxItem_ = (src.getComparator().compare(srcMax, tgtMax) > 0) ? srcMax : tgtMax; - } //only one could be null - else if (tgtMax == null) { //if srcMax were null we would leave tgt alone - tgt.maxItem_ = srcMax; - } - - if ((srcMin != null) && (tgtMin != null)) { - tgt.minItem_ = (src.getComparator().compare(srcMin, tgtMin) > 0) ? tgtMin : srcMin; - } //only one could be null - else if (tgtMin == null) { //if srcMin were null we would leave tgt alone - tgt.minItem_ = srcMin; - } - } - - private static void justZipWithStride( - final T[] bufSrc, final int startSrc, // input - final T[] bufC, final int startC, // output - final int kC, // number of items that should be in the output - final int stride) { - final int randomOffset = QuantilesItemsSketch.rand.nextInt(stride); - final int limC = startC + kC; - for (int a = startSrc + randomOffset, c = startC; c < limC; a += stride, c++ ) { - bufC[c] = bufSrc[a]; - } - } - - /** - * blockyTandemMergeSort() is an implementation of top-down merge sort specialized - * for the case where the input contains successive equal-length blocks - * that have already been sorted, so that only the top part of the - * merge tree remains to be executed. Also, two arrays are sorted in tandem, - * as discussed above. - * @param the data type - * @param quantiles array of quantiles - * @param cumWts array of cum weights - * @param arrLen length of quantiles array and cumWts array - * @param blkSize size of internal sorted blocks - * @param comparator the comparator for data type T - */ - //also used by ItemsSketchSortedView - static void blockyTandemMergeSort(final T[] quantiles, final long[] cumWts, final int arrLen, - final int blkSize, final Comparator comparator) { - assert blkSize >= 1; - if (arrLen <= blkSize) { return; } - int numblks = arrLen / blkSize; - if ((numblks * blkSize) < arrLen) { numblks += 1; } - assert ((numblks * blkSize) >= arrLen); - - // duplicate the input is preparation for the "ping-pong" copy reduction strategy. - final T[] keyTmp = Arrays.copyOf(quantiles, arrLen); - final long[] valTmp = Arrays.copyOf(cumWts, arrLen); - - blockyTandemMergeSortRecursion(keyTmp, valTmp, - quantiles, cumWts, - 0, numblks, - blkSize, arrLen, comparator); - } - - /** - * blockyTandemMergeSortRecursion() is called by blockyTandemMergeSort(). - * In addition to performing the algorithm's top down recursion, - * it manages the buffer swapping that eliminates most copying. - * It also maps the input's pre-sorted blocks into the subarrays - * that are processed by tandemMerge(). - * @param the data type - * @param qSrc source array of quantiles - * @param cwSrc source weights array - * @param qDst destination quantiles array - * @param cwDest destination weights array - * @param grpStart group start, refers to pre-sorted blocks such as block 0, block 1, etc. - * @param grpLen group length, refers to pre-sorted blocks such as block 0, block 1, etc. - * @param blkSize block size - * @param arrLim array limit - * @param comparator to compare keys - */ - private static void blockyTandemMergeSortRecursion(final T[] qSrc, final long[] cwSrc, - final T[] qDst, final long[] cwDest, final int grpStart, final int grpLen, // block indices - final int blkSize, final int arrLim, final Comparator comparator) { - // Important note: grpStart and grpLen do NOT refer to positions in the underlying array. - // Instead, they refer to the pre-sorted blocks, such as block 0, block 1, etc. - - assert (grpLen > 0); - if (grpLen == 1) { return; } - final int grpLen1 = grpLen / 2; - final int grpLen2 = grpLen - grpLen1; - assert (grpLen1 >= 1); - assert (grpLen2 >= grpLen1); - - final int grpStart1 = grpStart; - final int grpStart2 = grpStart + grpLen1; - - //swap roles of src and dst - blockyTandemMergeSortRecursion(qDst, cwDest, - qSrc, cwSrc, - grpStart1, grpLen1, blkSize, arrLim, comparator); - - //swap roles of src and dst - blockyTandemMergeSortRecursion(qDst, cwDest, - qSrc, cwSrc, - grpStart2, grpLen2, blkSize, arrLim, comparator); - - // here we convert indices of blocks into positions in the underlying array. - final int arrStart1 = grpStart1 * blkSize; - final int arrStart2 = grpStart2 * blkSize; - final int arrLen1 = grpLen1 * blkSize; - int arrLen2 = grpLen2 * blkSize; - - // special case for the final block which might be shorter than blkSize. - if ((arrStart2 + arrLen2) > arrLim) { - arrLen2 = arrLim - arrStart2; - } - - tandemMerge(qSrc, cwSrc, - arrStart1, arrLen1, - arrStart2, arrLen2, - qDst, cwDest, - arrStart1, comparator); // which will be arrStart3 - } - - /** - * Performs two merges in tandem. One of them provides the sort keys - * while the other one passively undergoes the same data motion. - * @param the data type - * @param qSrc quantiles source - * @param cwSrc cum wts source - * @param arrStart1 Array 1 start offset - * @param arrLen1 Array 1 length - * @param arrStart2 Array 2 start offset - * @param arrLen2 Array 2 length - * @param qDst quantiles destination - * @param cwDst cum wts destination - * @param arrStart3 Array 3 start offset - * @param comparator to compare keys - */ - private static void tandemMerge(final T[] qSrc, final long[] cwSrc, - final int arrStart1, final int arrLen1, - final int arrStart2, final int arrLen2, - final T[] qDst, final long[] cwDst, - final int arrStart3, final Comparator comparator) { - final int arrStop1 = arrStart1 + arrLen1; - final int arrStop2 = arrStart2 + arrLen2; - - int i1 = arrStart1; - int i2 = arrStart2; - int i3 = arrStart3; - while ((i1 < arrStop1) && (i2 < arrStop2)) { - if (comparator.compare(qSrc[i2], qSrc[i1]) < 0) { - qDst[i3] = qSrc[i2]; - cwDst[i3] = cwSrc[i2]; - i3++; i2++; - } else { - qDst[i3] = qSrc[i1]; - cwDst[i3] = cwSrc[i1]; - i3++; i1++; - } - } - - if (i1 < arrStop1) { - arraycopy(qSrc, i1, qDst, i3, arrStop1 - i1); - arraycopy(cwSrc, i1, cwDst, i3, arrStop1 - i1); - } else { - assert i2 < arrStop2; - arraycopy(qSrc, i2, qDst, i3, arrStop2 - i2); - arraycopy(cwSrc, i2, cwDst, i3, arrStop2 - i2); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/ItemsUpdateImpl.java b/src/main/java/org/apache/datasketches/quantiles/ItemsUpdateImpl.java deleted file mode 100644 index 9a978b1c9..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/ItemsUpdateImpl.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import java.util.Arrays; -import java.util.Comparator; - -final class ItemsUpdateImpl { - - private ItemsUpdateImpl() {} - - //important: newN might not equal n_ - // This only increases the size and does not touch or move any data. - static void maybeGrowLevels(final QuantilesItemsSketch sketch, final long newN) { - // important: newN might not equal n_ - final int k = sketch.getK(); - final int numLevelsNeeded = ClassicUtil.computeNumLevelsNeeded(k, newN); - if (numLevelsNeeded == 0) { - // don't need any levels yet, and might have small base buffer; this can happen during a merge - return; - } - // from here on we need a full-size base buffer and at least one level - assert newN >= 2L * k; - assert numLevelsNeeded > 0; - final int spaceNeeded = (2 + numLevelsNeeded) * k; - if (spaceNeeded <= sketch.getCombinedBufferAllocatedCount()) { - return; - } - // copies base buffer plus old levels - sketch.combinedBuffer_ = Arrays.copyOf(sketch.getCombinedBuffer(), spaceNeeded); - sketch.combinedBufferItemCapacity_ = spaceNeeded; - } - - @SuppressWarnings("unchecked") - static void inPlacePropagateCarry( - final int startingLevel, - final T[] sizeKBuf, final int sizeKStart, - final T[] size2KBuf, final int size2KStart, - final boolean doUpdateVersion, - final QuantilesItemsSketch sketch) { // else doMergeIntoVersion - final Object[] levelsArr = sketch.getCombinedBuffer(); - final long bitPattern = sketch.getBitPattern(); - final int k = sketch.getK(); - - final int endingLevel = ClassicUtil.lowestZeroBitStartingAt(bitPattern, startingLevel); - - if (doUpdateVersion) { // update version of computation - // its is okay for sizeKbuf to be null in this case - zipSize2KBuffer( - size2KBuf, size2KStart, - levelsArr, (2 + endingLevel) * k, - k); - } else { // mergeInto version of computation - System.arraycopy( - sizeKBuf, sizeKStart, - levelsArr, (2 + endingLevel) * k, - k); - } - - for (int lvl = startingLevel; lvl < endingLevel; lvl++) { - assert (bitPattern & (1L << lvl)) > 0; // internal consistency check - mergeTwoSizeKBuffers( - (T[]) levelsArr, (2 + lvl) * k, - (T[]) levelsArr, (2 + endingLevel) * k, - size2KBuf, size2KStart, - k, sketch.getComparator()); - zipSize2KBuffer( - size2KBuf, size2KStart, - levelsArr, (2 + endingLevel) * k, - k); - // to release the discarded objects - Arrays.fill(levelsArr, (2 + lvl) * k, (2 + lvl + 1) * k, null); - } // end of loop over lower levels - - // update bit pattern with binary-arithmetic ripple carry - sketch.bitPattern_ = bitPattern + (1L << startingLevel); - } - - //note: this version refers to the QuantilesItemsSketch.rand - private static void zipSize2KBuffer( - final Object[] bufA, final int startA, // input - final Object[] bufC, final int startC, // output - final int k) { - final int randomOffset = QuantilesItemsSketch.rand.nextBoolean() ? 1 : 0; - final int limC = startC + k; - for (int a = startA + randomOffset, c = startC; c < limC; a += 2, c++) { - bufC[c] = bufA[a]; - } - } - - //note: this version uses a comparator - private static void mergeTwoSizeKBuffers( - final T[] keySrc1, final int arrStart1, - final T[] keySrc2, final int arrStart2, - final T[] keyDst, final int arrStart3, - final int k, final Comparator comparator) { - final int arrStop1 = arrStart1 + k; - final int arrStop2 = arrStart2 + k; - - int i1 = arrStart1; - int i2 = arrStart2; - int i3 = arrStart3; - while (i1 < arrStop1 && i2 < arrStop2) { - if (comparator.compare(keySrc2[i2], keySrc1[i1]) < 0) { - keyDst[i3++] = keySrc2[i2++]; - } else { - keyDst[i3++] = keySrc1[i1++]; - } - } - - if (i1 < arrStop1) { - System.arraycopy(keySrc1, i1, keyDst, i3, arrStop1 - i1); - } else { - assert i2 < arrStop2; - System.arraycopy(keySrc1, i2, keyDst, i3, arrStop2 - i2); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/ItemsUtil.java b/src/main/java/org/apache/datasketches/quantiles/ItemsUtil.java deleted file mode 100644 index 7ae7cec2f..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/ItemsUtil.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.quantiles.ClassicUtil.computeNumLevelsNeeded; -import static org.apache.datasketches.quantiles.ClassicUtil.computeTotalLevels; -import static org.apache.datasketches.quantiles.ClassicUtil.computeValidLevels; -import static org.apache.datasketches.quantiles.ClassicUtil.getNormalizedRankError; - -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Utility class for generic quantiles sketch. - * - * @author Kevin Lang - * @author Alexander Saydakov - */ -final class ItemsUtil { - - private ItemsUtil() {} - - static final int ITEMS_SER_VER = 3; - static final int PRIOR_ITEMS_SER_VER = 2; - - /** - * Check the validity of the given serialization version - * @param serVer the given serialization version - */ - static void checkItemsSerVer(final int serVer) { - if ((serVer == ITEMS_SER_VER) || (serVer == PRIOR_ITEMS_SER_VER)) { return; } - throw new SketchesArgumentException( - "Possible corruption: Invalid Serialization Version: " + serVer); - } - - /** - * Called when the base buffer has just acquired 2*k elements. - * @param the data type - * @param sketch the given quantiles sketch - */ - @SuppressWarnings("unchecked") - static void processFullBaseBuffer(final QuantilesItemsSketch sketch) { - final int bbCount = sketch.getBaseBufferCount(); - final long n = sketch.getN(); - assert bbCount == (2 * sketch.getK()); // internal consistency check - - // make sure there will be enough levels for the propagation - ItemsUpdateImpl.maybeGrowLevels(sketch, n); // important: n_ was incremented by update before we got here - - // this aliasing is a bit dangerous; notice that we did it after the possible resizing - final Object[] baseBuffer = sketch.getCombinedBuffer(); - - Arrays.sort((T[]) baseBuffer, 0, bbCount, sketch.getComparator()); - ItemsUpdateImpl.inPlacePropagateCarry( - 0, - null, 0, // this null is okay - (T[]) baseBuffer, 0, - true, sketch); - sketch.baseBufferCount_ = 0; - Arrays.fill(baseBuffer, 0, 2 * sketch.getK(), null); // to release the discarded objects - assert (n / (2L * sketch.getK())) == sketch.getBitPattern(); // internal consistency check - } - - static String toString(final boolean withLevels, final boolean withLevelsAndItems, - final QuantilesItemsSketch sk) { - final StringBuilder sb = new StringBuilder(); - final String thisSimpleName = sk.getClass().getSimpleName(); - final int bbCount = sk.getBaseBufferCount(); - final int combBufCap = sk.getCombinedBufferAllocatedCount(); - final int k = sk.getK(); - final long bitPattern = sk.getBitPattern(); - - final long n = sk.getN(); - final String nStr = String.format("%,d", n); - final String bbCntStr = String.format("%,d", bbCount); - final String combBufCapStr = String.format("%,d", combBufCap); - final int neededLevels = computeNumLevelsNeeded(k, n); - final int totalLevels = computeTotalLevels(bitPattern); - final int validLevels = computeValidLevels(bitPattern); - final int numRetained = sk.getNumRetained(); - final String numRetainedStr = String.format("%,d", numRetained); - final int preBytes = sk.isEmpty() ? Long.BYTES : 2 * Long.BYTES; - final double epsPmf = getNormalizedRankError(k, true); - final String epsPmfPctStr = String.format("%.3f%%", epsPmf * 100.0); - final double eps = getNormalizedRankError(k, false); - final String epsPctStr = String.format("%.3f%%", eps * 100.0); - final T minItem = sk.isEmpty() ? null : sk.getMinItem(); - final T maxItem = sk.isEmpty() ? null : sk.getMaxItem(); - sb.append(LS).append("### Classic Quantiles ").append(thisSimpleName).append(" SUMMARY: ").append(LS); - sb.append(" Empty : ").append(sk.isEmpty()).append(LS); - sb.append(" Estimation Mode : ").append(sk.isEstimationMode()).append(LS); - sb.append(" K : ").append(k).append(LS); - sb.append(" N : ").append(nStr).append(LS); - sb.append(" Levels (Needed, Total, Valid): ").append(neededLevels + ", " + totalLevels + ", " + validLevels) - .append(LS); - sb.append(" Level Bit Pattern : ").append(Long.toBinaryString(bitPattern)).append(LS); - sb.append(" Base Buffer Count : ").append(bbCntStr).append(LS); - sb.append(" Combined Buffer Capacity : ").append(combBufCapStr).append(LS); - sb.append(" Retained Items : ").append(numRetainedStr).append(LS); - sb.append(" Preamble Bytes : ").append(preBytes).append(LS); - sb.append(" Normalized Rank Error : ").append(epsPctStr).append(LS); - sb.append(" Normalized Rank Error (PMF) : ").append(epsPmfPctStr).append(LS); - sb.append(" Min Item : ").append(minItem).append(LS); - sb.append(" Max Item : ").append(maxItem).append(LS); - sb.append("### END SKETCH SUMMARY").append(LS); - - if (withLevels) { sb.append(outputLevels(sk)); } - if (withLevelsAndItems) { sb.append(outputDataDetail(sk)); } - return sb.toString(); - } - - private static String outputLevels(final QuantilesItemsSketch sk) { - final String name = sk.getClass().getSimpleName(); - final int k = sk.getK(); - final long n = sk.getN(); - final int totNumLevels = computeNumLevelsNeeded(k, n); - final long bitPattern = sk.getBitPattern(); - final StringBuilder sb = new StringBuilder(); - sb.append(LS).append("### ").append(name).append(" LEVELS ABOVE BASE BUF:").append(LS); - if (totNumLevels == 0) { - sb.append(" ").append(LS); - } else { - sb.append(" Level | Valid | Weight").append(LS); - for (int i = 0; i < totNumLevels; i++) { - final String wt = "" + (1L << (i + 1)); - final String valid = getValidFromLevel(i, bitPattern) ? "T" : "F"; - final String row = String.format(" %7s %8s %9s", i, valid, wt); - sb.append(row).append(LS); - } - } - sb.append("### END LEVELS ABOVE BASE BUF").append(LS); - return sb.toString(); - } - - private static String outputDataDetail(final QuantilesItemsSketch sk) { - final String name = sk.getClass().getSimpleName(); - final int k = sk.getK(); - final long n = sk.getN(); - final long bitPattern = sk.getBitPattern(); - final int bbCount = sk.getBaseBufferCount(); - final int combBufCap = sk.getCombinedBufferAllocatedCount(); - final StringBuilder sb = new StringBuilder(); - - sb.append(LS).append("### ").append(name).append(" DATA DETAIL: ").append(LS); - final Object[] items = sk.getCombinedBuffer(); - if (n == 0) { - sb.append(" ").append(LS); - } else { - sb.append(" Index | Level | Valid | Item").append(LS); - for (int i = 0; i < combBufCap; i++) { - final int levelNum = getLevelNum(k, i); - final String lvlStr = (levelNum == -1) ? "BB" : ("" + levelNum); - final String validLvl = getValidFromIndex(levelNum, bitPattern, i, bbCount) ? "T" : "F"; - final String row = String.format("%7s %7s %7s %s", i, lvlStr, validLvl, items[i]); - sb.append(row).append(LS); - } - } - sb.append("### END DATA DETAIL").append(LS); - return sb.toString(); - } - - private static boolean getValidFromIndex(final int levelNum, final long bitPattern, final int index, - final int bbCount) { - return ((levelNum == -1) && (index < bbCount)) || getValidFromLevel(levelNum, bitPattern); - } - - private static boolean getValidFromLevel(final int levelNum, final long bitPattern) { - return ((1L << levelNum) & bitPattern) > 0; - } - - private static int getLevelNum(final int k, final int index) { - final int twoK = 2 * k; - return index < twoK ? - 1 : (index - twoK) / k; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/PreambleUtil.java b/src/main/java/org/apache/datasketches/quantiles/PreambleUtil.java deleted file mode 100644 index 1ba160c41..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/PreambleUtil.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.common.Family.idToFamily; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.quantiles.ClassicUtil.computeRetainedItems; - -import java.lang.foreign.MemorySegment; - -//@formatter:off - -/** - * This class defines the serialized data structure and provides access methods for the key fields. - * - *

The intent of the design of this class was to isolate the detailed knowledge of the bit and - * byte layout of the serialized form of the sketches derived from the base sketch classes into one place. - * This allows the possibility of the introduction of different serialization - * schemes with minimal impact on the rest of the library.

- * - *

- * LAYOUT: The low significance bytes of this long based data structure are on the right. - * The multi-byte primitives are stored in native byte order. - * The single byte fields are treated as unsigned.

- * - *

An empty QuantilesItemsSketch, on-heap QuantilesDoublesSketch or compact off-heap QuantilesDoublesSketch only require 8 - * bytes. An off-heap UpdatableQuantilesDoublesSketch and all non-empty sketches require at least 16 bytes of - * preamble.

- * - *
{@code
- * Long || Start Byte Adr: Common for both QuantilesDoublesSketch and QuantilesItemsSketch
- * Adr:
- *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |     0          |
- *  0   ||------unused-----|--------K--------|  Flags | FamID  | SerVer | Preamble_Longs |
- *
- *      ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |     8          |
- *  1   ||-----------------------------------N_LONG--------------------------------------|
- *
- *  Applies only to QuantilesDoublesSketch:
- *  (QuantilesItemsSketch has elements in the same order, but size depends on sizeOf(T)
- *
- *      ||   23   |   22   |   21   |   20   |   19   |   18   |   17   |    16          |
- *  2   ||---------------------------START OF DATA, MIN_DOUBLE---------------------------|
- *
- *      ||   31   |   30   |   29   |   28   |   27   |   26   |   25   |    24          |
- *  3   ||----------------------------------MAX_DOUBLE-----------------------------------|
- *
- *      ||   39   |   38   |   37   |   36   |   35   |   34   |   33   |    32          |
- *  4   ||---------------------------START OF COMBINED BUfFER----------------------------|
- *  }
- * - * @author Lee Rhodes - */ -final class PreambleUtil { - - private PreambleUtil() {} - - // ###### DO NOT MESS WITH THIS FROM HERE ... - // Preamble byte Addresses - static final int PREAMBLE_LONGS_BYTE = 0; - static final int SER_VER_BYTE = 1; - static final int FAMILY_BYTE = 2; - static final int FLAGS_BYTE = 3; - static final int K_SHORT = 4; //to 5 - static final int N_LONG = 8; //to 15 - - //After Preamble: - static final int MIN_DOUBLE = 16; //to 23 (Only for QuantilesDoublesSketch) - static final int MAX_DOUBLE = 24; //to 31 (Only for QuantilesDoublesSketch) - static final int COMBINED_BUFFER = 32; //to 39 (Only for QuantilesDoublesSketch) - - // flag bit masks - static final int RESERVED_FLAG_MASK = 1; - static final int READ_ONLY_FLAG_MASK = 2; - static final int EMPTY_FLAG_MASK = 4; - static final int COMPACT_FLAG_MASK = 8; - static final int ORDERED_FLAG_MASK = 16; - - /** - * Default K for about 1.7% normalized rank accuracy - */ - static final int DEFAULT_K = 128; - - // ###### TO HERE. - - // STRINGS - /** - * Returns a human readable string summary of the internal state of the given byte array. - * Used primarily in testing. - * - * @param byteArr the given byte array. - * @param isDoublesSketch flag to indicate that the byte array represents QuantilesDoublesSketch - * to output min and max quantiles in the summary - * @return the summary string. - */ - static String toString(final byte[] byteArr, final boolean isDoublesSketch) { - final MemorySegment seg = MemorySegment.ofArray(byteArr); - return toString(seg, isDoublesSketch); - } - - /** - * Returns a human readable string summary of the Preamble of the given MemorySegment. If this MemorySegment - * image is from a QuantilesDoublesSketch, the MinQuantile and MaxQuantile will also be output. - * Used primarily in testing. - * - * @param seg the given MemorySegment - * @param isDoublesSketch flag to indicate that the byte array represents QuantilesDoublesSketch - * to output min and max quantiles in the summary - * @return the summary string. - */ - static String toString(final MemorySegment seg, final boolean isDoublesSketch) { - return memorySegmentToString(seg, isDoublesSketch); - } - - private static String memorySegmentToString(final MemorySegment srcSeg, final boolean isDoublesSketch) { - final int preLongs = extractPreLongs(srcSeg); //either 1 or 2 - final int serVer = extractSerVer(srcSeg); - final int familyID = extractFamilyID(srcSeg); - final String famName = idToFamily(familyID).toString(); - final int flags = extractFlags(srcSeg); - final boolean readOnly = (flags & READ_ONLY_FLAG_MASK) > 0; - final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; - final boolean compact = (flags & COMPACT_FLAG_MASK) > 0; - final boolean ordered = (flags & ORDERED_FLAG_MASK) > 0; - final int k = extractK(srcSeg); - - final long n = (preLongs == 1) ? 0L : extractN(srcSeg); - double minDouble = Double.NaN; - double maxDouble = Double.NaN; - if ((preLongs > 1) && isDoublesSketch) { // preLongs = 2 or 3 - minDouble = extractMinDouble(srcSeg); - maxDouble = extractMaxDouble(srcSeg); - } - - final StringBuilder sb = new StringBuilder(); - sb.append(LS); - sb.append("### QUANTILES SKETCH PREAMBLE SUMMARY:").append(LS); - sb.append("Byte 0: Preamble Longs : ").append(preLongs).append(LS); - sb.append("Byte 1: Serialization Version: ").append(serVer).append(LS); - sb.append("Byte 2: Family : ").append(famName).append(LS); - sb.append("Byte 3: Flags Field : ").append(String.format("%02o", flags)).append(LS); - sb.append(" RESERVED : ").append(LS); - sb.append(" READ ONLY : ").append(readOnly).append(LS); - sb.append(" EMPTY : ").append(empty).append(LS); - sb.append(" COMPACT : ").append(compact).append(LS); - sb.append(" ORDERED : ").append(ordered).append(LS); - sb.append("Bytes 4-5 : K : ").append(k).append(LS); - if (preLongs == 1) { - sb.append(" --ABSENT, ASSUMED:").append(LS); - } - sb.append("Bytes 8-15 : N : ").append(n).append(LS); - if (isDoublesSketch) { - sb.append("MinDouble : ").append(minDouble).append(LS); - sb.append("MaxDouble : ").append(maxDouble).append(LS); - } - sb.append("Retained Items : ").append(computeRetainedItems(k, n)).append(LS); - sb.append("Total Bytes : ").append(srcSeg.byteSize()).append(LS); - sb.append("### END SKETCH PREAMBLE SUMMARY").append(LS); - return sb.toString(); - } - - //@formatter:on - static int extractPreLongs(final MemorySegment seg) { - return seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE) & 0XFF; - } - - static int extractSerVer(final MemorySegment seg) { - return seg.get(JAVA_BYTE, SER_VER_BYTE) & 0XFF; - } - - static int extractFamilyID(final MemorySegment seg) { - return seg.get(JAVA_BYTE, FAMILY_BYTE) & 0XFF; - } - - static int extractFlags(final MemorySegment seg) { - return seg.get(JAVA_BYTE, FLAGS_BYTE) & 0XFF; - } - - static int extractK(final MemorySegment seg) { - return seg.get(JAVA_SHORT_UNALIGNED, K_SHORT) & 0XFFFF; - } - - static long extractN(final MemorySegment seg) { - return seg.get(JAVA_LONG_UNALIGNED, N_LONG); - } - - static double extractMinDouble(final MemorySegment seg) { - return seg.get(JAVA_DOUBLE_UNALIGNED, MIN_DOUBLE); - } - - static double extractMaxDouble(final MemorySegment seg) { - return seg.get(JAVA_DOUBLE_UNALIGNED, MAX_DOUBLE); - } - - static void insertPreLongs(final MemorySegment wseg, final int numPreLongs) { - wseg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) numPreLongs); - } - - static void insertSerVer(final MemorySegment wseg, final int serVer) { - wseg.set(JAVA_BYTE, SER_VER_BYTE, (byte) serVer); - } - - static void insertFamilyID(final MemorySegment wseg, final int famId) { - wseg.set(JAVA_BYTE, FAMILY_BYTE, (byte) famId); - } - - static void insertFlags(final MemorySegment wseg, final int flags) { - wseg.set(JAVA_BYTE, FLAGS_BYTE, (byte) flags); - } - - static void insertK(final MemorySegment wseg, final int k) { - wseg.set(JAVA_SHORT_UNALIGNED, K_SHORT, (short) k); - } - - static void insertN(final MemorySegment wseg, final long n) { - wseg.set(JAVA_LONG_UNALIGNED, N_LONG, n); - } - - static void insertMinDouble(final MemorySegment wseg, final double minDouble) { - wseg.set(JAVA_DOUBLE_UNALIGNED, MIN_DOUBLE, minDouble); - } - - static void insertMaxDouble(final MemorySegment wseg, final double maxDouble) { - wseg.set(JAVA_DOUBLE_UNALIGNED, MAX_DOUBLE, maxDouble); - } -} diff --git a/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesSketch.java b/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesSketch.java deleted file mode 100644 index 85bf957d7..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesSketch.java +++ /dev/null @@ -1,830 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static java.lang.System.arraycopy; -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.quantiles.ClassicUtil.MAX_PRELONGS; -import static org.apache.datasketches.quantiles.ClassicUtil.MIN_K; -import static org.apache.datasketches.quantiles.ClassicUtil.checkIsMemorySegmentCompact; -import static org.apache.datasketches.quantiles.ClassicUtil.checkK; -import static org.apache.datasketches.quantiles.ClassicUtil.computeNumLevelsNeeded; -import static org.apache.datasketches.quantiles.ClassicUtil.computeRetainedItems; -import static org.apache.datasketches.quantiles.DoublesSketchAccessor.BB_LVL_IDX; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Random; - -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.quantilescommon.DoublesSketchSortedView; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; -import org.apache.datasketches.quantilescommon.QuantilesAPI; -import org.apache.datasketches.quantilescommon.QuantilesDoublesAPI; -import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIteratorAPI; - -/** - * This is an implementation of the Low Discrepancy Mergeable Quantiles Sketch, using doubles, - * described in section 3.2 of the journal version of the paper "Mergeable Summaries" - * by Agarwal, Cormode, Huang, Phillips, Wei, and Yi: - * - *

Reference:

- * - *

A k of 128 produces a normalized, rank error of about 1.7%. - * For example, the median returned from getQuantile(0.5) will be between the actual quantiles - * from the hypothetically sorted array of input quantiles at normalized ranks of 0.483 and 0.517, with - * a confidence of about 99%.

- * - *
-Table Guide for QuantilesDoublesSketch Size in Bytes and Approximate Error:
-          K => |      16      32      64     128     256     512   1,024
-    ~ Error => | 12.145%  6.359%  3.317%  1.725%  0.894%  0.463%  0.239%
-             N | Size in Bytes ->
-------------------------------------------------------------------------
-             0 |       8       8       8       8       8       8       8
-             1 |      72      72      72      72      72      72      72
-             3 |      72      72      72      72      72      72      72
-             7 |     104     104     104     104     104     104     104
-            15 |     168     168     168     168     168     168     168
-            31 |     296     296     296     296     296     296     296
-            63 |     424     552     552     552     552     552     552
-           127 |     552     808   1,064   1,064   1,064   1,064   1,064
-           255 |     680   1,064   1,576   2,088   2,088   2,088   2,088
-           511 |     808   1,320   2,088   3,112   4,136   4,136   4,136
-         1,023 |     936   1,576   2,600   4,136   6,184   8,232   8,232
-         2,047 |   1,064   1,832   3,112   5,160   8,232  12,328  16,424
-         4,095 |   1,192   2,088   3,624   6,184  10,280  16,424  24,616
-         8,191 |   1,320   2,344   4,136   7,208  12,328  20,520  32,808
-        16,383 |   1,448   2,600   4,648   8,232  14,376  24,616  41,000
-        32,767 |   1,576   2,856   5,160   9,256  16,424  28,712  49,192
-        65,535 |   1,704   3,112   5,672  10,280  18,472  32,808  57,384
-       131,071 |   1,832   3,368   6,184  11,304  20,520  36,904  65,576
-       262,143 |   1,960   3,624   6,696  12,328  22,568  41,000  73,768
-       524,287 |   2,088   3,880   7,208  13,352  24,616  45,096  81,960
-     1,048,575 |   2,216   4,136   7,720  14,376  26,664  49,192  90,152
-     2,097,151 |   2,344   4,392   8,232  15,400  28,712  53,288  98,344
-     4,194,303 |   2,472   4,648   8,744  16,424  30,760  57,384 106,536
-     8,388,607 |   2,600   4,904   9,256  17,448  32,808  61,480 114,728
-    16,777,215 |   2,728   5,160   9,768  18,472  34,856  65,576 122,920
-    33,554,431 |   2,856   5,416  10,280  19,496  36,904  69,672 131,112
-    67,108,863 |   2,984   5,672  10,792  20,520  38,952  73,768 139,304
-   134,217,727 |   3,112   5,928  11,304  21,544  41,000  77,864 147,496
-   268,435,455 |   3,240   6,184  11,816  22,568  43,048  81,960 155,688
-   536,870,911 |   3,368   6,440  12,328  23,592  45,096  86,056 163,880
- 1,073,741,823 |   3,496   6,696  12,840  24,616  47,144  90,152 172,072
- 2,147,483,647 |   3,624   6,952  13,352  25,640  49,192  94,248 180,264
- 4,294,967,295 |   3,752   7,208  13,864  26,664  51,240  98,344 188,456
- * 
- * - * @see QuantilesAPI - */ -public abstract class QuantilesDoublesSketch implements QuantilesDoublesAPI, MemorySegmentStatus { - - /** - * Setting the seed makes the results of the sketch deterministic if the input quantiles are - * received in exactly the same order. This is only useful when performing test comparisons, - * otherwise is not recommended. - */ - static Random rand = new Random(); - - /** - * Parameter that controls space usage of sketch and accuracy of estimates. - */ - final int k_; - - /** - * holder for SortedView - */ - DoublesSketchSortedView doublesSV = null; - - QuantilesDoublesSketch(final int k) { - checkK(k); - k_ = k; - } - - synchronized static void setRandom(final long seed) { - QuantilesDoublesSketch.rand = new Random(seed); - } - - /** - * Returns a new builder - * @return a new builder - */ - public static final QuantilesDoublesSketchBuilder builder() { - return new QuantilesDoublesSketchBuilder(); - } - - /** - * Heapify takes the sketch image in MemorySegment and instantiates an on-heap Sketch. - * The resulting sketch will not retain any link to the source MemorySegment. - * @param srcSeg a MemorySegment image of a Sketch. - * @return a heap-based Sketch based on the given MemorySegment - */ - public static QuantilesDoublesSketch heapify(final MemorySegment srcSeg) { - if (checkIsMemorySegmentCompact(srcSeg)) { - return HeapCompactDoublesSketch.heapifyInstance(srcSeg); - } - return HeapUpdateDoublesSketch.heapifyInstance(srcSeg); - } - - /** - * Wrap this sketch around the given MemorySegment image of a compact, read-only QuantilesDoublesSketch. - * - * @param srcSeg the given MemorySegment image of a compact, read-only QuantilesDoublesSketch. - * @return a compact, read-only sketch that wraps the given MemorySegment. - */ - public static QuantilesDoublesSketch wrap(final MemorySegment srcSeg) { - if (!checkIsMemorySegmentCompact(srcSeg)) { - throw new SketchesArgumentException( - "MemorySegment sketch image must be in compact form. " - + "Use {@link #writableWrap(MemorySegment writableWrap(...)} for updatable sketches."); - } - return DirectCompactDoublesSketch.wrapInstance(srcSeg); - } - - /** - * Wrap this sketch around the given MemorySegment image of an updatable QuantilesDoublesSketch. - * - *

The given MemorySegment must be writable and it must contain a UpdatableQuantilesDoublesSketch. - * The sketch will be updated and managed totally within the MemorySegment. If the given source - * MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

- * - *

NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch - * will request more capacity using the {@link MemorySegmentRequest MemorySegmentRequest} interface. The default of this interface will - * return a new MemorySegment on the heap.

- * - * @param srcSeg the given MemorySegment image of an UpdatableQuantilesDoublesSketch. - * @return an updatable sketch that wraps the given MemorySegment. - */ - public static QuantilesDoublesSketch writableWrap(final MemorySegment srcSeg) { - if (checkIsMemorySegmentCompact(srcSeg)) { - throw new SketchesArgumentException( - "MemorySegment sketch image must be in updatable form. " - + "Use {@link #wrap(MemorySegment wrap(...)} for compact sketches."); - } - return DirectUpdateDoublesSketch.wrapInstance(srcSeg, null); - } - - /** - * Wrap this sketch around the given MemorySegment image of an updatable QuantilesDoublesSketch. - * - *

The given MemorySegment must be writable and it must contain a UpdatableQuantilesDoublesSketch. - * The sketch will be updated and managed totally within the MemorySegment. If the given source - * MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

- * - *

NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch - * will request more capacity using the {@link MemorySegmentRequest MemorySegmentRequest} interface. The default of this interface will - * return a new MemorySegment on the heap. It is up to the user to optionally extend this interface if more flexible - * handling of requests for more capacity is required.

- * - * @param srcSeg the given MemorySegment image of a QuantilesDoublesSketch. - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return a sketch that wraps the given MemorySegment. - */ - public static QuantilesDoublesSketch writableWrap(final MemorySegment srcSeg, final MemorySegmentRequest mSegReq) { - if (checkIsMemorySegmentCompact(srcSeg)) { - throw new SketchesArgumentException("MemorySegment sketch image must be in updatable form."); - } - return DirectUpdateDoublesSketch.wrapInstance(srcSeg, mSegReq); - } - - @Override - public double[] getCDF(final double[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return doublesSV.getCDF(splitPoints, searchCrit); - } - - @Override - public abstract double getMaxItem(); - - @Override - public abstract double getMinItem(); - - @Override - public double[] getPMF(final double[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return doublesSV.getPMF(splitPoints, searchCrit); - } - - @Override - public double getQuantile(final double rank, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return doublesSV.getQuantile(rank, searchCrit); - } - - @Override - public double[] getQuantiles(final double[] ranks, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - final int len = ranks.length; - final double[] quantiles = new double[len]; - for (int i = 0; i < len; i++) { - quantiles[i] = doublesSV.getQuantile(ranks[i], searchCrit); - } - return quantiles; - } - - /** - * {@inheritDoc} - * The approximate probability that the true quantile is within the confidence interval - * specified by the upper and lower quantile bounds for this sketch is 0.99. - */ - @Override - public double getQuantileLowerBound(final double rank) { - return getQuantile(max(0, rank - getNormalizedRankError(k_, false))); - } - - /** - * {@inheritDoc} - * The approximate probability that the true quantile is within the confidence interval - * specified by the upper and lower quantile bounds for this sketch is 0.99. - */ - @Override - public double getQuantileUpperBound(final double rank) { - return getQuantile(min(1.0, rank + getNormalizedRankError(k_, false))); - } - - @Override - public double getRank(final double quantile, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return doublesSV.getRank(quantile, searchCrit); - } - - /** - * {@inheritDoc} - * The approximate probability that the true rank is within the confidence interval - * specified by the upper and lower rank bounds for this sketch is 0.99. - */ - @Override - public double getRankLowerBound(final double rank) { - return max(0.0, rank - getNormalizedRankError(k_, false)); - } - - /** - * {@inheritDoc} - * The approximate probability that the true rank is within the confidence interval - * specified by the upper and lower rank bounds for this sketch is 0.99. - */ - @Override - public double getRankUpperBound(final double rank) { - return min(1.0, rank + getNormalizedRankError(k_, false)); - } - - @Override - public double[] getRanks(final double[] quantiles, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - final int len = quantiles.length; - final double[] ranks = new double[len]; - for (int i = 0; i < len; i++) { - ranks[i] = doublesSV.getRank(quantiles[i], searchCrit); - } - return ranks; - } - - @Override - public int getK() { - return k_; - } - - @Override - public abstract long getN(); - - @Override - public double getNormalizedRankError(final boolean pmf) { - return getNormalizedRankError(k_, pmf); - } - - /** - * Gets the normalized rank error given k and pmf. - * Static method version of the getNormalizedRankError(boolean). - * The epsilon returned is a best fit to 99 percent confidence empirically measured max error - * in thousands of trials. - * @param k the configuration parameter - * @param pmf if true, returns the "double-sided" normalized rank error for the getPMF() function. - * Otherwise, it is the "single-sided" normalized rank error for all the other queries. - * @return if pmf is true, the normalized rank error for the getPMF() function. - * Otherwise, it is the "single-sided" normalized rank error for all the other queries. - */ - public static double getNormalizedRankError(final int k, final boolean pmf) { - return ClassicUtil.getNormalizedRankError(k, pmf); - } - - /** - * Gets the approximate k to use given epsilon, the normalized rank error. - * @param epsilon the normalized rank error between zero and one. - * @param pmf if true, this function returns k assuming the input epsilon - * is the desired "double-sided" epsilon for the getPMF() function. Otherwise, this function - * returns k assuming the input epsilon is the desired "single-sided" - * epsilon for all the other queries. - * @return k given epsilon. - */ - public static int getKFromEpsilon(final double epsilon, final boolean pmf) { - return ClassicUtil.getKFromEpsilon(epsilon, pmf); - } - - @Override - public abstract boolean hasMemorySegment(); - - @Override - public abstract boolean isOffHeap(); - - @Override - public boolean isEmpty() { - return getN() == 0; - } - - @Override - public boolean isEstimationMode() { - return getN() >= (2L * k_); - } - - @Override - public abstract boolean isReadOnly(); - - @Override - public abstract boolean isSameResource(final MemorySegment that); - - @Override - public byte[] toByteArray() { - if (isCompact()) { - return toByteArray(true); - } - return toByteArray(false); - } - - /** - * Serialize this sketch in a byte array form. - * @param compact if true the sketch will be serialized in compact form. - * DirectCompactDoublesSketch can wrap() only a compact byte array; - * DirectUpdateDoublesSketch can wrap() only a updatable byte array. - * @return this sketch in a byte array form. - */ - public byte[] toByteArray(final boolean compact) { - return DoublesByteArrayImpl.toByteArray(this, compact, compact); - } - - /** - * Returns human readable summary information about this sketch. - * Used for debugging. - */ - @Override - public String toString() { - return toString(true, false); - } - - /** - * Returns human readable summary information about this sketch. - * Used for debugging. - * @param withLevels if true includes sketch levels array summary information - * @param withLevelsAndItems if true include detail of levels array and items array together - * @return human readable summary information about this sketch. - */ - public String toString(final boolean withLevels, final boolean withLevelsAndItems) { - return DoublesUtil.toString(withLevels, withLevelsAndItems, this); - } - - /** - * Returns a human readable string of the preamble of a byte array image of a QuantilesDoublesSketch. - * Used for debugging. - * @param byteArr the given byte array - * @return a human readable string of the preamble of a byte array image of a QuantilesDoublesSketch. - */ - public static String toString(final byte[] byteArr) { - return PreambleUtil.toString(byteArr, true); - } - - /** - * Returns a human readable string of the preamble of a MemorySegment image of a QuantilesDoublesSketch. - * Used for debugging. - * @param seg the given MemorySegment - * @return a human readable string of the preamble of a MemorySegment image of a QuantilesDoublesSketch. - */ - public static String toString(final MemorySegment seg) { - return PreambleUtil.toString(seg, true); - } - - /** - * From an source sketch, create a new sketch that must have a smaller K. - * The original sketch is not modified. - * - * @param srcSketch the sourcing sketch - * @param smallerK the new sketch's K that must be smaller than this K. - * It is required that this.getK() = smallerK * 2^(nonnegative integer). - * @param dstSeg the destination MemorySegment. It must not overlap the MemorySegment of this sketch. - * If null, a heap sketch will be returned, otherwise it will be MemorySegment based. - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return the new sketch. - */ - public QuantilesDoublesSketch downSample(final QuantilesDoublesSketch srcSketch, final int smallerK, final MemorySegment dstSeg, - final MemorySegmentRequest mSegReq) { - return downSampleInternal(srcSketch, smallerK, dstSeg, mSegReq); - } - - @Override - public int getNumRetained() { - return computeRetainedItems(getK(), getN()); - } - - /** - * Returns the current number of bytes this sketch would require to store in the compact MemorySegment Format. - * @return the current number of bytes this sketch would require to store in the compact MemorySegment Format. - */ - public int getCurrentCompactSerializedSizeBytes() { - return getCompactSerialiedSizeBytes(getK(), getN()); - } - - /** - * Returns the number of bytes a QuantilesDoublesSketch would require to store in compact form - * given k and n. The compact form is not updatable. - * @param k the size configuration parameter for the sketch - * @param n the number of quantiles input into the sketch - * @return the number of bytes required to store this sketch in compact form. - */ - public static int getCompactSerialiedSizeBytes(final int k, final long n) { - if (n == 0) { return 8; } - final int metaPreLongs = MAX_PRELONGS + 2; //plus min, max - return (metaPreLongs + computeRetainedItems(k, n)) << 3; - } - - @Override - public int getSerializedSizeBytes() { - if (isCompact()) { return getCurrentCompactSerializedSizeBytes(); } - return getCurrentUpdatableSerializedSizeBytes(); - } - - /** - * Returns the current number of bytes this sketch would require to store in the updatable MemorySegment Format. - * @return the current number of bytes this sketch would require to store in the updatable MemorySegment Format. - */ - public int getCurrentUpdatableSerializedSizeBytes() { - return getUpdatableStorageBytes(getK(), getN()); - } - - /** - * Returns the number of bytes a sketch would require to store in updatable form. - * This uses roughly 2X the storage of the compact form - * given k and n. - * @param k the size configuration parameter for the sketch - * @param n the number of quantiles input into the sketch - * @return the number of bytes this sketch would require to store in updatable form. - */ - public static int getUpdatableStorageBytes(final int k, final long n) { - if (n == 0) { return 8; } - final int metaPre = MAX_PRELONGS + 2; //plus min, max - final int totLevels = computeNumLevelsNeeded(k, n); - if (n <= k) { - final int ceil = Math.max(ceilingPowerOf2((int)n), MIN_K * 2); - return (metaPre + ceil) << 3; - } - return (metaPre + ((2 + totLevels) * k)) << 3; - } - - /** - * Puts the current sketch into the given MemorySegment in compact form if there is sufficient space, - * otherwise, it throws an error. - * - * @param dstSeg the given MemorySegment. - */ - public void putIntoMemorySegment(final MemorySegment dstSeg) { - putIntoMemorySegment(dstSeg, true); - } - - /** - * Puts the current sketch into the given MemorySegment if there is sufficient space, otherwise, - * throws an error. - * - * @param dstSeg the given MemorySegment. - * @param compact if true, compacts and sorts the base buffer, which optimizes merge - * performance at the cost of slightly increased serialization time. - */ - public void putIntoMemorySegment(final MemorySegment dstSeg, final boolean compact) { - if (hasMemorySegment() && (isCompact() == compact)) { - final MemorySegment srcSeg = getMemorySegment(); - MemorySegment.copy(srcSeg, 0, dstSeg, 0, getSerializedSizeBytes()); - } else { - final byte[] byteArr = toByteArray(compact); - final int arrLen = byteArr.length; - final long segCap = dstSeg.byteSize(); - if (segCap < arrLen) { - throw new SketchesArgumentException( - "Destination MemorySegment not large enough: " + segCap + " < " + arrLen); - } - MemorySegment.copy(byteArr, 0, dstSeg, JAVA_BYTE, 0, arrLen); - } - } - - @Override - public QuantilesDoublesSketchIteratorAPI iterator() { - return new QuantilesDoublesSketchIterator(this, getBitPattern()); - } - - @Override - public abstract void reset(); - - //Restricted - - /* - * DoublesMergeImpl.downSamplingMergeInto requires the target sketch to implement update(), so - * we ensure that the target is an UpdateSketch. The public API, on the other hand, just - * specifies a QuantilesDoublesSketch. This lets us be more specific about the type without changing the - * public API. - */ - UpdatableQuantilesDoublesSketch downSampleInternal(final QuantilesDoublesSketch srcSketch, final int smallerK, final MemorySegment dstSeg, - final MemorySegmentRequest mSegReq) { - final UpdatableQuantilesDoublesSketch newSketch = dstSeg == null - ? HeapUpdateDoublesSketch.newInstance(smallerK) - : DirectUpdateDoublesSketch.newInstance(smallerK, dstSeg, mSegReq); - if (srcSketch.isEmpty()) { return newSketch; } - DoublesMergeImpl.downSamplingMergeInto(srcSketch, newSketch); - return newSketch; - } - - //Restricted abstract - - /** - * Returns true if this sketch is compact - * @return true if this sketch is compact - */ - abstract boolean isCompact(); - - /** - * Returns the base buffer count - * @return the base buffer count - */ - abstract int getBaseBufferCount(); - - /** - * Returns the bit pattern for valid log levels - * @return the bit pattern for valid log levels - */ - abstract long getBitPattern(); - - /** - * Returns the capacity for the combined base buffer + levels - * @return the capacity for the combined base buffer + levels - */ - abstract int getCombinedBufferItemCapacity(); - - /** - * Returns the combined buffer, in non-compact form. - * @return the combined buffer, in non-compact form. - */ - abstract double[] getCombinedBuffer(); - - /** - * Gets the MemorySegment if it exists, otherwise returns null. - * @return the MemorySegment if it exists, otherwise returns null. - */ - abstract MemorySegment getMemorySegment(); - - //************SORTED VIEW**************************** - - @Override - public final DoublesSketchSortedView getSortedView() { - return refreshSortedView(); - } - - private final DoublesSketchSortedView refreshSortedView() { - return (doublesSV == null) ? (doublesSV = getSV()) : doublesSV; - } - - private DoublesSketchSortedView getSV() { - final long totalN = getN(); - if (isEmpty() || (totalN == 0)) { throw new SketchesArgumentException(EMPTY_MSG); } - final int numQuantiles = getNumRetained(); - final double[] svQuantiles = new double[numQuantiles]; - final long[] svCumWeights = new long[numQuantiles]; - final DoublesSketchAccessor sketchAccessor = DoublesSketchAccessor.wrap(this, false); - - // Populate from QuantilesDoublesSketch: - // copy over the "levels" and then the base buffer, all with appropriate weights - populateFromDoublesSketch(getK(), totalN, getBitPattern(), sketchAccessor, svQuantiles, svCumWeights); - - // Sort the first "numSamples" slots of the two arrays in tandem, - // taking advantage of the already sorted blocks of length k - blockyTandemMergeSort(svQuantiles, svCumWeights, numQuantiles, getK()); - - if (convertToCumulative(svCumWeights) != totalN) { - throw new SketchesStateException("Sorted View is misconfigured. TotalN does not match cumWeights."); - } - return new DoublesSketchSortedView(svQuantiles, svCumWeights, this); - } - - private final static void populateFromDoublesSketch( - final int k, final long totalN, final long bitPattern, - final DoublesSketchAccessor sketchAccessor, - final double[] svQuantiles, final long[] svCumWeights) { - long weight = 1; - int index = 0; - long bits = bitPattern; - assert bits == (totalN / (2L * k)); // internal consistency check - for (int lvl = 0; bits != 0L; lvl++, bits >>>= 1) { - weight <<= 1; // X2 - if ((bits & 1L) > 0L) { - sketchAccessor.setLevel(lvl); - for (int i = 0; i < sketchAccessor.numItems(); i++) { - svQuantiles[index] = sketchAccessor.get(i); - svCumWeights[index] = weight; - index++; - } - } - } - - weight = 1; //NOT a mistake! We just copied the highest level; now we need to copy the base buffer - final int startOfBaseBufferBlock = index; - - // Copy BaseBuffer over, along with weight = 1 - sketchAccessor.setLevel(BB_LVL_IDX); - for (int i = 0; i < sketchAccessor.numItems(); i++) { - svQuantiles[index] = sketchAccessor.get(i); - svCumWeights[index] = weight; - index++; - } - assert index == svQuantiles.length; - - // Must sort the items that came from the base buffer. - // Don't need to sort the corresponding weights because they are all the same. - final int numSamples = index; - Arrays.sort(svQuantiles, startOfBaseBufferBlock, numSamples); - } - - /** - * blockyTandemMergeSort() is an implementation of top-down merge sort specialized - * for the case where the input contains successive equal-length blocks - * that have already been sorted, so that only the top part of the - * merge tree remains to be executed. Also, two arrays are sorted in tandem, - * as discussed below. - * @param svQuantiles array of quantiles for sorted view - * @param svCumWts array for the cumulative weights (but not yet cumulative) for sorted view - * @param arrLen length of quantiles array and cumWts array - * @param blkSize size of internal sorted blocks, equal to k - */ - //used by this and UtilTest - static void blockyTandemMergeSort(final double[] svQuantiles, final long[] svCumWts, final int arrLen, - final int blkSize) { - assert blkSize >= 1; - if (arrLen <= blkSize) { return; } - int numblks = arrLen / blkSize; - if ((numblks * blkSize) < arrLen) { numblks += 1; } - assert ((numblks * blkSize) >= arrLen); - - // duplication of the input arrays is preparation for the "ping-pong" copy reduction strategy. - final double[] qSrc = Arrays.copyOf(svQuantiles, arrLen); - final long[] cwSrc = Arrays.copyOf(svCumWts, arrLen); - - blockyTandemMergeSortRecursion(qSrc, cwSrc, - svQuantiles, svCumWts, - 0, numblks, - blkSize, arrLen); - } - - /** - * blockyTandemMergeSortRecursion() is called by blockyTandemMergeSort(). - * In addition to performing the algorithm's top down recursion, - * it manages the buffer swapping that eliminates most copying. - * It also maps the input's pre-sorted blocks into the subarrays - * that are processed by tandemMerge(). - * @param qSrc source array of quantiles - * @param cwSrc source weights array - * @param qDst destination quantiles array - * @param cwDst destination weights array - * @param grpStart group start, refers to pre-sorted blocks such as block 0, block 1, etc. - * @param grpLen group length, refers to pre-sorted blocks such as block 0, block 1, etc. - * @param blkSize block size - * @param arrLim array limit - */ - private static void blockyTandemMergeSortRecursion(final double[] qSrc, final long[] cwSrc, - final double[] qDst, final long[] cwDst, final int grpStart, final int grpLen, - /* indices of blocks */ final int blkSize, final int arrLim) { - // Important note: grpStart and grpLen do NOT refer to positions in the underlying array. - // Instead, they refer to the pre-sorted blocks, such as block 0, block 1, etc. - - assert (grpLen > 0); - if (grpLen == 1) { return; } - final int grpLen1 = grpLen / 2; - final int grpLen2 = grpLen - grpLen1; - assert (grpLen1 >= 1); - assert (grpLen2 >= grpLen1); - - final int grpStart1 = grpStart; - final int grpStart2 = grpStart + grpLen1; - - //swap roles of src and dst - blockyTandemMergeSortRecursion(qDst, cwDst, - qSrc, cwSrc, - grpStart1, grpLen1, blkSize, arrLim); - - //swap roles of src and dst - blockyTandemMergeSortRecursion(qDst, cwDst, - qSrc, cwSrc, - grpStart2, grpLen2, blkSize, arrLim); - - // here we convert indices of blocks into positions in the underlying array. - final int arrStart1 = grpStart1 * blkSize; - final int arrStart2 = grpStart2 * blkSize; - final int arrLen1 = grpLen1 * blkSize; - int arrLen2 = grpLen2 * blkSize; - - // special case for the final block which might be shorter than blkSize. - if ((arrStart2 + arrLen2) > arrLim) { arrLen2 = arrLim - arrStart2; } - - tandemMerge(qSrc, cwSrc, - arrStart1, arrLen1, - arrStart2, arrLen2, - qDst, cwDst, - arrStart1); // which will be arrStart3 - } - - /** - * Performs two merges in tandem. One of them provides the sort keys - * while the other one passively undergoes the same data motion. - * @param qSrc quantiles source - * @param cwSrc cumulative weights source - * @param arrStart1 Array 1 start offset - * @param arrLen1 Array 1 length - * @param arrStart2 Array 2 start offset - * @param arrLen2 Array 2 length - * @param qDst quantiles destination - * @param cwDst cumulative weights destination - * @param arrStart3 Array 3 start offset - */ - private static void tandemMerge(final double[] qSrc, final long[] cwSrc, - final int arrStart1, final int arrLen1, - final int arrStart2, final int arrLen2, - final double[] qDst, final long[] cwDst, - final int arrStart3) { - final int arrStop1 = arrStart1 + arrLen1; - final int arrStop2 = arrStart2 + arrLen2; - - int i1 = arrStart1; - int i2 = arrStart2; - int i3 = arrStart3; - while ((i1 < arrStop1) && (i2 < arrStop2)) { - if (qSrc[i2] < qSrc[i1]) { - qDst[i3] = qSrc[i2]; - cwDst[i3] = cwSrc[i2]; - i2++; - } else { - qDst[i3] = qSrc[i1]; - cwDst[i3] = cwSrc[i1]; - i1++; - } - i3++; - } - - if (i1 < arrStop1) { - arraycopy(qSrc, i1, qDst, i3, arrStop1 - i1); - arraycopy(cwSrc, i1, cwDst, i3, arrStop1 - i1); - } else { - assert i2 < arrStop2; - arraycopy(qSrc, i2, qDst, i3, arrStop2 - i2); - arraycopy(cwSrc, i2, cwDst, i3, arrStop2 - i2); - } - } - - /** - * Convert the individual weights into cumulative weights. - * An array of {1,1,1,1} becomes {1,2,3,4} - * @param array of actual weights from the sketch, none of the weights may be zero - * @return total weight - */ - private static long convertToCumulative(final long[] array) { - long subtotal = 0; - for (int i = 0; i < array.length; i++) { - final long newSubtotal = subtotal + array[i]; - subtotal = array[i] = newSubtotal; - } - return subtotal; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesSketchBuilder.java b/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesSketchBuilder.java deleted file mode 100644 index 6155b5803..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesSketchBuilder.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.TAB; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentRequest; - -/** - * For building a new quantiles QuantilesDoublesSketch. - * - * @author Lee Rhodes - */ -public class QuantilesDoublesSketchBuilder { - private int bK = PreambleUtil.DEFAULT_K; - - /** - * Constructor for a new QuantilesDoublesSketchBuilder. The default configuration is - *
    - *
  • k: 128. This produces a normalized rank error of about 1.7%
  • - *
  • MemorySegment: null
  • - *
- */ - public QuantilesDoublesSketchBuilder() {} - - /** - * Sets the parameter k that determines the accuracy and size of the sketch. - * @param k determines the accuracy and size of the sketch. - * It is recommended that k be a power of 2 to enable unioning of sketches with - * different k. It is only possible to union from - * larger k to smaller k. - * @return this builder - */ - public QuantilesDoublesSketchBuilder setK(final int k) { - ClassicUtil.checkK(k); - bK = k; - return this; - } - - /** - * Gets the current configured k - * @return the current configured k - */ - public int getK() { - return bK; - } - - /** - * Returns an UpdatableQuantilesDoublesSketch with the current configuration of this Builder. - * @return a UpdatableQuantilesDoublesSketch - */ - public UpdatableQuantilesDoublesSketch build() { - return HeapUpdateDoublesSketch.newInstance(bK); - } - - /** - * Returns a UpdatableQuantilesDoublesSketch with the current configuration of this builder - * and the specified backing destination MemorySegment store that can grow. - * @param dstSeg destination MemorySegment for use by the sketch - * @return an UpdatableQuantilesDoublesSketch - */ - public UpdatableQuantilesDoublesSketch build(final MemorySegment dstSeg) { - return this.build(dstSeg, null); - } - - /** - * Returns a UpdatableQuantilesDoublesSketch with the current configuration of this builder - * and the specified backing destination MemorySegment store that can grow. - * @param dstSeg destination MemorySegment for use by the sketch - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return an UpdatableQuantilesDoublesSketch - */ - public UpdatableQuantilesDoublesSketch build(final MemorySegment dstSeg, final MemorySegmentRequest mSegReq) { - return DirectUpdateDoublesSketch.newInstance(bK, dstSeg, mSegReq); - } - - /** - * Creates a human readable string that describes the current configuration of this builder. - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("QuantileSketchBuilder configuration:").append(LS); - sb.append("K : ").append(TAB).append(bK).append(LS); - return sb.toString(); - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesSketchIterator.java b/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesSketchIterator.java deleted file mode 100644 index 5b1d9bfbb..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesSketchIterator.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import java.util.Objects; - -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIteratorAPI; - -/** - * Iterator over QuantilesDoublesSketch. The order is not defined. - */ -public final class QuantilesDoublesSketchIterator implements QuantilesDoublesSketchIteratorAPI { - private final DoublesSketchAccessor sketchAccessor; - private long bitPattern; - private int level; - private long weight; - private int index; - - QuantilesDoublesSketchIterator(final QuantilesDoublesSketch sketch, final long bitPattern) { - Objects.requireNonNull(sketch, "sketch must not be null"); - sketchAccessor = DoublesSketchAccessor.wrap(sketch, false); - this.bitPattern = bitPattern; - level = -1; - weight = 1; - index = -1; - } - - @Override - public double getQuantile() { - if (index < 0) { throw new SketchesStateException("index < 0; getQuantile() was called before next()"); } - return sketchAccessor.get(index); - } - - @Override - public long getWeight() { - return weight; - } - - @Override - public boolean next() { - index++; // advance index within the current level - if (index < sketchAccessor.numItems()) { - return true; - } - // go to the next non-empty level - do { - level++; - if (level > 0) { - bitPattern >>>= 1; - } - if (bitPattern == 0L) { - return false; // run out of levels - } - weight *= 2; - } while ((bitPattern & 1L) == 0L); - index = 0; - sketchAccessor.setLevel(level); - return true; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesUnion.java b/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesUnion.java deleted file mode 100644 index 707513c65..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesUnion.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.MemorySegmentStatus; - -/** - * The API for Union operations for QuantilesDoublesSketches - * - * @author Lee Rhodes - */ -public abstract class QuantilesDoublesUnion implements MemorySegmentStatus { - - /** - * No argument constructor. - */ - public QuantilesDoublesUnion() { } - - /** - * Returns a new UnionBuilder - * @return a new UnionBuilder - */ - public static QuantilesDoublesUnionBuilder builder() { - return new QuantilesDoublesUnionBuilder(); - } - - /** - * Returns a Heap Union object that has been initialized with the data from the given sketch. - * @param sketch A QuantilesDoublesSketch to be used as a source of data only and will not be modified. - * @return a QuantilesDoublesUnion object - */ - public static QuantilesDoublesUnion heapify(final QuantilesDoublesSketch sketch) { - return QuantilesDoublesUnionImpl.heapifyInstance(sketch); - } - - /** - * Returns a Heap Union object that has been initialized with the data from the given MemorySegment that contains an - * image of a sketch. - * - * @param srcSeg A MemorySegment image of a QuantilesDoublesSketch to be used as a source of data and will not be modified. - * @return a Union object - */ - public static QuantilesDoublesUnion heapify(final MemorySegment srcSeg) { - return QuantilesDoublesUnionImpl.heapifyInstance(srcSeg); - } - - /** - * Returns an updatable Union object that wraps the given MemorySegment that contains an image of a QuantilesDoublesSketch. - * - * @param srcSeg A MemorySegment image of an updatable QuantilesDoublesSketch to be used as the data structure for the union - * and will be modified. - * @return a Union object - */ - public static QuantilesDoublesUnion wrap(final MemorySegment srcSeg) { - return QuantilesDoublesUnionImpl.wrapInstance(srcSeg, null); - } - - /** - * Returns an updatable Union object that wraps the given MemorySegment that contains an image of a QuantilesDoublesSketch. - * - * @param srcSeg A MemorySegment sketch to be used as the data structure for the union and will be modified. - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return a Union object - */ - public static QuantilesDoublesUnion wrap(final MemorySegment srcSeg, final MemorySegmentRequest mSegReq) { - return QuantilesDoublesUnionImpl.wrapInstance(srcSeg, mSegReq); - } - - @Override - public abstract boolean hasMemorySegment(); - - @Override - public abstract boolean isOffHeap(); - - @Override - public abstract boolean isSameResource(final MemorySegment that); - - /** - * Returns true if this union is empty - * @return true if this union is empty - */ - public abstract boolean isEmpty(); - - /** - * Returns the configured maxK of this Union. - * @return the configured maxK of this Union. - */ - public abstract int getMaxK(); - - /** - * Returns the effective k of this Union. - * @return the effective k of this Union. - */ - public abstract int getEffectiveK(); - - /** - * Iterative union operation, which means this method can be repeatedly called. - * Merges the given sketch into this union object. - * The given sketch is not modified. - * It is required that the ratio of the two K's be a power of 2. - * This is easily satisfied if each of the K's are already a power of 2. - * If the given sketch is null or empty it is ignored. - * - *

It is required that the results of the union operation, which can be obtained at any time, - * is obtained from {@link #getResult() }. - * - * @param sketchIn the sketch to be merged into this one. - */ - public abstract void union(QuantilesDoublesSketch sketchIn); - - /** - * Iterative union operation, which means this method can be repeatedly called. - * Merges the given MemorySegment image of a QuantilesDoublesSketch into this union object. - * The given MemorySegment object is not modified and a link to it is not retained. - * It is required that the ratio of the two K's be a power of 2. - * This is easily satisfied if each of the K's are already a power of 2. - * If the given sketch is null or empty it is ignored. - * - *

It is required that the results of the union operation, which can be obtained at any time, - * is obtained from {@link #getResult() }. - * - * @param seg MemorySegment image of sketch to be merged - */ - public abstract void union(MemorySegment seg); - - /** - * Update this union with the given double (or float) data Item. - * - * @param dataItem The given double datum. - */ - public abstract void update(double dataItem); - - /** - * Gets the result of this Union as an UpdatableQuantilesDoublesSketch, which enables further update - * operations on the resulting sketch. The Union state has not been changed, which allows - * further union operations. - * - * @return the result of this Union operation - */ - public abstract UpdatableQuantilesDoublesSketch getResult(); - - /** - * Places the result of this Union into the provided MemorySegment as an UpdatableQuantilesDoublesSketch, - * which enables further update operations on the resulting sketch. The Union state has not - * been changed, which allows further union operations. - * - * @param dstSeg the destination MemorySegment for the result - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return the result of this Union operation - */ - public abstract UpdatableQuantilesDoublesSketch getResult(MemorySegment dstSeg, MemorySegmentRequest mSegReq); - - /** - * Gets the result of this Union as an UpdatableQuantilesDoublesSketch, which enables further update - * operations on the resulting sketch. The Union is reset to the virgin state. - * - * @return the result of this Union operation and reset. - */ - public abstract UpdatableQuantilesDoublesSketch getResultAndReset(); - - /** - * Resets this Union to a virgin state. - */ - public abstract void reset(); - - /** - * Serialize this union to a byte array. Result is an UpdatableQuantilesDoublesSketch, serialized in an - * unordered, non-compact form. The resulting byte[] can be heapified or wrapped as either a - * sketch or a union. - * - * @return byte array of this union - */ - public abstract byte[] toByteArray(); - - /** - * Returns summary information about the backing sketch. - */ - @Override - public abstract String toString(); - - /** - * Returns summary information about the backing sketch. Used for debugging. - * @param sketchSummary if true includes sketch summary - * @param dataDetail if true includes data detail - * @return summary information about the sketch. - */ - public abstract String toString(boolean sketchSummary, boolean dataDetail); - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesUnionBuilder.java b/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesUnionBuilder.java deleted file mode 100644 index 555b2660a..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesUnionBuilder.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentRequest; - -/** - * For building a new QuantilesDoublesSketch Union operation. - * - * @author Lee Rhodes - */ -public class QuantilesDoublesUnionBuilder { - private int bMaxK = PreambleUtil.DEFAULT_K; - - /** - * Constructor for a new QuantilesDoublesUnionBuilder. The default configuration is - *

    - *
  • k: 128. This produces a normalized rank error of about 1.7%
  • - *
- */ - public QuantilesDoublesUnionBuilder() {} - - /** - * Sets the parameter masK that determines the maximum size of the sketch that - * results from a union and its accuracy. - * @param maxK determines the accuracy and size of the union and is a maximum. - * The effective k can be smaller due to unions with smaller k sketches. - * It is recommended that maxK be a power of 2 to enable unioning of sketches with - * different k. - * @return this builder - */ - public QuantilesDoublesUnionBuilder setMaxK(final int maxK) { - ClassicUtil.checkK(maxK); - bMaxK = maxK; - return this; - } - - /** - * Gets the current configured maxK - * @return the current configured maxK - */ - public int getMaxK() { - return bMaxK; - } - - /** - * Returns a new empty Union object with the current configuration of this Builder. - * @return a Union object - */ - public QuantilesDoublesUnion build() { - return QuantilesDoublesUnionImpl.heapInstance(bMaxK); - } - - /** - * Returns a new empty Union object with the current configuration of this Builder - * and the specified backing destination MemorySegment store. - * @param dstSeg the destination MemorySegment - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return a Union object - */ - public QuantilesDoublesUnion build(final MemorySegment dstSeg, final MemorySegmentRequest mSegReq) { - return QuantilesDoublesUnionImpl.directInstance(bMaxK, dstSeg, mSegReq); - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesUnionImpl.java b/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesUnionImpl.java deleted file mode 100644 index 8cd4552a3..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesUnionImpl.java +++ /dev/null @@ -1,339 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.quantiles.ClassicUtil.checkIsMemorySegmentCompact; -import static org.apache.datasketches.quantiles.DoublesUtil.copyToHeap; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesReadOnlyException; - -/** - * Union operation. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -final class QuantilesDoublesUnionImpl extends QuantilesDoublesUnion { - int maxK_; - UpdatableQuantilesDoublesSketch gadget_ = null; - - private QuantilesDoublesUnionImpl(final int maxK) { - maxK_ = maxK; - } - - /** - * Returns a empty QuantilesDoublesUnion object on the heap. - * @param maxK determines the accuracy and size of the union and is a maximum. - * The effective k can be smaller due to unions with smaller k sketches. - * It is recommended that maxK be a power of 2 to enable unioning of sketches with - * different k. - * @return a new QuantilesDoublesUnionImpl on the Java heap - */ - static QuantilesDoublesUnionImpl heapInstance(final int maxK) { - return new QuantilesDoublesUnionImpl(maxK); - } - - /** - * Returns a empty QuantilesDoublesUnion object that uses the given MemorySegment for its internal sketch gadget - * and will be initialized to the empty state. - * - * @param maxK determines the accuracy and size of the union and is a maximum. - * The effective k can be smaller due to unions with smaller k sketches. - * It is recommended that maxK be a power of 2 to enable unioning of sketches with - * different k. - * @param dstSeg the MemorySegment to be used by the internal sketch and must not be null. - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return a QuantilesDoublesUnion object - */ - static QuantilesDoublesUnionImpl directInstance(final int maxK, final MemorySegment dstSeg, final MemorySegmentRequest mSegReq) { - Objects.requireNonNull(dstSeg); - final DirectUpdateDoublesSketch sketch = DirectUpdateDoublesSketch.newInstance(maxK, dstSeg, mSegReq); - final QuantilesDoublesUnionImpl union = new QuantilesDoublesUnionImpl(maxK); - union.maxK_ = maxK; - union.gadget_ = sketch; - return union; - } - - /** - * Returns a Heap QuantilesDoublesUnion object that has been initialized with the data from the given - * sketch. - * - * @param sketch A QuantilesDoublesSketch to be used as a source of data only and will not be modified. - * @return a QuantilesDoublesUnion object - */ - static QuantilesDoublesUnionImpl heapifyInstance(final QuantilesDoublesSketch sketch) { - Objects.requireNonNull(sketch); - final int k = sketch.getK(); - final QuantilesDoublesUnionImpl union = new QuantilesDoublesUnionImpl(k); - union.maxK_ = k; - union.gadget_ = copyToHeap(sketch); - return union; - } - - /** - * Returns a Heap QuantilesDoublesUnion object that has been initialized with the data from the given - * MemorySegment image of a QuantilesDoublesSketch. The srcSeg object will not be modified and a reference to - * it is not retained. The maxK of the resulting union will be that obtained from - * the sketch MemorySegment image. - * - * @param srcSeg an optionally read-only MemorySegment image of a QuantilesDoublesSketch - * @return a QuantilesDoublesUnion object - */ - static QuantilesDoublesUnionImpl heapifyInstance(final MemorySegment srcSeg) { - Objects.requireNonNull(srcSeg); - final HeapUpdateDoublesSketch sketch = HeapUpdateDoublesSketch.heapifyInstance(srcSeg); - final QuantilesDoublesUnionImpl union = new QuantilesDoublesUnionImpl(sketch.getK()); - union.gadget_ = sketch; - return union; - } - - /** - * Returns an Union object that wraps the data of the given MemorySegment image of a UpdatableQuantilesDoublesSketch. - * The data of the Union will remain in the MemorySegment. - * - * @param srcSeg A MemorySegment image of an updatable QuantilesDoublesSketch to be used as the data structure for the union - * and will be modified. - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return a Union object - */ - static QuantilesDoublesUnionImpl wrapInstance(final MemorySegment srcSeg, final MemorySegmentRequest mSegReq) { - Objects.requireNonNull(srcSeg); - if (srcSeg.isReadOnly()) { throw new SketchesReadOnlyException("Cannot create a Union with a Read Only MemorySegment."); } - final DirectUpdateDoublesSketch sketch = DirectUpdateDoublesSketch.wrapInstance(srcSeg, mSegReq); - final QuantilesDoublesUnionImpl union = new QuantilesDoublesUnionImpl(sketch.getK()); - union.gadget_ = sketch; - return union; - } - - @Override - public void union(final QuantilesDoublesSketch sketchIn) { - Objects.requireNonNull(sketchIn); - gadget_ = updateLogic(maxK_, gadget_, sketchIn); - gadget_.doublesSV = null; - } - - @Override - public void union(final MemorySegment seg) { - Objects.requireNonNull(seg); - if (checkIsMemorySegmentCompact(seg)) { - gadget_ = updateLogic(maxK_, gadget_, QuantilesDoublesSketch.wrap(seg)); - } else { - gadget_ = updateLogic(maxK_, gadget_, QuantilesDoublesSketch.writableWrap(seg, null)); - } - - gadget_.doublesSV = null; - } - - @Override - public void update(final double dataItem) { - if (gadget_ == null) { - gadget_ = HeapUpdateDoublesSketch.newInstance(maxK_); - } - gadget_.update(dataItem); - gadget_.doublesSV = null; - } - - @Override - public byte[] toByteArray() { - if (gadget_ == null) { - return QuantilesDoublesSketch.builder().setK(maxK_).build().toByteArray(); - } - return gadget_.toByteArray(); - } - - @Override - public UpdatableQuantilesDoublesSketch getResult() { - if (gadget_ == null) { - return HeapUpdateDoublesSketch.newInstance(maxK_); - } - return DoublesUtil.copyToHeap(gadget_); - } - - @Override - public UpdatableQuantilesDoublesSketch getResult(final MemorySegment dstSeg, final MemorySegmentRequest mSegReq) { - final long segCapBytes = dstSeg.byteSize(); - if (gadget_ == null) { - if (segCapBytes < QuantilesDoublesSketch.getUpdatableStorageBytes(0, 0)) { - throw new SketchesArgumentException("Insufficient capacity for result: " + segCapBytes); - } - return DirectUpdateDoublesSketch.newInstance(maxK_, dstSeg, mSegReq); - } - - gadget_.putIntoMemorySegment(dstSeg, false); - return DirectUpdateDoublesSketch.wrapInstance(dstSeg, mSegReq); - } - - @Override - public UpdatableQuantilesDoublesSketch getResultAndReset() { - if (gadget_ == null) { return null; } //Intentionally return null here for speed. - final UpdatableQuantilesDoublesSketch ds = gadget_.getSketchAndReset(); - gadget_ = null; - return ds; - } - - @Override - public void reset() { - gadget_.reset(); - } - - @Override - public boolean hasMemorySegment() { - return (gadget_ != null) && gadget_.hasMemorySegment(); - } - - @Override - public boolean isOffHeap() { - return (gadget_ != null) && gadget_.isOffHeap(); - } - - @Override - public boolean isEmpty() { - return (gadget_ == null) || gadget_.isEmpty(); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return (gadget_ == null) ? false : gadget_.isSameResource(that); - } - - @Override - public int getMaxK() { - return maxK_; - } - - @Override - public int getEffectiveK() { - return (gadget_ != null) ? gadget_.getK() : maxK_; - } - - @Override - public String toString() { - return toString(true, false); - } - - @Override - public String toString(final boolean sketchSummary, final boolean dataDetail) { - final StringBuilder sb = new StringBuilder(); - final String thisSimpleName = this.getClass().getSimpleName(); - final int maxK = getMaxK(); - final String kStr = String.format("%,d", maxK); - sb.append(LS).append("### Quantiles ").append(thisSimpleName).append(LS); - sb.append(" maxK : ").append(kStr); - if (gadget_ == null) { - sb.append(HeapUpdateDoublesSketch.newInstance(maxK_).toString()); - return sb.toString(); - } - sb.append(gadget_.toString(sketchSummary, dataDetail)); - return sb.toString(); - } - - //@formatter:off - static UpdatableQuantilesDoublesSketch updateLogic(final int myMaxK, final UpdatableQuantilesDoublesSketch myQS, final QuantilesDoublesSketch other) { - int sw1 = ((myQS == null) ? 0 : myQS.isEmpty() ? 4 : 8); - sw1 |= ((other == null) ? 0 : other.isEmpty() ? 1 : 2); - int outCase = 0; //0=null, 1=NOOP, 2=copy, 3=merge - - switch (sw1) { - case 0: outCase = 0; break; //myQS = null, other = null ; return null - case 1: outCase = 4; break; //myQS = null, other = empty; create empty-heap(myMaxK) - case 2: outCase = 2; break; //myQS = null, other = valid; stream or downsample to myMaxK - case 4: outCase = 1; break; //myQS = empty, other = null ; no-op - case 5: outCase = 1; break; //myQS = empty, other = empty; no-op - case 6: outCase = 3; break; //myQS = empty, other = valid; merge - case 8: outCase = 1; break; //myQS = valid, other = null ; no-op - case 9: outCase = 1; break; //myQS = valid, other = empty: no-op - case 10: outCase = 3; break; //myQS = valid, other = valid; merge - default: break; //This cannot happen - } - UpdatableQuantilesDoublesSketch ret = null; - - switch (outCase) { - case 0: break; //return null - case 1: ret = myQS; break; //no-op - case 2: { //myQS = null, other = valid; stream or downsample to myMaxK - assert other != null; - if (!other.isEstimationMode()) { //other is exact, stream items in - ret = HeapUpdateDoublesSketch.newInstance(myMaxK); - // exact mode, only need copy base buffer - final DoublesSketchAccessor otherAccessor = DoublesSketchAccessor.wrap(other, false); - for (int i = 0; i < otherAccessor.numItems(); ++i) { - ret.update(otherAccessor.get(i)); - } - } - else { //myQS = null, other is est mode - ret = (myMaxK < other.getK()) - ? other.downSampleInternal(other, myMaxK, null, null) //null seg, null mSegReq - : DoublesUtil.copyToHeap(other); //copy required because caller has handle - } - break; - } - case 3: { //myQS = empty/valid, other = valid; merge - assert other != null; - assert myQS != null; - if (!other.isEstimationMode()) { //other is exact, stream items in - ret = myQS; - // exact mode, only need copy base buffer - final DoublesSketchAccessor otherAccessor = DoublesSketchAccessor.wrap(other, false); - for (int i = 0; i < otherAccessor.numItems(); ++i) { - ret.update(otherAccessor.get(i)); - } - } else if (myQS.getK() <= other.getK()) { //I am smaller or equal, thus the target - DoublesMergeImpl.mergeInto(other, myQS); - ret = myQS; - } else if (myQS.isEmpty()) { - if (myQS.hasMemorySegment()) { - final MemorySegment seg = myQS.getMemorySegment(); //myQS is empty, ok to reconfigure - other.putIntoMemorySegment(seg, false); // not compact, but BaseBuf ordered - ret = DirectUpdateDoublesSketch.wrapInstance(seg, null); - } else { //myQS is empty and on heap - ret = DoublesUtil.copyToHeap(other); - } - } else { //Not Empty: myQS has data, downsample to tmp - final UpdatableQuantilesDoublesSketch tmp = QuantilesDoublesSketch.builder().setK(other.getK()).build(); - - DoublesMergeImpl.downSamplingMergeInto(myQS, tmp); //myData -> tmp - ret = (myQS.hasMemorySegment()) - ? QuantilesDoublesSketch.builder().setK(other.getK()).build(myQS.getMemorySegment()) - : QuantilesDoublesSketch.builder().setK(other.getK()).build(); - - DoublesMergeImpl.mergeInto(tmp, ret); - DoublesMergeImpl.mergeInto(other, ret); - } - break; - } - case 4: { //myQS = null, other = empty; create empty-heap(myMaxK) - ret = HeapUpdateDoublesSketch.newInstance(myMaxK); - break; - } - default: break; //This cannot happen - } - return ret; - } - //@formatter:on - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/QuantilesItemsSketch.java b/src/main/java/org/apache/datasketches/quantiles/QuantilesItemsSketch.java deleted file mode 100644 index 17c94940d..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/QuantilesItemsSketch.java +++ /dev/null @@ -1,726 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.quantiles.ClassicUtil.MIN_K; -import static org.apache.datasketches.quantiles.ClassicUtil.checkFamilyID; -import static org.apache.datasketches.quantiles.ClassicUtil.checkK; -import static org.apache.datasketches.quantiles.ClassicUtil.checkPreLongsFlagsCap; -import static org.apache.datasketches.quantiles.ClassicUtil.computeBaseBufferItems; -import static org.apache.datasketches.quantiles.ClassicUtil.computeBitPattern; -import static org.apache.datasketches.quantiles.ClassicUtil.computeCombinedBufferItemCapacity; -import static org.apache.datasketches.quantiles.ClassicUtil.computeRetainedItems; -import static org.apache.datasketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFlags; -import static org.apache.datasketches.quantiles.PreambleUtil.extractK; -import static org.apache.datasketches.quantiles.PreambleUtil.extractN; -import static org.apache.datasketches.quantiles.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.quantiles.PreambleUtil.extractSerVer; - -import java.lang.foreign.MemorySegment; -import java.lang.reflect.Array; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Objects; -import java.util.Random; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.quantilescommon.GenericPartitionBoundaries; -import org.apache.datasketches.quantilescommon.ItemsSketchSortedView; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; -import org.apache.datasketches.quantilescommon.QuantilesAPI; -import org.apache.datasketches.quantilescommon.QuantilesGenericAPI; -import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI; - -/** - * This is an implementation of the Low Discrepancy Mergeable Quantiles Sketch, using generic items, - * described in section 3.2 of the journal version of the paper "Mergeable Summaries" - * by Agarwal, Cormode, Huang, Phillips, Wei, and Yi: - * - *

Reference:

- * - *

A k of 128 produces a normalized, rank error of about 1.7%. - * For example, the median returned from getQuantile(0.5) will be between the actual quantiles - * from the hypothetically sorted array of input quantiles at normalized ranks of 0.483 and 0.517, with - * a confidence of about 99%.

- * - *

The size of an QuantilesItemsSketch is very dependent on the size of the generic Items input into the sketch, - * so there is no comparable size table as there is for the QuantilesDoublesSketch.

- * - * @see QuantilesAPI - * - * @param The sketch item data type. - */ -public final class QuantilesItemsSketch implements QuantilesGenericAPI { - final Class clazz; - private final Comparator comparator_; - final int k_; - long n_; - T maxItem_; //The largest item ever seen in the stream. - T minItem_; //The smallest item ever seen in the stream. - - /** - * In the on-heap version, this equals combinedBuffer_.length. - * May differ in later versions that grow space more aggressively. - * Also, in the off-heap version, combinedBuffer_ won't even be a java array, - * so it won't know its own length. - */ - int combinedBufferItemCapacity_; - - /** - * Number of items currently in base buffer. - * - *

Count = N % (2 * K)

- */ - int baseBufferCount_; - - /** - * Active levels expressed as a bit pattern. - * - *

Pattern = N / (2 * K)

- */ - long bitPattern_; - - /** - * This single array contains the base buffer plus all levels some of which may not be used. - * A level is of size K and is either full and sorted, or not used. A "not used" buffer may have - * garbage. Whether a level buffer used or not is indicated by the bitPattern_. - * The base buffer has length 2*K but might not be full and isn't necessarily sorted. - * The base buffer precedes the level buffers. - * - *

The levels arrays require quite a bit of explanation, which we defer until later.

- */ - Object[] combinedBuffer_; - - ItemsSketchSortedView classicQisSV = null; - - /** - * Setting the seed makes the results of the sketch deterministic if the input items are - * received in exactly the same order. This is only useful when performing test comparisons, - * otherwise, it is not recommended. - */ - public static final Random rand = new Random(); - - //**Constructors** - - private QuantilesItemsSketch( - final int k, - final Class clazz, - final Comparator comparator) { - Objects.requireNonNull(clazz, "Class must not be null."); - Objects.requireNonNull(comparator, "Comparator must not be null."); - checkK(k); - k_ = k; - this.clazz = clazz; - comparator_ = comparator; - } - - /** - * Obtains a new instance of an QuantilesItemsSketch using the DEFAULT_K. - * @param The sketch item data type. - * @param clazz the given class of T. - * @param comparator to compare items. - * @return an ItemSketch<T>. - */ - public static QuantilesItemsSketch getInstance( - final Class clazz, - final Comparator comparator) { - return getInstance(clazz, PreambleUtil.DEFAULT_K, comparator); - } - - /** - * Obtains a new instance of an QuantilesItemsSketch using the given k. - * @param The sketch item data type. - * @param clazz the given class of T. - * @param k Parameter that controls space usage of sketch and accuracy of estimates. - * Must be greater than 2 and less than 65536 and a power of 2. - * @param comparator to compare items. - * @return an ItemSketch<T>. - */ - public static QuantilesItemsSketch getInstance( - final Class clazz, - final int k, - final Comparator comparator) { - final QuantilesItemsSketch qs = new QuantilesItemsSketch<>(k, clazz, comparator); - final int bufAlloc = 2 * Math.min(MIN_K, k); //the min is important - qs.n_ = 0; - qs.combinedBufferItemCapacity_ = bufAlloc; - qs.combinedBuffer_ = new Object[bufAlloc]; - qs.baseBufferCount_ = 0; - qs.bitPattern_ = 0; - qs.minItem_ = null; - qs.maxItem_ = null; - return qs; - } - - /** - * Heapifies the given srcSeg, which must be a MemorySegment image of a QuantilesItemsSketch. - * @param The sketch item data type. - * @param clazz the given class of T. - * @param srcSeg a MemorySegment image of a sketch generated from this class. - * @param comparator to compare items. - * @param serDe an instance of ArrayOfItemsSerDe. - * @return a QuantilesItemsSketch<T> on the Java heap. - */ - public static QuantilesItemsSketch heapify( - final Class clazz, - final MemorySegment srcSeg, - final Comparator comparator, - final ArrayOfItemsSerDe serDe) { - final long segCapBytes = srcSeg.byteSize(); - if (segCapBytes < 8) { - throw new SketchesArgumentException("MemorySegment too small: " + segCapBytes); - } - final int preambleLongs = extractPreLongs(srcSeg); - final int serVer = extractSerVer(srcSeg); - final int familyID = extractFamilyID(srcSeg); - final int flags = extractFlags(srcSeg); - final int k = extractK(srcSeg); - - ItemsUtil.checkItemsSerVer(serVer); - - if ((serVer == 3) && ((flags & COMPACT_FLAG_MASK) == 0)) { - throw new SketchesArgumentException("Non-compact MemorySegment images are not supported."); - } - - final boolean empty = checkPreLongsFlagsCap(preambleLongs, flags, segCapBytes); - checkFamilyID(familyID); - final QuantilesItemsSketch sk = getInstance(clazz, k, comparator); //checks k - if (empty) { return sk; } - - //Not empty, must have valid preamble + min, max - final long n = extractN(srcSeg); - - //can't check MemorySegment capacity here, not enough information - final int extra = 2; //for min, max - final int numSegItems = computeRetainedItems(k, n) + extra; - - //set class members - sk.n_ = n; - sk.combinedBufferItemCapacity_ = computeCombinedBufferItemCapacity(k, n); - sk.baseBufferCount_ = computeBaseBufferItems(k, n); - sk.bitPattern_ = computeBitPattern(k, n); - sk.combinedBuffer_ = new Object[sk.combinedBufferItemCapacity_]; - - final int srcSegItemsOffsetBytes = preambleLongs * Long.BYTES; - final MemorySegment slice = - srcSeg.asSlice(srcSegItemsOffsetBytes, srcSeg.byteSize() - srcSegItemsOffsetBytes); - final T[] itemsArray = serDe.deserializeFromMemorySegment(slice, 0, numSegItems); - sk.itemsArrayToCombinedBuffer(itemsArray); - return sk; - } - - /** - * Returns a copy of the given sketch. - * @param The sketch item data type. - * @param sketch the given sketch. - * @return a copy of the given sketch. - */ - static QuantilesItemsSketch copy(final QuantilesItemsSketch sketch) { - final QuantilesItemsSketch qsCopy = QuantilesItemsSketch.getInstance(sketch.clazz, sketch.k_, sketch.comparator_); - qsCopy.n_ = sketch.n_; - qsCopy.minItem_ = sketch.isEmpty() ? null : sketch.getMinItem(); - qsCopy.maxItem_ = sketch.isEmpty() ? null : sketch.getMaxItem(); - qsCopy.combinedBufferItemCapacity_ = sketch.getCombinedBufferAllocatedCount(); - qsCopy.baseBufferCount_ = sketch.getBaseBufferCount(); - qsCopy.bitPattern_ = sketch.getBitPattern(); - final Object[] combBuf = sketch.getCombinedBuffer(); - qsCopy.combinedBuffer_ = Arrays.copyOf(combBuf, combBuf.length); - return qsCopy; - } - - //**END of Constructors** - - @Override - public double[] getCDF(final T[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return classicQisSV.getCDF(splitPoints, searchCrit); - } - - @Override - public Class getClassOfT() { return clazz; } - - @Override - public Comparator getComparator() { - return comparator_; - } - - @Override - public T getMaxItem() { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return maxItem_; - } - - @Override - public T getMinItem() { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return minItem_; - } - - @Override - public GenericPartitionBoundaries getPartitionBoundariesFromNumParts( - final int numEquallySizedParts, - final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return classicQisSV.getPartitionBoundariesFromNumParts(numEquallySizedParts, searchCrit); - } - - @Override - public GenericPartitionBoundaries getPartitionBoundariesFromPartSize( - final long nominalPartSizeItems, - final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return classicQisSV.getPartitionBoundariesFromPartSize(nominalPartSizeItems, searchCrit); - } - - @Override - public double[] getPMF(final T[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return classicQisSV.getPMF(splitPoints, searchCrit); - } - - @Override - public T getQuantile(final double rank, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return classicQisSV.getQuantile(rank, searchCrit); - } - - @Override - public T getQuantileLowerBound(final double rank) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return getQuantile(max(0, rank - getNormalizedRankError(k_, false))); - } - - @Override - public T getQuantileUpperBound(final double rank) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return getQuantile(min(1.0, rank + getNormalizedRankError(k_, false))); - } - - @Override - public T[] getQuantiles(final double[] ranks, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return classicQisSV.getQuantiles(ranks, searchCrit); - } - - @Override - public double getRank(final T quantile, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return classicQisSV.getRank(quantile, searchCrit); - } - - @Override - public double getRankLowerBound(final double rank) { - return max(0.0, rank - getNormalizedRankError(k_, false)); - } - - @Override - public double getRankUpperBound(final double rank) { - return min(1.0, rank + getNormalizedRankError(k_, false)); - } - - @Override - public double[] getRanks(final T[] quantiles, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - final int len = quantiles.length; - final double[] ranks = new double[len]; - for (int i = 0; i < len; i++) { - ranks[i] = classicQisSV.getRank(quantiles[i], searchCrit); - } - return ranks; - } - - @Override - public QuantilesGenericSketchIteratorAPI iterator() { - return new QuantilesItemsSketchIterator<>(this, bitPattern_); - } - - @Override - public int getK() { - return k_; - } - - @Override - public long getN() { - return n_; - } - - @Override - public double getNormalizedRankError(final boolean pmf) { - return getNormalizedRankError(k_, pmf); - } - - /** - * Gets the normalized rank error given k and pmf. - * Static method version of the {@link #getNormalizedRankError(boolean)}. - * @param k the configuration parameter - * @param pmf if true, returns the "double-sided" normalized rank error for the getPMF() function. - * Otherwise, it is the "single-sided" normalized rank error for all the other queries. - * @return if pmf is true, the normalized rank error for the getPMF() function. - * Otherwise, it is the "single-sided" normalized rank error for all the other queries. - */ - public static double getNormalizedRankError(final int k, final boolean pmf) { - return ClassicUtil.getNormalizedRankError(k, pmf); - } - - /** - * Gets the approximate k to use given epsilon, the normalized rank error. - * @param epsilon the normalized rank error between zero and one. - * @param pmf if true, this function returns k assuming the input epsilon - * is the desired "double-sided" epsilon for the getPMF() function. Otherwise, this function - * returns k assuming the input epsilon is the desired "single-sided" - * epsilon for all the other queries. - * @return k given epsilon. - */ - public static int getKFromEpsilon(final double epsilon, final boolean pmf) { - return ClassicUtil.getKFromEpsilon(epsilon, pmf); - } - - @Override - public boolean isEmpty() { - return getN() == 0; - } - - @Override - public boolean isEstimationMode() { - return getN() >= (2L * k_); - } - - @Override - public boolean isReadOnly() { - return false; - } - - @Override - public void reset() { - n_ = 0; - combinedBufferItemCapacity_ = 2 * Math.min(MIN_K, k_); //the min is important - combinedBuffer_ = new Object[combinedBufferItemCapacity_]; - baseBufferCount_ = 0; - bitPattern_ = 0; - minItem_ = null; - maxItem_ = null; - classicQisSV = null; - } - - /** - * Serialize this sketch to a byte array form. - * @param serDe an instance of ArrayOfItemsSerDe - * @return byte array of this sketch - */ - public byte[] toByteArray(final ArrayOfItemsSerDe serDe) { - return toByteArray(false, serDe); - } - - /** - * Serialize this sketch to a byte array form. - * @param ordered if true the base buffer will be ordered (default == false). - * @param serDe an instance of ArrayOfItemsSerDe - * @return this sketch in a byte array form. - */ - public byte[] toByteArray(final boolean ordered, final ArrayOfItemsSerDe serDe) { - return ItemsByteArrayImpl.toByteArray(this, ordered, serDe); - } - - /** - * Returns human readable summary information about this sketch. - * Used for debugging. - */ - @Override - public String toString() { - return toString(false, false); - } - - /** - * Returns human readable summary information about this sketch. - * Used for debugging. - * @param withLevels if true includes sketch levels array summary information - * @param withLevelsAndItems if true include detail of levels array and items array together - * @return human readable summary information about this sketch. - */ - public String toString(final boolean withLevels, final boolean withLevelsAndItems) { - return ItemsUtil.toString(withLevels, withLevelsAndItems, this); - } - - /** - * Returns a human readable string of the preamble of a byte array image of an QuantilesItemsSketch. - * Used for debugging. - * @param byteArr the given byte array - * @return a human readable string of the preamble of a byte array image of an QuantilesItemsSketch. - */ - public static String toString(final byte[] byteArr) { - return PreambleUtil.toString(byteArr, false); - } - - /** - * Returns a human readable string of the preamble of a MemorySegment image of an QuantilesItemsSketch. - * Used for debugging. - * @param seg the given MemorySegment - * @return a human readable string of the preamble of a MemorySegment image of an QuantilesItemsSketch. - */ - public static String toString(final MemorySegment seg) { - return PreambleUtil.toString(seg, false); - } - - /** - * From an existing sketch, this creates a new sketch that can have a smaller K. - * The original sketch is not modified. - * - * @param newK the new K that must be smaller than current K. - * It is required that this.getK() = newK * 2^(nonnegative integer). - * @return the new sketch. - */ - public QuantilesItemsSketch downSample(final int newK) { - final QuantilesItemsSketch newSketch = QuantilesItemsSketch.getInstance(clazz, newK, comparator_); - ItemsMergeImpl.downSamplingMergeInto(this, newSketch); - return newSketch; - } - - @Override - public int getNumRetained() { - return computeRetainedItems(getK(), getN()); - } - - /** - * Puts the current sketch into the given MemorySegment if there is sufficient space. - * Otherwise, throws an error. - * - * @param dstSeg the given MemorySegment. - * @param serDe an instance of ArrayOfItemsSerDe - */ - public void putIntoMemorySegment(final MemorySegment dstSeg, final ArrayOfItemsSerDe serDe) { - final byte[] byteArr = toByteArray(serDe); - final long segCap = dstSeg.byteSize(); - if (segCap < byteArr.length) { - throw new SketchesArgumentException( - "Destination MemorySegment not large enough: " + segCap + " < " + byteArr.length); - } - MemorySegment.copy(byteArr, 0, dstSeg, JAVA_BYTE, 0, byteArr.length); - } - - @Override - public void update(final T item) { - // this method only uses the base buffer part of the combined buffer - - if (item == null) { return; } - if ((maxItem_ == null) || (comparator_.compare(item, maxItem_) > 0)) { maxItem_ = item; } - if ((minItem_ == null) || (comparator_.compare(item, minItem_) < 0)) { minItem_ = item; } - - if ((baseBufferCount_ + 1) > combinedBufferItemCapacity_) { - QuantilesItemsSketch.growBaseBuffer(this); - } - combinedBuffer_[baseBufferCount_++] = item; - n_++; - if (baseBufferCount_ == (2 * k_)) { - ItemsUtil.processFullBaseBuffer(this); - } - classicQisSV = null; - } - - // Restricted - - /** - * Returns the base buffer count - * @return the base buffer count - */ - int getBaseBufferCount() { - return baseBufferCount_; - } - - /** - * Returns the allocated count for the combined base buffer - * @return the allocated count for the combined base buffer - */ - int getCombinedBufferAllocatedCount() { - return combinedBufferItemCapacity_; - } - - /** - * Returns the bit pattern for valid log levels - * @return the bit pattern for valid log levels - */ - long getBitPattern() { - return bitPattern_; - } - - /** - * Returns the combined buffer reference - * @return the combined buffer reference - */ - Object[] getCombinedBuffer() { - return combinedBuffer_; - } - - /** - * Returns a copy of this sketch and then resets. - * @return a copy of this sketch and then resets. - */ - QuantilesItemsSketch getSketchAndReset() { - final QuantilesItemsSketch skCopy = copy(this); - reset(); - return skCopy; - } - - /** - * Loads the Combined Buffer, min and max from the given items array. - * The Combined Buffer is always in non-compact form and must be pre-allocated. - * @param itemsArray the given items array - */ - private void itemsArrayToCombinedBuffer(final T[] itemsArray) { - final int extra = 2; // space for min and max items - - //Load min, max - minItem_ = itemsArray[0]; - maxItem_ = itemsArray[1]; - - //Load base buffer - System.arraycopy(itemsArray, extra, combinedBuffer_, 0, baseBufferCount_); - - //Load levels - long bits = bitPattern_; - if (bits > 0) { - int index = extra + baseBufferCount_; - for (int level = 0; bits != 0L; level++, bits >>>= 1) { - if ((bits & 1L) > 0L) { - System.arraycopy(itemsArray, index, combinedBuffer_, (2 + level) * k_, k_); - index += k_; - } - } - } - } - - private static void growBaseBuffer(final QuantilesItemsSketch sketch) { - final Object[] baseBuffer = sketch.getCombinedBuffer(); - final int oldSize = sketch.getCombinedBufferAllocatedCount(); - final int k = sketch.getK(); - assert oldSize < (2 * k); - final int newSize = Math.max(Math.min(2 * k, 2 * oldSize), 1); - sketch.combinedBufferItemCapacity_ = newSize; - sketch.combinedBuffer_ = Arrays.copyOf(baseBuffer, newSize); - } - - //************SORTED VIEW**************************** - - @Override - public ItemsSketchSortedView getSortedView() { - return refreshSortedView(); - } - - private ItemsSketchSortedView refreshSortedView() { - return (classicQisSV == null) ? (classicQisSV = getSV(this)) : classicQisSV; - } - - @SuppressWarnings({"unchecked"}) - private static ItemsSketchSortedView getSV(final QuantilesItemsSketch sk) { - final long totalN = sk.getN(); - if (sk.isEmpty() || (totalN == 0)) { throw new SketchesArgumentException(EMPTY_MSG); } - final int k = sk.getK(); - final int numQuantiles = sk.getNumRetained(); - final T[] svQuantiles = (T[]) Array.newInstance(sk.clazz, numQuantiles); - final long[] svCumWeights = new long[numQuantiles]; - final Comparator comparator = sk.comparator_; - - final T[] combinedBuffer = (T[]) sk.getCombinedBuffer(); - final int baseBufferCount = sk.getBaseBufferCount(); - - // Populate from QuantilesItemsSketch: - // copy over the "levels" and then the base buffer, all with appropriate weights - populateFromItemsSketch(k, totalN, sk.getBitPattern(), combinedBuffer, baseBufferCount, - numQuantiles, svQuantiles, svCumWeights, sk.getComparator()); - - // Sort the first "numSamples" slots of the two arrays in tandem, - // taking advantage of the already sorted blocks of length k - ItemsMergeImpl.blockyTandemMergeSort(svQuantiles, svCumWeights, numQuantiles, k, comparator); - - if (convertToCumulative(svCumWeights) != totalN) { - throw new SketchesStateException("Sorted View is misconfigured. TotalN does not match cumWeights."); - } - - return new ItemsSketchSortedView<>(svQuantiles, svCumWeights, sk); - - } - - private static void populateFromItemsSketch( - final int k, final long totalN, final long bitPattern, final T[] combinedBuffer, - final int baseBufferCount, final int numQuantiles, final T[] svQuantiles, final long[] svCumWeights, - final Comparator comparator) { - - long weight = 1; - int index = 0; - long bits = bitPattern; - assert bits == (totalN / (2L * k)); // internal consistency check - for (int lvl = 0; bits != 0L; lvl++, bits >>>= 1) { - weight <<= 1; // X2 - if ((bits & 1L) > 0L) { - final int offset = (2 + lvl) * k; - for (int i = 0; i < k; i++) { - svQuantiles[index] = combinedBuffer[i + offset]; - svCumWeights[index] = weight; - index++; - } - } - } - - weight = 1; //NOT a mistake! We just copied the highest level; now we need to copy the base buffer - final int startOfBaseBufferBlock = index; - - // Copy BaseBuffer over, along with weight = 1 - for (int i = 0; i < baseBufferCount; i++) { - svQuantiles[index] = combinedBuffer[i]; - svCumWeights[index] = weight; - index++; - } - assert index == numQuantiles; - - // Must sort the items that came from the base buffer. - // Don't need to sort the corresponding weights because they are all the same. - Arrays.sort(svQuantiles, startOfBaseBufferBlock, numQuantiles, comparator); - } - - /** - * Convert the individual weights into cumulative weights. - * An array of {1,1,1,1} becomes {1,2,3,4} - * @param array of actual weights from the sketch, none of the weights may be zero - * @return total weight - */ - private static long convertToCumulative(final long[] array) { - long subtotal = 0; - for (int i = 0; i < array.length; i++) { - final long newSubtotal = subtotal + array[i]; - subtotal = array[i] = newSubtotal; - } - return subtotal; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/QuantilesItemsSketchIterator.java b/src/main/java/org/apache/datasketches/quantiles/QuantilesItemsSketchIterator.java deleted file mode 100644 index 58bbc8c4e..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/QuantilesItemsSketchIterator.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import java.util.Objects; - -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI; - -/** - * Iterator over QuantilesItemsSketch. The order is not defined. - * @param type of item - */ -public final class QuantilesItemsSketchIterator implements QuantilesGenericSketchIteratorAPI { - private Object[] combinedBuffer; - private long bitPattern; - private int level; - private long weight; - private int index; - private int offset; - private int num; - private int k; - - QuantilesItemsSketchIterator(final QuantilesItemsSketch sketch, final long bitPattern) { - Objects.requireNonNull(sketch, "sketch must not be null"); - combinedBuffer = sketch.combinedBuffer_; - num = sketch.getBaseBufferCount(); - this.k = sketch.getK(); - this.bitPattern = bitPattern; - this.level = -1; - this.weight = 1; - this.index = -1; - this.offset = 0; - } - - @Override - @SuppressWarnings("unchecked") - public T getQuantile() { - if (index < 0) { throw new SketchesStateException("index < 0; getQuantile() was called before next()"); } - return (T) combinedBuffer[offset + index]; - } - - @Override - public long getWeight() { - return weight; - } - - @Override - public boolean next() { - index++; // advance index within the current level - if (index < num) { - return true; - } - // go to the next non-empty level - do { - level++; - if (level > 0) { - bitPattern >>>= 1; - } - if (bitPattern == 0L) { - return false; // run out of levels - } - weight *= 2; - } while ((bitPattern & 1L) == 0L); - index = 0; - offset = (2 + level) * k; - num = k; - return true; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/QuantilesItemsUnion.java b/src/main/java/org/apache/datasketches/quantiles/QuantilesItemsUnion.java deleted file mode 100644 index 9e1ce9bc8..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/QuantilesItemsUnion.java +++ /dev/null @@ -1,341 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.Util.LS; - -import java.lang.foreign.MemorySegment; -import java.util.Comparator; -import java.util.Objects; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; - -/** - * The API for Union operations for generic QuantilesItemsSketches - * - * @param The sketch item data type. - * - * @author Lee Rhodes - * @author Alexander Saydakov - */ -public final class QuantilesItemsUnion { - - final int maxK_; - final Comparator comparator_; - QuantilesItemsSketch gadget_; - Class clazz_; - - private QuantilesItemsUnion( - final int maxK, - final Comparator comparator, - final QuantilesItemsSketch gadget) { - Objects.requireNonNull(gadget, "Gadget sketch must not be null."); - Objects.requireNonNull(comparator, "Comparator must not be null."); - maxK_ = maxK; - comparator_ = comparator; - gadget_ = gadget; - clazz_ = gadget.clazz; - gadget_.classicQisSV = null; - } - - /** - * Create an instance of QuantilesItemsUnion with the default k. - * @param The sketch item data type. - * @param clazz The sketch class type. - * @param comparator to compare items. - * @return a new instance of QuantilesItemsUnion - */ - public static QuantilesItemsUnion getInstance( - final Class clazz, - final Comparator comparator) { - final QuantilesItemsSketch emptySk = QuantilesItemsSketch.getInstance(clazz, comparator); - return new QuantilesItemsUnion<>(PreambleUtil.DEFAULT_K, comparator, emptySk); - } - - /** - * Create an instance of QuantilesItemsUnion - * @param The sketch item data type. - * @param clazz The sketch class type. - * @param maxK determines the accuracy and size of the union and is a maximum. - * The effective k can be smaller due to unions with smaller k sketches. - * maxK must be a power of 2 to enable unioning of sketches with a different k. - * @param comparator to compare items. - * @return an new instance of QuantilesItemsUnion - */ - public static QuantilesItemsUnion getInstance( - final Class clazz, - final int maxK, - final Comparator comparator) { - final QuantilesItemsSketch emptySk = QuantilesItemsSketch.getInstance(clazz, maxK, comparator); - return new QuantilesItemsUnion<>(maxK, comparator, emptySk); - } - - /** - * Initialize a new QuantilesItemsUnion with a heapified instance of an QuantilesItemsSketch from a MemorySegment. - * @param The sketch data type. - * @param clazz The sketch class type. - * @param srcSeg the given srcSeg, an image of an QuantilesItemsSketch. A reference to srcSeg will not be maintained internally. - * @param comparator to compare items. - * @param serDe an instance of ArrayOfItemsSerDe. - * @return an QuantilesItemsUnion initialized with a heapified QuantilesItemsSketch from a MemorySegment. - */ - public static QuantilesItemsUnion initializeWithMemorySegment( - final Class clazz, - final MemorySegment srcSeg, - final Comparator comparator, - final ArrayOfItemsSerDe serDe) { - final QuantilesItemsSketch gadget = QuantilesItemsSketch.heapify(clazz, srcSeg, comparator, serDe); - return new QuantilesItemsUnion<>(gadget.getK(), gadget.getComparator(), gadget); - } - - /** - * Initialize a new QuantilesItemsUnion with an instance of QuantilesItemsSketch - * @param The sketch data type - * @param sketch an instance of QuantilesItemsSketch to initialize this union - * @return an initialized instance of QuantilesItemsUnion - */ - public static QuantilesItemsUnion initialize(final QuantilesItemsSketch sketch) { - return new QuantilesItemsUnion<>(sketch.getK(), sketch.getComparator(), QuantilesItemsSketch.copy(sketch)); - } - - /** - * Iterative union operation, which means this method can be repeatedly called. - * Merges the given sketch into this union object. - * The given sketch is not modified. - * It is required that the ratio of the two K's be a power of 2. - * This is easily satisfied if each of the K's are already a power of 2. - * If the given sketch is null or empty it is ignored. - * - *

It is required that the results of the union operation, which can be obtained at any time, - * is obtained from {@link #getResult() }.

- * - * @param sketchIn the sketch to be merged into this one. - */ - public void union(final QuantilesItemsSketch sketchIn) { - gadget_ = updateLogic(maxK_, comparator_, gadget_, sketchIn); - } - - /** - * Iterative union operation, which means this method can be repeatedly called. - * Merges the given MemorySegment image of a QuantilesItemsSketch into this union object. - * The given MemorySegment object is not modified and a link to it is not retained. - * It is required that the ratio of the two K's be a power of 2. - * This is easily satisfied if each of the K's are already a power of 2. - * If the given sketch is null or empty it is ignored. - * - *

It is required that the results of the union operation, which can be obtained at any time, - * is obtained from {@link #getResult() }.

- * @param srcSeg MemorySegment image of sketch to be merged - * @param serDe an instance of ArrayOfItemsSerDe - */ - public void union( - final MemorySegment srcSeg, - final ArrayOfItemsSerDe serDe) { - final QuantilesItemsSketch that = QuantilesItemsSketch.heapify(clazz_, srcSeg, comparator_, serDe); - gadget_ = updateLogic(maxK_, comparator_, gadget_, that); - } - - /** - * Update this union with the given dataItem. - * - * @param dataItem The given datum. - */ - public void update(final T dataItem) { - if (dataItem == null) { return; } - if (gadget_ == null) { - gadget_ = QuantilesItemsSketch.getInstance(clazz_, maxK_, comparator_); - } - gadget_.update(dataItem); - } - - /** - * Gets the result of this Union operation as a copy of the internal state. - * This enables further union update operations on this state. - * @return the result of this Union operation - */ - public QuantilesItemsSketch getResult() { - if (gadget_ == null) { - return QuantilesItemsSketch.getInstance(clazz_, maxK_, comparator_); - } - return QuantilesItemsSketch.copy(gadget_); //can't have any externally owned handles. - } - - /** - * Gets the sketch result of this Union operation and resets this Union to the virgin state. - * - * @return the result of this Union operation and reset. - */ - public QuantilesItemsSketch getResultAndReset() { - if (gadget_ == null) { return null; } //Intentionally return null here for speed. - return gadget_.getSketchAndReset(); - } - - /** - * Resets this Union to a virgin state. - * Keeps maxK, comparator and clazz - */ - public void reset() { - gadget_ = null; - } - - /** - * Returns true if this union is empty - * @return true if this union is empty - */ - public boolean isEmpty() { - return (gadget_ == null) || gadget_.isEmpty(); - } - - /** - * Returns the configured maxK of this Union. - * @return the configured maxK of this Union. - */ - public int getMaxK() { - return maxK_; - } - - /** - * Returns the effective k of this Union. - * @return the effective k of this Union. - */ - public int getEffectiveK() { - return (gadget_ != null) ? gadget_.getK() : maxK_; - } - - /** - * Returns summary information about the backing sketch. - */ - @Override - public String toString() { - return toString(true, false); - } - - /** - * Returns summary information about the backing sketch. Used for debugging. - * @param sketchSummary if true includes sketch summary - * @param dataDetail if true includes data detail - * @return summary information about the sketch. - */ - public String toString(final boolean sketchSummary, final boolean dataDetail) { - final StringBuilder sb = new StringBuilder(); - final String thisSimpleName = this.getClass().getSimpleName(); - final int maxK = this.getMaxK(); - final String kStr = String.format("%,d", maxK); - sb.append(LS).append("### Quantiles ").append(thisSimpleName).append(LS); - sb.append(" maxK : ").append(kStr); - if (gadget_ == null) { - sb.append(QuantilesItemsSketch.getInstance(clazz_, maxK_, comparator_).toString()); - return sb.toString(); - } - sb.append(gadget_.toString(sketchSummary, dataDetail)); - return sb.toString(); - } - - /** - * Serialize this union to a byte array. Result is an QuantilesItemsSketch, serialized in an - * unordered, non-compact form. The resulting byte[] can be passed to getInstance for either a - * sketch or union. - * - * @param serDe an instance of ArrayOfItemsSerDe - * @return byte array of this union - */ - public byte[] toByteArray(final ArrayOfItemsSerDe serDe) { - if (gadget_ == null) { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(clazz_, maxK_, comparator_); - return sketch.toByteArray(serDe); - } - return gadget_.toByteArray(serDe); - } - - //@formatter:off - @SuppressWarnings("unchecked") - static QuantilesItemsSketch updateLogic(final int myMaxK, final Comparator comparator, - final QuantilesItemsSketch myQS, final QuantilesItemsSketch other) { - int sw1 = ((myQS == null) ? 0 : myQS.isEmpty() ? 4 : 8); - sw1 |= ((other == null) ? 0 : other.isEmpty() ? 1 : 2); - int outCase = 0; //0=null, 1=NOOP, 2=copy, 3=merge - - switch (sw1) { - case 0: outCase = 0; break; //myQS = null, other = null ; return null - case 1: outCase = 4; break; //myQS = null, other = empty; create empty-heap(myMaxK) - case 2: outCase = 2; break; //myQS = null, other = valid; stream or downsample to myMaxK - case 4: outCase = 1; break; //myQS = empty, other = null ; no-op - case 5: outCase = 1; break; //myQS = empty, other = empty; no-op - case 6: outCase = 3; break; //myQS = empty, other = valid; merge - case 8: outCase = 1; break; //myQS = valid, other = null ; no-op - case 9: outCase = 1; break; //myQS = valid, other = empty: no-op - case 10: outCase = 3; break; //myQS = valid, other = valid; merge - default: break; //This cannot happen - } - QuantilesItemsSketch ret = null; - - switch (outCase) { - case 0: break; - case 1: ret = myQS; break; - case 2: { //myQS = null, other = valid; stream or downsample to myMaxK - assert other != null; - if (!other.isEstimationMode()) { //other is exact, stream items in - ret = QuantilesItemsSketch.getInstance(other.getClassOfT(), myMaxK, comparator); - final int otherCnt = other.getBaseBufferCount(); - final Object[] combBuf = other.getCombinedBuffer(); - for (int i = 0; i < otherCnt; i++) { - ret.update((T) combBuf[i]); - } - } - else { //myQS = null, other is est mode - ret = (myMaxK < other.getK()) - ? other.downSample(myMaxK) - : QuantilesItemsSketch.copy(other); //required because caller has handle - } - break; - } - case 3: { //myQS = empty/valid, other = valid; merge - assert other != null; - assert myQS != null; - if (!other.isEstimationMode()) { //other is exact, stream items in - ret = myQS; - final int otherCnt = other.getBaseBufferCount(); - final Object[] combBuf = other.getCombinedBuffer(); - for (int i = 0; i < otherCnt; i++) { - ret.update((T) combBuf[i]); - } - } else if (myQS.getK() <= other.getK()) { //I am smaller or equal, thus the target - ItemsMergeImpl.mergeInto(other, myQS); - ret = myQS; - } - else { //Bigger: myQS.getK() > other.getK(), must reverse roles - //must copy other as it will become mine and can't have any externally owned handles. - ret = QuantilesItemsSketch.copy(other); - ItemsMergeImpl.mergeInto(myQS, ret); - } - break; - } - case 4: { - assert other != null; - ret = QuantilesItemsSketch.getInstance(other.getClassOfT(), Math.min(myMaxK, other.getK()), comparator); - break; - } - default: break; //This cannot happen - } - return ret; - } - //@formatter:on - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/UpdatableQuantilesDoublesSketch.java b/src/main/java/org/apache/datasketches/quantiles/UpdatableQuantilesDoublesSketch.java deleted file mode 100644 index 803484aac..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/UpdatableQuantilesDoublesSketch.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentRequest; - -/** - * Extends QuantilesDoubleSketch - * @author Jon Malkin - */ -public abstract class UpdatableQuantilesDoublesSketch extends QuantilesDoublesSketch { - - UpdatableQuantilesDoublesSketch(final int k) { - super(k); - } - - /** - * Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch. - * - *

The given MemorySegment must be writable and it must contain a UpdatableQuantilesDoublesSketch. - * The sketch will be updated and managed totally within the MemorySegment. If the given source - * MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

- * - *

NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch - * will request more capacity using the {@link MemorySegmentRequest MemorySegmentRequest} interface. The default of this interface will - * return a new MemorySegment on the heap.

- * - * @param srcSeg a MemorySegment that contains sketch data. - * @return an instance of this sketch that wraps the given MemorySegment. - */ - public static UpdatableQuantilesDoublesSketch wrap(final MemorySegment srcSeg) { - return DirectUpdateDoublesSketch.wrapInstance(srcSeg, null); - } - - /** - * Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch and including an - * optional, user defined {@link MemorySegmentRequest MemorySegmentRequest}. - * - *

The given MemorySegment must be writable and it must contain a UpdatableQuantilesDoublesSketch. - * The sketch will be updated and managed totally within the MemorySegment. If the given source - * MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

- * - *

NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch - * will request more capacity using the {@link MemorySegmentRequest MemorySegmentRequest} interface. The default of this interface will - * return a new MemorySegment on the heap. It is up to the user to optionally extend this interface if more flexible - * handling of requests for more capacity is required.

- * - * @param srcSeg a MemorySegment that contains sketch data. - * @param mSegReq the MemorySegmentRequest used if the given MemorySegment needs to expand. - * Otherwise, it can be null and the default MemorySegmentRequest will be used. - * @return an instance of this sketch that wraps the given MemorySegment. - */ - public static UpdatableQuantilesDoublesSketch wrap(final MemorySegment srcSeg, final MemorySegmentRequest mSegReq) { - return DirectUpdateDoublesSketch.wrapInstance(srcSeg, mSegReq); - } - - /** - * Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch. - * The resulting sketch will not retain any link to the source MemorySegment. - * @param srcSeg compact MemorySegment image of a sketch serialized by this sketch. - * @return a heap-based sketch based on the given MemorySegment. - */ - public static UpdatableQuantilesDoublesSketch heapify(final MemorySegment srcSeg) { - return HeapUpdateDoublesSketch.heapifyInstance(srcSeg); - } - - /** - * Returns a CompactQuantilesDoublesSketch of this class - * @return a CompactQuantilesDoublesSketch of this class - */ - public CompactQuantilesDoublesSketch compact() { - return compact(null); - } - - /** - * Returns a compact version of this sketch. If passing in a MemorySegment object, the compact sketch - * will use and load that MemorySegment; otherwise, an on-heap sketch will be returned. - * @param dstSeg An optional target MemorySegment to hold the sketch. - * @return A compact version of this sketch - */ - public CompactQuantilesDoublesSketch compact(final MemorySegment dstSeg) { - if (dstSeg == null) { - return HeapCompactDoublesSketch.createFromUpdateSketch(this); - } - return DirectCompactDoublesSketch.createFromUpdateSketch(this, dstSeg); - } - - /** - * Returns an on-heap copy of this sketch and then resets this sketch with the same value of k. - * @return an on-heap copy of this sketch and then resets this sketch with the same value of k. - */ - abstract UpdatableQuantilesDoublesSketch getSketchAndReset(); - - /** - * Grows the combined buffer to the given spaceNeeded - * - * @param currentSpace the current allocated space - * @param spaceNeeded the space needed - * @return the enlarged combined buffer with data from the original combined buffer. - */ - abstract double[] growCombinedBuffer(int currentSpace, int spaceNeeded); - - @Override - boolean isCompact() { - return false; - } - - /** - * Puts the minimum item - * - * @param minItem the given minimum item - */ - abstract void putMinItem(double minItem); - - /** - * Puts the max item - * - * @param maxItem the given maximum item - */ - abstract void putMaxItem(double maxItem); - - /** - * Puts the long n - * - * @param n the given long n - */ - abstract void putN(long n); - - /** - * Puts the combined, non-compact buffer. - * - * @param combinedBuffer the combined buffer array - */ - abstract void putCombinedBuffer(double[] combinedBuffer); - - /** - * Puts the base buffer count - * - * @param baseBufCount the given base buffer count - */ - abstract void putBaseBufferCount(int baseBufCount); - - /** - * Puts the bit pattern - * - * @param bitPattern the given bit pattern - */ - abstract void putBitPattern(long bitPattern); - - @Override - public abstract void update(double item); - -} diff --git a/src/main/java/org/apache/datasketches/quantiles/package-info.java b/src/main/java/org/apache/datasketches/quantiles/package-info.java deleted file mode 100644 index 7ff0dcdb3..000000000 --- a/src/main/java/org/apache/datasketches/quantiles/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * The quantiles package contains stochastic streaming algorithms that enable single-pass - * analysis of the distribution of a stream of quantiles. - * - * @see org.apache.datasketches.quantiles.QuantilesDoublesSketch - * @see org.apache.datasketches.quantiles.QuantilesItemsSketch - */ -package org.apache.datasketches.quantiles; diff --git a/src/main/java/org/apache/datasketches/quantilescommon/BinarySearch.java b/src/main/java/org/apache/datasketches/quantilescommon/BinarySearch.java deleted file mode 100644 index 9a5bd7592..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/BinarySearch.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -/** - * Contains common equality binary search algorithms. - * - * @author Lee Rhodes - */ -public final class BinarySearch { - - /** - * No argument constructor. - */ - public BinarySearch() { } - - /** - * Binary Search for the index of the exact float value in the given search range. - * If -1 is returned there are no values in the search range that equals the given value. - * @param arr The given ordered array to search. - * @param low the index of the lowest value of the search range - * @param high the index of the highest value of the search range - * @param v the value to search for - * @return return the index of the value, if found, otherwise, return -1; - */ - public static int find(final float[] arr, final int low, final int high, final float v) { - int lo = low; - int hi = high; - while (lo <= hi) { - final int mid = lo + (hi - lo) / 2; - if (v < arr[mid]) { hi = mid - 1; } - else { - if (v > arr[mid]) { lo = mid + 1; } - else { return mid; } - } - } - return -1; - } - - /** - * Binary Search for the index of the exact double value in the given search range. - * If -1 is returned there are no values in the search range that equals the given value. - * @param arr The given ordered array to search. - * @param low the index of the lowest value of the search range - * @param high the index of the highest value of the search range - * @param v the value to search for - * @return return the index of the value, if found, otherwise, return -1; - */ - public static int find(final double[] arr, final int low, final int high, final double v) { - int lo = low; - int hi = high; - while (lo <= hi) { - final int mid = lo + (hi - lo) / 2; - if (v < arr[mid]) { hi = mid - 1; } - else { - if (v > arr[mid]) { lo = mid + 1; } - else { return mid; } - } - } - return -1; - } - - /** - * Binary Search for the index of the exact long value in the given search range. - * If -1 is returned there are no values in the search range that equals the given value. - * @param arr The given ordered array to search. - * @param low the index of the lowest value of the search range - * @param high the index of the highest value of the search range - * @param v the value to search for - * @return return the index of the value, if found, otherwise, return -1; - */ - public static int find(final long[] arr, final int low, final int high, final long v) { - int lo = low; - int hi = high; - while (lo <= hi) { - final int mid = lo + (hi - lo) / 2; - if (v < arr[mid]) { hi = mid - 1; } - else { - if (v > arr[mid]) { lo = mid + 1; } - else { return mid; } - } - } - return -1; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/DoublesSketchSortedView.java b/src/main/java/org/apache/datasketches/quantilescommon/DoublesSketchSortedView.java deleted file mode 100644 index 42b19d983..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/DoublesSketchSortedView.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantilesAPI.EMPTY_MSG; -import static org.apache.datasketches.quantilescommon.QuantilesUtil.getNaturalRank; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.IncludeMinMax.DoublesPair; - -/** - * The SortedView of the Quantiles Classic QuantilesDoublesSketch and the KllDoublesSketch. - * @author Alexander Saydakov - * @author Lee Rhodes - */ -public final class DoublesSketchSortedView implements DoublesSortedView { - private final double[] quantiles; - private final long[] cumWeights; //cumulative natural weights - private final long totalN; - - /** - * Construct from elements, also used in testing. - * @param quantiles sorted array of quantiles - * @param cumWeights sorted, monotonically increasing cumulative weights. - * @param sk the underlying quantile sketch. - */ - public DoublesSketchSortedView( - final double[] quantiles, - final long[] cumWeights, - final QuantilesDoublesAPI sk) { - final DoublesPair dPair = - IncludeMinMax.includeDoublesMinMax(quantiles, cumWeights, sk.getMaxItem(), sk.getMinItem()); - this.quantiles = dPair.quantiles; - this.cumWeights = dPair.cumWeights; - this.totalN = sk.getN(); - } - - //Used for testing - DoublesSketchSortedView( - final double[] quantiles, - final long[] cumWeights, - final long totalN, - final double maxItem, - final double minItem) { - final DoublesPair dPair = - IncludeMinMax.includeDoublesMinMax(quantiles, cumWeights, maxItem, minItem); - this.quantiles = dPair.quantiles; - this.cumWeights = dPair.cumWeights; - this.totalN = totalN; - } - - @Override - public long[] getCumulativeWeights() { - return cumWeights.clone(); - } - - @Override - public double getMaxItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - final int top = quantiles.length - 1; - return quantiles[top]; - } - - @Override - public double getMinItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - return quantiles[0]; - } - - @Override - public long getN() { - return totalN; - } - - @Override - public int getNumRetained() { - return quantiles.length; - } - - @Override - public double getQuantile(final double rank, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - QuantilesUtil.checkNormalizedRankBounds(rank); - final int len = cumWeights.length; - final double naturalRank = getNaturalRank(rank, totalN, searchCrit); - final InequalitySearch crit = (searchCrit == INCLUSIVE) ? InequalitySearch.GE : InequalitySearch.GT; - final int index = InequalitySearch.find(cumWeights, 0, len - 1, naturalRank, crit); - if (index == -1) { - return quantiles[len - 1]; //EXCLUSIVE (GT) case: normRank == 1.0; - } - return quantiles[index]; - } - - @Override - public double[] getQuantiles() { - return quantiles.clone(); - } - - @Override - public double getRank(final double quantile, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - final int len = quantiles.length; - final InequalitySearch crit = (searchCrit == INCLUSIVE) ? InequalitySearch.LE : InequalitySearch.LT; - final int index = InequalitySearch.find(quantiles, 0, len - 1, quantile, crit); - if (index == -1) { - return 0; //EXCLUSIVE (LT) case: quantile <= minQuantile; INCLUSIVE (LE) case: quantile < minQuantile - } - return (double)cumWeights[index] / totalN; - } - - @Override - public boolean isEmpty() { - return totalN == 0; - } - - @Override - public DoublesSortedViewIterator iterator() { - return new DoublesSortedViewIterator(quantiles, cumWeights); - } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/DoublesSortedView.java b/src/main/java/org/apache/datasketches/quantilescommon/DoublesSortedView.java deleted file mode 100644 index 80bbcdbcd..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/DoublesSortedView.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * The Sorted View for quantile sketches of primitive type double. - * @see SortedView - * @author Alexander Saydakov - * @author Lee Rhodes - */ -public interface DoublesSortedView extends SortedView { - - /** - * Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream - * as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(false) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 overlapping intervals. - *
- *

The start of each interval is below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and the end of the interval - * is the rank or cumulative probability corresponding to the split point.

- * - *

The (m+1)th interval represents 100% of the distribution represented by the sketch - * and consistent with the definition of a cumulative probability distribution, thus the (m+1)th - * rank or probability in the returned array is always 1.0.

- * - *

If a split point exactly equals a retained item of the sketch and the search criterion is:

- * - *
    - *
  • INCLUSIVE, the resulting cumulative probability will include that item.
  • - *
  • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0]. - * @throws SketchesArgumentException if sketch is empty. - */ - default double[] getCDF(final double[] splitPoints, final QuantileSearchCriteria searchCrit) { - QuantilesUtil.checkDoublesSplitPointsOrder(splitPoints); - final int len = splitPoints.length + 1; - final double[] buckets = new double[len]; - for (int i = 0; i < len - 1; i++) { - buckets[i] = getRank(splitPoints[i], searchCrit); - } - buckets[len - 1] = 1.0; - return buckets; - } - - /** - * Returns the maximum item of the stream. This may be distinct from the largest item retained by the - * sketch algorithm. - * - * @return the maximum item of the stream - * @throws SketchesArgumentException if sketch is empty. - */ - double getMaxItem(); - - /** - * Returns the minimum item of the stream. This may be distinct from the smallest item retained by the - * sketch algorithm. - * - * @return the minimum item of the stream - * @throws SketchesArgumentException if sketch is empty. - */ - double getMinItem(); - - /** - * Returns an approximation to the Probability Mass Function (PMF) of the input stream - * as an array of probability masses as doubles on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(true) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 consecutive, non-overlapping intervals. - *
- *

Each interval except for the end intervals starts with a split point and ends with the next split - * point in sequence.

- * - *

The first interval starts below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and ends with the first split point

- * - *

The last (m+1)th interval starts with the last split point and ends after the last - * item retained by the sketch corresponding to a rank or probability of 1.0.

- * - *

The sum of the probability masses of all (m+1) intervals is 1.0.

- * - *

If the search criterion is:

- * - *
    - *
  • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude - * that item.
  • - *
  • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include - * that item.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0]. - * @throws SketchesArgumentException if sketch is empty. - */ - default double[] getPMF(final double[] splitPoints, final QuantileSearchCriteria searchCrit) { - final double[] buckets = getCDF(splitPoints, searchCrit); - final int len = buckets.length; - for (int i = len; i-- > 1; ) { - buckets[i] -= buckets[i - 1]; - } - return buckets; - } - - /** - * Gets the approximate quantile of the given normalized rank and the given search criterion. - * - * @param rank the given normalized rank, a double in the range [0.0, 1.0]. - * @param searchCrit If INCLUSIVE, the given rank includes all quantiles ≤ - * the quantile directly corresponding to the given rank. - * If EXCLUSIVE, he given rank includes all quantiles < - * the quantile directly corresponding to the given rank. - * @return the approximate quantile given the normalized rank. - * @throws SketchesArgumentException if sketch is empty. - * @see QuantileSearchCriteria - */ - double getQuantile(double rank, QuantileSearchCriteria searchCrit); - - /** - * Returns an array of all retained quantiles by the sketch. - * @return an array of all retained quantiles by the sketch. - */ - double[] getQuantiles(); - - /** - * Gets the normalized rank corresponding to the given a quantile. - * - * @param quantile the given quantile - * @param searchCrit if INCLUSIVE the given quantile is included into the rank. - * @return the normalized rank corresponding to the given quantile. - * @throws SketchesArgumentException if sketch is empty. - * @see QuantileSearchCriteria - */ - double getRank(double quantile, QuantileSearchCriteria searchCrit); - - @Override - DoublesSortedViewIterator iterator(); - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/DoublesSortedViewIterator.java b/src/main/java/org/apache/datasketches/quantilescommon/DoublesSortedViewIterator.java deleted file mode 100644 index 85bf96b68..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/DoublesSortedViewIterator.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -/** - * Iterator over quantile sketches of primitive type double. - */ -public final class DoublesSortedViewIterator extends SortedViewIterator { - private final double[] quantiles; - - /** - * Constructor. - * @param quantiles the given array of quantiles, which must be ordered. - * @param cumWeights the given array of cumulative weights, which must be ordered, start with the value one, and - * the last value must be equal to N, the total number of items updated to the sketch. - */ - public DoublesSortedViewIterator(final double[] quantiles, final long[] cumWeights) { - super(cumWeights); - this.quantiles = quantiles; //SpotBugs EI_EXPOSE_REP2 suppressed by FindBugsExcludeFilter - } - - /** - * Gets the quantile at the current index. - * - *

Don't call this before calling next() for the first time - * or after getting false from next().

- * - * @return the quantile at the current index. - */ - public double getQuantile() { - return quantiles[index]; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/FloatsSketchSortedView.java b/src/main/java/org/apache/datasketches/quantilescommon/FloatsSketchSortedView.java deleted file mode 100644 index 0260d1b3b..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/FloatsSketchSortedView.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.IncludeMinMax.FloatsPair; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantilesAPI.EMPTY_MSG; -import static org.apache.datasketches.quantilescommon.QuantilesUtil.getNaturalRank; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * The SortedView for the KllFloatsSketch and the ReqSketch. - * @author Alexander Saydakov - * @author Lee Rhodes - */ -public class FloatsSketchSortedView implements FloatsSortedView { - private final float[] quantiles; - private final long[] cumWeights; //cumulative natural weights - private final long totalN; - - /** - * Construct Sorted View. - * @param quantiles sorted array of quantiles - * @param cumWeights sorted, monotonically increasing cumulative weights. - * @param sk the underlying quantile sketch. - */ - public FloatsSketchSortedView( - final float[] quantiles, - final long[] cumWeights, - final QuantilesFloatsAPI sk) { - final FloatsPair fPair = - IncludeMinMax.includeFloatsMinMax(quantiles, cumWeights, sk.getMaxItem(), sk.getMinItem()); - this.quantiles = fPair.quantiles; - this.cumWeights = fPair.cumWeights; - this.totalN = sk.getN(); - } - - //Used for testing - FloatsSketchSortedView( - final float[] quantiles, - final long[] cumWeights, - final long totalN, - final float maxItem, - final float minItem) { - final FloatsPair fPair = - IncludeMinMax.includeFloatsMinMax(quantiles, cumWeights, maxItem, minItem); - this.quantiles = fPair.quantiles; - this.cumWeights = fPair.cumWeights; - this.totalN = totalN; - } - - @Override - public long[] getCumulativeWeights() { - return cumWeights.clone(); - } - - @Override - public float getMaxItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - final int top = quantiles.length - 1; - return quantiles[top]; - } - - @Override - public float getMinItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - return quantiles[0]; - } - - @Override - public long getN() { - return totalN; - } - - @Override - public int getNumRetained() { - return quantiles.length; - } - - @Override - public float getQuantile(final double rank, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - QuantilesUtil.checkNormalizedRankBounds(rank); - final int len = cumWeights.length; - final double naturalRank = getNaturalRank(rank, totalN, searchCrit); - final InequalitySearch crit = (searchCrit == INCLUSIVE) ? InequalitySearch.GE : InequalitySearch.GT; - final int index = InequalitySearch.find(cumWeights, 0, len - 1, naturalRank, crit); - if (index == -1) { - return quantiles[len - 1]; //EXCLUSIVE (GT) case: normRank == 1.0; - } - return quantiles[index]; - } - - @Override - public float[] getQuantiles() { - return quantiles.clone(); - } - - @Override - public double getRank(final float quantile, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - final int len = quantiles.length; - final InequalitySearch crit = (searchCrit == INCLUSIVE) ? InequalitySearch.LE : InequalitySearch.LT; - final int index = InequalitySearch.find(quantiles, 0, len - 1, quantile, crit); - if (index == -1) { - return 0; //EXCLUSIVE (LT) case: quantile <= minQuantile; INCLUSIVE (LE) case: quantile < minQuantile - } - return (double)cumWeights[index] / totalN; - } - - @Override - public boolean isEmpty() { - return totalN == 0; - } - - @Override - public FloatsSortedViewIterator iterator() { - return new FloatsSortedViewIterator(quantiles, cumWeights); - } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/FloatsSortedView.java b/src/main/java/org/apache/datasketches/quantilescommon/FloatsSortedView.java deleted file mode 100644 index 81e4c9cc2..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/FloatsSortedView.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * The Sorted View for quantiles of primitive type float. - * @see SortedView - * @author Alexander Saydakov - * @author Lee Rhodes - */ -public interface FloatsSortedView extends SortedView { - - /** - * Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream - * as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(false) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 overlapping intervals. - *
- *

The start of each interval is below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and the end of the interval - * is the rank or cumulative probability corresponding to the split point.

- * - *

The (m+1)th interval represents 100% of the distribution represented by the sketch - * and consistent with the definition of a cumulative probability distribution, thus the (m+1)th - * rank or probability in the returned array is always 1.0.

- * - *

If a split point exactly equals a retained item of the sketch and the search criterion is:

- * - *
    - *
  • INCLUSIVE, the resulting cumulative probability will include that item.
  • - *
  • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0]. - * @throws SketchesArgumentException if sketch is empty. - */ - default double[] getCDF(final float[] splitPoints, final QuantileSearchCriteria searchCrit) { - QuantilesUtil.checkFloatsSplitPointsOrder(splitPoints); - final int len = splitPoints.length + 1; - final double[] buckets = new double[len]; - for (int i = 0; i < len - 1; i++) { - buckets[i] = getRank(splitPoints[i], searchCrit); - } - buckets[len - 1] = 1.0; - return buckets; - } - - /** - * Returns the maximum item of the stream. This may be distinct from the largest item retained by the - * sketch algorithm. - * - * @return the maximum item of the stream - * @throws SketchesArgumentException if sketch is empty. - */ - float getMaxItem(); - - /** - * Returns the minimum item of the stream. This may be distinct from the smallest item retained by the - * sketch algorithm. - * - * @return the minimum item of the stream - * @throws SketchesArgumentException if sketch is empty. - */ - float getMinItem(); - - /** - * Returns an approximation to the Probability Mass Function (PMF) of the input stream - * as an array of probability masses as doubles on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(true) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 consecutive, non-overlapping intervals. - *
- *

Each interval except for the end intervals starts with a split point and ends with the next split - * point in sequence.

- * - *

The first interval starts below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and ends with the first split point

- * - *

The last (m+1)th interval starts with the last split point and ends after the last - * item retained by the sketch corresponding to a rank or probability of 1.0.

- * - *

The sum of the probability masses of all (m+1) intervals is 1.0.

- * - *

If the search criterion is:

- * - *
    - *
  • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude - * that item.
  • - *
  • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include - * that item.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0]. - * @throws SketchesArgumentException if sketch is empty. - */ - default double[] getPMF(final float[] splitPoints, final QuantileSearchCriteria searchCrit) { - final double[] buckets = getCDF(splitPoints, searchCrit); - final int len = buckets.length; - for (int i = len; i-- > 1; ) { - buckets[i] -= buckets[i - 1]; - } - return buckets; - } - - /** - * Gets the approximate quantile of the given normalized rank and the given search criterion. - * - * @param rank the given normalized rank, a double in the range [0.0, 1.0]. - * @param searchCrit If INCLUSIVE, the given rank includes all quantiles ≤ - * the quantile directly corresponding to the given rank. - * If EXCLUSIVE, he given rank includes all quantiles < - * the quantile directly corresponding to the given rank. - * @return the approximate quantile given the normalized rank. - * @throws SketchesArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - float getQuantile(double rank, QuantileSearchCriteria searchCrit); - - /** - * Returns an array of all retained quantiles by the sketch. - * @return an array of all retained quantiles by the sketch. - */ - float[] getQuantiles(); - - /** - * Gets the normalized rank corresponding to the given a quantile. - * - * @param quantile the given quantile - * @param searchCrit if INCLUSIVE the given quantile is included into the rank. - * @return the normalized rank corresponding to the given quantile. - * @throws SketchesArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - double getRank(float quantile, QuantileSearchCriteria searchCrit); - - @Override - FloatsSortedViewIterator iterator(); - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/FloatsSortedViewIterator.java b/src/main/java/org/apache/datasketches/quantilescommon/FloatsSortedViewIterator.java deleted file mode 100644 index 09b45da01..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/FloatsSortedViewIterator.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -/** - * Iterator over quantile sketches of primitive type float. - */ -public final class FloatsSortedViewIterator extends SortedViewIterator { - private final float[] quantiles; - - /** - * Constructor. - * @param quantiles the given array of quantiles, which must be ordered. - * @param cumWeights the given array of cumulative weights, which must be ordered, start with the value one, and - * the last value must be equal to N, the total number of items updated to the sketch. - */ - public FloatsSortedViewIterator(final float[] quantiles, final long[] cumWeights) { - super(cumWeights); - this.quantiles = quantiles; //SpotBugs EI_EXPOSE_REP2 suppressed by FindBugsExcludeFilter - } - - /** - * Gets the quantile at the current index. - * - *

Don't call this before calling next() for the first time - * or after getting false from next().

- * - * @return the quantile at the current index. - */ - public float getQuantile() { - return quantiles[index]; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/GenericInequalitySearch.java b/src/main/java/org/apache/datasketches/quantilescommon/GenericInequalitySearch.java deleted file mode 100644 index 460ef6b7b..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/GenericInequalitySearch.java +++ /dev/null @@ -1,251 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import java.util.Comparator; -import java.util.Objects; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This provides efficient, unique and unambiguous binary searching for inequality comparison criteria - * for ordered arrays of values that may include duplicate values. The inequality criteria include - * <, ≤, ==, ≥, >. All the inequality criteria use the same search algorithm. - * (Although == is not an inequality, it is included for convenience.) - * - *

In order to make the searching unique and unambiguous, we modified the traditional binary - * search algorithm to search for adjacent pairs of values {A, B} in the values array - * instead of just a single value, where a and b are the array indices of two - * adjacent values in the array. For all the search criteria, when the algorithm has narrowed the - * search down to a single value or adjacent pair of values, the resolve() method provides the - * final result of the search. If there is no valid value in the array that satisfies the search - * criterion, the algorithm will return -1 to the caller.

- * - *

Given a sorted array of values arr[] and a search key value v, the algorithms for - * the searching criteria are given with each enum criterion.

- * - * @see - * Sketching Quantiles and Ranks Tutorial - * @author Lee Rhodes - */ -public final class GenericInequalitySearch { - - /** - * No argument constructor. - */ - public GenericInequalitySearch() { } - - /** - * The enumerator of inequalities - */ - public enum Inequality { - - /** - * Given a sorted array of increasing values arr[] and a key value v, - * this criterion instructs the binary search algorithm to find the highest adjacent pair of - * values {A,B} such that A < v ≤ B.
- * Let low = index of the lowest value in the range.
- * Let high = index of the highest value in the range. - * - *

If v > arr[high], return arr[high].
- * If v ≤ arr[low], return -1.
- * Else return index of A.

- */ - LT, - - /** - * Given a sorted array of increasing values arr[] and a key value V, - * this criterion instructs the binary search algorithm to find the highest adjacent pair of - * values {A,B} such that A ≤ V < B.
- * Let low = index of the lowest value in the range.
- * Let high = index of the highest value in the range. - * - *

If v ≥ arr[high], return arr[high].
- * If v < arr[low], return -1.
- * Else return index of A.

- */ - LE, - - /** - * Given a sorted array of increasing values arr[] and a key value V, - * this criterion instructs the binary search algorithm to find the adjacent pair of - * values {A,B} such that A ≤ V ≤ B. - * The returned value from the binary search algorithm will be the index of A or B, - * if one of them is equal to V, or -1 if V is not equal to either one. - */ - EQ, - - /** - * Given a sorted array of increasing values arr[] and a key value V, - * this criterion instructs the binary search algorithm to find the lowest adjacent pair of - * values {A,B} such that A < V ≤ B.
- * Let low = index of the lowest value in the range.
- * Let high = index of the highest value in the range. - * - *

If v ≤ arr[low], return arr[low].
- * If v > arr[high], return -1.
- * Else return index of B.

- */ - GE, - - /** - * Given a sorted array of increasing values arr[] and a key value V, - * this criterion instructs the binary search algorithm to find the lowest adjacent pair of - * values {A,B} such that A ≤ V < B.
- * Let low = index of the lowest value in the range.
- * Let high = index of the highest value in the range. - * - *

If v < arr[low], return arr[low].
- * If v ≥ arr[high], return -1.
- * Else return index of B.

- */ - GT - } - - /** - * Binary Search for the index of the generic value in the given search range that satisfies - * the given Inequality criterion. - * If -1 is returned there are no values in the search range that satisfy the inequality. - * - * @param arr the given array of comparable values that must be sorted. - * The array must not be null or empty and the values of the array must not be null (or NaN) - * in the range [low, high]. - * @param low the lowest index of the lowest value in the search range, inclusive. - * @param high the highest index of the highest value in the search range, inclusive. - * @param v the value to search for. It must not be null (or NaN). - * @param crit one of the Inequality criteria: LT, LE, EQ, GE, GT. It must not be null. - * @param comparator for the type T. - * It must not be null. It must return: -1 if A < B, 0 if A == B, and +1 if A > B. - * @param The generic type of value to be used in the search process. - * @return the index of the value in the given search range that satisfies the Inequality criterion. - */ - public static int find(final T[] arr, final int low, final int high, final T v, - final Inequality crit, final Comparator comparator) { - Objects.requireNonNull(arr, "Input arr must not be null"); - Objects.requireNonNull(v,"Input v must not be null"); - Objects.requireNonNull(crit, "Input inequality must not be null"); - Objects.requireNonNull(comparator,"Input comparator must not be null"); - if (arr.length == 0) { throw new SketchesArgumentException("Input array must not be empty."); } - - int lo = low; - int hi = high; - while (lo <= hi) { - if (hi - lo <= 1) { - return resolve(arr, lo, hi, v, crit, comparator); - } - final int mid = lo + (hi - lo) / 2; - final int ret = compare(arr, mid, mid + 1, v, crit, comparator); - if (ret == -1 ) { hi = mid; } - else if (ret == 1) { lo = mid + 1; } - else { return getIndex(arr, mid, mid + 1, v, crit, comparator); } - } - return -1; //should never return here - } - - private static int compare(final T[] arr, final int a, final int b, final T v, - final Inequality crit, final Comparator comparator) { - int result = 0; - switch (crit) { - case GE: - case LT: { - result = comparator.compare(v, arr[a]) <= 0 ? -1 : comparator.compare(arr[b], v) < 0 ? 1 : 0; - break; - } - case GT: - case LE: { - result = comparator.compare(v, arr[a]) < 0 ? -1 : comparator.compare(arr[b], v) <= 0 ? 1 : 0; - break; - } - case EQ: { - result = comparator.compare(v, arr[a]) < 0 ? -1 : comparator.compare(arr[b], v) < 0 ? 1 : 0; - break; - } - } - return result; - } - - private static int getIndex(final T[] arr, final int a, final int b, final T v, - final Inequality crit, final Comparator comparator) { - int result = 0; - switch (crit) { - case LT: - case LE: { - result = a; break; - } - case GE: - case GT: { - result = b; break; - } - case EQ: { - result = comparator.compare(v, arr[a]) == 0 ? a : comparator.compare(v, arr[b]) == 0 ? b : -1; - } - } - return result; - } - - private static int resolve(final T[] arr, final int lo, final int hi, final T v, - final Inequality crit, final Comparator comparator) { - int result = 0; - switch (crit) { - case LT: { - result = (lo == hi) - ? (comparator.compare(v, arr[lo]) > 0 ? lo : -1) - : (comparator.compare(v, arr[hi]) > 0 - ? hi - : (comparator.compare(v, arr[lo]) > 0 ? lo : -1)); - break; - } - case LE: { - result = (lo == hi) - ? (comparator.compare(v, arr[lo]) >= 0 ? lo : -1) - : (comparator.compare(v, arr[hi]) >= 0 - ? hi - : (comparator.compare(v, arr[lo]) >= 0 ? lo : -1)); - break; - } - case EQ: { - result = (lo == hi) - ? (comparator.compare(v, arr[lo]) == 0 ? lo : -1) - : (comparator.compare(v, arr[hi]) == 0 - ? hi - : (comparator.compare(v, arr[lo]) == 0 ? lo : -1)); - break; - } - case GE: { - result = (lo == hi) - ? (comparator.compare(v, arr[lo]) <= 0 ? lo : -1) - : (comparator.compare(v, arr[lo]) <= 0 - ? lo - : (comparator.compare(v, arr[hi]) <= 0 ? hi : -1)); - break; - } - case GT: { - result = (lo == hi) - ? (comparator.compare(v, arr[lo]) < 0 ? lo : -1) - : (comparator.compare(v, arr[lo]) < 0 - ? lo - : (comparator.compare(v, arr[hi]) < 0 ? hi : -1)); - break; - } - } - return result; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/GenericPartitionBoundaries.java b/src/main/java/org/apache/datasketches/quantilescommon/GenericPartitionBoundaries.java deleted file mode 100644 index 0eb44f3e7..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/GenericPartitionBoundaries.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -import org.apache.datasketches.common.SketchesStateException; - -/** - * This defines the returned results of the getParitionBoundaries() function and - * includes the basic methods needed to construct actual partitions. - * @param the item class type - */ -public final class GenericPartitionBoundaries { - private long totalN; //totalN of source sketch - private T[] boundaries; //quantiles at the boundaries - private long[] natRanks; //natural ranks at the boundaries - private double[] normRanks; //normalized ranks at the boundaries - private T maxItem; //of the source sketch - private T minItem; //of the source sketch - private QuantileSearchCriteria searchCrit; //of the source sketch query to getPartitionBoundaries. - //computed - private long[] numDeltaItems; //num of items in each partition - private int numPartitions; //num of partitions - - /** - * Constructor. - * @param totalN the total number of items input to the sketch. - * @param boundaries The quantile boundaries between partitions - * @param natRanks The array of natural Ranks corresponding to the array of boundaries. - * @param normRanks The normalized Ranks corresponding to the array of boundaries. - * @param maxItem the maximum item of the stream. - * @param minItem the minimum item of the stream. - * @param searchCrit the user defined search criteria - */ - public GenericPartitionBoundaries( - final long totalN, - final T[] boundaries, - final long[] natRanks, - final double[] normRanks, - final T maxItem, - final T minItem, - final QuantileSearchCriteria searchCrit) { - this.totalN = totalN; - this.boundaries = boundaries; //SpotBugs EI_EXPOSE_REP2 OK: copying from sketch class to this "friend" class. - this.natRanks = natRanks; // " - this.normRanks = normRanks; // " - this.maxItem = maxItem; - this.minItem = minItem; - this.searchCrit = searchCrit; - //check and compute - final int len = boundaries.length; - if (len < 2) { throw new SketchesStateException("Source sketch is empty"); } //class is final, this is ok - numDeltaItems = new long[len]; - numDeltaItems[0] = 0; // index 0 is always 0 - for (int i = 1; i < len; i++) { - final int addOne = ( (i == 1 && (this.searchCrit == INCLUSIVE)) - || ((i == (len - 1)) && this.searchCrit == EXCLUSIVE) ) ? 1 : 0; - numDeltaItems[i] = natRanks[i] - natRanks[i - 1] + addOne; - } - this.numPartitions = len - 1; - } - - /** - * Gets the length of the input stream offered to the underlying sketch. - * @return the length of the input stream offered to the underlying sketch. - */ - public long getN() { return totalN; } - - /** - * Gets an ordered array of boundaries that sequentially define the upper and lower boundaries of partitions. - * These partitions are to be constructed by an external process. Each boundary is essentially a reference and - * should uniquely identify an item or a set of identical items from the original stream of data fed to the - * originating sketch. - * - *

Assume boundaries array has size N + 1. Let the indicies be sequentially numbered from 0 to N. - * The number of partitions is always one less than the size of the boundaries array. - * Let the the partitions be sequentially numbered from 1 to N. - * - *

If these results were computed using QuantileSearchCriteria.INCLUSIVE then these sequential boundaries - * are to be interpreted as follows: - *

    - *
  • Partition 1: include all items ≥ index 0 and ≤ index 1.
  • - *
  • Partition 2: include all items > index 1 and ≤ index 2.
  • - *
  • Partition N: include all items > index N-1 and ≤ index N.
  • - *
- * - *

If these results were computed using QuantileSearchCriteria.EXCLUSIVE then these sequential boundaries - * are to be interpreted as follows: - *

    - *
  • Partition 1: include all items ≥ index 0 and < index 1.
  • - *
  • Partition 2: include all items ≥ index 1 and < index 2.
  • - *
  • Partition N: include all items ≥ index N-1 and ≤ index N.
  • - *
- * - * @return an array of boundaries that sequentially define the upper and lower boundaries of partitions. - */ - public T[] getBoundaries() { return boundaries.clone(); } - - /** - * Gets an ordered array of natural ranks of the associated array of partition boundaries utilizing - * a specified search criterion. Natural ranks are integral values on the interval [1, N] - * @return an array of natural ranks. - */ - public long[] getNaturalRanks() { return natRanks.clone(); } - - /** - * Gets an ordered array of normalized ranks of the associated array of partition boundaries utilizing - * a specified search criterion. Normalized ranks are double values on the interval [0.0, 1.0]. - * @return an array of normalized ranks. - */ - public double[] getNormalizedRanks() { return normRanks.clone(); } - - /** - * Gets the number of items to be included for each partition as an array. - * The count at index 0 is 0. The number of items included in the first partition, defined by the boundaries at - * index 0 and index 1, is at index 1 in this array, etc. - * @return the number of items to be included for each partition as an array. - */ - public long[] getNumDeltaItems() { return numDeltaItems.clone(); } - - /** - * Gets the number of partitions - * @return the number of partitions - */ - public int getNumPartitions() { return numPartitions; } - - /** - * Returns the maximum item of the stream. This may be distinct from the largest item retained by the - * sketch algorithm. - * - * @return the maximum item of the stream - * @throws IllegalArgumentException if sketch is empty. - */ - public T getMaxItem() { return maxItem; } - - /** - * Returns the minimum item of the stream. This may be distinct from the smallest item retained by the - * sketch algorithm. - * - * @return the minimum item of the stream - * @throws IllegalArgumentException if sketch is empty. - */ - public T getMinItem() { return minItem; } - - /** - * Gets the search criteria specified for the source sketch - * @return The search criteria specified for the source sketch - */ - public QuantileSearchCriteria getSearchCriteria() { return searchCrit; } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/GenericSortedView.java b/src/main/java/org/apache/datasketches/quantilescommon/GenericSortedView.java deleted file mode 100644 index 294d60c9f..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/GenericSortedView.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.QuantilesAPI.EMPTY_MSG; - -import java.util.Comparator; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * The Sorted View for quantiles of generic type. - * @param The generic quantile type. - * @see SortedView - * @author Alexander Saydakov - * @author Lee Rhodes - */ -public interface GenericSortedView extends PartitioningFeature, SketchPartitionLimits, SortedView { - - /** - * Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream - * as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

If the sketch is empty this returns null.

- * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(false) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 overlapping intervals. - *
- *

The start of each interval is below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and the end of the interval - * is the rank or cumulative probability corresponding to the split point.

- * - *

The (m+1)th interval represents 100% of the distribution represented by the sketch - * and consistent with the definition of a cumulative probability distribution, thus the (m+1)th - * rank or probability in the returned array is always 1.0.

- * - *

If a split point exactly equals a retained item of the sketch and the search criterion is:

- * - *
    - *
  • INCLUSIVE, the resulting cumulative probability will include that item.
  • - *
  • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0]. - * @throws SketchesArgumentException if sketch is empty. - */ - default double[] getCDF(final T[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - GenericSortedView.validateItems(splitPoints, getComparator()); - final int len = splitPoints.length + 1; - final double[] buckets = new double[len]; - for (int i = 0; i < len - 1; i++) { - buckets[i] = getRank(splitPoints[i], searchCrit); - } - buckets[len - 1] = 1.0; - return buckets; - } - - /** - * Gets the Comparator for this generic type. - * @return the Comparator for this generic type. - */ - Comparator getComparator(); - - /** - * Returns the maximum item of the stream. This may be distinct from the largest item retained by the - * sketch algorithm. - * - * @return the maximum item of the stream - * @throws SketchesArgumentException if sketch is empty. - */ - T getMaxItem(); - - /** - * Returns the minimum item of the stream. This may be distinct from the smallest item retained by the - * sketch algorithm. - * - * @return the minimum item of the stream - * @throws SketchesArgumentException if sketch is empty. - */ - T getMinItem(); - - /** - * Returns an approximation to the Probability Mass Function (PMF) of the input stream - * as an array of probability masses as doubles on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(true) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 consecutive, non-overlapping intervals. - *
- *

Each interval except for the end intervals starts with a split point and ends with the next split - * point in sequence.

- * - *

The first interval starts below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and ends with the first split point

- * - *

The last (m+1)th interval starts with the last split point and ends after the last - * item retained by the sketch corresponding to a rank or probability of 1.0.

- * - *

The sum of the probability masses of all (m+1) intervals is 1.0.

- * - *

If the search criterion is:

- * - *
    - *
  • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude - * that item.
  • - *
  • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include - * that item.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0]. - * @throws SketchesArgumentException if sketch is empty. - */ - default double[] getPMF(final T[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - GenericSortedView.validateItems(splitPoints, getComparator()); - final double[] buckets = getCDF(splitPoints, searchCrit); - for (int i = buckets.length; i-- > 1; ) { - buckets[i] -= buckets[i - 1]; - } - return buckets; - } - - /** - * Gets the approximate quantile of the given normalized rank and the given search criterion. - * - * @param rank the given normalized rank, a double in the range [0.0, 1.0]. - * @param searchCrit If INCLUSIVE, the given rank includes all quantiles ≤ - * the quantile directly corresponding to the given rank. - * If EXCLUSIVE, he given rank includes all quantiles < - * the quantile directly corresponding to the given rank. - * @return the approximate quantile given the normalized rank. - * @throws SketchesArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - T getQuantile(double rank, QuantileSearchCriteria searchCrit); - - /** - * Returns the full array of quantiles. - * @return the full array of quantiles. - */ - T[] getQuantiles(); - - /** - * Gets the normalized rank corresponding to the given a quantile. - * - * @param quantile the given quantile - * @param searchCrit if INCLUSIVE the given quantile is included into the rank. - * @return the normalized rank corresponding to the given quantile. - * @throws SketchesArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - double getRank(T quantile, QuantileSearchCriteria searchCrit); - - @Override - GenericSortedViewIterator iterator(); - - /** - * Checks the sequential validity of the given array of generic items. - * They must be unique, monotonically increasing and not null. - * @param the data type - * @param items given array of generic items - * @param comparator the comparator for generic item data type T - */ - static void validateItems(final T[] items, final Comparator comparator) { - final int len = items.length; - if (len == 1 && items[0] == null) { - throw new SketchesArgumentException( - "Items must be unique, monotonically increasing and not null."); - } - for (int j = 0; j < len - 1; j++) { - if ((items[j] != null) && (items[j + 1] != null) - && (comparator.compare(items[j], items[j + 1]) < 0)) { - continue; - } - throw new SketchesArgumentException( - "Items must be unique, monotonically increasing and not null."); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/GenericSortedViewIterator.java b/src/main/java/org/apache/datasketches/quantilescommon/GenericSortedViewIterator.java deleted file mode 100644 index 062c462da..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/GenericSortedViewIterator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -/** - * Iterator over quantile sketches of generic type. - * @param The generic item class type - */ -public class GenericSortedViewIterator extends SortedViewIterator { - private final T[] quantiles; - - /** - * Constructor - * @param quantiles the given array of quantiles - * @param cumWeights the array of cumulative weights, corresponding to the array of quantiles, - * starting with the value one and the end value must equal N, the total number of items input to the sketch. - */ - public GenericSortedViewIterator(final T[] quantiles, final long[] cumWeights) { - super(cumWeights); - this.quantiles = quantiles; //SpotBugs EI_EXPOSE_REP2 suppressed by FindBugsExcludeFilter - } - - /** - * Gets the quantile at the current index - * This is equivalent to getQuantile(INCLUSIVE). - * - *

Don't call this before calling next() for the first time or after getting false from next().

- * - * @return the quantile at the current index. - */ - public T getQuantile() { - return quantiles[index]; - } - - /** - * Gets the quantile at the current index (or previous index) - * based on the chosen search criterion. - * - *

Don't call this before calling next() for the first time or after getting false from next().

- * - * @param searchCrit if INCLUSIVE, includes the quantile at the current index. - * Otherwise, returns the quantile of the previous index. - * - * @return the quantile at the current index (or previous index) - * based on the chosen search criterion. If the chosen search criterion is EXCLUSIVE and - * the current index is at zero, this will return null. - */ - public T getQuantile(final QuantileSearchCriteria searchCrit) { - if (searchCrit == INCLUSIVE) { return quantiles[index]; } - return (index == 0) ? null : quantiles[index - 1]; - } -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/IncludeMinMax.java b/src/main/java/org/apache/datasketches/quantilescommon/IncludeMinMax.java deleted file mode 100644 index 84061f840..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/IncludeMinMax.java +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import java.lang.reflect.Array; -import java.util.Comparator; - -/** - * This class reinserts the min and max values into the sorted view arrays as required. - */ -public class IncludeMinMax { - - /** - * No argument constructor. - */ - public IncludeMinMax() { } - - /** A simple structure to hold a pair of arrays */ - public static class DoublesPair { - /** the array of quantiles */ - public double[] quantiles; - /** the array of associated cumulative weights */ - public long[] cumWeights; - - /** - * Constructor. - * @param quantiles the array of quantiles - * @param cumWeights the array of associated cumulative weights - */ - public DoublesPair(final double[] quantiles, final long[] cumWeights) { - this.quantiles = quantiles; - this.cumWeights = cumWeights; - } - } - - /** A simple structure to hold a pair of arrays */ - public static class FloatsPair { - /** The array of quantiles */ - public float[] quantiles; - /** The array of associated cumulative weights */ - public long[] cumWeights; - - /** - * Constructor. - * @param quantiles the array of quantiles - * @param cumWeights the array of associated cumulative weights - */ - public FloatsPair(final float[] quantiles, final long[] cumWeights) { - this.quantiles = quantiles; - this.cumWeights = cumWeights; - } - } - - /** A simple structure to hold a pair of arrays */ - public static class LongsPair { - /** the array of quantiles */ - public long[] quantiles; - /** the array of associated cumulative weights */ - public long[] cumWeights; - - /** - * Constructor. - * @param quantiles the array of quantiles - * @param cumWeights the array of associated cumulative weights - */ - public LongsPair(final long[] quantiles, final long[] cumWeights) { - this.quantiles = quantiles; - this.cumWeights = cumWeights; - } - } - - /** - * A simple structure to hold a pair of arrays - * @param the item class type - */ - public static class ItemsPair { - /** The array of quantiles */ - public T[] quantiles; - /** The array of associated cumulative weights */ - public long[] cumWeights; - - /** - * Constructor. - * @param quantiles the array of quantiles - * @param cumWeights the array of associated cumulative weights - */ - public ItemsPair(final T[] quantiles, final long[] cumWeights) { - this.quantiles = quantiles; - this.cumWeights = cumWeights; - } - } - - /** - * The logic to include the min and max of type double. - * @param quantilesIn The array of quantiles - * @param cumWeightsIn The array of associated cumulative weights - * @param maxItem the maximum item of the stream - * @param minItem the minimum item of the stream - * @return a DoublesPair - */ - public static DoublesPair includeDoublesMinMax( - final double[] quantilesIn, - final long[] cumWeightsIn, - final double maxItem, - final double minItem) { - final int lenIn = cumWeightsIn.length; - final boolean adjLow = quantilesIn[0] != minItem; //if true, adjust the low end - final boolean adjHigh = quantilesIn[lenIn - 1] != maxItem; //if true, adjust the high end - int adjLen = lenIn; //this will be the length of the local copies of quantiles and cumWeights - adjLen += adjLow ? 1 : 0; - adjLen += adjHigh ? 1 : 0; - final double[] adjQuantiles; - final long[] adjCumWeights; - if (adjLen > lenIn) { //is any adjustment required at all? - adjQuantiles = new double[adjLen]; - adjCumWeights = new long[adjLen]; - final int offset = adjLow ? 1 : 0; - System.arraycopy(quantilesIn, 0, adjQuantiles, offset, lenIn); - System.arraycopy(cumWeightsIn,0, adjCumWeights, offset, lenIn); - - //Adjust the low end if required. Don't need to adjust weight of next one because it is cumulative. - if (adjLow) { - adjQuantiles[0] = minItem; - adjCumWeights[0] = 1; - } - - if (adjHigh) { - adjQuantiles[adjLen - 1] = maxItem; - adjCumWeights[adjLen - 1] = cumWeightsIn[lenIn - 1]; - adjCumWeights[adjLen - 2] = cumWeightsIn[lenIn - 1] - 1; - } - } else { //both min and max are already in place, no adjustments are required. - adjQuantiles = quantilesIn; - adjCumWeights = cumWeightsIn; - - } //END of Adjust End Points - return new DoublesPair(adjQuantiles, adjCumWeights); - } - - /** - * The logic to include the min and max of type double. - * @param quantilesIn The array of quantiles - * @param cumWeightsIn The array of associated cumulative weights - * @param maxItem the maximum item of the stream - * @param minItem the minimum item of the stream - * @return a DoublesPair - */ - public static LongsPair includeLongsMinMax( - final long[] quantilesIn, - final long[] cumWeightsIn, - final long maxItem, - final long minItem) { - final int lenIn = cumWeightsIn.length; - final boolean adjLow = quantilesIn[0] != minItem; //if true, adjust the low end - final boolean adjHigh = quantilesIn[lenIn - 1] != maxItem; //if true, adjust the high end - int adjLen = lenIn; //this will be the length of the local copies of quantiles and cumWeights - adjLen += adjLow ? 1 : 0; - adjLen += adjHigh ? 1 : 0; - final long[] adjQuantiles; - final long[] adjCumWeights; - if (adjLen > lenIn) { //is any adjustment required at all? - adjQuantiles = new long[adjLen]; - adjCumWeights = new long[adjLen]; - final int offset = adjLow ? 1 : 0; - System.arraycopy(quantilesIn, 0, adjQuantiles, offset, lenIn); - System.arraycopy(cumWeightsIn,0, adjCumWeights, offset, lenIn); - - //Adjust the low end if required. Don't need to adjust weight of next one because it is cumulative. - if (adjLow) { - adjQuantiles[0] = minItem; - adjCumWeights[0] = 1; - } - - if (adjHigh) { - adjQuantiles[adjLen - 1] = maxItem; - adjCumWeights[adjLen - 1] = cumWeightsIn[lenIn - 1]; - adjCumWeights[adjLen - 2] = cumWeightsIn[lenIn - 1] - 1; - } - } else { //both min and max are already in place, no adjustments are required. - adjQuantiles = quantilesIn; - adjCumWeights = cumWeightsIn; - - } //END of Adjust End Points - return new LongsPair(adjQuantiles, adjCumWeights); - } - - /** - * The logic to include the min and max of type float. - * @param quantilesIn The array of quantiles - * @param cumWeightsIn The array of associated cumulative weights - * @param maxItem the maximum item of the stream - * @param minItem the minimum item of the stream - * @return a FloatsPair - */ - public static FloatsPair includeFloatsMinMax( - final float[] quantilesIn, - final long[] cumWeightsIn, - final float maxItem, - final float minItem) { - final int lenIn = cumWeightsIn.length; - final boolean adjLow = quantilesIn[0] != minItem; //if true, adjust the low end - final boolean adjHigh = quantilesIn[lenIn - 1] != maxItem; //if true, adjust the high end - int adjLen = lenIn; //this will be the length of the local copies of quantiles and cumWeights - adjLen += adjLow ? 1 : 0; - adjLen += adjHigh ? 1 : 0; - final float[] adjQuantiles; - final long[] adjCumWeights; - if (adjLen > lenIn) { //is any adjustment required at all? - adjQuantiles = new float[adjLen]; - adjCumWeights = new long[adjLen]; - final int offset = adjLow ? 1 : 0; - System.arraycopy(quantilesIn, 0, adjQuantiles, offset, lenIn); - System.arraycopy(cumWeightsIn,0, adjCumWeights, offset, lenIn); - - //Adjust the low end if required. - if (adjLow) { - adjQuantiles[0] = minItem; - adjCumWeights[0] = 1; - } - - if (adjHigh) { - adjQuantiles[adjLen - 1] = maxItem; - adjCumWeights[adjLen - 1] = cumWeightsIn[lenIn - 1]; - adjCumWeights[adjLen - 2] = cumWeightsIn[lenIn - 1] - 1; - } - } else { //both min and max are already in place, no adjustments are required. - adjQuantiles = quantilesIn; - adjCumWeights = cumWeightsIn; - - } //END of Adjust End Points - return new FloatsPair(adjQuantiles, adjCumWeights); - } - - /** - * The logic to include the min and max of type T. - * @param quantilesIn The array of quantiles - * @param cumWeightsIn The array of associated cumulative weights - * @param maxItem the maximum item of the stream - * @param minItem the minimum item of the stream - * @param comparator a comparator for type T - * @param the item class type - * @return an ItemsPair - */ - @SuppressWarnings("unchecked") - public static ItemsPair includeItemsMinMax( - final T[] quantilesIn, - final long[] cumWeightsIn, - final T maxItem, - final T minItem, - final Comparator comparator) { - final int lenIn = cumWeightsIn.length; - final boolean adjLow = comparator.compare(quantilesIn[0], minItem) != 0; //if true, adjust the low end - final boolean adjHigh = comparator.compare(quantilesIn[lenIn - 1], maxItem) != 0; //if true, adjust the high end - int adjLen = lenIn; //this will be the length of the local copies of quantiles and cumWeights - adjLen += adjLow ? 1 : 0; - adjLen += adjHigh ? 1 : 0; - final T[] adjQuantiles; - final long[] adjCumWeights; - if (adjLen > lenIn) { //is any adjustment required at all? - adjQuantiles = (T[]) Array.newInstance(minItem.getClass(), adjLen); - adjCumWeights = new long[adjLen]; - final int offset = adjLow ? 1 : 0; - System.arraycopy(quantilesIn, 0, adjQuantiles, offset, lenIn); - System.arraycopy(cumWeightsIn,0, adjCumWeights, offset, lenIn); - - //Adjust the low end if required. - if (adjLow) { - adjQuantiles[0] = minItem; - adjCumWeights[0] = 1; - } - - if (adjHigh) { - adjQuantiles[adjLen - 1] = maxItem; - adjCumWeights[adjLen - 1] = cumWeightsIn[lenIn - 1]; - adjCumWeights[adjLen - 2] = cumWeightsIn[lenIn - 1] - 1; - } - } else { //both min and max are already in place, no adjustments are required. - adjQuantiles = quantilesIn; - adjCumWeights = cumWeightsIn; - - } //END of Adjust End Points - return new ItemsPair<>(adjQuantiles, adjCumWeights); - } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/InequalitySearch.java b/src/main/java/org/apache/datasketches/quantilescommon/InequalitySearch.java deleted file mode 100644 index 21af2b531..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/InequalitySearch.java +++ /dev/null @@ -1,1038 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import java.util.Objects; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This provides efficient, unique and unambiguous binary searching for inequality comparison criteria - * for ordered arrays of values that may include duplicate values. The inequality criteria include - * <, ≤, ==, ≥, >. All the inequality criteria use the same search algorithm. - * (Although == is not an inequality, it is included for convenience.) - * - *

In order to make the searching unique and unambiguous, we modified the traditional binary - * search algorithm to search for adjacent pairs of values {A, B} in the values array - * instead of just a single value, where a and b are the array indices of two - * adjacent values in the array. For all the search criteria, when the algorithm has narrowed the - * search down to a single value or adjacent pair of values, the resolve() method provides the - * final result of the search. If there is no valid value in the array that satisfies the search - * criterion, the algorithm will return -1 to the caller.

- * - *

Given a sorted array of values arr[] and a search key value v, the algorithms for - * the searching criteria are given with each enum criterion.

- * - * @see - * Sketching Quantiles and Ranks Tutorial - * @author Lee Rhodes - */ -public enum InequalitySearch { - - /** - * Given a sorted array of increasing values arr[] and a key value v, - * this criterion instructs the binary search algorithm to find the highest adjacent pair of - * values {A,B} such that A < v ≤ B.
- * Let low = index of the lowest value in the range.
- * Let high = index of the highest value in the range. - * - *

If v > arr[high], return arr[high].
- * If v ≤ arr[low], return -1.
- * Else return index of A.

- */ - LT { //arr[A] < V <= arr[B], return A - @Override - int compare(final double[] arr, final int a, final int b, final double v) { - return v <= arr[a] ? -1 : arr[b] < v ? 1 : 0; - } - - @Override - int compare(final float[] arr, final int a, final int b, final float v) { - return v <= arr[a] ? -1 : arr[b] < v ? 1 : 0; - } - - @Override - int compare(final long[] arr, final int a, final int b, final long v) { - return v <= arr[a] ? -1 : arr[b] < v ? 1 : 0; - } - - @Override - int compare(final long[] arr, final int a, final int b, final double v) { - return v <= arr[a] ? -1 : arr[b] < v ? 1 : 0; - } - - @Override - int getIndex(final double[] arr, final int a, final int b, final double v) { - return a; - } - - @Override - int getIndex(final float[] arr, final int a, final int b, final float v) { - return a; - } - - @Override - int getIndex(final long[] arr, final int a, final int b, final long v) { - return a; - } - - @Override - int getIndex(final long[] arr, final int a, final int b, final double v) { - return a; - } - - @Override - int resolve(final double[] arr, final int lo, final int hi, final double v) { - return (lo == hi) - ? (v > arr[lo] ? lo : -1) - : v > arr[hi] ? hi : (v > arr[lo] ? lo : -1); - } - - @Override - int resolve(final float[] arr, final int lo, final int hi, final float v) { - return (lo == hi) - ? (v > arr[lo] ? lo : -1) - : v > arr[hi] ? hi : (v > arr[lo] ? lo : -1); - } - - @Override - int resolve(final long[] arr, final int lo, final int hi, final long v) { - return (lo == hi) - ? (v > arr[lo] ? lo : -1) - : v > arr[hi] ? hi : (v > arr[lo] ? lo : -1); - } - - @Override - int resolve(final long[] arr, final int lo, final int hi, final double v) { - return (lo == hi) - ? (v > arr[lo] ? lo : -1) - : v > arr[hi] ? hi : (v > arr[lo] ? lo : -1); - } - - @Override - public String desc(final double[] arr, final int low, final int high, final double v, final int idx) { - if (idx == -1) { - return "LT: " + v + " <= arr[" + low + "]=" + arr[low] + "; return -1"; - } - if (idx == high) { - return "LT: " + v + " > arr[" + high + "]=" + arr[high] - + "; return arr[" + high + "]=" + arr[high]; - } //idx < high - return "LT: " + v - + ": arr[" + idx + "]=" + arr[idx] + " < " + v + " <= arr[" + (idx + 1) + "]=" + arr[idx + 1] - + "; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final float[] arr, final int low, final int high, final float v, final int idx) { - if (idx == -1) { - return "LT: " + v + " <= arr[" + low + "]=" + arr[low] + "; return -1"; - } - if (idx == high) { - return "LT: " + v + " > arr[" + high + "]=" + arr[high] - + "; return arr[" + high + "]=" + arr[high]; - } //idx < high - return "LT: " + v - + ": arr[" + idx + "]=" + arr[idx] + " < " + v + " <= arr[" + (idx + 1) + "]=" + arr[idx + 1] - + "; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final long[] arr, final int low, final int high, final long v, final int idx) { - if (idx == -1) { - return "LT: " + v + " <= arr[" + low + "]=" + arr[low] + "; return -1"; - } - if (idx == high) { - return "LT: " + v + " > arr[" + high + "]=" + arr[high] - + "; return arr[" + high + "]=" + arr[high]; - } //idx < high - return "LT: " + v - + ": arr[" + idx + "]=" + arr[idx] + " < " + v + " <= arr[" + (idx + 1) + "]=" + arr[idx + 1] - + "; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final long[] arr, final int low, final int high, final double v, final int idx) { - if (idx == -1) { - return "LT: " + v + " <= arr[" + low + "]=" + arr[low] + "; return -1"; - } - if (idx == high) { - return "LT: " + v + " > arr[" + high + "]=" + arr[high] - + "; return arr[" + high + "]=" + arr[high]; - } //idx < high - return "LT: " + v - + ": arr[" + idx + "]=" + arr[idx] + " < " + v + " <= arr[" + (idx + 1) + "]=" + arr[idx + 1] - + "; return arr[" + idx + "]=" + arr[idx]; - } - }, - - /** - * Given a sorted array of increasing values arr[] and a key value V, - * this criterion instructs the binary search algorithm to find the highest adjacent pair of - * values {A,B} such that A ≤ V < B.
- * Let low = index of the lowest value in the range.
- * Let high = index of the highest value in the range. - * - *

If v ≥ arr[high], return arr[high].
- * If v < arr[low], return -1.
- * Else return index of A.

- */ - LE { //arr[A] <= V < arr[B], return A - @Override - int compare(final double[] arr, final int a, final int b, final double v) { - return v < arr[a] ? -1 : arr[b] <= v ? 1 : 0; - } - - @Override - int compare(final float[] arr, final int a, final int b, final float v) { - return v < arr[a] ? -1 : arr[b] <= v ? 1 : 0; - } - - @Override - int compare(final long[] arr, final int a, final int b, final long v) { - return v < arr[a] ? -1 : arr[b] <= v ? 1 : 0; - } - - @Override - int compare(final long[] arr, final int a, final int b, final double v) { - return v < arr[a] ? -1 : arr[b] <= v ? 1 : 0; - } - - @Override - int getIndex(final double[] arr, final int a, final int b, final double v) { - return a; - } - - @Override - int getIndex(final float[] arr, final int a, final int b, final float v) { - return a; - } - - @Override - int getIndex(final long[] arr, final int a, final int b, final long v) { - return a; - } - - @Override - int getIndex(final long[] arr, final int a, final int b, final double v) { - return a; - } - - @Override - int resolve(final double[] arr, final int lo, final int hi, final double v) { - return (lo == hi) - ? (v >= arr[lo] ? lo : -1) - : v >= arr[hi] ? hi : (v >= arr[lo] ? lo : -1); - } - - @Override - int resolve(final float[] arr, final int lo, final int hi, final float v) { - return (lo == hi) - ? (v >= arr[lo] ? lo : -1) - : v >= arr[hi] ? hi : (v >= arr[lo] ? lo : -1); - } - - @Override - int resolve(final long[] arr, final int lo, final int hi, final long v) { - return (lo == hi) - ? (v >= arr[lo] ? lo : -1) - : v >= arr[hi] ? hi : (v >= arr[lo] ? lo : -1); - } - - @Override - int resolve(final long[] arr, final int lo, final int hi, final double v) { - return (lo == hi) - ? (v >= arr[lo] ? lo : -1) - : v >= arr[hi] ? hi : (v >= arr[lo] ? lo : -1); - } - - @Override - public String desc(final double[] arr, final int low, final int high, final double v, final int idx) { - if (idx == -1) { - return "LE: " + v + " < arr[" + low + "]=" + arr[low] + "; return -1"; - } - if (idx == high) { - return "LE: " + v + " >= arr[" + high + "]=" + arr[high] - + "; return arr[" + high + "]=" + arr[high]; - } - return "LE: " + v - + ": arr[" + idx + "]=" + arr[idx] + " <= " + v + " < arr[" + (idx + 1) + "]=" + arr[idx + 1] - + "; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final float[] arr, final int low, final int high, final float v, final int idx) { - if (idx == -1) { - return "LE: " + v + " < arr[" + low + "]=" + arr[low] + "; return -1"; - } - if (idx == high) { - return "LE: " + v + " >= arr[" + high + "]=" + arr[high] - + "; return arr[" + high + "]=" + arr[high]; - } - return "LE: " + v - + ": arr[" + idx + "]=" + arr[idx] + " <= " + v + " < arr[" + (idx + 1) + "]=" + arr[idx + 1] - + "; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final long[] arr, final int low, final int high, final long v, final int idx) { - if (idx == -1) { - return "LE: " + v + " < arr[" + low + "]=" + arr[low] + "; return -1"; - } - if (idx == high) { - return "LE: " + v + " >= arr[" + high + "]=" + arr[high] - + "; return arr[" + high + "]=" + arr[high]; - } - return "LE: " + v - + ": arr[" + idx + "]=" + arr[idx] + " <= " + v + " < arr[" + (idx + 1) + "]=" + arr[idx + 1] - + "; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final long[] arr, final int low, final int high, final double v, final int idx) { - if (idx == -1) { - return "LE: " + v + " < arr[" + low + "]=" + arr[low] + "; return -1"; - } - if (idx == high) { - return "LE: " + v + " >= arr[" + high + "]=" + arr[high] - + "; return arr[" + high + "]=" + arr[high]; - } - return "LE: " + v - + ": arr[" + idx + "]=" + arr[idx] + " <= " + v + " < arr[" + (idx + 1) + "]=" + arr[idx + 1] - + "; return arr[" + idx + "]=" + arr[idx]; - } - }, - - /** - * Given a sorted array of increasing values arr[] and a key value V, - * this criterion instructs the binary search algorithm to find the adjacent pair of - * values {A,B} such that A ≤ V ≤ B. - * The returned value from the binary search algorithm will be the index of A or B, - * if one of them is equal to V, or -1 if V is not equal to either one. - */ - EQ { //arr[A] <= V <= arr[B], return A or B - @Override - int compare(final double[] arr, final int a, final int b, final double v) { - return v < arr[a] ? -1 : arr[b] < v ? 1 : 0; - } - - @Override - int compare(final float[] arr, final int a, final int b, final float v) { - return v < arr[a] ? -1 : arr[b] < v ? 1 : 0; - } - - @Override - int compare(final long[] arr, final int a, final int b, final long v) { - return v < arr[a] ? -1 : arr[b] < v ? 1 : 0; - } - - @Override - int compare(final long[] arr, final int a, final int b, final double v) { - return v < arr[a] ? -1 : arr[b] < v ? 1 : 0; - } - - @Override - int getIndex(final double[] arr, final int a, final int b, final double v) { - return v == arr[a] ? a : v == arr[b] ? b : -1; - } - - @Override - int getIndex(final float[] arr, final int a, final int b, final float v) { - return v == arr[a] ? a : v == arr[b] ? b : -1; - } - - @Override - int getIndex(final long[] arr, final int a, final int b, final long v) { - return v == arr[a] ? a : v == arr[b] ? b : -1; - } - - @Override - int getIndex(final long[] arr, final int a, final int b, final double v) { - return v == arr[a] ? a : v == arr[b] ? b : -1; - } - - @Override - int resolve(final double[] arr, final int lo, final int hi, final double v) { - return (lo == hi) - ? (v == arr[lo] ? lo : -1) - : v == arr[lo] ? lo : (v == arr[hi] ? hi : -1); - } - - @Override - int resolve(final float[] arr, final int lo, final int hi, final float v) { - return (lo == hi) - ? (v == arr[lo] ? lo : -1) - : v == arr[lo] ? lo : (v == arr[hi] ? hi : -1); - } - - @Override - int resolve(final long[] arr, final int lo, final int hi, final long v) { - return (lo == hi) - ? (v == arr[lo] ? lo : -1) - : v == arr[lo] ? lo : (v == arr[hi] ? hi : -1); - } - - @Override - int resolve(final long[] arr, final int lo, final int hi, final double v) { - return (lo == hi) - ? (v == arr[lo] ? lo : -1) - : v == arr[lo] ? lo : (v == arr[hi] ? hi : -1); - } - - @Override - public String desc(final double[] arr, final int low, final int high, final double v, final int idx) { - if (idx == -1) { - if (v > arr[high]) { - return "EQ: " + v + " > arr[" + high + "]; return -1"; - } - if (v < arr[low]) { - return "EQ: " + v + " < arr[" + low + "]; return -1"; - } - return "EQ: " + v + " Cannot be found within arr[" + low + "], arr[" + high + "]; return -1"; - } - return "EQ: " + v + " == arr[" + idx + "]; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final float[] arr, final int low, final int high, final float v, final int idx) { - if (idx == -1) { - if (v > arr[high]) { - return "EQ: " + v + " > arr[" + high + "]; return -1"; - } - if (v < arr[low]) { - return "EQ: " + v + " < arr[" + low + "]; return -1"; - } - return "EQ: " + v + " Cannot be found within arr[" + low + "], arr[" + high + "]; return -1"; - } - return "EQ: " + v + " == arr[" + idx + "]; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final long[] arr, final int low, final int high, final long v, final int idx) { - if (idx == -1) { - if (v > arr[high]) { - return "EQ: " + v + " > arr[" + high + "]; return -1"; - } - if (v < arr[low]) { - return "EQ: " + v + " < arr[" + low + "]; return -1"; - } - return "EQ: " + v + " Cannot be found within arr[" + low + "], arr[" + high + "]; return -1"; - } - return "EQ: " + v + " == arr[" + idx + "]; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final long[] arr, final int low, final int high, final double v, final int idx) { - if (idx == -1) { - if (v > arr[high]) { - return "EQ: " + v + " > arr[" + high + "]; return -1"; - } - if (v < arr[low]) { - return "EQ: " + v + " < arr[" + low + "]; return -1"; - } - return "EQ: " + v + " Cannot be found within arr[" + low + "], arr[" + high + "]; return -1"; - } - return "EQ: " + v + " == arr[" + idx + "]; return arr[" + idx + "]=" + arr[idx]; - } - }, - - /** - * Given a sorted array of increasing values arr[] and a key value V, - * this criterion instructs the binary search algorithm to find the lowest adjacent pair of - * values {A,B} such that A < V ≤ B.
- * Let low = index of the lowest value in the range.
- * Let high = index of the highest value in the range. - * - *

If v ≤ arr[low], return arr[low].
- * If v > arr[high], return -1.
- * Else return index of B.

- */ - GE { //arr[A] < V <= arr[B], return B - @Override - int compare(final double[] arr, final int a, final int b, final double v) { - return v <= arr[a] ? -1 : arr[b] < v ? 1 : 0; - } - - @Override - int compare(final float[] arr, final int a, final int b, final float v) { - return v <= arr[a] ? -1 : arr[b] < v ? 1 : 0; - } - - @Override - int compare(final long[] arr, final int a, final int b, final long v) { - return v <= arr[a] ? -1 : arr[b] < v ? 1 : 0; - } - - @Override - int compare(final long[] arr, final int a, final int b, final double v) { - return v <= arr[a] ? -1 : arr[b] < v ? 1 : 0; - } - - @Override - int getIndex(final double[] arr, final int a, final int b, final double v) { - return b; - } - - @Override - int getIndex(final float[] arr, final int a, final int b, final float v) { - return b; - } - - @Override - int getIndex(final long[] arr, final int a, final int b, final long v) { - return b; - } - - @Override - int getIndex(final long[] arr, final int a, final int b, final double v) { - return b; - } - - @Override - int resolve(final double[] arr, final int lo, final int hi, final double v) { - return (lo == hi) - ? (v <= arr[lo] ? lo : -1) - : v <= arr[lo] ? lo : (v <= arr[hi] ? hi : -1); - } - - @Override - int resolve(final float[] arr, final int lo, final int hi, final float v) { - return (lo == hi) - ? (v <= arr[lo] ? lo : -1) - : v <= arr[lo] ? lo : (v <= arr[hi] ? hi : -1); - } - - @Override - int resolve(final long[] arr, final int lo, final int hi, final long v) { - return (lo == hi) - ? (v <= arr[lo] ? lo : -1) - : v <= arr[lo] ? lo : (v <= arr[hi] ? hi : -1); - } - - @Override - int resolve(final long[] arr, final int lo, final int hi, final double v) { - return (lo == hi) - ? (v <= arr[lo] ? lo : -1) - : v <= arr[lo] ? lo : (v <= arr[hi] ? hi : -1); - } - - @Override - public String desc(final double[] arr, final int low, final int high, final double v, final int idx) { - if (idx == -1) { - return "GE: " + v + " > arr[" + high + "]=" + arr[high] + "; return -1"; - } - if (idx == low) { - return "GE: " + v + " <= arr[" + low + "]=" + arr[low] - + "; return arr[" + low + "]=" + arr[low]; - } //idx > low - return "GE: " + v - + ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " < " + v + " <= arr[" + idx + "]=" + arr[idx] - + "; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final float[] arr, final int low, final int high, final float v, final int idx) { - if (idx == -1) { - return "GE: " + v + " > arr[" + high + "]=" + arr[high] + "; return -1"; - } - if (idx == low) { - return "GE: " + v + " <= arr[" + low + "]=" + arr[low] - + "; return arr[" + low + "]=" + arr[low]; - } //idx > low - return "GE: " + v - + ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " < " + v + " <= arr[" + idx + "]=" + arr[idx] - + "; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final long[] arr, final int low, final int high, final long v, final int idx) { - if (idx == -1) { - return "GE: " + v + " > arr[" + high + "]=" + arr[high] + "; return -1"; - } - if (idx == low) { - return "GE: " + v + " <= arr[" + low + "]=" + arr[low] - + "; return arr[" + low + "]=" + arr[low]; - } //idx > low - return "GE: " + v - + ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " < " + v + " <= arr[" + idx + "]=" + arr[idx] - + "; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final long[] arr, final int low, final int high, final double v, final int idx) { - if (idx == -1) { - return "GE: " + v + " > arr[" + high + "]=" + arr[high] + "; return -1"; - } - if (idx == low) { - return "GE: " + v + " <= arr[" + low + "]=" + arr[low] - + "; return arr[" + low + "]=" + arr[low]; - } //idx > low - return "GE: " + v - + ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " < " + v + " <= arr[" + idx + "]=" + arr[idx] - + "; return arr[" + idx + "]=" + arr[idx]; - } - }, - - /** - * Given a sorted array of increasing values arr[] and a key value V, - * this criterion instructs the binary search algorithm to find the lowest adjacent pair of - * values {A,B} such that A ≤ V < B.
- * Let low = index of the lowest value in the range.
- * Let high = index of the highest value in the range. - * - *

If v < arr[low], return arr[low].
- * If v ≥ arr[high], return -1.
- * Else return index of B.

- */ - GT { //arr[A] <= V < arr[B], return B - @Override - int compare(final double[] arr, final int a, final int b, final double v) { - return v < arr[a] ? -1 : arr[b] <= v ? 1 : 0; - } - - @Override - int compare(final float[] arr, final int a, final int b, final float v) { - return v < arr[a] ? -1 : arr[b] <= v ? 1 : 0; - } - - @Override - int compare(final long[] arr, final int a, final int b, final long v) { - return v < arr[a] ? -1 : arr[b] <= v ? 1 : 0; - } - - @Override - int compare(final long[] arr, final int a, final int b, final double v) { - return v < arr[a] ? -1 : arr[b] <= v ? 1 : 0; - } - - @Override - int getIndex(final double[] arr, final int a, final int b, final double v) { - return b; - } - - @Override - int getIndex(final float[] arr, final int a, final int b, final float v) { - return b; - } - - @Override - int getIndex(final long[] arr, final int a, final int b, final long v) { - return b; - } - - @Override - int getIndex(final long[] arr, final int a, final int b, final double v) { - return b; - } - - @Override - int resolve(final double[] arr, final int lo, final int hi, final double v) { - return (lo == hi) - ? (v < arr[lo] ? lo : -1) - : v < arr[lo] ? lo : (v < arr[hi] ? hi : -1); - } - - @Override - int resolve(final float[] arr, final int lo, final int hi, final float v) { - return (lo == hi) - ? (v < arr[lo] ? lo : -1) - : v < arr[lo] ? lo : (v < arr[hi] ? hi : -1); - } - - @Override - int resolve(final long[] arr, final int lo, final int hi, final long v) { - return (lo == hi) - ? (v < arr[lo] ? lo : -1) - : v < arr[lo] ? lo : (v < arr[hi] ? hi : -1); - } - - @Override - int resolve(final long[] arr, final int lo, final int hi, final double v) { - return (lo == hi) - ? (v < arr[lo] ? lo : -1) - : v < arr[lo] ? lo : (v < arr[hi] ? hi : -1); - } - - @Override - public String desc(final double[] arr, final int low, final int high, final double v, final int idx) { - if (idx == -1) { - return "GT: " + v + " >= arr[" + high + "]=" + arr[high] + "; return -1"; - } - if (idx == low) { - return "GT: " + v + " < arr[" + low + "]=" + arr[low] - + "; return arr[" + low + "]=" + arr[low]; - } //idx > low - return "GT: " + v - + ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " <= " + v + " < arr[" + idx + "]=" + arr[idx] - + "; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final float[] arr, final int low, final int high, final float v, final int idx) { - if (idx == -1) { - return "GT: " + v + " >= arr[" + high + "]=" + arr[high] + "; return -1"; - } - if (idx == low) { - return "GT: " + v + " < arr[" + low + "]=" + arr[low] - + "; return arr[" + low + "]=" + arr[low]; - } //idx > low - return "GT: " + v - + ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " <= " + v + " < arr[" + idx + "]=" + arr[idx] - + "; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final long[] arr, final int low, final int high, final long v, final int idx) { - if (idx == -1) { - return "GT: " + v + " >= arr[" + high + "]=" + arr[high] + "; return -1"; - } - if (idx == low) { - return "GT: " + v + " < arr[" + low + "]=" + arr[low] - + "; return arr[" + low + "]=" + arr[low]; - } //idx > low - return "GT: " + v - + ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " <= " + v + " < arr[" + idx + "]=" + arr[idx] - + "; return arr[" + idx + "]=" + arr[idx]; - } - - @Override - public String desc(final long[] arr, final int low, final int high, final double v, final int idx) { - if (idx == -1) { - return "GT: " + v + " >= arr[" + high + "]=" + arr[high] + "; return -1"; - } - if (idx == low) { - return "GT: " + v + " < arr[" + low + "]=" + arr[low] - + "; return arr[" + low + "]=" + arr[low]; - } //idx > low - return "GT: " + v - + ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " <= " + v + " < arr[" + idx + "]=" + arr[idx] - + "; return arr[" + idx + "]=" + arr[idx]; - } - }; - - /** - * The call to compare index a and index b with the value v. - * @param arr The underlying sorted array of values - * @param a the lower index of the current pair - * @param b the higher index of the current pair - * @param v the value to search for - * @return +1, which means we must search higher in the array, or -1, which means we must - * search lower in the array, or 0, which means we have found the correct bounding pair. - */ - abstract int compare(double[] arr, int a, int b, double v); - - /** - * The call to compare index a and index b with the value v. - * @param arr The underlying sorted array of values - * @param a the lower index of the current pair - * @param b the higher index of the current pair - * @param v the value to search for - * @return +1, which means we must search higher in the array, or -1, which means we must - * search lower in the array, or 0, which means we have found the correct bounding pair. - */ - abstract int compare(float[] arr, int a, int b, float v); - - /** - * The call to compare index a and index b with the value v. - * @param arr The underlying sorted array of values - * @param a the lower index of the current pair - * @param b the higher index of the current pair - * @param v the value to search for - * @return +1, which means we must search higher in the array, or -1, which means we must - * search lower in the array, or 0, which means we have found the correct bounding pair. - */ - abstract int compare(long[] arr, int a, int b, long v); - - /** - * The call to compare index a and index b with the value v. - * @param arr The underlying sorted array of values - * @param a the lower index of the current pair - * @param b the higher index of the current pair - * @param v the value to search for - * @return +1, which means we must search higher in the array, or -1, which means we must - * search lower in the array, or 0, which means we have found the correct bounding pair. - */ - abstract int compare(long[] arr, int a, int b, double v); - - /** - * If the compare operation returns 0, which means "found", this returns the index of the - * found value that satisfies the selected criteria. - * @param arr the array being searched - * @param a the lower index of the current pair - * @param b the higher index of the current pair - * @param v the value being searched for. - * @return the index of the found value that satisfies the selected criteria. - */ - abstract int getIndex(double[] arr, int a, int b, double v); - - /** - * If the compare operation returns 0, which means "found", this returns the index of the - * found value that satisfies the selected criteria. - * @param arr the array being searched - * @param a the lower index of the current pair - * @param b the higher index of the current pair - * @param v the value being searched for. - * @return the index of the found value that satisfies the selected criteria. - */ - abstract int getIndex(float[] arr, int a, int b, float v); - - /** - * If the compare operation returns 0, which means "found", this returns the index of the - * found value that satisfies the selected criteria. - * @param arr the array being searched - * @param a the lower index of the current pair - * @param b the higher index of the current pair - * @param v the value being searched for. - * @return the index of the found value that satisfies the selected criteria. - */ - abstract int getIndex(long[] arr, int a, int b, long v); - - /** - * If the compare operation returns 0, which means "found", this returns the index of the - * found value that satisfies the selected criteria. - * @param arr the array being searched - * @param a the lower index of the current pair - * @param b the higher index of the current pair - * @param v the value being searched for. - * @return the index of the found value that satisfies the selected criteria. - */ - abstract int getIndex(long[] arr, int a, int b, double v); - - /** - * Called to resolve the search when the hi and lo pointers are equal or adjacent. - * @param arr the array being searched - * @param lo the current lo value - * @param hi the current hi value - * @param v the value being searched for - * @return the index of the resolution or -1, if it cannot be resolved. - */ - abstract int resolve(double[] arr, int lo, int hi, double v); - - /** - * Called to resolve the search when the hi and lo pointers are equal or adjacent. - * @param arr the array being searched - * @param lo the current lo value - * @param hi the current hi value - * @param v the value being searched for - * @return the index of the resolution or -1, if it cannot be resolved. - */ - abstract int resolve(float[] arr, int lo, int hi, float v); - - /** - * Called to resolve the search when the hi and lo pointers are equal or adjacent. - * @param arr the array being searched - * @param lo the current lo value - * @param hi the current hi value - * @param v the value being searched for - * @return the index of the resolution or -1, if it cannot be resolved. - */ - abstract int resolve(long[] arr, int lo, int hi, long v); - - /** - * Called to resolve the search when the hi and lo pointers are equal or adjacent. - * @param arr the array being searched - * @param lo the current lo value - * @param hi the current hi value - * @param v the value being searched for - * @return the index of the resolution or -1, if it cannot be resolved. - */ - abstract int resolve(long[] arr, int lo, int hi, double v); - - /** - * Optional call that describes the details of the results of the search. - * Used primarily for debugging. - * @param arr The underlying sorted array of values - * @param low the low index of the range - * @param high the high index of the range - * @param v the value to search for - * @param idx the resolved index from the search - * @return the descriptive string. - */ - public abstract String desc(double[] arr, int low, int high, double v, int idx); - - /** - * Optional call that describes the details of the results of the search. - * Used primarily for debugging. - * @param arr The underlying sorted array of values - * @param low the low index of the range - * @param high the high index of the range - * @param v the value to search for - * @param idx the resolved index from the search - * @return the descriptive string. - */ - public abstract String desc(float[] arr, int low, int high, float v, int idx); - - /** - * Optional call that describes the details of the results of the search. - * Used primarily for debugging. - * @param arr The underlying sorted array of values - * @param low the low index of the range - * @param high the high index of the range - * @param v the value to search for - * @param idx the resolved index from the search - * @return the descriptive string. - */ - public abstract String desc(long[] arr, int low, int high, long v, int idx); - - /** - * Optional call that describes the details of the results of the search. - * Used primarily for debugging. - * @param arr The underlying sorted array of values - * @param low the low index of the range - * @param high the high index of the range - * @param v the value to search for - * @param idx the resolved index from the search - * @return the descriptive string. - */ - public abstract String desc(long[] arr, int low, int high, double v, int idx); - - /** - * Binary Search for the index of the double value in the given search range that satisfies - * the given InequalitySearch criterion. - * If -1 is returned there are no values in the search range that satisfy the criterion. - * - * @param arr the given array of comparable values that must be sorted with increasing values. - * The array must not be null and the values of the array must not be NaN in the range [low, high]. - * @param low the lowest index of the lowest value in the search range, inclusive. - * @param high the highest index of the highest value in the search range, inclusive. - * @param v the value to search for. It must not be NaN. - * @param crit one of the InequalitySearch criteria: LT, LE, EQ, GT, GE. It must not be null. - * @return the index of the value in the given search range that satisfies the InequalitySearch criterion - */ - public static int find(final double[] arr, final int low, final int high, - final double v, final InequalitySearch crit) { - Objects.requireNonNull(arr, "Input arr must not be null"); - Objects.requireNonNull(crit, "Input crit must not be null"); - if (arr.length == 0) { throw new SketchesArgumentException("Input array must not be empty."); } - if (Double.isNaN(v)) { throw new SketchesArgumentException("Input v must not be NaN."); } - int lo = low; - int hi = high; - while (lo <= hi) { - if (hi - lo <= 1) { - return crit.resolve(arr, lo, hi, v); - } - final int mid = lo + (hi - lo) / 2; - final int ret = crit.compare(arr, mid, mid + 1, v); - if (ret == -1 ) { hi = mid; } - else if (ret == 1) { lo = mid + 1; } - else { return crit.getIndex(arr, mid, mid + 1, v); } - } - return -1; //should never return here - } - - /** - * Binary Search for the index of the float value in the given search range that satisfies - * the given InequalitySearch criterion. - * If -1 is returned there are no values in the search range that satisfy the criterion. - * - * @param arr the given array that must be sorted. - * It must not be null and must not contain any NaN values in the range {low, high} inclusive. - * @param low the lowest index of the lowest value in the search range, inclusive. - * @param high the highest index of the highest value in the search range, inclusive. - * @param v the value to search for. It must not be NaN. - * @param crit one of LT, LE, EQ, GT, GE - * @return the index of the value in the given search range that satisfies the criterion - */ - public static int find(final float[] arr, final int low, final int high, - final float v, final InequalitySearch crit) { - Objects.requireNonNull(arr, "Input arr must not be null"); - Objects.requireNonNull(crit, "Input crit must not be null"); - if (arr.length == 0) { throw new SketchesArgumentException("Input array must not be empty."); } - if (Float.isNaN(v)) { throw new SketchesArgumentException("Input v must not be NaN."); } - int lo = low; - int hi = high; - while (lo <= hi) { - if (hi - lo <= 1) { - return crit.resolve(arr, lo, hi, v); - } - final int mid = lo + (hi - lo) / 2; - final int ret = crit.compare(arr, mid, mid + 1, v); - if (ret == -1 ) { hi = mid; } - else if (ret == 1) { lo = mid + 1; } - else { return crit.getIndex(arr, mid, mid + 1, v); } - } - return -1; //should never return here - } - - /** - * Binary Search for the index of the long value in the given search range that satisfies - * the given InequalitySearch criterion. - * If -1 is returned there are no values in the search range that satisfy the criterion. - * - * @param arr the given array that must be sorted. - * @param low the lowest index of the lowest value in the search range, inclusive. - * @param high the highest index of the highest value in the search range, inclusive. - * @param v the value to search for. - * @param crit one of LT, LE, EQ, GT, GE - * @return the index of the value in the given search range that satisfies the criterion - */ - public static int find(final long[] arr, final int low, final int high, - final long v, final InequalitySearch crit) { - Objects.requireNonNull(arr, "Input arr must not be null"); - Objects.requireNonNull(crit, "Input crit must not be null"); - if (arr.length == 0) { throw new SketchesArgumentException("Input array must not be empty."); } - int lo = low; - int hi = high; - while (lo <= hi) { - if (hi - lo <= 1) { - return crit.resolve(arr, lo, hi, v); - } - final int mid = lo + (hi - lo) / 2; - final int ret = crit.compare(arr, mid, mid + 1, v); - if (ret == -1 ) { hi = mid; } - else if (ret == 1) { lo = mid + 1; } - else { return crit.getIndex(arr, mid, mid + 1, v); } - } - return -1; //should never return here - } - - /** - * Binary Search for the index of the double value in the given search range that satisfies - * the given InequalitySearch criterion. - * If -1 is returned there are no values in the search range that satisfy the criterion. - * - * @param arr the given array that must be sorted. - * @param low the lowest index of the lowest value in the search range, inclusive. - * @param high the highest index of the highest value in the search range, inclusive. - * @param v the value to search for. - * @param crit one of LT, LE, EQ, GT, GE - * @return the index of the value in the given search range that satisfies the criterion - */ - public static int find(final long[] arr, final int low, final int high, - final double v, final InequalitySearch crit) { - Objects.requireNonNull(arr, "Input arr must not be null"); - Objects.requireNonNull(crit, "Input crit must not be null"); - if (arr.length == 0) { throw new SketchesArgumentException("Input array must not be empty."); } - int lo = low; - int hi = high; - while (lo <= hi) { - if (hi - lo <= 1) { - return crit.resolve(arr, lo, hi, v); - } - final int mid = lo + (hi - lo) / 2; - final int ret = crit.compare(arr, mid, mid + 1, v); - if (ret == -1 ) { hi = mid; } - else if (ret == 1) { lo = mid + 1; } - else { return crit.getIndex(arr, mid, mid + 1, v); } - } - return -1; //should never return here - } - -} //End of enum diff --git a/src/main/java/org/apache/datasketches/quantilescommon/ItemsSketchSortedView.java b/src/main/java/org/apache/datasketches/quantilescommon/ItemsSketchSortedView.java deleted file mode 100644 index 4b0f8dd24..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/ItemsSketchSortedView.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static java.lang.Math.min; -import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.find; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantilesAPI.EMPTY_MSG; -import static org.apache.datasketches.quantilescommon.QuantilesUtil.evenlySpacedDoubles; -import static org.apache.datasketches.quantilescommon.QuantilesUtil.getNaturalRank; - -import java.lang.reflect.Array; -import java.util.Comparator; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality; -import org.apache.datasketches.quantilescommon.IncludeMinMax.ItemsPair; - -/** - * The SortedView for the KllItemsSketch and the classic QuantilesItemsSketch. - * @param The sketch data type - * @author Alexander Saydakov - * @author Lee Rhodes - */ -public class ItemsSketchSortedView implements GenericSortedView { - private final T[] quantiles; - private final long[] cumWeights; //cumulative natural weights - private final long totalN; - private final Comparator comparator; - private final Class clazz; - private final double normRankError; - private final int numRetItems; - - /** - * Constructor. - * @param quantiles the given array of quantiles, which must be ordered. - * @param cumWeights the given array of cumulative weights, which must be ordered, start with the value one, and - * the last value must be equal to N, the total number of items updated to the sketch. - * @param sk the underlying quantile sketch. - */ - public ItemsSketchSortedView( - final T[] quantiles, - final long[] cumWeights, //or Natural Ranks - final QuantilesGenericAPI sk) { - this.comparator = sk.getComparator(); - final ItemsPair iPair = - IncludeMinMax.includeItemsMinMax(quantiles, cumWeights, sk.getMaxItem(), sk.getMinItem(), comparator); - this.quantiles = iPair.quantiles; - this.cumWeights = iPair.cumWeights; - this.totalN = sk.getN(); - this.clazz = sk.getClassOfT(); - this.normRankError = sk.getNormalizedRankError(true); - this.numRetItems = sk.getNumRetained(); - } - - //Used for testing - ItemsSketchSortedView( - final T[] quantiles, - final long[] cumWeights, - final long totalN, - final Comparator comparator, - final T maxItem, - final T minItem, - final Class clazz, - final double normRankError, - final int numRetItems) { - this.comparator = comparator; - final ItemsPair iPair = - IncludeMinMax.includeItemsMinMax(quantiles, cumWeights, maxItem, minItem, comparator); - this.quantiles = iPair.quantiles; - this.cumWeights = iPair.cumWeights; - this.totalN = totalN; - this.clazz = clazz; - this.normRankError = normRankError; - this.numRetItems = numRetItems; - } - - //end of constructors - - @Override - public Comparator getComparator() { return comparator; } - - @Override - public long[] getCumulativeWeights() { - return cumWeights.clone(); - } - - @Override - public T getMaxItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - final int top = quantiles.length - 1; - return quantiles[top]; - } - - @Override - public T getMinItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - return quantiles[0]; - } - - @Override - public long getN() { - return totalN; - } - - @Override - public int getNumRetained() { - return quantiles.length; - } - - @Override - public int getMaxPartitions() { - return (int) min(1.0 / normRankError, numRetItems / 2.0); - } - - @Override - public GenericPartitionBoundaries getPartitionBoundariesFromPartSize( - final long nominalPartitionSize, - final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(QuantilesAPI.EMPTY_MSG); } - final long minPartSizeItems = getMinPartitionSizeItems(); - if (nominalPartitionSize < minPartSizeItems) { - throw new SketchesArgumentException(QuantilesAPI.UNSUPPORTED_MSG - + " The requested nominal partition size is too small for this sketch."); - } - final long totalN = this.totalN; - final int numEquallySizedParts = (int) min(totalN / minPartSizeItems, getMaxPartitions()); - return getPartitionBoundariesFromNumParts(numEquallySizedParts); - } - - @Override - @SuppressWarnings("unchecked") - public GenericPartitionBoundaries getPartitionBoundariesFromNumParts( - final int numEquallySizedParts, - final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(QuantilesAPI.EMPTY_MSG); } - final int maxParts = getMaxPartitions(); - if (numEquallySizedParts > maxParts) { - throw new SketchesArgumentException(QuantilesAPI.UNSUPPORTED_MSG - + " The requested number of partitions is too large for this sketch."); - } - - final double[] searchNormRanks = evenlySpacedDoubles(0, 1.0, numEquallySizedParts + 1); - final int partArrLen = searchNormRanks.length; - final T[] partQuantiles = (T[]) Array.newInstance(clazz, partArrLen); - final long[] partNatRanks = new long[partArrLen]; - final double[] partNormRanks = new double[partArrLen]; - - //compute the quantiles and natural and normalized ranks for the partition boundaries. - for (int i = 0; i < partArrLen; i++) { - final int index = getQuantileIndex(searchNormRanks[i], cumWeights, searchCrit); - partQuantiles[i] = quantiles[index]; - final long cumWt = cumWeights[index]; - partNatRanks[i] = cumWt; - partNormRanks[i] = (double)cumWt / totalN; - } - //Return the GPB of the complete specification of the boundaries. - final GenericPartitionBoundaries gpb = new GenericPartitionBoundaries<>( - this.totalN, - partQuantiles, - partNatRanks, - partNormRanks, - getMaxItem(), - getMinItem(), - searchCrit); - return gpb; - } //End of getPartitionBoundaries - - @Override - public T getQuantile(final double rank, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - QuantilesUtil.checkNormalizedRankBounds(rank); - final int index = getQuantileIndex(rank, cumWeights, searchCrit); - return quantiles[index]; - } - - private int getQuantileIndex(final double normRank, final long[] localCumWeights, - final QuantileSearchCriteria searchCrit) { - final int len = localCumWeights.length; - final double naturalRank = getNaturalRank(normRank, totalN, searchCrit); - final InequalitySearch crit = (searchCrit == INCLUSIVE) ? InequalitySearch.GE : InequalitySearch.GT; - final int index = InequalitySearch.find(localCumWeights, 0, len - 1, naturalRank, crit); - if (index == -1) { return len - 1; } - return index; - } - - /** - * Gets an array of quantiles corresponding to the given array of ranks. - * @param ranks the given array of normalized ranks - * @param searchCrit The search criterion: either INCLUSIVE or EXCLUSIVE. - * @return an array of quantiles corresponding to the given array of ranks. - */ - @SuppressWarnings("unchecked") - public T[] getQuantiles(final double[] ranks, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - final int len = ranks.length; - final T[] quants = (T[]) Array.newInstance(clazz, len); - for (int i = 0; i < len; i++) { - quants[i] = getQuantile(ranks[i], searchCrit); - } - return quants; - } - - @Override - public T[] getQuantiles() { - return quantiles.clone(); - } - - @Override - public double getRank(final T quantile, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - final int len = quantiles.length; - final Inequality crit = (searchCrit == INCLUSIVE) ? Inequality.LE : Inequality.LT; - final int index = find(quantiles, 0, len - 1, quantile, crit, comparator); - if (index == -1) { - return 0; //EXCLUSIVE (LT) case: quantile <= minQuantile; INCLUSIVE (LE) case: quantile < minQuantile - } - return (double)cumWeights[index] / totalN; - } - - @Override - public boolean isEmpty() { - return totalN == 0; - } - - @Override - public GenericSortedViewIterator iterator() { - return new GenericSortedViewIterator<>(quantiles, cumWeights); - } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/KolmogorovSmirnov.java b/src/main/java/org/apache/datasketches/quantilescommon/KolmogorovSmirnov.java deleted file mode 100644 index 5ed11347b..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/KolmogorovSmirnov.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static java.lang.Math.abs; -import static java.lang.Math.log; -import static java.lang.Math.max; -import static java.lang.Math.sqrt; -import static org.apache.datasketches.quantilescommon.QuantilesAPI.UNSUPPORTED_MSG; - -import org.apache.datasketches.req.ReqSketch; - -/** - * Kolmogorov-Smirnov Test - * See Kolmogorov–Smirnov Test - */ -public final class KolmogorovSmirnov { - - /** - * No argument constructor. - */ - public KolmogorovSmirnov() { } - - /** - * Computes the raw delta between two QuantilesDoublesAPI sketches for the kolmogorovSmirnovTest(...) method. - * @param sketch1 first Input QuantilesDoublesAPI - * @param sketch2 second Input QuantilesDoublesAPI - * @return the raw delta area between two QuantilesDoublesAPI sketches - */ - public static double computeKSDelta(final QuantilesDoublesAPI sketch1, final QuantilesDoublesAPI sketch2) { - final DoublesSortedView p = sketch1.getSortedView(); - final DoublesSortedView q = sketch2.getSortedView(); - - final double[] pSamplesArr = p.getQuantiles(); - final double[] qSamplesArr = q.getQuantiles(); - final long[] pCumWtsArr = p.getCumulativeWeights(); - final long[] qCumWtsArr = q.getCumulativeWeights(); - final int pSamplesArrLen = pSamplesArr.length; - final int qSamplesArrLen = qSamplesArr.length; - - final double n1 = sketch1.getN(); - final double n2 = sketch2.getN(); - - double deltaHeight = 0; - int i = 0; - int j = 0; - - while ((i < pSamplesArrLen - 1) && (j < qSamplesArrLen - 1)) { - deltaHeight = max(deltaHeight, abs(pCumWtsArr[i] / n1 - qCumWtsArr[j] / n2)); - if (pSamplesArr[i] < qSamplesArr[j]) { - i++; - } else if (qSamplesArr[j] < pSamplesArr[i]) { - j++; - } else { - i++; - j++; - } - } - - deltaHeight = max(deltaHeight, abs(pCumWtsArr[i] / n1 - qCumWtsArr[j] / n2)); - return deltaHeight; - } - - /** - * Computes the raw delta between two QuantilesFloatsAPI sketches for the kolmogorovSmirnovTest(...) method. - * method. - * @param sketch1 first Input QuantilesFloatsAPI sketch - * @param sketch2 second Input QuantilesFloatsAPI sketch - * @return the raw delta area between two QuantilesFloatsAPI sketches - */ - public static double computeKSDelta(final QuantilesFloatsAPI sketch1, final QuantilesFloatsAPI sketch2) { - final FloatsSortedView p = sketch1.getSortedView(); - final FloatsSortedView q = sketch2.getSortedView(); - - final float[] pSamplesArr = p.getQuantiles(); - final float[] qSamplesArr = q.getQuantiles(); - final long[] pCumWtsArr = p.getCumulativeWeights(); - final long[] qCumWtsArr = q.getCumulativeWeights(); - final int pSamplesArrLen = pSamplesArr.length; - final int qSamplesArrLen = qSamplesArr.length; - - final double n1 = sketch1.getN(); - final double n2 = sketch2.getN(); - - double deltaHeight = 0; - int i = 0; - int j = 0; - - while ((i < pSamplesArrLen - 1) && (j < qSamplesArrLen - 1)) { - deltaHeight = max(deltaHeight, abs(pCumWtsArr[i] / n1 - qCumWtsArr[j] / n2)); - if (pSamplesArr[i] < qSamplesArr[j]) { - i++; - } else if (qSamplesArr[j] < pSamplesArr[i]) { - j++; - } else { - i++; - j++; - } - } - - deltaHeight = max(deltaHeight, abs(pCumWtsArr[i] / n1 - qCumWtsArr[j] / n2)); - return deltaHeight; - } - - /** - * Computes the adjusted delta height threshold for the kolmogorovSmirnovTest(...) method. - * This adjusts the computed threshold by the error epsilons of the two given sketches. - * The two sketches must be of the same primitive type, double or float. - * This will not work with the REQ sketch. - * @param sketch1 first Input QuantilesAPI sketch - * @param sketch2 second Input QuantilesAPI sketch - * @param tgtPvalue Target p-value. Typically .001 to .1, e.g., .05. - * @return the adjusted threshold to be compared with the raw delta area. - */ - public static double computeKSThreshold(final QuantilesAPI sketch1, - final QuantilesAPI sketch2, - final double tgtPvalue) { - final double r1 = sketch1.getNumRetained(); - final double r2 = sketch2.getNumRetained(); - final double alpha = tgtPvalue; - final double alphaFactor = sqrt(-0.5 * log(0.5 * alpha)); - final double deltaAreaThreshold = alphaFactor * sqrt((r1 + r2) / (r1 * r2)); - final double eps1 = sketch1.getNormalizedRankError(false); - final double eps2 = sketch2.getNormalizedRankError(false); - return deltaAreaThreshold + eps1 + eps2; - } - - /** - * Performs the Kolmogorov-Smirnov Test between two QuantilesAPI sketches. - * Note: if the given sketches have insufficient data or if the sketch sizes are too small, - * this will return false. The two sketches must be of the same primitive type, double or float. - * This will not work with the REQ sketch. - * @param sketch1 first Input QuantilesAPI - * @param sketch2 second Input QuantilesAPI - * @param tgtPvalue Target p-value. Typically .001 to .1, e.g., .05. - * @return Boolean indicating whether we can reject the null hypothesis (that the sketches - * reflect the same underlying distribution) using the provided tgtPValue. - */ - public static boolean kolmogorovSmirnovTest(final QuantilesAPI sketch1, - final QuantilesAPI sketch2, final double tgtPvalue) { - - final double delta = isDoubleType(sketch1, sketch2) - ? computeKSDelta((QuantilesDoublesAPI)sketch1, (QuantilesDoublesAPI)sketch2) - : computeKSDelta((QuantilesFloatsAPI)sketch1, (QuantilesFloatsAPI)sketch2); - final double thresh = computeKSThreshold(sketch1, sketch2, tgtPvalue); - return delta > thresh; - } - - private static boolean isDoubleType(final Object sk1, final Object sk2) { - if (sk1 instanceof ReqSketch || sk2 instanceof ReqSketch) { - throw new UnsupportedOperationException(UNSUPPORTED_MSG); - } - final boolean isDbl = (sk1 instanceof QuantilesDoublesAPI && sk2 instanceof QuantilesDoublesAPI); - final boolean isFlt = (sk1 instanceof QuantilesFloatsAPI && sk2 instanceof QuantilesFloatsAPI); - if (isDbl ^ isFlt) { return isDbl; } - else { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } - } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/LongsSketchSortedView.java b/src/main/java/org/apache/datasketches/quantilescommon/LongsSketchSortedView.java deleted file mode 100644 index 32735938d..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/LongsSketchSortedView.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantilesAPI.EMPTY_MSG; -import static org.apache.datasketches.quantilescommon.QuantilesUtil.getNaturalRank; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.IncludeMinMax.LongsPair; - -/** - * The SortedView of the KllLongsSketch. - * @author Lee Rhodes - * @author Zac Blanco - */ -public final class LongsSketchSortedView implements LongsSortedView { - private final long[] quantiles; - private final long[] cumWeights; //cumulative natural weights - private final long totalN; - - /** - * Construct from elements, also used in testing. - * @param quantiles sorted array of quantiles - * @param cumWeights sorted, monotonically increasing cumulative weights. - * @param sk the underlying quantile sketch. - */ - public LongsSketchSortedView( - final long[] quantiles, - final long[] cumWeights, - final QuantilesLongsAPI sk) { - final LongsPair dPair = - IncludeMinMax.includeLongsMinMax(quantiles, cumWeights, sk.getMaxItem(), sk.getMinItem()); - this.quantiles = dPair.quantiles; - this.cumWeights = dPair.cumWeights; - this.totalN = sk.getN(); - } - - //Used for testing - LongsSketchSortedView( - final long[] quantiles, - final long[] cumWeights, - final long totalN, - final long maxItem, - final long minItem) { - final LongsPair dPair = - IncludeMinMax.includeLongsMinMax(quantiles, cumWeights, maxItem, minItem); - this.quantiles = dPair.quantiles; - this.cumWeights = dPair.cumWeights; - this.totalN = totalN; - } - - @Override - public long[] getCumulativeWeights() { - return cumWeights.clone(); - } - - @Override - public long getMaxItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - final int top = quantiles.length - 1; - return quantiles[top]; - } - - @Override - public long getMinItem() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - return quantiles[0]; - } - - @Override - public long getN() { - return totalN; - } - - @Override - public int getNumRetained() { - return quantiles.length; - } - - @Override - public long getQuantile(final double rank, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - QuantilesUtil.checkNormalizedRankBounds(rank); - final int len = cumWeights.length; - final double naturalRank = getNaturalRank(rank, totalN, searchCrit); - final InequalitySearch crit = (searchCrit == INCLUSIVE) ? InequalitySearch.GE : InequalitySearch.GT; - final int index = InequalitySearch.find(cumWeights, 0, len - 1, naturalRank, crit); - if (index == -1) { - return quantiles[len - 1]; //EXCLUSIVE (GT) case: normRank == 1.0; - } - return quantiles[index]; - } - - @Override - public long[] getQuantiles() { - return quantiles.clone(); - } - - @Override - public double getRank(final long quantile, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - final int len = quantiles.length; - final InequalitySearch crit = (searchCrit == INCLUSIVE) ? InequalitySearch.LE : InequalitySearch.LT; - final int index = InequalitySearch.find(quantiles, 0, len - 1, quantile, crit); - if (index == -1) { - return 0; //EXCLUSIVE (LT) case: quantile <= minQuantile; INCLUSIVE (LE) case: quantile < minQuantile - } - return (double)cumWeights[index] / totalN; - } - - @Override - public boolean isEmpty() { - return totalN == 0; - } - - @Override - public LongsSortedViewIterator iterator() { - return new LongsSortedViewIterator(quantiles, cumWeights); - } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/LongsSortedView.java b/src/main/java/org/apache/datasketches/quantilescommon/LongsSortedView.java deleted file mode 100644 index 59819b851..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/LongsSortedView.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * The Sorted View for quantile sketches of primitive type long. - * @see SortedView - * @author Lee Rhodes - * @author Zac Blanco - */ -public interface LongsSortedView extends SortedView { - - /** - * Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream - * as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(false) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 overlapping intervals. - *
- *

The start of each interval is below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and the end of the interval - * is the rank or cumulative probability corresponding to the split point.

- * - *

The (m+1)th interval represents 100% of the distribution represented by the sketch - * and consistent with the definition of a cumulative probability distribution, thus the (m+1)th - * rank or probability in the returned array is always 1.0.

- * - *

If a split point exactly equals a retained item of the sketch and the search criterion is:

- * - *
    - *
  • INCLUSIVE, the resulting cumulative probability will include that item.
  • - *
  • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0]. - * @throws SketchesArgumentException if sketch is empty. - */ - default double[] getCDF(final long[] splitPoints, final QuantileSearchCriteria searchCrit) { - QuantilesUtil.checkLongsSplitPointsOrder(splitPoints); - final int len = splitPoints.length + 1; - final double[] buckets = new double[len]; - for (int i = 0; i < len - 1; i++) { - buckets[i] = getRank(splitPoints[i], searchCrit); - } - buckets[len - 1] = 1; - return buckets; - } - - /** - * Returns the maximum item of the stream. This may be distinct from the largest item retained by the - * sketch algorithm. - * - * @return the maximum item of the stream - * @throws SketchesArgumentException if sketch is empty. - */ - long getMaxItem(); - - /** - * Returns the minimum item of the stream. This may be distinct from the smallest item retained by the - * sketch algorithm. - * - * @return the minimum item of the stream - * @throws SketchesArgumentException if sketch is empty. - */ - long getMinItem(); - - /** - * Returns an approximation to the Probability Mass Function (PMF) of the input stream - * as an array of probability masses as doubles on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(true) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 consecutive, non-overlapping intervals. - *
- *

Each interval except for the end intervals starts with a split point and ends with the next split - * point in sequence.

- * - *

The first interval starts below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and ends with the first split point

- * - *

The last (m+1)th interval starts with the last split point and ends after the last - * item retained by the sketch corresponding to a rank or probability of 1.0.

- * - *

The sum of the probability masses of all (m+1) intervals is 1.0.

- * - *

If the search criterion is:

- * - *
    - *
  • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude - * that item.
  • - *
  • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include - * that item.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0]. - * @throws SketchesArgumentException if sketch is empty. - */ - default double[] getPMF(final long[] splitPoints, final QuantileSearchCriteria searchCrit) { - final double[] buckets = getCDF(splitPoints, searchCrit); - final int len = buckets.length; - for (int i = len; i-- > 1; ) { - buckets[i] -= buckets[i - 1]; - } - return buckets; - } - - /** - * Gets the approximate quantile of the given normalized rank and the given search criterion. - * - * @param rank the given normalized rank, a double in the range [0.0, 1.0]. - * @param searchCrit If INCLUSIVE, the given rank includes all quantiles ≤ - * the quantile directly corresponding to the given rank. - * If EXCLUSIVE, he given rank includes all quantiles < - * the quantile directly corresponding to the given rank. - * @return the approximate quantile given the normalized rank. - * @throws SketchesArgumentException if sketch is empty. - * @see QuantileSearchCriteria - */ - long getQuantile(double rank, QuantileSearchCriteria searchCrit); - - /** - * Returns an array of all retained quantiles by the sketch. - * @return an array of all retained quantiles by the sketch. - */ - long[] getQuantiles(); - - /** - * Gets the normalized rank corresponding to the given a quantile. - * - * @param quantile the given quantile - * @param searchCrit if INCLUSIVE the given quantile is included into the rank. - * @return the normalized rank corresponding to the given quantile. - * @throws SketchesArgumentException if sketch is empty. - * @see QuantileSearchCriteria - */ - double getRank(long quantile, QuantileSearchCriteria searchCrit); - - @Override - LongsSortedViewIterator iterator(); - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/LongsSortedViewIterator.java b/src/main/java/org/apache/datasketches/quantilescommon/LongsSortedViewIterator.java deleted file mode 100644 index 77510cd5a..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/LongsSortedViewIterator.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -/** - * Iterator over quantile sketches of primitive type long. - */ -public final class LongsSortedViewIterator extends SortedViewIterator { - private final long[] quantiles; - - /** - * Constructor. - * @param quantiles the given array of quantiles, which must be ordered. - * @param cumWeights the given array of cumulative weights, which must be ordered, start with the value one, and - * the last value must be equal to N, the total number of items updated to the sketch. - */ - public LongsSortedViewIterator(final long[] quantiles, final long[] cumWeights) { - super(cumWeights); - this.quantiles = quantiles; //SpotBugs EI_EXPOSE_REP2 suppressed by FindBugsExcludeFilter - } - - /** - * Gets the quantile at the current index. - * - *

Don't call this before calling next() for the first time - * or after getting false from next().

- * - * @return the quantile at the current index. - */ - public long getQuantile() { - return quantiles[index]; - } - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/PartitioningFeature.java b/src/main/java/org/apache/datasketches/quantilescommon/PartitioningFeature.java deleted file mode 100644 index 82b293b3a..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/PartitioningFeature.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -/** - * This enables the special functions for performing efficient partitioning of massive data. - * @param the item class type - */ -public interface PartitioningFeature { - - /** - * This method returns an instance of - * {@link GenericPartitionBoundaries GenericPartitionBoundaries} which provides - * sufficient information for the user to create the given number of equally sized partitions, where "equally sized" - * refers to an approximately equal number of items per partition. - * - *

This method is equivalent to - * {@link #getPartitionBoundariesFromNumParts(int, QuantileSearchCriteria) - * getPartitionBoundariesFromNumParts(numEquallySizedParts, INCLUSIVE)}. - *

- * - *

The sketch must not be empty.

- * - * @param numEquallySizedParts an integer that specifies the number of equally sized partitions between - * {@link GenericPartitionBoundaries#getMinItem() getMinItem()} and - * {@link GenericPartitionBoundaries#getMaxItem() getMaxItem()}. - * This must be a positive integer less than - * {@link SketchPartitionLimits#getMaxPartitions() getMaxPartitions()} - *
    - *
  • A 1 will return: minItem, maxItem.
  • - *
  • A 2 will return: minItem, median quantile, maxItem.
  • - *
  • Etc.
  • - *
- * - * @return an instance of {@link GenericPartitionBoundaries GenericPartitionBoundaries}. - */ - default GenericPartitionBoundaries getPartitionBoundariesFromNumParts(final int numEquallySizedParts) { - return getPartitionBoundariesFromNumParts(numEquallySizedParts, INCLUSIVE); - } - - /** - * This method returns an instance of - * {@link GenericPartitionBoundaries GenericPartitionBoundaries} which provides - * sufficient information for the user to create the given number of equally sized partitions, where "equally sized" - * refers to an approximately equal number of items per partition. - * - *

The sketch must not be empty.

- * - * @param numEquallySizedParts an integer that specifies the number of equally sized partitions between - * {@link GenericPartitionBoundaries#getMinItem() getMinItem()} and - * {@link GenericPartitionBoundaries#getMaxItem() getMaxItem()}. - * This must be a positive integer less than - * {@link SketchPartitionLimits#getMaxPartitions() getMaxPartitions()} - *
    - *
  • A 1 will return: minItem, maxItem.
  • - *
  • A 2 will return: minItem, median quantile, maxItem.
  • - *
  • Etc.
  • - *
- * - * @param searchCrit - * If INCLUSIVE, all the returned quantiles are the upper boundaries of the equally sized partitions - * with the exception of the lowest returned quantile, which is the lowest boundary of the lowest ranked partition. - * If EXCLUSIVE, all the returned quantiles are the lower boundaries of the equally sized partitions - * with the exception of the highest returned quantile, which is the upper boundary of the highest ranked partition. - * - * @return an instance of {@link GenericPartitionBoundaries GenericPartitionBoundaries}. - */ - GenericPartitionBoundaries getPartitionBoundariesFromNumParts( - int numEquallySizedParts, QuantileSearchCriteria searchCrit); - - /** - * This method returns an instance of - * {@link GenericPartitionBoundaries GenericPartitionBoundaries} which provides - * sufficient information for the user to create the given number of equally sized partitions, where "equally sized" - * refers to an approximately equal number of items per partition. - * - *

This method is equivalent to - * {@link #getPartitionBoundariesFromPartSize(long, QuantileSearchCriteria) - * getPartitionBoundariesFromPartSize(nominalPartSizeItems, INCLUSIVE)}. - *

- * - *

The sketch must not be empty.

- * - * @param nominalPartSizeItems an integer that specifies the nominal size, in items, of each target partition. - * This must be a positive integer greater than - * {@link SketchPartitionLimits#getMinPartitionSizeItems() getMinPartitionSizeItems()} - * - * @return an instance of {@link GenericPartitionBoundaries GenericPartitionBoundaries}. - */ - default GenericPartitionBoundaries getPartitionBoundariesFromPartSize(final long nominalPartSizeItems) { - return getPartitionBoundariesFromPartSize(nominalPartSizeItems, INCLUSIVE); - } - - /** - * This method returns an instance of - * {@link GenericPartitionBoundaries GenericPartitionBoundaries} which provides - * sufficient information for the user to create the given number of equally sized partitions, where "equally sized" - * refers to an approximately equal number of items per partition. - * - *

The sketch must not be empty.

- * - * @param nominalPartSizeItems an integer that specifies the nominal size, in items, of each target partition. - * This must be a positive integer greater than - * {@link SketchPartitionLimits#getMinPartitionSizeItems() getMinPartitionSizeItems()}. - * - * @param searchCrit - * If INCLUSIVE, all the returned quantiles are the upper boundaries of the equally sized partitions - * with the exception of the lowest returned quantile, which is the lowest boundary of the lowest ranked partition. - * If EXCLUSIVE, all the returned quantiles are the lower boundaries of the equally sized partitions - * with the exception of the highest returned quantile, which is the upper boundary of the highest ranked partition. - * - * @return an instance of {@link GenericPartitionBoundaries GenericPartitionBoundaries}. - */ - GenericPartitionBoundaries getPartitionBoundariesFromPartSize( - long nominalPartSizeItems, QuantileSearchCriteria searchCrit); - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/QuantileSearchCriteria.java b/src/main/java/org/apache/datasketches/quantilescommon/QuantileSearchCriteria.java deleted file mode 100644 index e7b9e6ef6..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/QuantileSearchCriteria.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -/** - * These search criteria are used by the KLL, REQ and Classic Quantiles sketches in the DataSketches library. - * - * @see - * Sketching Quantiles and Ranks Tutorial - * - * @author Lee Rhodes - */ -public enum QuantileSearchCriteria { - - /** - * Definition of INCLUSIVE getQuantile(r) search:
- * Given rank r, return the quantile of the smallest rank that is - * strictly greater than or equal to r. - * - *

Definition of INCLUSIVE getRank(q) search:
- * Given quantile q, return the rank, r, of the largest quantile that is - * less than or equal to q.

- */ - INCLUSIVE, - - /** - * Definition of EXCLUSIVE getQuantile(r) search:
- * Given rank r, return the quantile of the smallest rank that is - * strictly greater than r. - * - *

However, if the given rank is is equal to 1.0, or there is no quantile that satisfies this criterion - * the method will return a NaN or null.

- * - *

Definition of EXCLUSIVE getRank(q) search:
- * Given quantile q, return the rank, r, of the largest quantile that is - * strictly less than q.

- * - *

If there is no quantile value that is strictly less than q, - * the method will return a rank of zero.

- * - */ - EXCLUSIVE; - -} - diff --git a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesAPI.java b/src/main/java/org/apache/datasketches/quantilescommon/QuantilesAPI.java deleted file mode 100644 index 1ad4213dd..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesAPI.java +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -/** - * This is a stochastic streaming sketch that enables near-real time analysis of the - * approximate distribution of items from a very large stream in a single pass, requiring only - * that the items are comparable. - * The analysis is obtained using the getQuantile() function or the - * inverse functions getRank(), getPMF() (the Probability Mass Function), and getCDF() - * (the Cumulative Distribution Function). - * - *

Given an input stream of N items, the natural rank of any specific - * item is defined as its index (1 to N) in the hypothetical sorted stream of all - * N input items.

- * - *

The normalized rank (rank) of any specific item is defined as its - * natural rank divided by N, which is a number in the interval [0.0, 1.0]. - * In the Javadocs for all the quantile sketches natural rank is seldom used - * so any reference to just rank should be interpreted as normalized rank.

- * - *

Inputs into a quantile sketch are called "items" that can be either generic or specific - * primitives, like float or double depending on the sketch implementation. - * In order to keep its size small, sketches don't retain all the items offered and retain only - * a small fraction of all the items, thus purging most of the items. The items retained are - * then sorted and associated with a rank. At this point we call the retained items quantiles. - * Thus, all quantiles are items, but only a few items become quantiles. Depending on the context - * the two terms can be interchangeable.

- * - *

All quantile sketches are configured with a parameter k, which affects the size of - * the sketch and its estimation error.

- * - *

In the research literature, the estimation error is commonly called epsilon - * (or eps) and is a fraction between zero and one. - * Larger sizes of k result in a smaller epsilon, but also a larger sketch. - * The epsilon error is always with respect to the rank domain. Estimating the confidence interval - * in the quantile domain can be done by first computing the error in the rank domain and then - * translating that to the quantile domain. The sketch provides methods to assist with that.

- * - *

The relationship between the normalized rank and the corresponding quantiles can be viewed - * as a two dimensional monotonic plot with the normalized rank on one axis and the - * corresponding quantiles on the other axis. Let q := quantile and r := rank then both - * q = getQuantile(r) and r = getRank(q) are monotonically increasing functions. - * If the y-axis is used for the rank domain and the x-axis for the quantile domain, - * then y = getRank(x) is also the single point Cumulative Distribution Function (CDF).

- * - *

The functions getQuantile() translate ranks into corresponding quantiles. - * The functions getRank(), getCDF(), and getPMF() (Probability Mass Function) - * perform the opposite operation and translate quantiles into ranks (or cumulative probabilities, - * or probability masses, depending on the context).

- * - *

As an example, consider a large stream of one million items such as packet sizes coming into a network node. - * The absolute rank of any specific item size is simply its index in the hypothetical sorted - * array of such items. - * The normalized rank is the natural rank divided by the stream size, or N, - * in this case one million. - * The quantile corresponding to the normalized rank of 0.5 represents the 50th percentile or median - * of the distribution, obtained from getQuantile(0.5). Similarly, the 95th percentile is obtained from - * getQuantile(0.95).

- * - *

From the min and max quantiles, for example, say 1 and 1000 bytes, - * you can obtain the PMF from getPMF(100, 500, 900) that will result in an array of - * 4 probability masses such as {.4, .3, .2, .1}, which means that - *

    - *
  • 40% of the mass was < 100,
  • - *
  • 30% of the mass was ≥ 100 and < 500,
  • - *
  • 20% of the mass was ≥ 500 and < 900, and
  • - *
  • 10% of the mass was ≥ 900.
  • - *
- * A frequency histogram can be obtained by simply multiplying these probability masses by getN(), - * which is the total count of items received. - * The getCDF() works similarly, but produces the cumulative distribution instead. - * - *

The accuracy of this sketch is a function of the configured k, which also affects - * the overall size of the sketch. Accuracy of this quantile sketch is always with respect to - * the normalized rank. - * - *

The getPMF() function has about 13 to 47% worse rank error (depending - * on k) than the other queries because the mass of each "bin" of the PMF has - * "double-sided" error from the upper and lower edges of the bin as a result of a subtraction - * of random variables where the errors from the two edges can sometimes add.

- * - *

A getQuantile(rank) query has the following probabilistic guarantees:

- *
    - *
  • Let q = getQuantile(r) where r is the rank between zero and one.
  • - *
  • The quantile q will be a quantile from the input stream.
  • - *
  • Let trueRank be the true rank of q derived from the hypothetical sorted - * stream of all N quantiles.
  • - *
  • Let eps = getNormalizedRankError(false)[*].
  • - *
  • Then r - eps ≤ trueRank ≤ r + eps. - * Note that the error is on the rank, not the quantile.
  • - *
- * - *

A getRank(quantile) query has the following probabilistic guarantees:

- *
    - *
  • Let r = getRank(q) where q is a quantile between the min and max quantiles of - * the input stream.
  • - *
  • Let trueRank be the true rank of q derived from the hypothetical sorted - * stream of all N quantiles.
  • - *
  • Let eps = getNormalizedRankError(false)[*].
  • - *
  • Then r - eps ≤ trueRank ≤ r + eps.
  • - *
- * - *

A getPMF() query has the following probabilistic guarantees:

- *
    - *
  • Let {r1, r2, ..., rm+1} - * = getPMF(v1, v2, ..., vm) where - * q1, q2, ..., qm are monotonically increasing quantiles - * supplied by the user that are part of the monotonic sequence - * q0 = min, q1, q2, ..., qm, qm+1 = max, - * and where min and max are the actual minimum and maximum quantiles of the input - * stream automatically included in the sequence by the getPMF(...) function. - * - *
  • Let ri = massi = estimated mass between - * vi-1 and qi where q0 = min - * and qm+1 = max.
  • - * - *
  • Let trueMass be the true mass between the quantiles of qi, - * qi+1 derived from the hypothetical sorted stream of all N quantiles.
  • - *
  • Let eps = getNormalizedRankError(true)[*].
  • - *
  • Then mass - eps ≤ trueMass ≤ mass + eps.
  • - *
  • r1 includes the mass of all points between min = q0 and - * q1.
  • - *
  • rm+1 includes the mass of all points between qm and - * max = qm+1.
  • - *
- * - *

A getCDF(...) query has the following probabilistic guarantees:

- *
    - *
  • Let {r1, r2, ..., rm+1} - * = getCDF(q1, q2, ..., qm) where - * q1, q2, ..., qm) are monotonically increasing quantiles - * supplied by the user that are part of the monotonic sequence - * {q0 = min, q1, q2, ..., qm, qm+1 = max}, - * and where min and max are the actual minimum and maximum quantiles of the input - * stream automatically included in the sequence by the getCDF(...) function. - * - *
  • Let ri = massi = estimated mass between - * q0 = min and qi.
  • - * - *
  • Let trueMass be the true mass between the true ranks of qi, - * qi+1 derived from the hypothetical sorted stream of all N quantiles.
  • - *
  • Let eps = getNormalizedRankError(true)[*].
  • - *
  • then mass - eps ≤ trueMass ≤ mass + eps.
  • - *
  • r1 includes the mass of all points between min = q0 and - * q1.
  • - *
  • rm+1 includes the mass of all points between min = q0 and - * max = qm+1.
  • - *
- * - *

Because errors are independent, we can make some estimates of the size of the confidence bounds - * for the quantile returned from a call to getQuantile(), but not error bounds. - * These confidence bounds may be quite large for certain distributions.

- * - *
    - *
  • Let q = getQuantile(r), the estimated quantile of rank r.
  • - *
  • Let eps = getNormalizedRankError(false)[*].
  • - *
  • Let qlo = estimated quantile of rank (r - eps).
  • - *
  • Let qhi = estimated quantile of rank (r + eps).
  • - *
  • Then qlo ≤ q ≤ qhi.
  • - *
- * - *

This sketch is order and distribution insensitive

- * - *

This algorithm intentionally inserts randomness into the sampling process for items that - * ultimately get retained in the sketch. Thus, the results produced by this algorithm are not - * deterministic. For example, if the same stream is inserted into two different instances of this - * sketch, the answers obtained from the two sketches should be close, but may not be be identical.

- * - *

Similarly, there may be directional inconsistencies. For example, if a quantile obtained - * from getQuantile(rank) is input into the reverse query - * getRank(quantile), the resulting rank should be close, but may not exactly equal the original rank.

- * - *

Please visit our website: DataSketches Home Page - * and specific Javadocs for more information.

- * - *

[*] Note that obtaining epsilon may require using a similar function but with more parameters - * based on the specific sketch implementation.

- * - * @see - * Sketching Quantiles and Ranks, Tutorial - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - * - * @author Lee Rhodes - * @author Kevin Lang - * @author Alexander Saydakov - */ - -public interface QuantilesAPI { - - /** The sketch must not be empty for this operation. */ - String EMPTY_MSG = "The sketch must not be empty for this operation. "; - - /** Unsupported operation for this Sketch Type. */ - String UNSUPPORTED_MSG = "Unsupported operation for this Sketch Type. "; - - /** Sketch does not have just one item. */ - String NOT_SINGLE_ITEM_MSG = "Sketch does not have just one item. "; - - /** MemoryRequestServer must not be null. */ - String MEM_REQ_SVR_NULL_MSG = "MemoryRequestServer must not be null. "; - - /** Target sketch is Read Only, cannot write. */ - String TGT_IS_READ_ONLY_MSG = "Target sketch is Read Only, cannot write. "; - - /** A sketch cannot merge with itself. */ - String SELF_MERGE_MSG = "A sketch cannot merge with itself. "; - - /** - * Gets the user configured parameter k, which controls the accuracy of the sketch - * and its memory space usage. - * @return the user configured parameter k, which controls the accuracy of the sketch - * and its memory space usage. - */ - int getK(); - - /** - * Gets the length of the input stream offered to the sketch.. - * @return the length of the input stream offered to the sketch. - */ - long getN(); - - /** - * Gets the approximate rank error of this sketch normalized as a fraction between zero and one. - * The epsilon returned is a best fit to 99 percent confidence empirically measured max error - * in thousands of trials. - * @param pmf if true, returns the "double-sided" normalized rank error for the getPMF() function. - * Otherwise, it is the "single-sided" normalized rank error for all the other queries. - * @return if pmf is true, returns the "double-sided" normalized rank error for the getPMF() function. - * Otherwise, it is the "single-sided" normalized rank error for all the other queries. - */ - double getNormalizedRankError(boolean pmf); - - /** - * Gets the number of quantiles retained by the sketch. - * @return the number of quantiles retained by the sketch - */ - int getNumRetained(); - - /** - * Gets the lower bound of the rank confidence interval in which the true rank of the - * given rank exists. - * @param rank the given normalized rank. - * @return the lower bound of the rank confidence interval in which the true rank of the - * given rank exists. - */ - double getRankLowerBound(double rank); - - /** - * Gets the upper bound of the rank confidence interval in which the true rank of the - * given rank exists. - * @param rank the given normalized rank. - * @return the upper bound of the rank confidence interval in which the true rank of the - * given rank exists. - */ - double getRankUpperBound(double rank); - - /** - * Returns true if this sketch is empty. - * @return true if this sketch is empty. - */ - boolean isEmpty(); - - /** - * Returns true if this sketch is in estimation mode. - * @return true if this sketch is in estimation mode. - */ - boolean isEstimationMode(); - - /** - * Returns true if this sketch is read only. - * @return true if this sketch is read only. - */ - boolean isReadOnly(); - - /** - * Resets this sketch to the empty state. - * If the sketch is read only this does nothing. - * - *

The parameter k will not change.

- */ - void reset(); - - /** - * Returns a summary of the key parameters of the sketch. - * @return a summary of the key parameters of the sketch. - */ - @Override - String toString(); - -} - diff --git a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesDoublesAPI.java b/src/main/java/org/apache/datasketches/quantilescommon/QuantilesDoublesAPI.java deleted file mode 100644 index 63ec15284..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesDoublesAPI.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -/** - * The Quantiles API for item type double. - * @see QuantilesAPI - * - * @author Lee Rhodes - */ -public interface QuantilesDoublesAPI extends QuantilesAPI { - - /** - * This is equivalent to {@link #getCDF(double[], QuantileSearchCriteria) getCDF(splitPoints, INCLUSIVE)} - * @param splitPoints an array of m unique, monotonically increasing items. - * @return a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getCDF(final double[] splitPoints) { - return getCDF(splitPoints, INCLUSIVE); - } - - /** - * Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream - * as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(false) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 overlapping intervals. - *
- *

The start of each interval is below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and the end of the interval - * is the rank or cumulative probability corresponding to the split point.

- * - *

The (m+1)th interval represents 100% of the distribution represented by the sketch - * and consistent with the definition of a cumulative probability distribution, thus the (m+1)th - * rank or probability in the returned array is always 1.0.

- * - *

If a split point exactly equals a retained item of the sketch and the search criterion is:

- * - *
    - *
  • INCLUSIVE, the resulting cumulative probability will include that item.
  • - *
  • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - double[] getCDF(double[] splitPoints, QuantileSearchCriteria searchCrit); - - /** - * Returns the maximum item of the stream. This is provided for convenience and may be different from the - * item returned by getQuantile(1.0). - * - * @return the maximum item of the stream - * @throws IllegalArgumentException if sketch is empty. - */ - double getMaxItem(); - - /** - * Returns the minimum item of the stream. This is provided for convenience and may be different from the - * item returned by getQuantile(0.0). - * - * @return the minimum item of the stream - * @throws IllegalArgumentException if sketch is empty. - */ - double getMinItem(); - - /** - * This is equivalent to {@link #getPMF(double[], QuantileSearchCriteria) getPMF(splitPoints, INCLUSIVE)} - * @param splitPoints an array of m unique, monotonically increasing items. - * @return a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getPMF(final double[] splitPoints) { - return getPMF(splitPoints, INCLUSIVE); - } - - /** - * Returns an approximation to the Probability Mass Function (PMF) of the input stream - * as an array of probability masses as doubles on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(true) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 consecutive, non-overlapping intervals. - *
- *

Each interval except for the end intervals starts with a split point and ends with the next split - * point in sequence.

- * - *

The first interval starts below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and ends with the first split point

- * - *

The last (m+1)th interval starts with the last split point and ends after the last - * item retained by the sketch corresponding to a rank or probability of 1.0.

- * - *

The sum of the probability masses of all (m+1) intervals is 1.0.

- * - *

If the search criterion is:

- * - *
    - *
  • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude - * that item.
  • - *
  • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include - * that item.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - double[] getPMF(double[] splitPoints, QuantileSearchCriteria searchCrit); - - /** - * This is equivalent to {@link #getQuantile(double, QuantileSearchCriteria) getQuantile(rank, INCLUSIVE)} - * @param rank the given normalized rank, a double in the range [0.0, 1.0]. - * @return the approximate quantile given the normalized rank. - * @throws IllegalArgumentException if sketch is empty. - */ - default double getQuantile(final double rank) { - return getQuantile(rank, INCLUSIVE); - } - - /** - * Gets the approximate quantile of the given normalized rank and the given search criterion. - * - * @param rank the given normalized rank, a double in the range [0.0, 1.0]. - * @param searchCrit If INCLUSIVE, the given rank includes all quantiles ≤ - * the quantile directly corresponding to the given rank. - * If EXCLUSIVE, he given rank includes all quantiles < - * the quantile directly corresponding to the given rank. - * @return the approximate quantile given the normalized rank. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - double getQuantile(double rank, QuantileSearchCriteria searchCrit); - - /** - * Gets the lower bound of the quantile confidence interval in which the quantile of the - * given rank exists. - * - *

Although it is possible to estimate the probability that the true quantile - * exists within the quantile confidence interval specified by the upper and lower quantile bounds, - * it is not possible to guarantee the width of the quantile confidence interval - * as an additive or multiplicative percent of the true quantile.

- * - * @param rank the given normalized rank - * @return the lower bound of the quantile confidence interval in which the quantile of the - * given rank exists. - * @throws IllegalArgumentException if sketch is empty. - */ - double getQuantileLowerBound(double rank); - - /** - * Gets the upper bound of the quantile confidence interval in which the true quantile of the - * given rank exists. - * - *

Although it is possible to estimate the probability that the true quantile - * exists within the quantile confidence interval specified by the upper and lower quantile bounds, - * it is not possible to guarantee the width of the quantile interval - * as an additive or multiplicative percent of the true quantile.

- * - * @param rank the given normalized rank - * @return the upper bound of the quantile confidence interval in which the true quantile of the - * given rank exists. - * @throws IllegalArgumentException if sketch is empty. - */ - double getQuantileUpperBound(double rank); - - /** - * This is equivalent to {@link #getQuantiles(double[], QuantileSearchCriteria) getQuantiles(ranks, INCLUSIVE)} - * @param ranks the given array of normalized ranks, each of which must be - * in the interval [0.0,1.0]. - * @return an array of quantiles corresponding to the given array of normalized ranks. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getQuantiles(final double[] ranks) { - return getQuantiles(ranks, INCLUSIVE); - } - - /** - * Gets an array of quantiles from the given array of normalized ranks. - * - * @param ranks the given array of normalized ranks, each of which must be - * in the interval [0.0,1.0]. - * @param searchCrit if INCLUSIVE, the given ranks include all quantiles ≤ - * the quantile directly corresponding to each rank. - * @return an array of quantiles corresponding to the given array of normalized ranks. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - double[] getQuantiles(double[] ranks, QuantileSearchCriteria searchCrit); - - /** - * This is equivalent to {@link #getRank(double, QuantileSearchCriteria) getRank(quantile, INCLUSIVE)} - * @param quantile the given quantile - * @return the normalized rank corresponding to the given quantile - * @throws IllegalArgumentException if sketch is empty. - */ - default double getRank(final double quantile) { - return getRank(quantile, INCLUSIVE); - } - - /** - * Gets the normalized rank corresponding to the given a quantile. - * - * @param quantile the given quantile - * @param searchCrit if INCLUSIVE the given quantile is included into the rank. - * @return the normalized rank corresponding to the given quantile - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - double getRank(double quantile, QuantileSearchCriteria searchCrit); - - /** - * This is equivalent to {@link #getRanks(double[], QuantileSearchCriteria) getRanks(quantiles, INCLUSIVE)} - * @param quantiles the given array of quantiles - * @return an array of normalized ranks corresponding to the given array of quantiles. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getRanks(final double[] quantiles) { - return getRanks(quantiles, INCLUSIVE); - } - - /** - * Gets an array of normalized ranks corresponding to the given array of quantiles and the given - * search criterion. - * - * @param quantiles the given array of quantiles - * @param searchCrit if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile. - * @return an array of normalized ranks corresponding to the given array of quantiles. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - double[] getRanks(double[] quantiles, QuantileSearchCriteria searchCrit); - - /** - * Returns the current number of bytes this Sketch would require if serialized. - * @return the number of bytes this sketch would require if serialized. - */ - int getSerializedSizeBytes(); - - /** - * Gets the sorted view of this sketch - * @return the sorted view of this sketch - */ - DoublesSortedView getSortedView(); - - /** - * Gets the iterator for this sketch, which is not sorted. - * @return the iterator for this sketch - */ - QuantilesDoublesSketchIteratorAPI iterator(); - - /** - * Returns a byte array representation of this sketch. - * @return a byte array representation of this sketch. - */ - byte[] toByteArray(); - - /** - * Updates this sketch with the given item. - * @param item from a stream of items. NaNs are ignored. - */ - void update(double item); - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesDoublesSketchIteratorAPI.java b/src/main/java/org/apache/datasketches/quantilescommon/QuantilesDoublesSketchIteratorAPI.java deleted file mode 100644 index 87131f3fb..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesDoublesSketchIteratorAPI.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -/** - * The quantiles sketch iterator for primitive type double. - * @see QuantilesSketchIteratorAPI - * @author Lee Rhodes - */ -public interface QuantilesDoublesSketchIteratorAPI extends QuantilesSketchIteratorAPI { - - /** - * Gets the double quantile at the current index. - * - *

Don't call this before calling next() for the first time - * or after getting false from next().

- * - * @return the double quantile at the current index. - */ - double getQuantile(); - -} - diff --git a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesFloatsAPI.java b/src/main/java/org/apache/datasketches/quantilescommon/QuantilesFloatsAPI.java deleted file mode 100644 index 2713e1b02..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesFloatsAPI.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -/** - * The Quantiles API for item type float. - * @see QuantilesAPI - * @author Lee Rhodes - */ -public interface QuantilesFloatsAPI extends QuantilesAPI { - - /** - * This is equivalent to {@link #getCDF(float[], QuantileSearchCriteria) getCDF(splitPoints, INCLUSIVE)} - * @param splitPoints an array of m unique, monotonically increasing items. - * @return a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getCDF(final float[] splitPoints) { - return getCDF(splitPoints, INCLUSIVE); - } - - /** - * Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream - * as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(false) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 overlapping intervals. - *
- *

The start of each interval is below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and the end of the interval - * is the rank or cumulative probability corresponding to the split point.

- * - *

The (m+1)th interval represents 100% of the distribution represented by the sketch - * and consistent with the definition of a cumulative probability distribution, thus the (m+1)th - * rank or probability in the returned array is always 1.0.

- * - *

If a split point exactly equals a retained item of the sketch and the search criterion is:

- * - *
    - *
  • INCLUSIVE, the resulting cumulative probability will include that item.
  • - *
  • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - double[] getCDF(float[] splitPoints, QuantileSearchCriteria searchCrit); - - /** - * Returns the maximum item of the stream. This is provided for convenience, but may be different from the largest - * item retained by the sketch algorithm. - * - * @return the maximum item of the stream - * @throws IllegalArgumentException if sketch is empty. - */ - float getMaxItem(); - - /** - * Returns the minimum item of the stream. This is provided for convenience, but is distinct from the smallest - * item retained by the sketch algorithm. - * - * @return the minimum item of the stream - * @throws IllegalArgumentException if sketch is empty. - */ - float getMinItem(); - - /** - * This is equivalent to {@link #getPMF(float[], QuantileSearchCriteria) getPMF(splitPoints, INCLUSIVE)} - * @param splitPoints an array of m unique, monotonically increasing items. - * @return a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getPMF(final float[] splitPoints) { - return getPMF(splitPoints, INCLUSIVE); - } - - /** - * Returns an approximation to the Probability Mass Function (PMF) of the input stream - * as an array of probability masses as doubles on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(true) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 consecutive, non-overlapping intervals. - *
- *

Each interval except for the end intervals starts with a split point and ends with the next split - * point in sequence.

- * - *

The first interval starts below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and ends with the first split point

- * - *

The last (m+1)th interval starts with the last split point and ends after the last - * item retained by the sketch corresponding to a rank or probability of 1.0.

- * - *

The sum of the probability masses of all (m+1) intervals is 1.0.

- * - *

If the search criterion is:

- * - *
    - *
  • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude - * that item.
  • - *
  • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include - * that item.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - double[] getPMF(float[] splitPoints, QuantileSearchCriteria searchCrit); - - /** - * This is equivalent to {@link #getQuantile(double, QuantileSearchCriteria) getQuantile(rank, INCLUSIVE)} - * @param rank the given normalized rank, a double in the range [0.0, 1.0]. - * @return the approximate quantile given the normalized rank. - * @throws IllegalArgumentException if sketch is empty. - */ - default float getQuantile(final double rank) { - return getQuantile(rank, INCLUSIVE); - } - - /** - * Gets the approximate quantile of the given normalized rank and the given search criterion. - * - * @param rank the given normalized rank, a double in the range [0.0, 1.0]. - * @param searchCrit If INCLUSIVE, the given rank includes all quantiles ≤ - * the quantile directly corresponding to the given rank. - * If EXCLUSIVE, he given rank includes all quantiles < - * the quantile directly corresponding to the given rank. - * @return the approximate quantile given the normalized rank. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - float getQuantile(double rank, QuantileSearchCriteria searchCrit); - - /** - * Gets the lower bound of the quantile confidence interval in which the quantile of the - * given rank exists. - * - *

Although it is possible to estimate the probability that the true quantile - * exists within the quantile confidence interval specified by the upper and lower quantile bounds, - * it is not possible to guarantee the width of the quantile confidence interval - * as an additive or multiplicative percent of the true quantile.

- * - * @param rank the given normalized rank - * @return the lower bound of the quantile confidence interval in which the quantile of the - * given rank exists. - * @throws IllegalArgumentException if sketch is empty. - */ - float getQuantileLowerBound(double rank); - - /** - * Gets the upper bound of the quantile confidence interval in which the true quantile of the - * given rank exists. - * - *

Although it is possible to estimate the probability that the true quantile - * exists within the quantile confidence interval specified by the upper and lower quantile bounds, - * it is not possible to guarantee the width of the quantile interval - * as an additive or multiplicative percent of the true quantile.

- * - * @param rank the given normalized rank - * @return the upper bound of the quantile confidence interval in which the true quantile of the - * given rank exists. - * @throws IllegalArgumentException if sketch is empty. - */ - float getQuantileUpperBound(double rank); - - /** - * This is equivalent to {@link #getQuantiles(double[], QuantileSearchCriteria) getQuantiles(ranks, INCLUSIVE)} - * @param ranks the given array of normalized ranks, each of which must be - * in the interval [0.0,1.0]. - * @return an array of quantiles corresponding to the given array of normalized ranks. - * @throws IllegalArgumentException if sketch is empty. - */ - default float[] getQuantiles(final double[] ranks) { - return getQuantiles(ranks, INCLUSIVE); - } - - /** - * Gets an array of quantiles from the given array of normalized ranks. - * - * @param ranks the given array of normalized ranks, each of which must be - * in the interval [0.0,1.0]. - * @param searchCrit if INCLUSIVE, the given ranks include all quantiles ≤ - * the quantile directly corresponding to each rank. - * @return an array of quantiles corresponding to the given array of normalized ranks. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - float[] getQuantiles(double[] ranks, QuantileSearchCriteria searchCrit); - - /** - * This is equivalent to {@link #getRank(float, QuantileSearchCriteria) getRank(quantile, INCLUSIVE)} - * @param quantile the given quantile - * @return the normalized rank corresponding to the given quantile. - * @throws IllegalArgumentException if sketch is empty. - */ - default double getRank(final float quantile) { - return getRank(quantile, INCLUSIVE); - } - - /** - * Gets the normalized rank corresponding to the given a quantile. - * - * @param quantile the given quantile - * @param searchCrit if INCLUSIVE the given quantile is included into the rank. - * @return the normalized rank corresponding to the given quantile. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - double getRank(float quantile, QuantileSearchCriteria searchCrit); - - /** - * This is equivalent to {@link #getRanks(float[], QuantileSearchCriteria) getRanks(quantiles, INCLUSIVE)} - * @param quantiles the given array of quantiles - * @return an array of normalized ranks corresponding to the given array of quantiles. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getRanks(final float[] quantiles) { - return getRanks(quantiles, INCLUSIVE); - } - - /** - * Gets an array of normalized ranks corresponding to the given array of quantiles and the given - * search criterion. - * - * @param quantiles the given array of quantiles - * @param searchCrit if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile. - * @return an array of normalized ranks corresponding to the given array of quantiles. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - double[] getRanks(float[] quantiles, QuantileSearchCriteria searchCrit); - - /** - * Returns the current number of bytes this Sketch would require if serialized. - * @return the number of bytes this sketch would require if serialized. - */ - int getSerializedSizeBytes(); - - /** - * Gets the sorted view of this sketch - * @return the sorted view of this sketch - */ - FloatsSortedView getSortedView(); - - /** - * Gets the iterator for this sketch, which is not sorted. - * @return the iterator for this sketch - */ - QuantilesFloatsSketchIterator iterator(); - - /** - * Returns a byte array representation of this sketch. - * @return a byte array representation of this sketch. - */ - byte[] toByteArray(); - - /** - * Updates this sketch with the given item. - * @param item from a stream of quantiles. NaNs are ignored. - */ - void update(float item); - -} - diff --git a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesFloatsSketchIterator.java b/src/main/java/org/apache/datasketches/quantilescommon/QuantilesFloatsSketchIterator.java deleted file mode 100644 index 176cffcea..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesFloatsSketchIterator.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -/** - * The quantiles sketch iterator for primitive type float. - * @see QuantilesSketchIteratorAPI - * @author Lee Rhodes - */ -public interface QuantilesFloatsSketchIterator extends QuantilesSketchIteratorAPI { - - /** - * Gets the float quantile at the current index. - * - *

Don't call this before calling next() for the first time - * or after getting false from next().

- * - * @return the float quantile at the current index. - */ - float getQuantile(); - -} - diff --git a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesGenericAPI.java b/src/main/java/org/apache/datasketches/quantilescommon/QuantilesGenericAPI.java deleted file mode 100644 index 6251a9596..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesGenericAPI.java +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static java.lang.Math.min; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -import java.util.Comparator; - -/** - * The Quantiles API for item type generic. - * @see QuantilesAPI - * @param The given item type - * @author Lee Rhodes - */ -public interface QuantilesGenericAPI extends QuantilesAPI, PartitioningFeature, SketchPartitionLimits { - - /** - * This is equivalent to {@link #getCDF(Object[], QuantileSearchCriteria) getCDF(splitPoints, INCLUSIVE)} - * @param splitPoints an array of m unique, monotonically increasing items. - * @return a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getCDF(final T[] splitPoints) { - return getCDF(splitPoints, INCLUSIVE); - } - - /** - * Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream - * as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(false) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 overlapping intervals. - *
- *

The start of each interval is below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and the end of the interval - * is the rank or cumulative probability corresponding to the split point.

- * - *

The (m+1)th interval represents 100% of the distribution represented by the sketch - * and consistent with the definition of a cumulative probability distribution, thus the (m+1)th - * rank or probability in the returned array is always 1.0.

- * - *

If a split point exactly equals a retained item of the sketch and the search criterion is:

- * - *
    - *
  • INCLUSIVE, the resulting cumulative probability will include that item.
  • - *
  • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - double[] getCDF(T[] splitPoints, QuantileSearchCriteria searchCrit); - - /** - * Returns the sketch item class - * @return the sketch item class - */ - Class getClassOfT(); - - /** - * Returns the Comparator of T - * @return Comparator of the sketch - */ - Comparator getComparator(); - - /** - * Returns the maximum item of the stream. This may be distinct from the largest item retained by the - * sketch algorithm. - * - * @return the maximum item of the stream - * @throws IllegalArgumentException if sketch is empty. - */ - T getMaxItem(); - - @Override - default int getMaxPartitions() { - return (int) min(1.0 / getNormalizedRankError(true), getNumRetained() / 2.0); - } - - /** - * Returns the minimum item of the stream. This may be distinct from the smallest item retained by the - * sketch algorithm. - * - * @return the minimum item of the stream - * @throws IllegalArgumentException if sketch is empty. - */ - T getMinItem(); - - /** - * This is equivalent to {@link #getPMF(Object[], QuantileSearchCriteria) getPMF(splitPoints, INCLUSIVE)} - * @param splitPoints an array of m unique, monotonically increasing items. - * @return a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getPMF(final T[] splitPoints) { - return getPMF(splitPoints, INCLUSIVE); - } - - /** - * Returns an approximation to the Probability Mass Function (PMF) of the input stream - * as an array of probability masses as doubles on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(true) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 consecutive, non-overlapping intervals. - *
- *

Each interval except for the end intervals starts with a split point and ends with the next split - * point in sequence.

- * - *

The first interval starts below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and ends with the first split point

- * - *

The last (m+1)th interval starts with the last split point and ends after the last - * item retained by the sketch corresponding to a rank or probability of 1.0.

- * - *

The sum of the probability masses of all (m+1) intervals is 1.0.

- * - *

If the search criterion is:

- * - *
    - *
  • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude - * that item.
  • - *
  • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include - * that item.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - double[] getPMF(T[] splitPoints, QuantileSearchCriteria searchCrit); - - /** - * This is equivalent to {@link #getQuantile(double, QuantileSearchCriteria) getQuantile(rank, INCLUSIVE)} - * @param rank the given normalized rank, a double in the range [0.0, 1.0]. - * @return the approximate quantile given the normalized rank. - * @throws IllegalArgumentException if sketch is empty. - */ - default T getQuantile(final double rank) { - return getQuantile(rank, INCLUSIVE); - } - - /** - * Gets the approximate quantile of the given normalized rank and the given search criterion. - * - * @param rank the given normalized rank, a double in the range [0.0, 1.0]. - * @param searchCrit If INCLUSIVE, the given rank includes all quantiles ≤ - * the quantile directly corresponding to the given rank. - * If EXCLUSIVE, he given rank includes all quantiles < - * the quantile directly corresponding to the given rank. - * @return the approximate quantile given the normalized rank. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - T getQuantile(double rank, QuantileSearchCriteria searchCrit); - - /** - * Gets the lower bound of the quantile confidence interval in which the quantile of the - * given rank exists. - * - *

Although it is possible to estimate the probability that the true quantile - * exists within the quantile confidence interval specified by the upper and lower quantile bounds, - * it is not possible to guarantee the width of the quantile confidence interval - * as an additive or multiplicative percent of the true quantile.

- * - * @param rank the given normalized rank - * @return the lower bound of the quantile confidence interval in which the quantile of the - * given rank exists. - * @throws IllegalArgumentException if sketch is empty. - */ - T getQuantileLowerBound(double rank); - - /** - * Gets the upper bound of the quantile confidence interval in which the true quantile of the - * given rank exists. - * - *

Although it is possible to estimate the probability that the true quantile - * exists within the quantile confidence interval specified by the upper and lower quantile bounds, - * it is not possible to guarantee the width of the quantile interval - * as an additive or multiplicative percent of the true quantile.

- * - * @param rank the given normalized rank - * @return the upper bound of the quantile confidence interval in which the true quantile of the - * given rank exists. - * @throws IllegalArgumentException if sketch is empty. - */ - T getQuantileUpperBound(double rank); - - /** - * This is equivalent to {@link #getQuantiles(double[], QuantileSearchCriteria) getQuantiles(ranks, INCLUSIVE)} - * @param ranks the given array of normalized ranks, each of which must be - * in the interval [0.0,1.0]. - * @return an array of quantiles corresponding to the given array of normalized ranks. - * @throws IllegalArgumentException if sketch is empty. - */ - default T[] getQuantiles(final double[] ranks) { - return getQuantiles(ranks, INCLUSIVE); - } - - /** - * Gets an array of quantiles from the given array of normalized ranks. - * - * @param ranks the given array of normalized ranks, each of which must be - * in the interval [0.0,1.0]. - * @param searchCrit if INCLUSIVE, the given ranks include all quantiles ≤ - * the quantile directly corresponding to each rank. - * @return an array of quantiles corresponding to the given array of normalized ranks. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - T[] getQuantiles(double[] ranks, QuantileSearchCriteria searchCrit); - - /** - * This is equivalent to {@link #getRank(Object, QuantileSearchCriteria) getRank(T quantile, INCLUSIVE)} - * @param quantile the given quantile - * @return the normalized rank corresponding to the given quantile. - * @throws IllegalArgumentException if sketch is empty. - */ - default double getRank(final T quantile) { - return getRank(quantile, INCLUSIVE); - } - - /** - * Gets the normalized rank corresponding to the given a quantile. - * - * @param quantile the given quantile - * @param searchCrit if INCLUSIVE the given quantile is included into the rank. - * @return the normalized rank corresponding to the given quantile. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - double getRank(T quantile, QuantileSearchCriteria searchCrit); - - /** - * This is equivalent to {@link #getRanks(Object[], QuantileSearchCriteria) getRanks(quantiles, INCLUSIVE)} - * @param quantiles the given array of quantiles - * @return an array of normalized ranks corresponding to the given array of quantiles. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getRanks(final T[] quantiles) { - return getRanks(quantiles, INCLUSIVE); - } - - /** - * Gets an array of normalized ranks corresponding to the given array of quantiles and the given - * search criterion. - * - * @param quantiles the given array of quantiles - * @param searchCrit if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile. - * @return an array of normalized ranks corresponding to the given array of quantiles. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - double[] getRanks(T[] quantiles, QuantileSearchCriteria searchCrit); - - /** - * Gets the sorted view of this sketch - * @return the sorted view of this sketch - */ - GenericSortedView getSortedView(); - - /** - * Gets the iterator for this sketch, which is not sorted. - * @return the iterator for this sketch - */ - QuantilesGenericSketchIteratorAPI iterator(); - - /** - * Updates this sketch with the given item. - * @param item from a stream of items. Nulls are ignored. - */ - void update(T item); - -} - diff --git a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesGenericSketchIteratorAPI.java b/src/main/java/org/apache/datasketches/quantilescommon/QuantilesGenericSketchIteratorAPI.java deleted file mode 100644 index d2c50c450..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesGenericSketchIteratorAPI.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -/** - * The quantiles sketch iterator for generic types. - * @see QuantilesSketchIteratorAPI - * @param The generic quantile type - * @author Lee Rhodes - */ -public interface QuantilesGenericSketchIteratorAPI extends QuantilesSketchIteratorAPI { - - /** - * Gets the generic quantile at the current index. - * - *

Don't call this before calling next() for the first time - * or after getting false from next().

- * - * @return the generic quantile at the current index. - */ - T getQuantile(); - -} - diff --git a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesLongsAPI.java b/src/main/java/org/apache/datasketches/quantilescommon/QuantilesLongsAPI.java deleted file mode 100644 index 51802df71..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesLongsAPI.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -/** - * The Quantiles API for item type long. - * @see QuantilesAPI - * @author Lee Rhodes - * @author Zac Blanco - */ -public interface QuantilesLongsAPI extends QuantilesAPI { - - /** - * This is equivalent to {@link #getCDF(long[], QuantileSearchCriteria) getCDF(splitPoints, INCLUSIVE)} - * @param splitPoints an array of m unique, monotonically increasing items. - * @return a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getCDF(final long[] splitPoints) { - return getCDF(splitPoints, INCLUSIVE); - } - - /** - * Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream - * as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(false) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 overlapping intervals. - *
- *

The start of each interval is below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and the end of the interval - * is the rank or cumulative probability corresponding to the split point.

- * - *

The (m+1)th interval represents 100% of the distribution represented by the sketch - * and consistent with the definition of a cumulative probability distribution, thus the (m+1)th - * rank or probability in the returned array is always 1.0.

- * - *

If a split point exactly equals a retained item of the sketch and the search criterion is:

- * - *
    - *
  • INCLUSIVE, the resulting cumulative probability will include that item.
  • - *
  • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - double[] getCDF(long[] splitPoints, QuantileSearchCriteria searchCrit); - - /** - * Returns the maximum item of the stream. This is provided for convenience and may be different from the - * item returned by getQuantile(1.0). - * - * @return the maximum item of the stream - * @throws IllegalArgumentException if sketch is empty. - */ - long getMaxItem(); - - /** - * Returns the minimum item of the stream. This is provided for convenience and may be different from the - * item returned by getQuantile(0.0). - * - * @return the minimum item of the stream - * @throws IllegalArgumentException if sketch is empty. - */ - long getMinItem(); - - /** - * This is equivalent to {@link #getPMF(long[], QuantileSearchCriteria) getPMF(splitPoints, INCLUSIVE)} - * @param splitPoints an array of m unique, monotonically increasing items. - * @return a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getPMF(final long[] splitPoints) { - return getPMF(splitPoints, INCLUSIVE); - } - - /** - * Returns an approximation to the Probability Mass Function (PMF) of the input stream - * as an array of probability masses as doubles on the interval [0.0, 1.0], - * given a set of splitPoints. - * - *

The resulting approximations have a probabilistic guarantee that can be obtained from the - * getNormalizedRankError(true) function.

- * - * @param splitPoints an array of m unique, monotonically increasing items - * (of the same type as the input items) - * that divide the item input domain into m+1 consecutive, non-overlapping intervals. - *
- *

Each interval except for the end intervals starts with a split point and ends with the next split - * point in sequence.

- * - *

The first interval starts below the lowest item retained by the sketch - * corresponding to a zero rank or zero probability, and ends with the first split point

- * - *

The last (m+1)th interval starts with the last split point and ends after the last - * item retained by the sketch corresponding to a rank or probability of 1.0.

- * - *

The sum of the probability masses of all (m+1) intervals is 1.0.

- * - *

If the search criterion is:

- * - *
    - *
  • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude - * that item.
  • - *
  • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval - * will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include - * that item.
  • - *
- * - *

It is not recommended to include either the minimum or maximum items of the input stream.

- *
- * @param searchCrit the desired search criteria. - * @return a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0]. - * @throws IllegalArgumentException if sketch is empty. - */ - double[] getPMF(long[] splitPoints, QuantileSearchCriteria searchCrit); - - /** - * This is equivalent to {@link #getQuantile(double, QuantileSearchCriteria) getQuantile(rank, INCLUSIVE)} - * @param rank the given normalized rank, a double in the range [0.0, 1.0]. - * @return the approximate quantile given the normalized rank. - * @throws IllegalArgumentException if sketch is empty. - */ - default long getQuantile(final double rank) { - return getQuantile(rank, INCLUSIVE); - } - - /** - * Gets the approximate quantile of the given normalized rank and the given search criterion. - * - * @param rank the given normalized rank, a double in the range [0.0, 1.0]. - * @param searchCrit If INCLUSIVE, the given rank includes all quantiles ≤ - * the quantile directly corresponding to the given rank. - * If EXCLUSIVE, he given rank includes all quantiles < - * the quantile directly corresponding to the given rank. - * @return the approximate quantile given the normalized rank. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - long getQuantile(double rank, QuantileSearchCriteria searchCrit); - - /** - * Gets the lower bound of the quantile confidence interval in which the quantile of the - * given rank exists. - * - *

Although it is possible to estimate the probability that the true quantile - * exists within the quantile confidence interval specified by the upper and lower quantile bounds, - * it is not possible to guarantee the width of the quantile confidence interval - * as an additive or multiplicative percent of the true quantile.

- * - * @param rank the given normalized rank - * @return the lower bound of the quantile confidence interval in which the quantile of the - * given rank exists. - * @throws IllegalArgumentException if sketch is empty. - */ - long getQuantileLowerBound(double rank); - - /** - * Gets the upper bound of the quantile confidence interval in which the true quantile of the - * given rank exists. - * - *

Although it is possible to estimate the probability that the true quantile - * exists within the quantile confidence interval specified by the upper and lower quantile bounds, - * it is not possible to guarantee the width of the quantile interval - * as an additive or multiplicative percent of the true quantile.

- * - * @param rank the given normalized rank - * @return the upper bound of the quantile confidence interval in which the true quantile of the - * given rank exists. - * @throws IllegalArgumentException if sketch is empty. - */ - long getQuantileUpperBound(double rank); - - /** - * This is equivalent to {@link #getQuantiles(double[], QuantileSearchCriteria) getQuantiles(ranks, INCLUSIVE)} - * @param ranks the given array of normalized ranks, each of which must be - * in the interval [0.0,1.0]. - * @return an array of quantiles corresponding to the given array of normalized ranks. - * @throws IllegalArgumentException if sketch is empty. - */ - default long[] getQuantiles(final double[] ranks) { - return getQuantiles(ranks, INCLUSIVE); - } - - /** - * Gets an array of quantiles from the given array of normalized ranks. - * - * @param ranks the given array of normalized ranks, each of which must be - * in the interval [0.0,1.0]. - * @param searchCrit if INCLUSIVE, the given ranks include all quantiles ≤ - * the quantile directly corresponding to each rank. - * @return an array of quantiles corresponding to the given array of normalized ranks. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - long[] getQuantiles(double[] ranks, QuantileSearchCriteria searchCrit); - - /** - * This is equivalent to {@link #getRank(long, QuantileSearchCriteria) getRank(quantile, INCLUSIVE)} - * @param quantile the given quantile - * @return the normalized rank corresponding to the given quantile - * @throws IllegalArgumentException if sketch is empty. - */ - default double getRank(final long quantile) { - return getRank(quantile, INCLUSIVE); - } - - /** - * Gets the normalized rank corresponding to the given a quantile. - * - * @param quantile the given quantile - * @param searchCrit if INCLUSIVE the given quantile is included into the rank. - * @return the normalized rank corresponding to the given quantile - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - double getRank(long quantile, QuantileSearchCriteria searchCrit); - - /** - * This is equivalent to {@link #getRanks(long[], QuantileSearchCriteria) getRanks(quantiles, INCLUSIVE)} - * @param quantiles the given array of quantiles - * @return an array of normalized ranks corresponding to the given array of quantiles. - * @throws IllegalArgumentException if sketch is empty. - */ - default double[] getRanks(final long[] quantiles) { - return getRanks(quantiles, INCLUSIVE); - } - - /** - * Gets an array of normalized ranks corresponding to the given array of quantiles and the given - * search criterion. - * - * @param quantiles the given array of quantiles - * @param searchCrit if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile. - * @return an array of normalized ranks corresponding to the given array of quantiles. - * @throws IllegalArgumentException if sketch is empty. - * @see org.apache.datasketches.quantilescommon.QuantileSearchCriteria - */ - double[] getRanks(long[] quantiles, QuantileSearchCriteria searchCrit); - - /** - * Returns the current number of bytes this Sketch would require if serialized. - * @return the number of bytes this sketch would require if serialized. - */ - int getSerializedSizeBytes(); - - /** - * Gets the sorted view of this sketch - * @return the sorted view of this sketch - */ - LongsSortedView getSortedView(); - - /** - * Gets the iterator for this sketch, which is not sorted. - * @return the iterator for this sketch - */ - QuantilesLongsSketchIterator iterator(); - - /** - * Returns a byte array representation of this sketch. - * @return a byte array representation of this sketch. - */ - byte[] toByteArray(); - - /** - * Updates this sketch with the given item. - * @param item from a stream of items. NaNs are ignored. - */ - void update(long item); - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesLongsSketchIterator.java b/src/main/java/org/apache/datasketches/quantilescommon/QuantilesLongsSketchIterator.java deleted file mode 100644 index 5e2912e85..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesLongsSketchIterator.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -/** - * The quantiles sketch iterator for primitive type long. - * @see QuantilesSketchIteratorAPI - * @author Zac Blanco - */ -public interface QuantilesLongsSketchIterator extends QuantilesSketchIteratorAPI { - - /** - * Gets the long quantile at the current index. - * - *

Don't call this before calling next() for the first time - * or after getting false from next().

- * - * @return the long quantile at the current index. - */ - long getQuantile(); - -} - diff --git a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesSketchIteratorAPI.java b/src/main/java/org/apache/datasketches/quantilescommon/QuantilesSketchIteratorAPI.java deleted file mode 100644 index 4358bd9ec..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesSketchIteratorAPI.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -/** - * This is the base API for the iterator hierarchy used for viewing the - * non-ordered quantiles retained by the classic Quantiles* sketches and KLL sketches, for example. - * - *

Prototype example of the recommended iteration loop:

- *
{@code
- *   SketchIterator itr = sketch.iterator();
- *   while (itr.next()) {
- *     ...get*();
- *   }
- * }
- * - * @author Lee Rhodes - */ - -public interface QuantilesSketchIteratorAPI { - - /** - * Gets the natural weight at the current index. - * - *

Don't call this before calling next() for the first time - * or after getting false from next().

- * - * @return the natural weight at the current index. - */ - long getWeight(); - - /** - * Advances the index and checks if it is valid. - * The state of this iterator is undefined before the first call of this method. - * @return true if the next index is valid. - */ - boolean next(); - -} - diff --git a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesUtil.java b/src/main/java/org/apache/datasketches/quantilescommon/QuantilesUtil.java deleted file mode 100644 index 529fd386d..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/QuantilesUtil.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static java.lang.Math.log; -import static java.lang.Math.pow; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -import java.util.Objects; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; - -/** - * Utilities for the quantiles sketches. - * - * @author Lee Rhodes - */ -public final class QuantilesUtil { - - private QuantilesUtil() {} - - /** - * Checks that the given normalized rank: 0 ≤ nRank ≤ 1.0. - * @param nRank the given normalized rank. - */ - public static final void checkNormalizedRankBounds(final double nRank) { - if ((nRank < 0.0) || (nRank > 1.0)) { - throw new SketchesArgumentException( - "A normalized rank must be >= 0 and <= 1.0: " + nRank); - } - } - - /** - * Checks the sequential validity of the given array of double values. - * They must be unique, monotonically increasing and not NaN. - * @param values the given array of double values - */ - public static final void checkDoublesSplitPointsOrder(final double[] values) { - Objects.requireNonNull(values); - final int len = values.length; - if (len == 1 && Double.isNaN(values[0])) { - throw new SketchesArgumentException( - "Values must be unique, monotonically increasing and not NaN."); - } - for (int j = 0; j < len - 1; j++) { - if (values[j] < values[j + 1]) { continue; } - throw new SketchesArgumentException( - "Values must be unique, monotonically increasing and not NaN."); - } - } - - /** - * Checks the sequential validity of the given array of double values. - * They must be unique and monotonically increasing. - * @param values the given array of double values - */ - public static void checkLongsSplitPointsOrder(final long[] values) { - Objects.requireNonNull(values); - final int len = values.length; - for (int j = 0; j < len - 1; j++) { - if (values[j] < values[j + 1]) { continue; } - throw new SketchesArgumentException( - "Values must be unique and monotonically increasing."); - } - } - - /** - * Checks the sequential validity of the given array of float values. - * They must be unique, monotonically increasing and not NaN. - * @param values the given array of double values - */ - public static final void checkFloatsSplitPointsOrder(final float[] values) { - Objects.requireNonNull(values); - final int len = values.length; - if (len == 1 && Float.isNaN(values[0])) { - throw new SketchesArgumentException( - "Values must be unique, monotonically increasing and not NaN."); - } - for (int j = 0; j < len - 1; j++) { - if (values[j] < values[j + 1]) { continue; } - throw new SketchesArgumentException( - "Values must be unique, monotonically increasing and not NaN."); - } - } - - /** - * Returns an array of (num + 1) values that define equally sized intervals between 0.0, inclusive, and 1.0, - * inclusive. The end points 0.0 and 1.0 are part of the returned array. - * - *

For example, if num == 2, three values will be returned: 0.0, .5, and 1, where the two equally sized regions - * are {0.0,0.5}, and {0.5, 1.0}.

- * @param num the total number of equally sized intervals between 0.0, inclusive and 1.0, inclusive. - * Must be 1 or greater. - * @return a double array of values that define (num + 1) equally sized intervals between 0.0, inclusive and 1.0, - * inclusive. - * @throws IllegalArgumentException if num is less than 1. - */ - public static double[] equallySpacedDoubles(final int num) { - if (num < 1) { throw new IllegalArgumentException("num must be >= 1"); } - final double[] out = new double[num + 1]; - out[0] = 0.0; - out[num] = 1.0; - final double delta = 1.0 / num; - for (int i = 1; i < num; i++) { out[i] = i * delta; } - return out; - } - - /** - * Returns an array of (num + 1) longs that define, approximately, equally spaced intervals between the given - * max, inclusive, and min, inclusive. The end points max and min are part of the - * returned array. Because the range of the values may not exactly divide into num intervals, - * the size of these intervals may vary by plus or minus one. - * @param min the lowest positive valued (or zero) number of the range - * @param max the highest positive valued number of the range. max must be greater than min - * @param num Number of requested intervals. Must be greater or equal to one, and less than or equal to - * max - min. - * - * @return an array of (num + 1) longs that are approximately equally spaced between the given min and max. - */ - public static long[] equallySpacedLongs(final long min, final long max, final int num) { - if (num < 1 || min < 0 || max < 1 || (min >= max) || num > (max - min)) { - throw new SketchesArgumentException( - "Improper inputs: n < 1, min < 0, max < 1, min >= max, or n > (max - min)"); - } - final long span = (max - min); - final double[] splits = equallySpacedDoubles(num); - final int len = num + 1; - final long[] out = new long[len]; - long prev = -1L; - for (int i = 0; i < len; i++) { - long cur = Math.round(splits[i] * span); - if (cur == prev) { cur++; } else { prev = cur; } - out[i] = min + cur; - } - return out; - } - - /** - * Returns a float array of evenly spaced values between value1, inclusive, and value2 inclusive. - * If value2 > value1, the resulting sequence will be increasing. - * If value2 < value1, the resulting sequence will be decreasing. - * @param value1 will be in index 0 of the returned array - * @param value2 will be in the highest index of the returned array - * @param num the total number of values including value1 and value2. Must be 2 or greater. - * @return a float array of evenly spaced values between value1, inclusive, and value2 inclusive. - */ - public static float[] evenlySpacedFloats(final float value1, final float value2, final int num) { - if (num < 2) { - throw new SketchesArgumentException("num must be >= 2"); - } - final float[] out = new float[num]; - out[0] = value1; - out[num - 1] = value2; - if (num == 2) { return out; } - - final float delta = (value2 - value1) / (num - 1); - - for (int i = 1; i < num - 1; i++) { out[i] = i * delta + value1; } - return out; - } - - /** - * Returns a double array of evenly spaced values between value1, inclusive, and value2 inclusive. - * If value2 > value1, the resulting sequence will be increasing. - * If value2 < value1, the resulting sequence will be decreasing. - * @param value1 will be in index 0 of the returned array - * @param value2 will be in the highest index of the returned array - * @param num the total number of values including value1 and value2. Must be 2 or greater. - * @return a float array of evenly spaced values between value1, inclusive, and value2 inclusive. - */ - public static double[] evenlySpacedDoubles(final double value1, final double value2, final int num) { - if (num < 2) { - throw new SketchesArgumentException("num must be >= 2"); - } - final double[] out = new double[num]; - out[0] = value1; - out[num - 1] = value2; - if (num == 2) { return out; } - - final double delta = (value2 - value1) / (num - 1); - - for (int i = 1; i < num - 1; i++) { out[i] = i * delta + value1; } - return out; - } - - /** - * Returns a double array of values between min and max inclusive where the log of the - * returned values are evenly spaced. - * If value2 > value1, the resulting sequence will be increasing. - * If value2 < value1, the resulting sequence will be decreasing. - * @param value1 will be in index 0 of the returned array, and must be greater than zero. - * @param value2 will be in the highest index of the returned array, and must be greater than zero. - * @param num the total number of values including value1 and value2. Must be 2 or greater - * @return a double array of exponentially spaced values between value1 and value2 inclusive. - */ - public static double[] evenlyLogSpaced(final double value1, final double value2, final int num) { - if (num < 2) { - throw new SketchesArgumentException("num must be >= 2"); - } - if (value1 <= 0 || value2 <= 0) { - throw new SketchesArgumentException("value1 and value2 must be > 0."); - } - - final double[] arr = evenlySpacedDoubles(log(value1) / Util.LOG2, log(value2) / Util.LOG2, num); - for (int i = 0; i < arr.length; i++) { arr[i] = pow(2.0,arr[i]); } - return arr; - } - - /** used in search to improve rounding over a wide dynamic range */ - public static final double tailRoundingFactor = 1e7; - - /** - * Computes the closest Natural Rank from a given Normalized Rank - * @param normalizedRank the given normalized rank - * @param totalN the total N - * @param searchCrit the search criterion. - * @return the closest Natural Rank from a given Normalized Rank - */ - public static double getNaturalRank( - final double normalizedRank, - final long totalN, - final QuantileSearchCriteria searchCrit) { - double naturalRank = (normalizedRank * totalN); - if (totalN <= tailRoundingFactor) { - naturalRank = Math.round(naturalRank * tailRoundingFactor) / tailRoundingFactor; - } - return (searchCrit == INCLUSIVE) ? (long)Math.ceil(naturalRank) : (long)Math.floor(naturalRank); - } - -} - diff --git a/src/main/java/org/apache/datasketches/quantilescommon/SketchPartitionLimits.java b/src/main/java/org/apache/datasketches/quantilescommon/SketchPartitionLimits.java deleted file mode 100644 index 624ec21ca..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/SketchPartitionLimits.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.QuantilesAPI.EMPTY_MSG; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This defines the methods required to compute the partition limits. - */ -public interface SketchPartitionLimits { - - /** - * Gets the maximum number of partitions this sketch will support based on the configured size K - * and the number of retained values of this sketch. - * @return the maximum number of partitions this sketch will support. - */ - int getMaxPartitions(); - - /** - * Gets the minimum partition size in items this sketch will support based on the configured size K of this - * sketch and the number of retained values of this sketch. - * @return the minimum partition size in items this sketch will support. - */ - default long getMinPartitionSizeItems() { - final long totalN = getN(); - if (totalN <= 0) { throw new SketchesArgumentException(EMPTY_MSG); } - return totalN / getMaxPartitions(); - } - - /** - * Gets the length of the input stream offered to the sketch.. - * @return the length of the input stream offered to the sketch. - */ - long getN(); - -} diff --git a/src/main/java/org/apache/datasketches/quantilescommon/SortedView.java b/src/main/java/org/apache/datasketches/quantilescommon/SortedView.java deleted file mode 100644 index f789bfc5c..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/SortedView.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -/** - * This is the base interface for the Sorted View interface hierarchy and defines the methods that are type independent. - * - *

The SortedView interface hierarchy provides a sorted view of the data retained by a quantiles-type sketch that - * would be cumbersome to get any other way. - * One could use the sketch's iterator to iterate over the contents of the sketch, - * but the result would not be sorted.

- * - *

The data from a Sorted view is an unbiased random sample of the input stream that can be used for other kinds of - * analysis not directly provided by the sketch.

- * - * @author Alexander Saydakov - * @author Lee Rhodes - */ -public interface SortedView { - - /** - * Returns the array of cumulative weights from the sketch. - * Also known as the natural ranks, which are the Natural Numbers on the interval [1, N]. - * @return the array of cumulative weights (or natural ranks). - */ - long[] getCumulativeWeights(); - - /** - * Returns the total number of items presented to the sourcing sketch. - * @return the total number of items presented to the sourcing sketch. - */ - long getN(); - - /** - * Gets the number of quantiles retained by this sorted view. - * This may be slightly different from the function with the same name when called from the originating sketch. - * @return the number of quantiles retained by this sorted view - */ - int getNumRetained(); - - /** - * Returns true if this sorted view is empty. - * @return true if this sorted view is empty. - */ - boolean isEmpty(); - - /** - * Returns an iterator for this Sorted View. - * @return an iterator for this Sorted View. - */ - SortedViewIterator iterator(); - -} - diff --git a/src/main/java/org/apache/datasketches/quantilescommon/SortedViewIterator.java b/src/main/java/org/apache/datasketches/quantilescommon/SortedViewIterator.java deleted file mode 100644 index 01af51eab..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/SortedViewIterator.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -/** - * This is the base interface for the SortedViewIterator hierarchy used with a SortedView obtained - * from a quantile-type sketch. This provides an ordered iterator over the retained quantiles of - * the associated quantile-type sketch. - * - *

Prototype example of the recommended iteration loop:

- *
{@code
- *   SortedViewIterator itr = sketch.getSortedView().iterator();
- *   while (itr.next()) {
- *     long weight = itr.getWeight();
- *     ...
- *   }
- * }
- * @author Alexander Saydakov - * @author Lee Rhodes - */ -public class SortedViewIterator { - protected final long[] cumWeights; - protected long totalN; - protected int index; - - SortedViewIterator(final long[] cumWeights) { - this.cumWeights = cumWeights; //SpotBugs EI_EXPOSE_REP2 suppressed by FindBugsExcludeFilter - this.totalN = (cumWeights.length > 0) ? cumWeights[cumWeights.length - 1] : 0; - index = -1; - } - - /** - * Gets the natural rank at the current index. - * This is equivalent to getNaturalRank(INCLUSIVE). - * - *

Don't call this before calling next() for the first time or after getting false from next().

- * - * @return the natural rank at the current index. - */ - public long getNaturalRank() { - return cumWeights[index]; - } - - /** - * Gets the natural rank at the current index (or previous index) based on the chosen search criterion. - * This is also referred to as the "cumulative weight". The natural rank is a number in the range [1, N], - * where N ({@link #getN()}) is the total number of items fed to the sketch. - * - *

Don't call this before calling next() for the first time or after getting false from next().

- * - * @param searchCrit if INCLUSIVE, includes the weight of the item at the current index in the computation of - * the natural rank. - * Otherwise, it will return the natural rank of the previous index. - * - * @return the natural rank at the current index (or previous index) based on the chosen search criterion. - */ - public long getNaturalRank(final QuantileSearchCriteria searchCrit) { - if (searchCrit == INCLUSIVE) { return cumWeights[index]; } - return (index == 0) ? 0 : cumWeights[index - 1]; - } - - /** - * Gets the total count of all items presented to the sketch. - * @return the total count of all items presented to the sketch. - */ - public long getN() { - return totalN; - } - - /** - * Gets the normalized rank at the current index. - * This is equivalent to getNormalizedRank(INCLUSIVE). - * - *

Don't call this before calling next() for the first time or after getting false from next().

- * - * @return the normalized rank at the current index - */ - public double getNormalizedRank() { - return (double) getNaturalRank() / totalN; - } - - /** - * Gets the normalized rank at the current index (or previous index) - * based on the chosen search criterion. Where normalized rank = natural rank / N ({@link #getN()}) - * and is a fraction in the range (0,1.0]. - * - *

Don't call this before calling next() for the first time or after getting false from next().

- * - * @param searchCrit if INCLUSIVE, includes the normalized rank at the current index. - * Otherwise, returns the normalized rank of the previous index. - * - * @return the normalized rank at the current index (or previous index) - * based on the chosen search criterion. - */ - public double getNormalizedRank(final QuantileSearchCriteria searchCrit) { - return (double) getNaturalRank(searchCrit) / totalN; - } - - /** - * Gets the weight contribution of the item at the current index. - * - *

Don't call this before calling next() for the first time or after getting false from next().

- * - * @return the weight contribution of the item at the current index. - */ - public long getWeight() { - if (index == 0) { return cumWeights[0]; } - return cumWeights[index] - cumWeights[index - 1]; - } - - /** - * Advances the index and checks if it is valid. - * The state of this iterator is undefined before the first call of this method. - * @return true if the next index is valid. - */ - public boolean next() { - index++; - return index < cumWeights.length; - } - -} - diff --git a/src/main/java/org/apache/datasketches/quantilescommon/package-info.java b/src/main/java/org/apache/datasketches/quantilescommon/package-info.java deleted file mode 100644 index 483636d93..000000000 --- a/src/main/java/org/apache/datasketches/quantilescommon/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package contains common tools and methods for the quantiles, kll and - * req packages. - */ -package org.apache.datasketches.quantilescommon; diff --git a/src/main/java/org/apache/datasketches/req/BaseReqSketch.java b/src/main/java/org/apache/datasketches/req/BaseReqSketch.java deleted file mode 100644 index fd44a12df..000000000 --- a/src/main/java/org/apache/datasketches/req/BaseReqSketch.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import org.apache.datasketches.quantilescommon.FloatsSortedView; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; -import org.apache.datasketches.quantilescommon.QuantilesFloatsAPI; -import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator; - -/** - * This abstract class provides a single place to define and document the public API - * for the Relative Error Quantiles Sketch. - * - * @see - * Sketching Quantiles and Ranks Tutorial - * - * @author Lee Rhodes - */ -abstract class BaseReqSketch implements QuantilesFloatsAPI { - static final byte INIT_NUMBER_OF_SECTIONS = 3; - //These two factors are used by upper and lower bounds - private static final double relRseFactor = Math.sqrt(0.0512 / INIT_NUMBER_OF_SECTIONS); //0.1306394529 - private static final double fixRseFactor = .084; - - @Override - public abstract double[] getCDF(float[] splitPoints, QuantileSearchCriteria searchCrit); - - /** - * If true, the high ranks are prioritized for better accuracy. Otherwise - * the low ranks are prioritized for better accuracy. This state is chosen during sketch - * construction. - * @return the high ranks accuracy state. - */ - public abstract boolean getHighRankAccuracyMode(); - - @Override - public abstract int getK(); - - @Override - public abstract float getMaxItem(); - - @Override - public abstract float getMinItem(); - - /** - * Returns an a priori estimate of relative standard error (RSE, expressed as a number in [0,1]). - * Derived from Lemma 12 in https://arxiv.org/abs/2004.01668v2, but the constant factors were - * adjusted based on empirical measurements. - * - * @param k the given size of k - * @param rank the given normalized rank, a number in [0,1]. - * @param hra if true High Rank Accuracy mode is being selected, otherwise, Low Rank Accuracy. - * @param totalN an estimate of the total number of items submitted to the sketch. - * @return an a priori estimate of relative standard error (RSE, expressed as a number in [0,1]). - */ - public static double getRSE(final int k, final double rank, final boolean hra, final long totalN) { - return getRankUB(k, 2, rank, 1, hra, totalN) - rank; //more conservative to assume > 1 level - } - - @Override - public abstract long getN(); - - @Override - public abstract double[] getPMF(float[] splitPoints, QuantileSearchCriteria searchCrit); - - @Override - public abstract float getQuantile(double rank, QuantileSearchCriteria searchCrit); - - @Override - public abstract float[] getQuantiles(double[] normRanks, QuantileSearchCriteria searchCrit); - - @Override - public abstract float getQuantileLowerBound(double rank); - - /** - * Gets an approximate lower bound of the quantile associated with the given rank. - * @param rank the given normalized rank, a number between 0 and 1.0. - * @param numStdDev the number of standard deviations. Must be 1, 2, or 3. - * @return an approximate lower bound quantile, if it exists. - */ - public abstract float getQuantileLowerBound(double rank, int numStdDev); - - @Override - public abstract float getQuantileUpperBound(double rank); - - /** - * Gets an approximate upper bound of the quantile associated with the given rank. - * @param rank the given normalized rank, a number between 0 and 1.0. - * @param numStdDev the number of standard deviations. Must be 1, 2, or 3. - * @return an approximate upper bound quantile, if it exists. - */ - public abstract float getQuantileUpperBound(double rank, int numStdDev); - - @Override - public abstract double getRank(float quantile, QuantileSearchCriteria searchCrit); - - /** - * Gets an approximate lower bound rank of the given normalized rank. - * @param rank the given normalized rank, a number between 0 and 1.0. - * @param numStdDev the number of standard deviations. Must be 1, 2, or 3. - * @return an approximate lower bound rank. - */ - public abstract double getRankLowerBound(double rank, int numStdDev); - - @Override - public abstract double[] getRanks(float[] quantiles, QuantileSearchCriteria searchCrit); - - /** - * Gets an approximate upper bound rank of the given rank. - * @param rank the given rank, a number between 0 and 1.0. - * @param numStdDev the number of standard deviations. Must be 1, 2, or 3. - * @return an approximate upper bound rank. - */ - public abstract double getRankUpperBound(double rank, int numStdDev); - - @Override - public abstract int getNumRetained(); - - @Override - public abstract int getSerializedSizeBytes(); - - @Override - public abstract FloatsSortedView getSortedView(); - - @Override - public abstract boolean isEmpty(); - - @Override - public abstract boolean isEstimationMode(); - - @Override - public boolean isReadOnly() { - return false; - } - - @Override - public abstract QuantilesFloatsSketchIterator iterator(); - - /** - * Merge other sketch into this one. The other sketch is not modified. - * @param other sketch to be merged into this one. - * @return this - */ - public abstract ReqSketch merge(final ReqSketch other); - - /** - * {@inheritDoc} - * - *

The parameters k, highRankAccuracy, and reqDebug will not change.

- */ - @Override - public abstract void reset(); - - @Override - public abstract byte[] toByteArray(); - - @Override - public abstract String toString(); - - @Override - public abstract void update(final float item); - - /** - * A detailed, human readable view of the sketch compactors and their data. - * Each compactor string is prepended by the compactor lgWeight, the current number of retained - * quantiles of the compactor and the current nominal capacity of the compactor. - * @param fmt the format string for the quantiles; example: "%4.0f". - * @param allData all the retained quantiles for the sketch will be output by - * compactor level. Otherwise, just a summary will be output. - * @return a detailed view of the compactors and their data - */ - public abstract String viewCompactorDetail(String fmt, boolean allData); - - static boolean exactRank(final int k, final int levels, final double rank, final boolean hra, final long totalN) { - final long baseCap = (long)k * INIT_NUMBER_OF_SECTIONS; - if ((levels == 1) || (totalN <= baseCap)) { return true; } - final double exactRankThresh = (double)baseCap / totalN; - return (hra ? (rank >= (1.0 - exactRankThresh)) : (rank <= exactRankThresh)); - } - - static double getRankLB(final int k, final int levels, final double rank, - final int numStdDev, final boolean hra, final long totalN) { - if (exactRank(k, levels, rank, hra, totalN)) { return rank; } - final double relative = (relRseFactor / k) * (hra ? 1.0 - rank : rank); - final double fixed = fixRseFactor / k; - final double lbRel = rank - (numStdDev * relative); - final double lbFix = rank - (numStdDev * fixed); - return Math.max(lbRel, lbFix); - } - - static double getRankUB(final int k, final int levels, final double rank, - final int numStdDev, final boolean hra, final long totalN) { - if (exactRank(k, levels, rank, hra, totalN)) { return rank; } - final double relative = (relRseFactor / k) * (hra ? 1.0 - rank : rank); - final double fixed = fixRseFactor / k; - final double ubRel = rank + (numStdDev * relative); - final double ubFix = rank + (numStdDev * fixed); - return Math.min(ubRel, ubFix); - } - -} diff --git a/src/main/java/org/apache/datasketches/req/FloatBuffer.java b/src/main/java/org/apache/datasketches/req/FloatBuffer.java deleted file mode 100755 index 1c63906b9..000000000 --- a/src/main/java/org/apache/datasketches/req/FloatBuffer.java +++ /dev/null @@ -1,465 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.positional.PositionalSegment; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.InequalitySearch; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; - -/** - * A special buffer of floats specifically designed to support the ReqCompactor class. - * - * @author Lee Rhodes - */ -class FloatBuffer { - private float[] arr_; - private int count_; - private int capacity_; - private final int delta_; - private boolean sorted_; - private final boolean spaceAtBottom_; //tied to hra - - /** - * Constructs an new empty FloatBuffer with an initial capacity specified by - * the capacity argument. - * - * @param capacity the initial capacity. - * @param delta add space in increments of this size - * @param spaceAtBottom if true, create any extra space at the bottom of the buffer, - * otherwise, create any extra space at the top of the buffer. - */ - FloatBuffer(final int capacity, final int delta, final boolean spaceAtBottom) { - arr_ = new float[capacity]; - count_ = 0; - capacity_ = capacity; - delta_ = delta; - sorted_ = true; - spaceAtBottom_ = spaceAtBottom; - } - - /** - * Copy Constructor - * @param buf the FloatBuffer to be copied into this one - */ - FloatBuffer(final FloatBuffer buf) { - arr_ = buf.arr_.clone(); - count_ = buf.count_; - capacity_ = buf.capacity_; - delta_ = buf.delta_; - sorted_ = buf.sorted_; - spaceAtBottom_ = buf.spaceAtBottom_; - } - - /** - * Exact construction from elements. - * The active region must be properly positioned in the array. - * @param arr the array to be used directly as the internal array - * @param count the number of active elements in the given array - * @param capacity the initial capacity - * @param delta add space in increments of this size - * @param sorted true if already sorted - * @param spaceAtBottom if true, create any extra space at the bottom of the buffer, - * otherwise, create any extra space at the top of the buffer. - */ - private FloatBuffer(final float[] arr, final int count, final int capacity, final int delta, - final boolean sorted, final boolean spaceAtBottom) { - arr_ = arr; - count_ = count; - capacity_ = capacity; - delta_ = delta; - sorted_ = sorted; - spaceAtBottom_ = spaceAtBottom; - } - - /** - * Used by ReqSerDe. The array is only the active region and will be positioned - * based on capacity, delta, and sab. This copies over the sorted flag. - * @param arr the active items extracted from the deserialization. - * @param count the number of active items - * @param capacity the capacity of the internal array - * @param delta add space in this increment - * @param sorted if the incoming array is sorted - * @param sab equivalent to the HRA flag, e.g., space-at-bottom. - * @return a new FloatBuffer - */ - static FloatBuffer reconstruct( - final float[] arr, - final int count, - final int capacity, - final int delta, - final boolean sorted, - final boolean sab //hra - ) { - final float[] farr = new float[capacity]; - if (sab) { - System.arraycopy(arr, 0, farr, capacity - count, count); - } else { - System.arraycopy(arr, 0, farr, 0, count); - } - return new FloatBuffer(farr, count, capacity, delta, sorted, sab); - } - - /** - * Wraps the given array to use as the internal array; thus no copies. For internal use. - * @param arr the given array - * @param isSorted set true, if incoming array is already sorted. - * @param spaceAtBottom if true, create any extra space at the bottom of the buffer, - * otherwise, create any extra space at the top of the buffer. - * @return this, which will be sorted, if necessary. - */ - static FloatBuffer wrap(final float[] arr, final boolean isSorted, final boolean spaceAtBottom) { - final FloatBuffer buf = new FloatBuffer(arr, arr.length, arr.length, 0, isSorted, spaceAtBottom); - buf.sort(); - return buf; - } - - /** - * Appends the given item to the active array and increments the active count. - * This will expand the array if necessary. - * @param item the given item - * @return this - */ - FloatBuffer append(final float item) { - ensureSpace(1); - final int index = spaceAtBottom_ ? capacity_ - count_ - 1 : count_; - arr_[index] = item; - count_++; - sorted_ = false; - return this; - } - - /** - * Ensures that the capacity of this FloatBuffer is at least newCapacity. - * If newCapacity < capacity(), no action is taken. - * @param newCapacity the new desired capacity - * @return this - */ - FloatBuffer ensureCapacity(final int newCapacity) { - if (newCapacity > capacity_) { - final float[] out = new float[newCapacity]; - final int srcPos = spaceAtBottom_ ? capacity_ - count_ : 0; - final int destPos = spaceAtBottom_ ? newCapacity - count_ : 0; - System.arraycopy(arr_, srcPos, out, destPos, count_); - arr_ = out; - capacity_ = newCapacity; - } - return this; - } - - /** - * Ensures that the space remaining (capacity() - getCount()) is at least the given space. - * @param space the requested space remaining - * @return this - */ - private FloatBuffer ensureSpace(final int space) { - if ((count_ + space) > capacity_) { - final int newCap = count_ + space + delta_; - ensureCapacity(newCap); - } - return this; - } - - /** - * Returns a reference to the internal quantiles array. Be careful and don't modify this array! - * @return the internal quantiles array. - */ - float[] getArray() { - return arr_; - } - - /** - * Gets the current capacity of this FloatBuffer. The capacity is the total amount of storage - * currently available without expanding the array. - * - * @return the current capacity - */ - int getCapacity() { - return capacity_; - } - - /** - * Returns the count of items based on the given criteria. - * Also used in test. - * @param item the given item - * @param searchCrit the chosen criterion: LT, LT Strict, or LE - * @return count of items based on the given criterion. - */ - int getCountWithCriterion(final float item, final QuantileSearchCriteria searchCrit) { - assert !Float.isNaN(item) : "Float items must not be NaN."; - if (!sorted_) { sort(); } //we must be sorted! - int low = 0; //Initialized to space at top - int high = count_ - 1; - if (spaceAtBottom_) { - low = capacity_ - count_; - high = capacity_ - 1; - } - final InequalitySearch crit = (searchCrit == INCLUSIVE) ? InequalitySearch.LE : InequalitySearch.LT; - final int index = InequalitySearch.find(arr_, low, high, item, crit); - return index == -1 ? 0 : (index - low) + 1; - } - - /** - * Returns a sorted FloatBuffer of the odd or even offsets from the range startOffset (inclusive) - * to endOffset (exclusive). The size of the range must be of even size. - * The offsets are with respect to the start of the active region and independent of the - * location of the active region within the overall buffer. The requested region will be sorted - * first. - * @param startOffset the starting offset within the active region - * @param endOffset the end offset within the active region, exclusive - * @param odds if true, return the odds, otherwise return the evens. - * @return the selected odds from the range - */ - FloatBuffer getEvensOrOdds(final int startOffset, final int endOffset, final boolean odds) { - final int start = spaceAtBottom_ ? (capacity_ - count_) + startOffset : startOffset; - final int end = spaceAtBottom_ ? (capacity_ - count_) + endOffset : endOffset; - sort(); - final int range = endOffset - startOffset; - if ((range & 1) == 1) { - throw new SketchesArgumentException("Input range size must be even"); - } - final int odd = odds ? 1 : 0; - final float[] out = new float[range / 2]; - for (int i = start + odd, j = 0; i < end; i += 2, j++) { - out[j] = arr_[i]; - } - return wrap(out, true, spaceAtBottom_); - } - - /** - * Gets an item from the backing array given its index. - * Only used in test or debug. - * @param index the given index - * @return an item given its backing array index - */ - float getItemFromIndex(final int index) { - return arr_[index]; - } - - /** - * Gets an item given its offset in the active region - * @param offset the given offset in the active region - * @return an item given its offset - */ - float getItem(final int offset) { - final int index = spaceAtBottom_ ? (capacity_ - count_) + offset : offset; - return arr_[index]; - } - - /** - * Returns the delta margin - * @return the delta margin - */ - int getDelta() { - return delta_; - } - - /** - * Returns the active item count. - * - * @return the active item count of this buffer. - */ - int getCount() { - return count_; - } - - /** - * Gets available space, which is getCapacity() - getCount(). - * When spaceAtBottom is true this is the start position for active data, otherwise it is zero. - * @return available space - */ - int getSpace() { - return capacity_ - count_; - } - - /** - * Returns the space at bottom flag - * @return the space at bottom flag - */ - boolean isSpaceAtBottom() { - return spaceAtBottom_; - } - - /** - * Returns true if getCount() == 0. - * @return true if getCount() == 0. - */ - boolean isEmpty() { - return count_ == 0; - } - - /** - * Returns true iff this is exactly equal to that FloatBuffer. - * @param that the other buffer - * @return true iff this is exactly equal to that FloatBuffer. - */ - boolean isEqualTo(final FloatBuffer that) { - if ((capacity_ != that.capacity_) - || (count_ != that.count_) - || (delta_ != that.delta_) - || (sorted_ != that.sorted_) - || (spaceAtBottom_ != that.spaceAtBottom_)) { return false; } - for (int i = 0; i < capacity_; i++) { - if (arr_[i] != that.arr_[i]) { return false; } - } - return true; - } - - /** - * Returns true if this FloatBuffer is sorted. - * @return true if sorted - */ - boolean isSorted() { - return sorted_; - } - - /** - * Merges the incoming sorted buffer into this sorted buffer. - * @param bufIn sorted buffer in - * @return this - */ - FloatBuffer mergeSortIn(final FloatBuffer bufIn) { - if (!sorted_ || !bufIn.isSorted()) { - throw new SketchesArgumentException("Both buffers must be sorted."); - } - final float[] arrIn = bufIn.getArray(); //may be larger than its item count. - final int bufInLen = bufIn.getCount(); - ensureSpace(bufInLen); - final int totLen = count_ + bufInLen; - if (spaceAtBottom_) { //scan up, insert at bottom - final int tgtStart = capacity_ - totLen; - int i = capacity_ - count_; - int j = bufIn.capacity_ - bufIn.count_; - for (int k = tgtStart; k < capacity_; k++) { - if ((i < capacity_) && (j < bufIn.capacity_)) { //both valid - arr_[k] = arr_[i] <= arrIn[j] ? arr_[i++] : arrIn[j++]; - } else if (i < capacity_) { //i is valid - arr_[k] = arr_[i++]; - } else if (j < bufIn.capacity_) { //j is valid - arr_[k] = arrIn[j++]; - } else { - break; - } - } - } else { //scan down, insert at top - int i = count_ - 1; - int j = bufInLen - 1; - for (int k = totLen; k-- > 0; ) { - if ((i >= 0) && (j >= 0)) { //both valid - arr_[k] = arr_[i] >= arrIn[j] ? arr_[i--] : arrIn[j--]; - } else if (i >= 0) { //i is valid - arr_[k] = arr_[i--]; - } else if (j >= 0) { //j is valid - arr_[k] = arrIn[j--]; - } else { - break; - } - } - } - count_ += bufInLen; - sorted_ = true; - return this; - } - - /** - * Sorts the active region; - * @return this - */ - FloatBuffer sort() { - if (sorted_) { return this; } - final int start = spaceAtBottom_ ? capacity_ - count_ : 0; - final int end = spaceAtBottom_ ? capacity_ : count_; - Arrays.sort(arr_, start, end); - sorted_ = true; - return this; - } - - // This only serializes count * floats - byte[] floatsToBytes() { - final int bytes = Float.BYTES * count_; - final byte[] arr = new byte[bytes]; - final PositionalSegment posSeg = PositionalSegment.wrap(MemorySegment.ofArray(arr)); - if (spaceAtBottom_) { - posSeg.setFloatArray(arr_, capacity_ - count_, count_); - } else { - posSeg.setFloatArray(arr_, 0, count_); - } - assert posSeg.getPosition() == bytes; - return arr; - } - - /** - * Returns a printable formatted string of the items of this FloatBuffer separated by a single space. - * @param fmt The format for each printed item. - * @param width the number of items to print per line - * @return a printable, formatted string of the items of this buffer. - */ - String toHorizList(final String fmt, final int width) { - final StringBuilder sb = new StringBuilder(); - final String spaces = " "; - final int start = spaceAtBottom_ ? capacity_ - count_ : 0; - final int end = spaceAtBottom_ ? capacity_ : count_; - int cnt = 0; - sb.append(spaces); - for (int i = start; i < end; i++) { - final float v = arr_[i]; - final String str = String.format(fmt, v); - if ((i > start) && ((++cnt % width) == 0)) { sb.append(LS).append(spaces); } - sb.append(str); - } - return sb.toString(); - } - - /** - * Trims the capacity of this FloatBuffer to the active count. - * @return this - */ - FloatBuffer trimCapacity() { - if (count_ < capacity_) { - final float[] out = new float[count_]; - final int start = spaceAtBottom_ ? capacity_ - count_ : 0; - System.arraycopy(arr_, start, out, 0, count_); - capacity_ = count_; - arr_ = out; - } - return this; - } - - /** - * Trims the count_ to newCount. If newCount > count_ this does nothing and returns. - * Otherwise, the internal count_ is reduced to the given newCount. There is no clearing of - * the remainder of the capacity. Any items there are considered garbage. - * - * @param newCount the new active count - * @return this - */ - FloatBuffer trimCount(final int newCount) { - if (newCount < count_) { - count_ = newCount; - } - return this; - } -} diff --git a/src/main/java/org/apache/datasketches/req/ReqCompactor.java b/src/main/java/org/apache/datasketches/req/ReqCompactor.java deleted file mode 100644 index 151cd8ff3..000000000 --- a/src/main/java/org/apache/datasketches/req/ReqCompactor.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import static java.lang.Math.round; -import static org.apache.datasketches.common.Util.numberOfTrailingOnes; -import static org.apache.datasketches.req.BaseReqSketch.INIT_NUMBER_OF_SECTIONS; -import static org.apache.datasketches.req.ReqSketch.MIN_K; -import static org.apache.datasketches.req.ReqSketch.NOM_CAP_MULT; - -import java.lang.foreign.MemorySegment; -import java.util.Random; - -import org.apache.datasketches.common.positional.PositionalSegment; -import org.apache.datasketches.req.ReqSketch.CompactorReturn; - -/** - * The compactor class for the ReqSketch - * @author Lee Rhodes - */ -class ReqCompactor { - //finals - private static final double SQRT2 = Math.sqrt(2.0); - private final byte lgWeight; - private final boolean hra; - //state variables - private long state; //State of the deterministic compaction schedule - private float sectionSizeFlt; - private int sectionSize; //initialized with k, minimum 4 - private byte numSections; //# of sections, initial size 3 - private boolean coin; //true or false at random for each compaction - //objects - private FloatBuffer buf; - private final ReqDebug reqDebug = null; - - /** - * Normal Constructor - * @param lgWeight the lgWeight of this compactor - * @param hra High Rank Accuracy - * @param sectionSize initially the size of k - * @param reqDebug The debug signaling interface - */ - ReqCompactor( - final byte lgWeight, - final boolean hra, - final int sectionSize, - final ReqDebug reqDebug) { - this.lgWeight = lgWeight; - this.hra = hra; - this.sectionSize = sectionSize; - sectionSizeFlt = sectionSize; - state = 0; - coin = false; - numSections = INIT_NUMBER_OF_SECTIONS; - final int nomCap = getNomCapacity(); - buf = new FloatBuffer(2 * nomCap, nomCap, hra); - } - - /** - * Copy Constructor - * @param other the compactor to be copied into this one - */ - ReqCompactor(final ReqCompactor other) { - lgWeight = other.lgWeight; - hra = other.hra; - sectionSizeFlt = other.sectionSizeFlt; - numSections = other.numSections; - sectionSize = other.sectionSize; - state = other.state; - coin = other.coin; - buf = new FloatBuffer(other.buf); - } - - /** - * Construct from elements. The buffer will need to be constructed first - */ - ReqCompactor( - final byte lgWeight, - final boolean hra, - final long state, - final float sectionSizeFlt, - final byte numSections, - final FloatBuffer buf) { - this.lgWeight = lgWeight; - this.hra = hra; - this.buf = buf; - this.sectionSizeFlt = sectionSizeFlt; - this.numSections = numSections; - this.state = state; - coin = false; - sectionSize = nearestEven(sectionSizeFlt); - //ReqDebug left at null - } - - /** - * Perform a compaction operation on this compactor - * @return the array of items to be promoted to the next level compactor - */ - FloatBuffer compact(final CompactorReturn cReturn, final Random rand) { - if (reqDebug != null) { reqDebug.emitCompactingStart(lgWeight); } - final int startRetItems = buf.getCount(); - final int startNomCap = getNomCapacity(); - // choose a part of the buffer to compact - final int secsToCompact = Math.min(numberOfTrailingOnes(state) + 1, numSections); - final long compactionRange = computeCompactionRange(secsToCompact); - final int compactionStart = (int) (compactionRange & 0xFFFF_FFFFL); //low 32 - final int compactionEnd = (int) (compactionRange >>> 32); //high 32 - assert (compactionEnd - compactionStart) >= 2; - - if ((state & 1L) == 1L) { coin = !coin; } //if numCompactions odd, flip coin; - else { coin = rand.nextBoolean(); } //random coin flip - - final FloatBuffer promote = buf.getEvensOrOdds(compactionStart, compactionEnd, coin); - - if (reqDebug != null) { - reqDebug.emitCompactionDetail(compactionStart, compactionEnd, secsToCompact, - promote.getCount(), coin); - } - - buf.trimCount(buf.getCount() - (compactionEnd - compactionStart)); - state += 1; - ensureEnoughSections(); - cReturn.deltaRetItems = (buf.getCount() - startRetItems) + promote.getCount(); - cReturn.deltaNomSize = getNomCapacity() - startNomCap; - if (reqDebug != null) { reqDebug.emitCompactionDone(lgWeight); } - return promote; - } //End Compact - - /** - * Gets a reference to this compactor's internal FloatBuffer - * @return a reference to this compactor's internal FloatBuffer - */ - FloatBuffer getBuffer() { return buf; } - - boolean getCoin() { - return coin; - } - - /** - * Gets the lgWeight of this buffer - * @return the lgWeight of this buffer - */ - byte getLgWeight() { - return lgWeight; - } - - /** - * Gets the current nominal capacity of this compactor. - * @return the current nominal capacity of this compactor. - */ - final int getNomCapacity() { //called from constructor - return NOM_CAP_MULT * numSections * sectionSize; - } - - /** - * Serialize state(8) sectionSizeFlt(4), numSections(1), lgWeight(1), pad(2), count(4) + floatArr - * @return required bytes to serialize. - */ - int getSerializationBytes() { - final int count = buf.getCount(); - return 8 + 4 + 1 + 1 + 2 + 4 + (count * Float.BYTES); // 20 + array - } - - int getNumSections() { - return numSections; - } - - int getSectionSize() { - return sectionSize; - } - - float getSectionSizeFlt() { - return sectionSizeFlt; - } - - long getState() { - return state; - } - - boolean isHighRankAccuracy() { - return hra; - } - - /** - * Merge the other given compactor into this one. They both must have the - * same lgWeight - * @param other the other given compactor - * @return this - */ - ReqCompactor merge(final ReqCompactor other) { - assert lgWeight == other.lgWeight; - state |= other.state; - while (ensureEnoughSections()) { /* do nothing */ } - buf.sort(); - final FloatBuffer otherBuf = new FloatBuffer(other.buf); - otherBuf.sort(); - if (otherBuf.getCount() > buf.getCount()) { - otherBuf.mergeSortIn(buf); - buf = otherBuf; - } else { - buf.mergeSortIn(otherBuf); - } - return this; - } - - /** - * Adjust the sectionSize and numSections if possible. - * @return true if the SectionSize and NumSections were adjusted. - */ - private boolean ensureEnoughSections() { - final float szf; - final int ne; - if ((state >= (1L << (numSections - 1))) - && (sectionSize > MIN_K) - && ((ne = nearestEven(szf = (float)(sectionSizeFlt / SQRT2))) >= MIN_K)) - { - sectionSizeFlt = szf; - sectionSize = ne; - numSections <<= 1; - buf.ensureCapacity(2 * getNomCapacity()); - if (reqDebug != null) { reqDebug.emitAdjSecSizeNumSec(lgWeight); } - return true; - } - return false; - } - - /** - * Computes the start and end indices of the compacted region - * @param secsToCompact the number of contiguous sections to compact - * @return the start and end indices of the compacted region - */ - private long computeCompactionRange(final int secsToCompact) { - final int bufLen = buf.getCount(); - int nonCompact = (getNomCapacity() / 2) + ((numSections - secsToCompact) * sectionSize); - //make compacted region even: - nonCompact = ((bufLen - nonCompact) & 1) == 1 ? nonCompact + 1 : nonCompact; - final long low = hra ? 0 : nonCompact; - final long high = hra ? bufLen - nonCompact : bufLen; - return (high << 32) + low; - } - - /** - * Returns the nearest even integer to the given float. Also used by test. - * @param fltVal the given float - * @return the nearest even integer to the given float. - */ - static final int nearestEven(final float fltVal) { - return (int) round(fltVal / 2.0) << 1; - } - - /** - * ReqCompactor SERIALIZATION FORMAT. - * - *

Low significance bytes of this data structure are on the right just for visualization. - * The multi-byte primitives are stored in native byte order. - * The byte primitives are treated as unsigned. Multibyte primitives are indicated with "*" and - * their size depends on the specific implementation.

- * - *

The binary format for a compactor:

- * - *
-   * Binary Format. Starting offset is either 24 or 8, both are 8-byte aligned.
-   *
-   * +Long Adr / +Byte Offset
-   *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |    0   |
-   *  0   ||-----------------------------state-------------------------------------|
-   *
-   *      ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |    8   |
-   *  1   ||----(empty)------|-#Sects-|--lgWt--|------------sectionSizeFlt---------|
-   *
-   *      ||        |        |        |        |        |        |        |   16   |
-   *  2   ||--------------floats[]-------------|---------------count---------------|
-   *
-   * 
- */ - byte[] toByteArray() { - final int bytes = getSerializationBytes(); - final byte[] arr = new byte[bytes]; - final PositionalSegment posSeg = PositionalSegment.wrap(MemorySegment.ofArray(arr)); - posSeg.setLong(state); - posSeg.setFloat(sectionSizeFlt); - posSeg.setByte(lgWeight); - posSeg.setByte(numSections); - posSeg.incrementPosition(2); //pad 2 - //buf.sort(); //sort if necessary - posSeg.setInt(buf.getCount()); //count - posSeg.setByteArray(buf.floatsToBytes(), 0, Float.BYTES * buf.getCount()); - assert posSeg.getPosition() == bytes; - return arr; - } - - /** - * Returns a printable formatted prefix string summarizing the list. - * The first number is the compactor height. the second number in brackets is the current count - * of the compactor buffer. The third number in brackets is the nominal capacity of the compactor. - * @return a printable formatted prefix string summarizing the list. - */ - String toListPrefix() { - final int h = getLgWeight(); - final int len = buf.getCount(); - final int nom = getNomCapacity(); - final int secSz = getSectionSize(); - final int numSec = getNumSections(); - final long num = getState(); - return String.format( - " C:%d Len:%d NomSz:%d SecSz:%d NumSec:%d State:%d", - h, len, nom, secSz, numSec, num); - } - -} diff --git a/src/main/java/org/apache/datasketches/req/ReqDebug.java b/src/main/java/org/apache/datasketches/req/ReqDebug.java deleted file mode 100644 index e0a72698d..000000000 --- a/src/main/java/org/apache/datasketches/req/ReqDebug.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -/** - * The signaling interface that allows comprehensive analysis of the ReqSketch and ReqCompactor - * while eliminating code clutter in the main classes. The implementation of this interface can be - * found in the test tree. - * - * @author Lee Rhodes - */ -public interface ReqDebug { - - //Sketch signals - - /** - * Emit the start signal - * @param sk the sketch - */ - void emitStart(ReqSketch sk); - - /** - * Emit Start Compress - */ - void emitStartCompress(); - - /** - * Emit compress done. - */ - void emitCompressDone(); - - /** - * Emit all horizontal lists - */ - void emitAllHorizList(); - - /** - * Emit Must add compactor - */ - void emitMustAddCompactor(); - - //Compactor signals - - /** - * Emit Compaction Start. - * @param lgWeight compactor lgWeight or height - */ - void emitCompactingStart(byte lgWeight); - - /** - * Emit new compactor configuration - * @param lgWeight the log weight - */ - void emitNewCompactor(byte lgWeight); - - /** - * Emit adjusting section size and number of sections. - * @param lgWeight the log weight - */ - void emitAdjSecSizeNumSec(byte lgWeight); - - /** - * Emit Compaction details. - * @param compactionStart the offset of compaction start - * @param compactionEnd the offset of compaction end - * @param secsToCompact the number of sections to compact - * @param promoteLen the length of the promotion field - * @param coin the state of the random coin. - */ - void emitCompactionDetail(int compactionStart, int compactionEnd, - int secsToCompact, int promoteLen, boolean coin); - - /** - * Emit compaction done and number of compactions so far. - * @param lgWeight the log weight - */ - void emitCompactionDone(byte lgWeight); - -} diff --git a/src/main/java/org/apache/datasketches/req/ReqSerDe.java b/src/main/java/org/apache/datasketches/req/ReqSerDe.java deleted file mode 100644 index ab1fdc391..000000000 --- a/src/main/java/org/apache/datasketches/req/ReqSerDe.java +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static java.lang.Math.round; - -import java.lang.foreign.MemorySegment; -import java.util.ArrayList; -import java.util.List; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.positional.PositionalSegment; - -/** - * This class handles serialization and deserialization. - * - *

ReqSketch SERIALIZATION FORMAT.

- * - *

Low significance bytes of this data structure are on the right just for visualization. - * The multi-byte primitives are stored in native byte order. - * The byte primitives are treated as unsigned. Multibyte primitives are indicated with "*" and - * their size depends on the specific implementation.

- * - *

The ESTIMATION binary format for an estimating sketch with > one item:

- * - *
-   * Normal Binary Format:
-   * PreInts=4
-   * Empty=false
-   * RawItems=false
-   * # Constructors > 1, C0 to Cm, whatever is required
-   *
-   * Long Adr / Byte Offset
-   *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |     0              |
-   *  0   || (empty)| #Ctors |        K        | Flags  |FamID=17| SerVer |     PreInts = 4    |
-   *
-   *      ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |     8              |
-   *  1   ||-----------------------------------N-----------------------------------------------|
-   *
-   *      ||        |        |        |        |        |        |        |    16              |
-   *      ||--------------MaxItem*----------------------|--------------MinItem*----------------|
-   *
-   *      ||        |        |        |        |        |        |        |                    |
-   *      ||----------------C1*-------------------------|----------------C0*-------------------|
-   * 
- * - *

An EXACT-binary format sketch has only one serialized compactor:

- * - *
-   * PreInts=2
-   * Empty=false
-   * RawItems=false
-   * # Constructors=C0=1
-   *
-   * Long Adr / Byte Offset
-   *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |     0              |
-   *  0   || (empty)|    1   |        K        | Flags  |FamID=17| SerVer |     PreInts = 2    |
-   *
-   *      ||        |        |        |        |        |        |        |     8              |
-   *  1   ||                                   |-------------------------C0*-------------------|
-   * 
- * - *

A RAW ITEMS binary format sketch has only a few items:

- * - *
-   * PreInts=2
-   * Empty=false
-   * RawItems=true
-   * # Constructors=C0=1
-   *
-   * Long Adr / Byte Offset
-   *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |     0              |
-   *  0   || #Raw   |    1   |        K        | Flags  |FamID=17| SerVer |     PreInts = 2    |
-   *
-   *      ||        |        |        |        |        |        |        |     8              |
-   *  1   ||                                   |------------------------ITEM*-----------------|
-   * 
- * - *

An EMPTY binary format sketch has only 8 bytes including a reserved empty byte: - * - *

-   * PreInts=2
-   * Empty=true
-   * RawItems=false
-   * # Constructors==C0=1
-   *
-   * Long Adr / Byte Offset
-   *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |     0              |
-   *  0   || (empty)|    0   |        K        | Flags  |FamID=17| SerVer |     PreInts = 2    |
-   * 
- *
-   *
-   * Flags:
-   * Bit 0 : Endianness, reserved
-   * Bit 1 : ReadOnly, reserved
-   * Bit 2 : Empty
-   * Bit 3 : HRA
-   * Bit 4 : Raw Items
-   * Bit 5 : L0 Sorted
-   * Bit 6 : reserved
-   * Bit 7 : reserved
-   * 
- * - * @author Lee Rhodes - */ -class ReqSerDe { - enum SerDeFormat { EMPTY, RAWITEMS, EXACT, ESTIMATION } - - private static final byte SER_VER = 1; - private static final byte FAMILY_ID = (byte) Family.REQ.getID(); - - static ReqSketch heapify(final MemorySegment seg) { - final PositionalSegment posSeg = PositionalSegment.wrap(seg); - //Extract first 8 bytes - final byte preInts = posSeg.getByte(); - final byte serVer = posSeg.getByte(); - assert serVer == (byte)1; - final byte familyId = posSeg.getByte(); - assert familyId == 17; - // Extract flags - final int flags = posSeg.getByte() & 0xFF; - final boolean empty = (flags & 4) > 0; - final boolean hra = (flags & 8) > 0; - final boolean rawItems = (flags & 16) > 0; - final boolean lvl0Sorted = (flags & 32) > 0; - // remainder fields - final int k = posSeg.getShort() & 0xFFFF; - final int numCompactors = posSeg.getByte() & 0xFF; - final int numRawItems = posSeg.getByte() & 0xFF; - // extract different serialization formats - final SerDeFormat deserFormat = getDeserFormat(empty, rawItems, numCompactors); - switch (deserFormat) { - case EMPTY: { - assert preInts == 2; - return new ReqSketch(k, hra, null); - } - case RAWITEMS: { - assert preInts == 2; - final ReqSketch sk = new ReqSketch(k, hra, null); - for (int i = 0; i < numRawItems; i++) { sk.update(posSeg.getFloat()); } - return sk; - } - case EXACT: { - assert preInts == 2; - final Compactor compactor = extractCompactor(posSeg, lvl0Sorted, hra); - //Construct sketch - final long totalN = compactor.count; - final float minItem = compactor.minItem; - final float maxItem = compactor.maxItem; - final List compactors = new ArrayList<>(); - compactors.add(compactor.reqCompactor); - final ReqSketch sk = new ReqSketch(k, hra, totalN, minItem, maxItem, compactors); - sk.setMaxNomSize(sk.computeMaxNomSize()); - sk.setRetainedItems(sk.computeTotalRetainedItems()); - return sk; - } - default: { //ESTIMATION - assert preInts == 4; - final long totalN = posSeg.getLong(); - final float minItem = posSeg.getFloat(); - final float maxItem = posSeg.getFloat(); - - final List compactors = new ArrayList<>(); - for (int i = 0; i < numCompactors; i++) { - final boolean level0sorted = i == 0 ? lvl0Sorted : true; - final Compactor compactor = extractCompactor(posSeg, level0sorted, hra); - compactors.add(compactor.reqCompactor); - } - final ReqSketch sk = new ReqSketch(k, hra, totalN, minItem, maxItem, compactors); - sk.setMaxNomSize(sk.computeMaxNomSize()); - sk.setRetainedItems(sk.computeTotalRetainedItems()); - return sk; - } - } - } - - static final Compactor extractCompactor(final PositionalSegment posSeg, final boolean lvl0Sorted, - final boolean hra) { - final long state = posSeg.getLong(); - final float sectionSizeFlt = posSeg.getFloat(); - final int sectionSize = round(sectionSizeFlt); - final byte lgWt = posSeg.getByte(); - final byte numSections = posSeg.getByte(); - posSeg.incrementPosition(2); - final int count = posSeg.getInt(); - final float[] arr = new float[count]; - posSeg.getFloatArray(arr, 0, count); - float minItem = Float.POSITIVE_INFINITY; - float maxItem = Float.NEGATIVE_INFINITY; - for (int i = 0; i < count; i++) { - minItem = min(minItem, arr[i]); - maxItem = max(maxItem, arr[i]); - } - final int delta = 2 * sectionSize * numSections; - final int nomCap = 2 * delta; - final int cap = max(count, nomCap); - final FloatBuffer fltBuf = FloatBuffer.reconstruct(arr, count, cap, delta, lvl0Sorted, hra); - final ReqCompactor reqCompactor = - new ReqCompactor(lgWt, hra, state, sectionSizeFlt, numSections, fltBuf); - return new Compactor(reqCompactor, minItem, maxItem, count); - } - - static class Compactor { - ReqCompactor reqCompactor; - float minItem; - float maxItem; - int count; - - Compactor(final ReqCompactor reqCompactor, final float minItem, final float maxItem, - final int count) { - this.reqCompactor = reqCompactor; - this.minItem = minItem; - this.maxItem = maxItem; - this.count = count; - } - } - - private static byte getFlags(final ReqSketch sk) { - final boolean rawItems = sk.getN() <= ReqSketch.MIN_K; - final boolean level0Sorted = sk.getCompactors().get(0).getBuffer().isSorted(); - final int flags = (sk.isEmpty() ? 4 : 0) - | (sk.getHighRankAccuracyMode() ? 8 : 0) - | (rawItems ? 16 : 0) - | (level0Sorted ? 32 : 0); - return (byte) flags; - } - - static SerDeFormat getSerFormat(final ReqSketch sk) { - if (sk.isEmpty()) { return SerDeFormat.EMPTY; } - if (sk.getN() <= ReqSketch.MIN_K) { return SerDeFormat.RAWITEMS; } - if (sk.getNumLevels() == 1) { return SerDeFormat.EXACT; } - return SerDeFormat.ESTIMATION; - } - - private static SerDeFormat getDeserFormat(final boolean empty, final boolean rawItems, - final int numCompactors) { - if (numCompactors <= 1) { - if (empty) { return SerDeFormat.EMPTY; } - if (rawItems) { return SerDeFormat.RAWITEMS; } - return SerDeFormat.EXACT; - } - return SerDeFormat.ESTIMATION; - } - - static byte[] toByteArray(final ReqSketch sk) { - final SerDeFormat serDeFormat = getSerFormat(sk); - final int bytes = getSerBytes(sk, serDeFormat); - final byte[] arr = new byte[bytes]; - final PositionalSegment posSeg = PositionalSegment.wrap(MemorySegment.ofArray(arr)); - - final byte preInts = (byte)(serDeFormat == SerDeFormat.ESTIMATION ? 4 : 2); - final byte flags = getFlags(sk); - final byte numCompactors = sk.isEmpty() ? 0 : (byte) sk.getNumLevels(); - final byte numRawItems = sk.getN() <= 4 ? (byte) sk.getN() : 0; - posSeg.setByte(preInts); - posSeg.setByte(SER_VER); - posSeg.setByte(FAMILY_ID); - posSeg.setByte(flags); - posSeg.setShort((short)sk.getK()); - posSeg.setByte(numCompactors); - posSeg.setByte(numRawItems); - - switch (serDeFormat) { - case EMPTY: { - assert posSeg.getPosition() == bytes; - return arr; - } - case RAWITEMS: { - final ReqCompactor c0 = sk.getCompactors().get(0); - final FloatBuffer fbuf = c0.getBuffer(); - for (int i = 0; i < numRawItems; i++) { posSeg.setFloat(fbuf.getItem(i)); } - assert posSeg.getPosition() == bytes; - return arr; - } - case EXACT: { - final ReqCompactor c0 = sk.getCompactors().get(0); - posSeg.setByteArray(c0.toByteArray(), 0, c0.getSerializationBytes()); - assert posSeg.getPosition() == bytes; - return arr; - } - default: { //Normal Estimation - posSeg.setLong(sk.getN()); - posSeg.setFloat(sk.getMinItem()); - posSeg.setFloat(sk.getMaxItem()); - for (int i = 0; i < numCompactors; i++) { - final ReqCompactor c = sk.getCompactors().get(i); - posSeg.setByteArray(c.toByteArray(), 0, c.getSerializationBytes()); - } - assert posSeg.getPosition() == bytes : posSeg.getPosition() + ", " + bytes; - return arr; - } - } - } - - static int getSerBytes(final ReqSketch sk, final SerDeFormat serDeFormat) { - switch (serDeFormat) { - case EMPTY: { - return 8; - } - case RAWITEMS: { - return (sk.getCompactors().get(0).getBuffer().getCount() * Float.BYTES) + 8; - } - case EXACT: { - return sk.getCompactors().get(0).getSerializationBytes() + 8; - } - default: { //ESTIMATION - int cBytes = 0; - for (int i = 0; i < sk.getNumLevels(); i++) { - cBytes += sk.getCompactors().get(i).getSerializationBytes(); - } - return cBytes + 24; - } - } - } - -} diff --git a/src/main/java/org/apache/datasketches/req/ReqSketch.java b/src/main/java/org/apache/datasketches/req/ReqSketch.java deleted file mode 100644 index 7de815750..000000000 --- a/src/main/java/org/apache/datasketches/req/ReqSketch.java +++ /dev/null @@ -1,650 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -import java.lang.foreign.MemorySegment; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.FloatsSketchSortedView; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; -import org.apache.datasketches.quantilescommon.QuantilesAPI; -import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator; - -/** - * This Relative Error Quantiles Sketch is the Java implementation based on the paper - * "Relative Error Streaming Quantiles" by Graham Cormode, Zohar Karnin, Edo Liberty, - * Justin Thaler, Pavel Veselý, and loosely derived from a Python prototype written by Pavel Veselý. - * - *

Reference: https://arxiv.org/abs/2004.01668

- * - *

This implementation differs from the algorithm described in the paper in the following:

- * - *
    - *
  • The algorithm requires no upper bound on the stream length. - * Instead, each relative-compactor counts the number of compaction operations performed - * so far (via variable state). Initially, the relative-compactor starts with INIT_NUMBER_OF_SECTIONS. - * Each time the number of compactions (variable state) exceeds 2^{numSections - 1}, we double - * numSections. Note that after merging the sketch with another one variable state may not correspond - * to the number of compactions performed at a particular level, however, since the state variable - * never exceeds the number of compactions, the guarantees of the sketch remain valid.
  • - * - *
  • The size of each section (variable k and sectionSize in the code and parameter k in - * the paper) is initialized with a number set by the user via variable k. - * When the number of sections doubles, we decrease sectionSize by a factor of sqrt(2). - * This is applied at each level separately. Thus, when we double the number of sections, the - * nominal compactor size increases by a factor of approx. sqrt(2) (+/- rounding).
  • - * - *
  • The merge operation here does not perform "special compactions", which are used in the paper - * to allow for a tight mathematical analysis of the sketch.
  • - *
- * - *

This implementation provides a number of capabilities not discussed in the paper or provided - * in the Python prototype.

- * - *
  • The Python prototype only implemented high accuracy for low ranks. This implementation - * provides the user with the ability to choose either high rank accuracy or low rank accuracy at - * the time of sketch construction.
  • - *
  • The Python prototype only implemented a comparison criterion of "INCLUSIVE". This implementation - * allows the user to switch back and forth between the "INCLUSIVE" criterion and the "EXCLUSIVE" criterion.
  • - *
  • This implementation provides extensive debug visibility into the operation of the sketch with - * two levels of detail output. This is not only useful for debugging, but is a powerful tool to - * help users understand how the sketch works.
  • - *
- * - * @see QuantilesAPI - * - * @author Edo Liberty - * @author Pavel Vesely - * @author Lee Rhodes - */ -public final class ReqSketch extends BaseReqSketch { - - static class CompactorReturn { - int deltaRetItems; - int deltaNomSize; - } - - //static finals - static final byte MIN_K = 4; - static final byte NOM_CAP_MULT = 2; - - //finals - private final int k; //default is 12 (1% @ 95% Confidence) - private final boolean hra; //default is true - //state variables - private long totalN = 0; - private float minItem = Float.NaN; - private float maxItem = Float.NaN; - //computed from compactors - private int retItems = 0; //number of retained items in the sketch - private int maxNomSize = 0; //sum of nominal capacities of all compactors - //Objects - private FloatsSketchSortedView reqSV = null; - private List compactors = new ArrayList<>(); - private ReqDebug reqDebug = null; //user config, default: null, can be set after construction. - - private final CompactorReturn cReturn = new CompactorReturn(); //used in compress() - - private final Random rand; - - /** - * Construct from elements. After sketch is constructed, retItems and maxNomSize must be computed. - * Used by ReqSerDe. - */ - ReqSketch(final int k, final boolean hra, final long totalN, final float minItem, - final float maxItem, final List compactors) { - checkK(k); - this.k = k; - this.hra = hra; - this.totalN = totalN; - this.minItem = minItem; - this.maxItem = maxItem; - this.compactors = compactors; - rand = new Random(); - } - - /** - * Normal Constructor used by ReqSketchBuilder. - * @param k Controls the size and error of the sketch. It must be even and in the range - * [4, 1024]. - * The default number 12 roughly corresponds to 1% relative error guarantee at 95% confidence. - * @param highRankAccuracy if true, the default, the high ranks are prioritized for better - * accuracy. Otherwise the low ranks are prioritized for better accuracy. - * @param reqDebug the debug handler. It may be null. - */ - ReqSketch(final int k, final boolean highRankAccuracy, final ReqDebug reqDebug) { - checkK(k); - this.k = k; - hra = highRankAccuracy; - this.reqDebug = reqDebug; - rand = (reqDebug == null) ? new Random() : new Random(1); - grow(); - } - - /** - * Copy Constructor. Only used in test. - * @param other the other sketch to be deep copied into this one. - */ - ReqSketch(final ReqSketch other) { - k = other.k; - hra = other.hra; - totalN = other.totalN; - retItems = other.retItems; - maxNomSize = other.maxNomSize; - minItem = other.minItem; - maxItem = other.maxItem; - reqDebug = other.reqDebug; - reqSV = null; - rand = (reqDebug == null) ? new Random() : new Random(1); - - for (int i = 0; i < other.getNumLevels(); i++) { - compactors.add(new ReqCompactor(other.compactors.get(i))); - } - } - - /** - * Returns a new ReqSketchBuilder - * @return a new ReqSketchBuilder - */ - public static ReqSketchBuilder builder() { - return new ReqSketchBuilder(); - } - - /** - * Returns an ReqSketch on the heap from a MemorySegment image of the sketch. - * @param seg The MemorySegment object holding a valid image of an ReqSketch - * @return an ReqSketch on the heap from a MemorySegment image of the sketch. - */ - public static ReqSketch heapify(final MemorySegment seg) { - return ReqSerDe.heapify(seg); - } - - @Override - public int getK() { - return k; - } - - /** - * This checks the given float array to make sure that it contains only finite numbers - * and is monotonically increasing. - * @param splits the given array - */ - static void validateSplits(final float[] splits) { - final int len = splits.length; - for (int i = 0; i < len; i++) { - final float v = splits[i]; - if (!Float.isFinite(v)) { - throw new SketchesArgumentException("Numbers must be finite"); - } - if ((i < (len - 1)) && (v >= splits[i + 1])) { - throw new SketchesArgumentException( - "Numbers must be unique and monotonically increasing"); - } - } - } - - @Override - public double[] getCDF(final float[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return reqSV.getCDF(splitPoints, searchCrit); - } - - @Override - public boolean getHighRankAccuracyMode() { - return hra; - } - - @Override - public float getMaxItem() { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return maxItem; - } - - @Override - public float getMinItem() { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - return minItem; - } - - @Override - public long getN() { - return totalN; - } - - @Override - /** - * This is an unsupported operation for this sketch - */ - public double getNormalizedRankError(final boolean pmf) { - throw new UnsupportedOperationException(UNSUPPORTED_MSG); - - } - - @Override - public double[] getPMF(final float[] splitPoints, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return reqSV.getPMF(splitPoints, searchCrit); - } - - @Override - public float getQuantile(final double normRank, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - if ((normRank < 0) || (normRank > 1.0)) { - throw new SketchesArgumentException( - "Normalized rank must be in the range [0.0, 1.0]: " + normRank); - } - refreshSortedView(); - return reqSV.getQuantile(normRank, searchCrit); - } - - @Override - public float[] getQuantiles(final double[] normRanks, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - final int len = normRanks.length; - final float[] qArr = new float[len]; - for (int i = 0; i < len; i++) { - qArr[i] = reqSV.getQuantile(normRanks[i], searchCrit); - } - return qArr; - } - - /** - * {@inheritDoc} - * The approximate probability that the true quantile is within the confidence interval - * specified by the upper and lower quantile bounds for this sketch is 0.95. - */ - @Override - public float getQuantileLowerBound(final double rank) { - return getQuantile(getRankLowerBound(rank, 2), INCLUSIVE); - } - - @Override - public float getQuantileLowerBound(final double rank, final int numStdDev) { - return getQuantile(getRankLowerBound(rank, numStdDev), INCLUSIVE); - } - - /** - * {@inheritDoc} - * The approximate probability that the true quantile is within the confidence interval - * specified by the upper and lower quantile bounds for this sketch is 0.95. - */ - @Override - public float getQuantileUpperBound(final double rank) { - return getQuantile(getRankUpperBound(rank, 2), INCLUSIVE); - } - - @Override - public float getQuantileUpperBound(final double rank, final int numStdDev) { - return getQuantile(getRankUpperBound(rank, numStdDev), INCLUSIVE); - } - - @Override - public double getRank(final float quantile, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - return reqSV.getRank(quantile, searchCrit); - } - - /** - * {@inheritDoc} - * The approximate probability that the true rank is within the confidence interval - * specified by the upper and lower rank bounds for this sketch is 0.95. - */ - @Override - public double getRankLowerBound(final double rank) { - return getRankLB(k, getNumLevels(), rank, 2, hra, getN()); - } - - @Override - public double getRankLowerBound(final double rank, final int numStdDev) { - return getRankLB(k, getNumLevels(), rank, numStdDev, hra, getN()); - } - - @Override - public double[] getRanks(final float[] quantiles, final QuantileSearchCriteria searchCrit) { - if (isEmpty()) { throw new IllegalArgumentException(QuantilesAPI.EMPTY_MSG); } - refreshSortedView(); - final int numQuantiles = quantiles.length; - final double[] retArr = new double[numQuantiles]; - for (int i = 0; i < numQuantiles; i++) { - retArr[i] = reqSV.getRank(quantiles[i], searchCrit); //already normalized - } - return retArr; - } - - /** - * {@inheritDoc} - * The approximate probability that the true rank is within the confidence interval - * specified by the upper and lower rank bounds for this sketch is 0.95. - */ - @Override - public double getRankUpperBound(final double rank) { - return getRankUB(k, getNumLevels(), rank, 2, hra, getN()); - } - - @Override - public double getRankUpperBound(final double rank, final int numStdDev) { - return getRankUB(k, getNumLevels(), rank, numStdDev, hra, getN()); - } - - @Override - public int getNumRetained() { return retItems; } - - @Override - public int getSerializedSizeBytes() { - final ReqSerDe.SerDeFormat serDeFormat = ReqSerDe.getSerFormat(this); - return ReqSerDe.getSerBytes(this, serDeFormat); - } - - @Override - public boolean isEmpty() { - return totalN == 0; - } - - @Override - public boolean isEstimationMode() { - return getNumLevels() > 1; - } - - @Override - public QuantilesFloatsSketchIterator iterator() { - return new ReqSketchIterator(this); - } - - @Override - public ReqSketch merge(final ReqSketch other) { - if ((other == null) || other.isEmpty()) { return this; } - if (other.hra != hra) { - throw new SketchesArgumentException( - "Both sketches must have the same HighRankAccuracy setting."); - } - totalN += other.totalN; - //update min, max items, n - if (Float.isNaN(minItem) || (other.minItem < minItem)) { minItem = other.minItem; } - if (Float.isNaN(maxItem) || (other.maxItem > maxItem)) { maxItem = other.maxItem; } - //Grow until self has at least as many compactors as other - while (getNumLevels() < other.getNumLevels()) { grow(); } - //Merge the items in all height compactors - for (int i = 0; i < other.getNumLevels(); i++) { - compactors.get(i).merge(other.compactors.get(i)); - } - maxNomSize = computeMaxNomSize(); - retItems = computeTotalRetainedItems(); - if (retItems >= maxNomSize) { - compress(); - } - assert retItems < maxNomSize; - reqSV = null; - return this; - } - - @Override - public void reset() { - totalN = 0; - retItems = 0; - maxNomSize = 0; - minItem = Float.NaN; - maxItem = Float.NaN; - reqSV = null; - compactors = new ArrayList<>(); - grow(); - } - - @Override - public byte[] toByteArray() { - return ReqSerDe.toByteArray(this); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("**********Relative Error Quantiles Sketch Summary**********").append(LS); - sb.append(" K : " + k).append(LS); - sb.append(" N : " + totalN).append(LS); - sb.append(" Retained Items : " + retItems).append(LS); - sb.append(" Min Item : " + minItem).append(LS); - sb.append(" Max Item : " + maxItem).append(LS); - sb.append(" Estimation Mode : " + isEstimationMode()).append(LS); - sb.append(" High Rank Acc : " + hra).append(LS); - sb.append(" Levels : " + compactors.size()).append(LS); - sb.append("************************End Summary************************").append(LS); - return sb.toString(); - } - - @Override - public void update(final float item) { - if (Float.isNaN(item)) { return; } - if (isEmpty()) { - minItem = item; - maxItem = item; - } else { - if (item < minItem) { minItem = item; } - if (item > maxItem) { maxItem = item; } - } - final FloatBuffer fbuf = compactors.get(0).getBuffer(); - fbuf.append(item); - retItems++; - totalN++; - if (retItems >= maxNomSize) { - fbuf.sort(); - compress(); - } - reqSV = null; - } - - @Override - public String viewCompactorDetail(final String fmt, final boolean allData) { - final StringBuilder sb = new StringBuilder(); - sb.append("*********Relative Error Quantiles Compactor Detail*********").append(LS); - sb.append("Compactor Detail: Ret Items: ").append(getNumRetained()) - .append(" N: ").append(getN()); - sb.append(LS); - for (int i = 0; i < getNumLevels(); i++) { - final ReqCompactor c = compactors.get(i); - sb.append(c.toListPrefix()).append(LS); - if (allData) { sb.append(c.getBuffer().toHorizList(fmt, 20)).append(LS); } - } - sb.append("************************End Detail*************************").append(LS); - return sb.toString(); - } - - /** - * Computes a new bound for determining when to compress the sketch. - */ - int computeMaxNomSize() { - int cap = 0; - for (final ReqCompactor c : compactors) { cap += c.getNomCapacity(); } - return cap; - } - - /** - * Computes the retained Items for the sketch. - */ - int computeTotalRetainedItems() { - int count = 0; - for (final ReqCompactor c : compactors) { - count += c.getBuffer().getCount(); - } - return count; - } - - List getCompactors() { - return compactors; - } - - int getMaxNomSize() { - return maxNomSize; - } - - /** - * Gets the number of levels of compactors in the sketch. - * @return the number of levels of compactors in the sketch. - */ - int getNumLevels() { - return compactors.size(); - } - - void setMaxNomSize(final int maxNomSize) { - this.maxNomSize = maxNomSize; - } - - void setRetainedItems(final int retItems) { - this.retItems = retItems; - } - - private static void checkK(final int k) { - if (((k & 1) > 0) || (k < 4) || (k > 1024)) { - throw new SketchesArgumentException( - "K must be even and in the range [4, 1024]: " + k ); - } - } - - private void compress() { - if (reqDebug != null) { reqDebug.emitStartCompress(); } - for (int h = 0; h < compactors.size(); h++) { - final ReqCompactor c = compactors.get(h); - final int compRetItems = c.getBuffer().getCount(); - final int compNomCap = c.getNomCapacity(); - - if (compRetItems >= compNomCap) { - if ((h + 1) >= getNumLevels()) { //at the top? - if (reqDebug != null) { reqDebug.emitMustAddCompactor(); } - grow(); //add a level, increases maxNomSize - } - final FloatBuffer promoted = c.compact(cReturn, rand); - compactors.get(h + 1).getBuffer().mergeSortIn(promoted); - retItems += cReturn.deltaRetItems; - maxNomSize += cReturn.deltaNomSize; - //we specifically decided not to do lazy compression. - } - } - reqSV = null; - if (reqDebug != null) { reqDebug.emitCompressDone(); } - } - - private void grow() { - final byte lgWeight = (byte)getNumLevels(); - if ((lgWeight == 0) && (reqDebug != null)) { reqDebug.emitStart(this); } - compactors.add(new ReqCompactor(lgWeight, hra, k, reqDebug)); - maxNomSize = computeMaxNomSize(); - if (reqDebug != null) { reqDebug.emitNewCompactor(lgWeight); } - } - - // SORTED VIEW - - @Override - public FloatsSketchSortedView getSortedView() { - refreshSortedView(); - return reqSV; - } - - private FloatsSketchSortedView refreshSortedView() { - if (reqSV == null) { - final CreateSortedView csv = new CreateSortedView(); - reqSV = csv.getSV(); - } - return reqSV; - } - - private final class CreateSortedView { - float[] quantiles; - long[] cumWeights; - - FloatsSketchSortedView getSV() { - if (isEmpty()) { throw new SketchesArgumentException(EMPTY_MSG); } - //build the SV arrays - final List compactors = getCompactors(); - final int numComp = compactors.size(); - final int totalQuantiles = getNumRetained(); - quantiles = new float[totalQuantiles]; //could have zero entries - cumWeights = new long[totalQuantiles]; - int count = 0; - for (int i = 0; i < numComp; i++) { - final ReqCompactor c = compactors.get(i); - final FloatBuffer fbufIn = c.getBuffer(); - final long fbufWeight = 1 << c.getLgWeight(); - final int fbufInLen = fbufIn.getCount(); - mergeSortIn(fbufIn, fbufWeight, count, getHighRankAccuracyMode()); - count += fbufInLen; - } - createCumulativeNativeRanks(); - return new FloatsSketchSortedView(quantiles, cumWeights, ReqSketch.this); - } - - /** - * Specially modified version of FloatBuffer.mergeSortIn(). Here spaceAtBottom is always false and - * the ultimate array size has already been set. However, this must simultaneously deal with - * sorting the base FloatBuffer as well. - * - * @param fbufIn given FloatBuffer. If not sorted it will be sorted here. - * @param fbufWeight associated weight of input FloatBuffer - * @param count tracks number of items inserted into the class arrays - */ - private void mergeSortIn(final FloatBuffer fbufIn, final long fbufWeight, final int count, final boolean hra) { - if (!fbufIn.isSorted()) { fbufIn.sort(); } - final float[] arrIn = fbufIn.getArray(); //may be larger than its item count. - final int fbufInLen = fbufIn.getCount(); - final int totLen = count + fbufInLen; - int i = count - 1; - int j = fbufInLen - 1; - int h = hra ? fbufIn.getCapacity() - 1 : fbufInLen - 1; - for (int k = totLen; k-- > 0; ) { - if ((i >= 0) && (j >= 0)) { //both valid - if (quantiles[i] >= arrIn[h]) { - quantiles[k] = quantiles[i]; - cumWeights[k] = cumWeights[i--]; //not yet natRanks, just individual wts - } else { - quantiles[k] = arrIn[h--]; j--; - cumWeights[k] = fbufWeight; - } - } else if (i >= 0) { //i is valid - quantiles[k] = quantiles[i]; - cumWeights[k] = cumWeights[i--]; - } else if (j >= 0) { //j is valid - quantiles[k] = arrIn[h--]; j--; - cumWeights[k] = fbufWeight; - } else { - break; - } - } - } - - private void createCumulativeNativeRanks() { - final int len = quantiles.length; - for (int i = 1; i < len; i++) { - cumWeights[i] += cumWeights[i - 1]; - } - if (totalN > 0) { - assert cumWeights[len - 1] == totalN; - } - } - - } //End CreateSortedView - -} diff --git a/src/main/java/org/apache/datasketches/req/ReqSketchBuilder.java b/src/main/java/org/apache/datasketches/req/ReqSketchBuilder.java deleted file mode 100644 index 6ed9ce279..000000000 --- a/src/main/java/org/apache/datasketches/req/ReqSketchBuilder.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.TAB; - -/** - * For building a new ReqSketch - * - * @author Lee Rhodes - */ -public class ReqSketchBuilder { - private final static int DEFAULT_K = 12; - private int bK = DEFAULT_K; - private boolean bHRA; - private ReqDebug bReqDebug; - - /** - * Constructor for the ReqSketchBuilder. - */ - public ReqSketchBuilder() { - bK = DEFAULT_K; - bHRA = true; - bReqDebug = null; - } - - /** - * Returns a new ReqSketch with the current configuration of the builder. - * @return a new ReqSketch - */ - public ReqSketch build() { - final ReqSketch sk = new ReqSketch(bK, bHRA, bReqDebug); - return sk; - } - - /** - * Gets the builder configured High Rank Accuracy. - * @return the builder configured High Rank Accuracy. - */ - public boolean getHighRankAccuracy() { - return bHRA; - } - - /** - * Gets the builder configured k. - * @return the builder configured k. - */ - public int getK() { - return bK; - } - - /** - * Gets the builder configured ReqDebug - * @return the builder configured ReqDebug, or null. - */ - public ReqDebug getReqDebug() { - return bReqDebug; - } - - /** - * This sets the parameter highRankAccuracy. - * @param hra See ReqSketch#ReqSketch(int, boolean, ReqDebug) - * @return this - */ - public ReqSketchBuilder setHighRankAccuracy(final boolean hra) { - bHRA = hra; - return this; - } - - /** - * This sets the parameter k. - * @param k See ReqSketch#ReqSketch(int, boolean, ReqDebug) - * @return this - */ - public ReqSketchBuilder setK(final int k) { - bK = k; - return this; - } - - /** - * This sets the parameter reqDebug. - * @param reqDebug See ReqSketch#ReqSketch(int, boolean, ReqDebug) - * @return this - */ - public ReqSketchBuilder setReqDebug(final ReqDebug reqDebug) { - bReqDebug = reqDebug; - return this; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("ReqSketchBuilder configuration:").append(LS); - sb.append("K:").append(TAB).append(bK).append(LS); - sb.append("HRA:").append(TAB).append(bHRA).append(LS); - final String valid = bReqDebug != null ? "valid" : "invalid"; - sb.append("ReqDebug:").append(TAB).append(valid).append(LS); - return sb.toString(); - } - -} diff --git a/src/main/java/org/apache/datasketches/req/ReqSketchIterator.java b/src/main/java/org/apache/datasketches/req/ReqSketchIterator.java deleted file mode 100644 index 8fc69d32d..000000000 --- a/src/main/java/org/apache/datasketches/req/ReqSketchIterator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import java.util.List; - -import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator; - -/** - * Iterator over all retained items of the ReqSketch. The order is not defined. - * - * @author Lee Rhodes - */ -public final class ReqSketchIterator implements QuantilesFloatsSketchIterator { - private List compactors; - private int cIndex; - private int bIndex; - private int numRetainedItems; - private FloatBuffer currentBuf; - - ReqSketchIterator(final ReqSketch sketch) { - compactors = sketch.getCompactors(); - numRetainedItems = sketch.getNumRetained(); - currentBuf = compactors.get(0).getBuffer(); - cIndex = 0; - bIndex = -1; - } - - @Override - public float getQuantile() { - return currentBuf.getItem(bIndex); - } - - @Override - public long getWeight() { - return 1 << cIndex; - } - - @Override - public boolean next() { - if ((numRetainedItems == 0) - || ((cIndex == (compactors.size() - 1)) && (bIndex == (currentBuf.getCount() - 1)))) { - return false; - } - if (bIndex == (currentBuf.getCount() - 1)) { - cIndex++; - currentBuf = compactors.get(cIndex).getBuffer(); - bIndex = 0; - } else { - bIndex++; - } - return true; - } -} diff --git a/src/main/java/org/apache/datasketches/req/package-info.java b/src/main/java/org/apache/datasketches/req/package-info.java deleted file mode 100644 index cee899473..000000000 --- a/src/main/java/org/apache/datasketches/req/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package is for the implementation of the Relative Error Quantiles sketch algorithm. - * @see org.apache.datasketches.req.ReqSketch - */ -package org.apache.datasketches.req; diff --git a/src/main/java/org/apache/datasketches/sampling/EbppsItemsSample.java b/src/main/java/org/apache/datasketches/sampling/EbppsItemsSample.java deleted file mode 100644 index 3e13b6bf9..000000000 --- a/src/main/java/org/apache/datasketches/sampling/EbppsItemsSample.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static org.apache.datasketches.common.Util.LS; - -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; - -import org.apache.datasketches.common.SketchesArgumentException; - -// this is a supporting class used to hold the raw data sample -final class EbppsItemsSample { - - private double c_; // Current sample size, including fractional part - private T partialItem_; // a sample item corresponding to a partial weight - private ArrayList data_; // full sample items - - private Random rand_; // ThreadLocalRandom.current() in general - - // basic constructor - EbppsItemsSample(final int reservedSize) { - c_ = 0.0; - data_ = new ArrayList<>(reservedSize); - rand_ = ThreadLocalRandom.current(); - } - - // copy constructor used during merge - EbppsItemsSample(final EbppsItemsSample other) { - c_ = other.c_; - partialItem_ = other.partialItem_; - data_ = new ArrayList<>(other.data_); - rand_ = other.rand_; - } - - // constructor used for deserialization and testing - // does NOT copy the incoming ArrayList since this is an internal - // class's package-private constructor, not something directly - // taking user data - EbppsItemsSample(final ArrayList data, final T partialItem, final double c) { - if (c < 0.0 || Double.isNaN(c) || Double.isInfinite(c)) { - throw new SketchesArgumentException("C must be nonnegative and finite. Found: " + c); - } - - c_ = c; - partialItem_ = partialItem; - data_ = data; - rand_ = ThreadLocalRandom.current(); - } - - // Used in lieu of a constructor to populate a temporary sample - // with data before immediately merging it. This approach - // avoids excessive object allocation calls. - // rand_ is not set since it is not expected to be used from - // this object - void replaceContent(final T item, final double theta) { - if (theta < 0.0 || theta > 1.0 || Double.isNaN(theta)) { - throw new SketchesArgumentException("Theta must be in the range [0.0, 1.0]. Found: " + theta); - } - - c_ = theta; - if (theta == 1.0) { - if (data_ != null && data_.size() == 1) { - data_.set(0, item); - } else { - data_ = new ArrayList<>(1); - data_.add(item); - } - partialItem_ = null; - } else { - data_ = null; - partialItem_ = item; - } - } - - void reset() { - c_ = 0.0; - partialItem_ = null; - data_.clear(); - } - - ArrayList getSample() { - final double cFrac = c_ % 1; - final boolean includePartial = partialItem_ != null && rand_.nextDouble() < cFrac; - final int resultSize = (data_ != null ? data_.size() : 0) + (includePartial ? 1 : 0); - - if (resultSize == 0) { - return null; - } - - final ArrayList result = new ArrayList<>(resultSize); - if (data_ != null) { - result.addAll(data_); - } - - if (includePartial) { - result.add(partialItem_); - } - - return result; - } - - @SuppressWarnings("unchecked") - T[] getAllSamples(final Class clazz) { - // Is it faster to use sublist and append 1? - final T[] itemsArray = (T[]) Array.newInstance(clazz, getNumRetainedItems()); - int i = 0; - if (data_ != null) { - for (T item : data_) { - if (item != null) { - itemsArray[i++] = item; - } - } - } - if (partialItem_ != null) { - itemsArray[i] = partialItem_; // no need to increment i again - } - - return itemsArray; - } - - // package-private for use in merge and serialization - ArrayList getFullItems() { - return data_; - } - - // package-private for use in merge and serialization - T getPartialItem() { - return partialItem_; - } - - double getC() { return c_; } - - boolean hasPartialItem() { return partialItem_ != null; } - - // for testing to allow setting the seed - void replaceRandom(final Random r) { - rand_ = r; - } - - void downsample(final double theta) { - if (theta >= 1.0) { return; } - - final double newC = theta * c_; - final double newCInt = Math.floor(newC); - final double newCFrac = newC % 1; - final double cInt = Math.floor(c_); - final double cFrac = c_ % 1; - - if (newCInt == 0.0) { - // no full items retained - if (rand_.nextDouble() > (cFrac / c_)) { - swapWithPartialItem(); - } - data_.clear(); - } else if (newCInt == cInt) { - // no items deleted - if (rand_.nextDouble() > (1 - theta * cFrac) / (1 - newCFrac)) { - swapWithPartialItem(); - } - } else { - if (rand_.nextDouble() < theta * cFrac) { - // subsample data in random order; last item is partial - // create sample size newC then swapWithPartialItem() - subsample((int) newCInt); - swapWithPartialItem(); - } else { - // create sample size newCInt + 1 then moveOneToPartialItem() - subsample((int) newCInt + 1); - moveOneToPartialItem(); - } - } - - if (newC == newCInt) { - partialItem_ = null; - } - - c_ = newC; - } - - void merge(final EbppsItemsSample other) { - //double cInt = Math.floor(c_); - final double cFrac = c_ % 1; - final double otherCFrac = other.c_ % 1; - - // update c_ here but do NOT recompute fractional part yet - c_ += other.c_; - - if (other.data_ != null) { - data_.addAll(other.data_); - } - - // This modifies the original algorithm slightly due to numeric - // precision issues. Specifically, the test if cFrac + otherCFrac == 1.0 - // happens before tests for < 1.0 or > 1.0 and can also be triggered - // if c_ == floor(c_) (the updated value of c_, not the input). - // - // We can still run into issues where cFrac + otherCFrac == epsilon - // and the first case would have ideally triggered. As a result, we must - // check if the partial item exists before adding to the data_ vector. - - if (cFrac == 0.0 && otherCFrac == 0.0) { - partialItem_ = null; - } else if (cFrac + otherCFrac == 1.0 || c_ == Math.floor(c_)) { - if (rand_.nextDouble() <= cFrac) { - if (partialItem_ != null) { - data_.add(partialItem_); - } - } else { - if (other.partialItem_ != null) { - data_.add(other.partialItem_); - } - } - partialItem_ = null; - } else if (cFrac + otherCFrac < 1.0) { - if (rand_.nextDouble() > cFrac / (cFrac + otherCFrac)) { - partialItem_ = other.partialItem_; - } - } else { // cFrac + otherCFrac > 1 - if (rand_.nextDouble() <= (1 - cFrac) / ((1 - cFrac) + (1 - otherCFrac))) { - data_.add(other.partialItem_); - } else { - data_.add(partialItem_); - partialItem_ = other.partialItem_; - } - } - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - - sb.append(" sample:").append(LS); - int idx = 0; - for (T item : data_) { - sb.append("\t").append(idx++).append(":\t").append(item.toString()).append(LS); - } - sb.append(" partial: "); - if (partialItem_ != null) { - sb.append(partialItem_).append(LS); - } else { - sb.append("NULL").append(LS); - } - - return sb.toString(); - } - - void subsample(final int numSamples) { - // we can perform a Fisher-Yates style shuffle, stopping after - // numSamples points since subsequent swaps would only be - // between items after num_samples. This is valid since a - // point from anywhere in the initial array would be eligible - // to end up in the final subsample. - - if (numSamples == data_.size()) { return; } - - final int dataLen = data_.size(); - for (int i = 0; i < numSamples; ++i) { - final int j = i + rand_.nextInt(dataLen - i); - // swap i and j - final T tmp = data_.get(i); - data_.set(i, data_.get(j)); - data_.set(j, tmp); - } - - // clear anything beyond numSamples - data_.subList(numSamples, data_.size()).clear(); - } - - void swapWithPartialItem() { - if (partialItem_ == null) { - moveOneToPartialItem(); - } else { - final int idx = rand_.nextInt(data_.size()); - final T tmp = partialItem_; - partialItem_ = data_.get(idx); - data_.set(idx, tmp); - } - } - - void moveOneToPartialItem() { - final int idx = rand_.nextInt(data_.size()); - // swap selected item to end so we can delete it easily - final int lastIdx = data_.size() - 1; - if (idx != lastIdx) { - final T tmp = data_.get(idx); - data_.set(idx, data_.get(lastIdx)); - partialItem_ = tmp; - } else { - partialItem_ = data_.get(lastIdx); - } - - data_.remove(lastIdx); - } - - int getNumRetainedItems() { - return (data_ != null ? data_.size() : 0) - + (partialItem_ != null ? 1 : 0); - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/EbppsItemsSketch.java b/src/main/java/org/apache/datasketches/sampling/EbppsItemsSketch.java deleted file mode 100644 index d1d147021..000000000 --- a/src/main/java/org/apache/datasketches/sampling/EbppsItemsSketch.java +++ /dev/null @@ -1,538 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.sampling.PreambleUtil.EBPPS_SER_VER; -import static org.apache.datasketches.sampling.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.sampling.PreambleUtil.HAS_PARTIAL_ITEM_MASK; - -import java.lang.foreign.MemorySegment; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * An implementation of an Exact and Bounded Sampling Proportional to Size sketch. - * - *

From: "Exact PPS Sampling with Bounded Sample Size", - * B. Hentschel, P. J. Haas, Y. Tian. Information Processing Letters, 2023. - * - *

This sketch samples data from a stream of items proportional to the weight of each item. - * The sample guarantees the presence of an item in the result is proportional to that item's - * portion of the total weight seen by the sketch, and returns a sample no larger than size k. - * - *

The sample may be smaller than k and the resulting size of the sample potentially includes - * a probabilistic component, meaning the resulting sample size is not always constant. - * @param the item class type - * @author Jon Malkin - */ -public final class EbppsItemsSketch { - private static final int MAX_K = Integer.MAX_VALUE - 2; - private static final int EBPPS_C_DOUBLE = 40; // part of sample state, not preamble - private static final int EBPPS_ITEMS_START = 48; - - private int k_; // max size of sketch, in items - private long n_; // total number of items processed by the sketch - - private double cumulativeWt_; // total weight of items processed by the sketch - private double wtMax_; // maximum weight seen so far - private double rho_; // latest scaling parameter for downsampling - - private EbppsItemsSample sample_; // Object holding the current state of the sample - - final private EbppsItemsSample tmp_; // temporary storage - - /** - * Constructor - * @param k The maximum number of samples to retain - */ - public EbppsItemsSketch(final int k) { - checkK(k); - k_ = k; - rho_ = 1.0; - sample_ = new EbppsItemsSample<>(k); - tmp_ = new EbppsItemsSample<>(1); - } - - // private copy constructor - private EbppsItemsSketch(final EbppsItemsSketch other) { - k_ = other.k_; - n_ = other.n_; - rho_ = other.rho_; - cumulativeWt_ = other.cumulativeWt_; - wtMax_ = other.wtMax_; - sample_ = new EbppsItemsSample<>(other.sample_); - tmp_ = new EbppsItemsSample<>(1); - } - - // private constructor for heapify - private EbppsItemsSketch(final EbppsItemsSample sample, - final int k, - final long n, - final double cumWt, - final double maxWt, - final double rho) { - k_ = k; - n_ = n; - cumulativeWt_ = cumWt; - wtMax_ = maxWt; - rho_ = rho; - sample_ = sample; - tmp_ = new EbppsItemsSample<>(1); - } - - /** - * Returns a sketch instance of this class from the given srcSeg, - * which must be a MemorySegment representation of this sketch class. - * - * @param The type of item this sketch contains - * @param srcSeg a MemorySegment representation of a sketch of this class. - * @param serDe An instance of ArrayOfItemsSerDe - * @return a sketch instance of this class - */ - public static EbppsItemsSketch heapify(final MemorySegment srcSeg, final ArrayOfItemsSerDe serDe) - { - final int numPreLongs = PreambleUtil.getAndCheckPreLongs(srcSeg); - final int serVer = PreambleUtil.extractSerVer(srcSeg); - final int familyId = PreambleUtil.extractFamilyID(srcSeg); - final int flags = PreambleUtil.extractFlags(srcSeg); - final boolean isEmpty = (flags & EMPTY_FLAG_MASK) != 0; - final boolean hasPartialItem = (flags & HAS_PARTIAL_ITEM_MASK) != 0; - - // Check values - if (isEmpty) { - if (numPreLongs != Family.EBPPS.getMinPreLongs()) { - throw new SketchesArgumentException("Possible corruption: Must be " + Family.EBPPS.getMinPreLongs() - + " for an empty sketch. Found: " + numPreLongs); - } - } else if (numPreLongs != Family.EBPPS.getMaxPreLongs()) { - throw new SketchesArgumentException("Possible corruption: Must be " - + Family.EBPPS.getMaxPreLongs() + " for a non-empty sketch. Found: " + numPreLongs); - } - if (serVer != EBPPS_SER_VER) { - throw new SketchesArgumentException( - "Possible Corruption: Ser Ver must be " + EBPPS_SER_VER + ": " + serVer); - } - final int reqFamilyId = Family.EBPPS.getID(); - if (familyId != reqFamilyId) { - throw new SketchesArgumentException( - "Possible Corruption: FamilyID must be " + reqFamilyId + ": " + familyId); - } - - final int k = PreambleUtil.extractK(srcSeg); - if ((k < 1) || (k > MAX_K)) { - throw new SketchesArgumentException("Possible Corruption: k must be at least 1 " - + "and less than " + MAX_K + ". Found: " + k); - } - - if (isEmpty) { - return new EbppsItemsSketch<>(k); - } - - final long n = PreambleUtil.extractN(srcSeg); - if (n < 0) { - throw new SketchesArgumentException("Possible Corruption: n cannot be negative: " + n); - } - - final double cumWt = PreambleUtil.extractEbppsCumulativeWeight(srcSeg); - if ((cumWt < 0.0) || Double.isNaN(cumWt) || Double.isInfinite(cumWt)) { - throw new SketchesArgumentException("Possible Corruption: cumWt must be nonnegative and finite: " + cumWt); - } - - final double maxWt = PreambleUtil.extractEbppsMaxWeight(srcSeg); - if ((maxWt < 0.0) || Double.isNaN(maxWt) || Double.isInfinite(maxWt)) { - throw new SketchesArgumentException("Possible Corruption: maxWt must be nonnegative and finite: " + maxWt); - } - - final double rho = PreambleUtil.extractEbppsRho(srcSeg); - if ((rho < 0.0) || (rho > 1.0) || Double.isNaN(rho) || Double.isInfinite(rho)) { - throw new SketchesArgumentException("Possible Corruption: rho must be in [0.0, 1.0]: " + rho); - } - - // extract C (part of sample_, not the preamble) - // due to numeric precision issues, c may occasionally be very slightly larger than k - final double c = srcSeg.get(JAVA_DOUBLE_UNALIGNED, EBPPS_C_DOUBLE); - if ((c < 0) || (c >= (k + 1)) || Double.isNaN(c) || Double.isInfinite(c)) { - throw new SketchesArgumentException("Possible Corruption: c must be between 0 and k: " + c); - } - - // extract items - final int numTotalItems = (int) Math.ceil(c); - final int numFullItems = (int) Math.floor(c); // floor() not strictly necessary - final int offsetBytes = EBPPS_ITEMS_START; - final T[] rawItems = serDe.deserializeFromMemorySegment(srcSeg.asSlice(offsetBytes), 0, numTotalItems); - final List itemsList = Arrays.asList(rawItems); - final ArrayList data; - final T partialItem; - if (hasPartialItem) { - if (numFullItems >= numTotalItems) { - throw new SketchesArgumentException("Possible Corruption: Expected partial item but none found"); - } - - data = new ArrayList<>(itemsList.subList(0, numFullItems)); - partialItem = itemsList.get(numFullItems); // 0-based, so last item - } else { - data = new ArrayList<>(itemsList); - partialItem = null; // just to be explicit - } - - final EbppsItemsSample sample = new EbppsItemsSample<>(data, partialItem, c); - - return new EbppsItemsSketch<>(sample, k, n, cumWt, maxWt, rho); - } - - /** - * Updates this sketch with the given data item with weight 1.0. - * @param item an item from a stream of items - */ - public void update(final T item) { - update(item, 1.0); - } - - /** - * Updates this sketch with the given data item with the given weight. - * @param item an item from a stream of items - * @param weight the weight of the item - */ - public void update(final T item, final double weight) { - if ((weight < 0.0) || Double.isNaN(weight) || Double.isInfinite(weight)) { - throw new SketchesArgumentException("Item weights must be nonnegative and finite. " - + "Found: " + weight); - } - if (weight == 0.0) { - return; - } - - final double newCumWt = cumulativeWt_ + weight; - final double newWtMax = Math.max(wtMax_, weight); - final double newRho = Math.min(1.0 / newWtMax, k_ / newCumWt); - - if (cumulativeWt_ > 0.0) { - sample_.downsample((newRho / rho_)); - } - - tmp_.replaceContent(item, newRho * weight); - sample_.merge(tmp_); - - cumulativeWt_ = newCumWt; - wtMax_ = newWtMax; - rho_ = newRho; - ++n_; - } - - /* Merging - * There is a trivial merge algorithm that involves downsampling each sketch A and B - * as A.cum_wt / (A.cum_wt + B.cum_wt) and B.cum_wt / (A.cum_wt + B.cum_wt), - * respectively. That merge does preserve first-order probabilities, specifically - * the probability proportional to size property, and like all other known merge - * algorithms distorts second-order probabilities (co-occurrences). There are - * pathological cases, most obvious with k=2 and A.cum_wt == B.cum_wt where that - * approach will always take exactly 1 item from A and 1 from B, meaning the - * co-occurrence rate for two items from either sketch is guaranteed to be 0.0. - * - * With EBPPS, once an item is accepted into the sketch we no longer need to - * track the item's weight: All accepted items are treated equally. As a result, we - * can take inspiration from the reservoir sampling merge in the datasketches-java - * library. We need to merge the smaller sketch into the larger one, swapping as - * needed to ensure that, at which point we simply call update() with the items - * in the smaller sketch as long as we adjust the weight appropriately. - * Merging smaller into larger is essential to ensure that no item has a - * contribution to C > 1.0. - */ - - /** - * Merges the provided sketch into the current one. - * @param other the sketch to merge into the current object - */ - public void merge(final EbppsItemsSketch other) { - if (other.getCumulativeWeight() == 0.0) { /* do nothing */ } - else if (other.getCumulativeWeight() > cumulativeWt_) { - // need to swap this with other - // make a copy of other, merge into it, and take the result - final EbppsItemsSketch copy = new EbppsItemsSketch<>(other); - copy.internalMerge(this); - k_ = copy.k_; - n_ = copy.n_; - cumulativeWt_ = copy.cumulativeWt_; - wtMax_ = copy.wtMax_; - rho_ = copy.rho_; - sample_ = copy.sample_; - } else { - internalMerge(other); - } - } - - // merge implementation called exclusively from public merge() - private void internalMerge(final EbppsItemsSketch other) { - // assumes that other.cumulativeWeight_ <= cumulativeWt_m - // which must be checked before calling this - - final double finalCumWt = cumulativeWt_ + other.cumulativeWt_; - final double newWtMax = Math.max(wtMax_, other.wtMax_); - k_ = Math.min(k_, other.k_); - final long newN = n_ + other.n_; - - // Insert other's items with the cumulative weight - // split between the input items. We repeat the same process - // for full items and the partial item, scaling the input - // weight appropriately. - // We handle all C input items, meaning we always process - // the partial item using a scaled down weight. - // Handling the partial item by probabilistically including - // it as a full item would be correct on average but would - // introduce bias for any specific merge operation. - final double avgWt = other.cumulativeWt_ / other.getC(); - final ArrayList items = other.sample_.getFullItems(); - if (items != null) { - for (final T item : items) { - // newWtMax is pre-computed - final double newCumWt = cumulativeWt_ + avgWt; - final double newRho = Math.min(1.0 / newWtMax, k_ / newCumWt); - - if (cumulativeWt_ > 0.0) { - sample_.downsample(newRho / rho_); - } - - tmp_.replaceContent(item, newRho * avgWt); - sample_.merge(tmp_); - - cumulativeWt_ = newCumWt; - rho_ = newRho; - } - } - - // insert partial item with weight scaled by the fractional part of C - if (other.sample_.hasPartialItem()) { - final double otherCFrac = other.getC() % 1; - final double newCumWt = cumulativeWt_ + (otherCFrac * avgWt); - final double newRho = Math.min(1.0 / newWtMax, k_ / newCumWt); - - if (cumulativeWt_ > 0.0) { - sample_.downsample(newRho / rho_); - } - - tmp_.replaceContent(other.sample_.getPartialItem(), newRho * otherCFrac * avgWt); - sample_.merge(tmp_); - - // cumulativeWt_ will be assigned momentarily - rho_ = newRho; - } - - // avoid numeric issues by setting cumulative weight to the - // pre-computed value - cumulativeWt_ = finalCumWt; - n_ = newN; - } - - /** - * Returns a copy of the current sample. The exact size may be - * probabilistic, differing by at most 1 item. - * @return the current sketch sample - */ - public ArrayList getResult() { return sample_.getSample(); } - - /** - * Provides a human-readable summary of the sketch - * @return a summary of information in the sketch - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - - sb.append(LS); - final String thisSimpleName = this.getClass().getSimpleName(); - sb.append("### ").append(thisSimpleName).append(" SUMMARY: ").append(LS); - sb.append(" k : ").append(k_).append(LS); - sb.append(" n : ").append(n_).append(LS); - sb.append(" Cum. weight : ").append(cumulativeWt_).append(LS); - sb.append(" wtMax : ").append(wtMax_).append(LS); - sb.append(" rho : ").append(rho_).append(LS); - sb.append(" C : ").append(sample_.getC()).append(LS); - sb.append("### END SKETCH SUMMARY").append(LS); - - return sb.toString(); - } - - /** - * Returns the configured maximum sample size. - * @return configured maximum sample size - */ - public int getK() { return k_; } - - /** - * Returns the number of items processed by the sketch, regardless - * of item weight. - * @return count of items processed by the sketch - */ - public long getN() { return n_; } - - /** - * Returns the cumulative weight of items processed by the sketch. - * @return cumulative weight of items seen - */ - public double getCumulativeWeight() { return cumulativeWt_; } - - /** - * Returns the expected number of samples returned upon a call to - * getResult(). The number is a floating point value, where the - * fractional portion represents the probability of including a - * "partial item" from the sample. - * - *

The value C should be no larger than the sketch's configured - * value of k, although numerical precision limitations mean it - * may exceed k by double precision floating point error margins - * in certain cases. - * @return The expected number of samples returned when querying the sketch - */ - public double getC() { return sample_.getC(); } - - /** - * Returns true if the sketch is empty. - * @return empty flag - */ - public boolean isEmpty() { return n_ == 0; } - - /** - * Resets the sketch to its default, empty state. - */ - public void reset() { - n_ = 0; - cumulativeWt_ = 0.0; - wtMax_ = 0.0; - rho_ = 1.0; - sample_ = new EbppsItemsSample<>(k_); - } - - /** - * Returns the size of a byte array representation of this sketch. May fail for polymorphic item types. - * - * @param serDe An instance of ArrayOfItemsSerDe - * @return the length of a byte array representation of this sketch - */ - public int getSerializedSizeBytes(final ArrayOfItemsSerDe serDe) { - if (isEmpty()) { - return Family.EBPPS.getMinPreLongs() << 3; - } else if (sample_.getC() < 1.0) { - return getSerializedSizeBytes(serDe, sample_.getPartialItem().getClass()); - } else { - return getSerializedSizeBytes(serDe, sample_.getSample().get(0).getClass()); - } - } - - /** - * Returns the length of a byte array representation of this sketch. Copies contents into an array of the - * specified class for serialization to allow for polymorphic types. - * - * @param serDe An instance of ArrayOfItemsSerDe - * @param clazz The class represented by <T> - * @return the length of a byte array representation of this sketch - */ - public int getSerializedSizeBytes(final ArrayOfItemsSerDe serDe, final Class clazz) { - if (n_ == 0) { - return Family.EBPPS.getMinPreLongs() << 3; - } - - final int preLongs = Family.EBPPS.getMaxPreLongs(); - final byte[] itemBytes = serDe.serializeToByteArray(sample_.getAllSamples(clazz)); - // in C++, c_ is serialized as part of the sample_ and not included in the header size - return (preLongs << 3) + Double.BYTES + itemBytes.length; - } - - /** - * Returns a byte array representation of this sketch. May fail for polymorphic item types. - * - * @param serDe An instance of ArrayOfItemsSerDe - * @return a byte array representation of this sketch - */ - public byte[] toByteArray(final ArrayOfItemsSerDe serDe) { - if (n_ == 0) { - // null class is ok since empty -- no need to call serDe - return toByteArray(serDe, null); - } else if (sample_.getC() < 1.0) { - return toByteArray(serDe, sample_.getPartialItem().getClass()); - } else { - return toByteArray(serDe, sample_.getSample().get(0).getClass()); - } - } - - /** - * Returns a byte array representation of this sketch. Copies contents into an array of the - * specified class for serialization to allow for polymorphic types. - * - * @param serDe An instance of ArrayOfItemsSerDe - * @param clazz The class represented by <T> - * @return a byte array representation of this sketch - */ - public byte[] toByteArray(final ArrayOfItemsSerDe serDe, final Class clazz) { - final int preLongs, outBytes; - final boolean empty = n_ == 0; - byte[] itemBytes = null; // for serialized items from sample_ - - if (empty) { - preLongs = 1; - outBytes = 8; - } else { - preLongs = Family.EBPPS.getMaxPreLongs(); - itemBytes = serDe.serializeToByteArray(sample_.getAllSamples(clazz)); - // in C++, c_ is serialized as part of the sample_ and not included in the header size - outBytes = (preLongs << 3) + Double.BYTES + itemBytes.length; - } - final byte[] outArr = new byte[outBytes]; - final MemorySegment seg = MemorySegment.ofArray(outArr); - - // Common header elements - PreambleUtil.insertPreLongs(seg, preLongs); // Byte 0 - PreambleUtil.insertSerVer(seg, EBPPS_SER_VER); // Byte 1 - PreambleUtil.insertFamilyID(seg, Family.EBPPS.getID()); // Byte 2 - if (empty) { - PreambleUtil.insertFlags(seg, EMPTY_FLAG_MASK); // Byte 3 - } else { - PreambleUtil.insertFlags(seg, sample_.hasPartialItem() ? HAS_PARTIAL_ITEM_MASK : 0); - } - PreambleUtil.insertK(seg, k_); // Bytes 4-7 - - // conditional elements - if (!empty) { - PreambleUtil.insertN(seg, n_); - PreambleUtil.insertEbppsCumulativeWeight(seg, cumulativeWt_); - PreambleUtil.insertEbppsMaxWeight(seg, wtMax_); - PreambleUtil.insertEbppsRho(seg, rho_); - - // data from sample_ -- itemBytes includes the partial item - seg.set(JAVA_DOUBLE_UNALIGNED, EBPPS_C_DOUBLE, sample_.getC()); - MemorySegment.copy(itemBytes, 0, seg, JAVA_BYTE, EBPPS_ITEMS_START, itemBytes.length); - } - - return outArr; - } - - private static void checkK(final int k) { - if ((k <= 0) || (k > MAX_K)) { - throw new SketchesArgumentException("k must be strictly positive and less than " + MAX_K); - } - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/PreambleUtil.java b/src/main/java/org/apache/datasketches/sampling/PreambleUtil.java deleted file mode 100644 index 52d93362e..000000000 --- a/src/main/java/org/apache/datasketches/sampling/PreambleUtil.java +++ /dev/null @@ -1,528 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.zeroPad; - -import java.lang.foreign.MemorySegment; -import java.util.Locale; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; - -//@formatter:off - -/** - * This class defines the preamble items structure and provides basic utilities for some of the key - * fields. Fields are presented in Little Endian format, but multi-byte values (int, long, double) - * are stored in native byte order. All byte values are treated as unsigned. - * - *

Reservoir Sampling

- * - *

Sketch: The count of items seen is limited to 48 bits (~256 trillion) even - * though there are adjacent unused preamble bits. The acceptance probability for an item is a - * double in the range [0,1), limiting us to 53 bits of randomness due to details of the IEEE - * floating point format. To ensure meaningful probabilities as the items seen count approaches - * capacity, we intentionally use slightly fewer bits.

- * - *

An empty reservoir sampling sketch only requires 8 bytes. A non-empty sampling sketch - * requires 16 bytes of preamble.

- * - *
- * Long || Start Byte Adr:
- * Adr:
- *      ||       0        |    1   |    2   |    3   |    4   |    5   |    6   |    7   |
- *  0   || Preamble_Longs | SerVer | FamID  |  Flags |---------Max Res. Size (K)---------|
- *
- *      ||       8        |    9   |   10   |   11   |   12   |   13   |   14   |   15   |
- *  1   ||----------------------------Items Seen Count (N)-------------------------------|
- *  
- * - *

Union: The reservoir union has fewer internal parameters to track and uses - * a slightly different preamble structure. The maximum reservoir size intentionally occupies the - * same byte range as the reservoir size in the sketch preamble, allowing the same methods to be - * used for reading and writing the values. The varopt union takes advantage of the same format. - * The items in the union are stored in a reservoir sketch-compatible format after the union - * preamble. - *

- * - *

An empty union only requires 8 bytes. A non-empty union requires 8 bytes of preamble.

- * - *
- * Long || Start Byte Adr:
- * Adr:
- *      ||       0        |    1   |    2   |    3   |    4   |    5   |    6   |    7   |
- *  0   || Preamble_Longs | SerVer | FamID  |  Flags |---------Max Res. Size (K)---------|
- * 
- * - * - *

VarOpt Sampling

- * - *

VarOpt: A VarOpt sketch has a more complex internal items structure and - * requires a larger preamble. Values serving a similar purpose in both reservoir and varopt sampling - * share the same byte ranges, allowing method re-use where practical.

- * - *

An empty varopt sample requires 8 bytes. A non-empty sketch requires 16 bytes of preamble - * for an under-full sample and otherwise 32 bytes of preamble.

- * - *
- * Long || Start Byte Adr:
- * Adr:
- *      ||       0        |    1   |    2   |    3   |    4   |    5   |    6   |    7   |
- *  0   || Preamble_Longs | SerVer | FamID  |  Flags |---------Max Res. Size (K)---------|
- *
- *      ||       8        |    9   |   10   |   11   |   12   |   13   |   14   |   15   |
- *  1   ||----------------------------Items Seen Count (N)-------------------------------|
- *
- *      ||      16        |   17   |   18   |   19   |   20   |   21   |   22   |   23   |
- *  2   ||--------Item Count in R-----------|-----------Item Count in H------------------|
- *
- *      ||      24        |   25   |   26   |   27   |   28   |   29   |   30   |   31   |
- *  3   ||------------------------------Total Weight in R--------------------------------|
- *  
- * - *

VarOpt Union: VarOpt unions also store more information than a reservoir - * sketch. As before, we keep values with similar to the same meaning in corresponding locations - * actoss sketch and union formats. The items in the union are stored in a varopt sketch-compatible - * format after the union preamble.

- * - *

An empty union only requires 8 bytes. A non-empty union requires 32 bytes of preamble.

- * - *
- * Long || Start Byte Adr:
- * Adr:
- *      ||       0        |    1   |    2   |    3   |    4   |    5   |    6   |    7   |
- *  0   || Preamble_Longs | SerVer | FamID  |  Flags |---------Max Res. Size (K)---------|
- *
- *      ||       8        |    9   |   10   |   11   |   12   |   13   |   14   |   15   |
- *  1   ||----------------------------Items Seen Count (N)-------------------------------|
- *
- *      ||      16        |   17   |   18   |   19   |   20   |   21   |   22   |   23   |
- *  2   ||-------------------------Outer Tau Numerator (double)--------------------------|
- *
- *      ||      24        |   25   |   26   |   27   |   28   |   29   |   30   |   31   |
- *  3   ||-------------------------Outer Tau Denominator (long)--------------------------|
- *  
- * - * - *

EPPS Sampling

- * - *

An empty sketch requires 8 bytes. - * - *

- * Long || Start Byte Adr:
- * Adr:
- *      ||       0        |    1   |    2   |    3   |    4   |    5   |    6   |    7   |
- *  0   || Preamble_Longs | SerVer | FamID  |  Flags |---------Max Res. Size (K)---------|
- * 
- * - *

A non-empty sketch requires 40 bytes of preamble. C looks like part of - * the preamble but is treated as part of the sample state. - * - *

The count of items seen is not used but preserved as the value seems like a useful - * count to track. - * - *

- * Long || Start Byte Adr:
- * Adr:
- *      ||       0        |    1   |    2   |    3   |    4   |    5   |    6   |    7   |
- *  0   || Preamble_Longs | SerVer | FamID  |  Flags |---------Max Res. Size (K)---------|
- *
- *      ||       8        |    9   |   10   |   11   |   12   |   13   |   14   |   15   |
- *  1   ||---------------------------Items Seen Count (N)--------------------------------|
- *
- *      ||      16        |   17   |   18   |   19   |   20   |   21   |   22   |   23   |
- *  2   ||----------------------------Cumulative Weight----------------------------------|
- *
- *      ||      24        |   25   |   26   |   27   |   28   |   29   |   30   |   31   |
- *  3   ||-----------------------------Max Item Weight-----------------------------------|
- *
- *      ||      32        |   33   |   34   |   35   |   36   |   37   |   38   |   39   |
- *  4   ||----------------------------------Rho------------------------------------------|
- *
- *      ||      40        |   41   |   42   |   43   |   44   |   45   |   46   |   47   |
- *  5   ||-----------------------------------C-------------------------------------------|
- *
- *      ||      40+                      |
- *  6+  ||  {Items Array}                |
- *      ||  {Optional Item (if needed)}  |
- * 
- * - * @author Jon Malkin - * @author Lee Rhodes - */ -final class PreambleUtil { - - private PreambleUtil() {} - - // ###### DO NOT MESS WITH THIS FROM HERE ... - // Preamble byte Addresses - static final int PREAMBLE_LONGS_BYTE = 0; // Only low 6 bits used - static final int LG_RESIZE_FACTOR_BIT = 6; // upper 2 bits. Not used by compact or direct. - static final int SER_VER_BYTE = 1; - static final int FAMILY_BYTE = 2; - static final int FLAGS_BYTE = 3; - static final int RESERVOIR_SIZE_SHORT = 4; // used in ser_ver 1 - static final int RESERVOIR_SIZE_INT = 4; - static final int SERDE_ID_SHORT = 6; // used in ser_ver 1 - static final int ITEMS_SEEN_LONG = 8; - - static final int MAX_K_SIZE_INT = 4; // used in Union only - static final int OUTER_TAU_NUM_DOUBLE = 16; // used in Varopt Union only - static final int OUTER_TAU_DENOM_LONG = 24; // used in Varopt Union only - - // constants and addresses used in varopt - static final int ITEM_COUNT_H_INT = 16; - static final int ITEM_COUNT_R_INT = 20; - static final int TOTAL_WEIGHT_R_DOUBLE = 24; - static final int VO_PRELONGS_EMPTY = Family.VAROPT.getMinPreLongs(); - static final int VO_PRELONGS_WARMUP = 3; // Doesn't match min or max prelongs in Family - static final int VO_PRELONGS_FULL = Family.VAROPT.getMaxPreLongs(); - - // constants and addresses used in EBPPS - static final int EBPPS_CUM_WT_DOUBLE = 16; - static final int EBPPS_MAX_WT_DOUBLE = 24; - static final int EBPPS_RHO_DOUBLE = 32; - - // flag bit masks - static final int EMPTY_FLAG_MASK = 4; - static final int HAS_PARTIAL_ITEM_MASK = 8; // EBPPS only - static final int GADGET_FLAG_MASK = 128; - - //Other constants - static final int RESERVOIR_SER_VER = 2; - static final int VAROPT_SER_VER = 2; - static final int EBPPS_SER_VER = 1; - - // STRINGS - - /** - * Returns a human readable string summary of the preamble state of the given byte array. - * Used primarily in testing. - * - * @param byteArr the given byte array. - * @return the summary preamble string. - */ - static String preambleToString(final byte[] byteArr) { - final MemorySegment seg = MemorySegment.ofArray(byteArr); - return preambleToString(seg); - } - - /** - * Returns a human readable string summary of the preamble state of the given MemorySegment. - * Note: other than making sure that the given MemorySegment size is large - * enough for just the preamble, this does not do much value checking of the contents of the - * preamble as this is primarily a tool for debugging the preamble visually. - * - * @param seg the given MemorySegment. - * @return the summary preamble string. - */ - static String preambleToString(final MemorySegment seg) { - final int preLongs = getAndCheckPreLongs(seg); // make sure we can get the assumed preamble - - final Family family = Family.idToFamily(seg.get(JAVA_BYTE, FAMILY_BYTE)); - - switch (family) { - case RESERVOIR: - case VAROPT: - return sketchPreambleToString(seg, family, preLongs); - case RESERVOIR_UNION: - case VAROPT_UNION: - return unionPreambleToString(seg, family, preLongs); - default: - throw new SketchesArgumentException("Inspecting preamble with Sampling family's " - + "PreambleUtil with object of family " + family.getFamilyName()); - } - } - - private static String sketchPreambleToString(final MemorySegment seg, - final Family family, - final int preLongs) { - final ResizeFactor rf = ResizeFactor.getRF(extractResizeFactor(seg)); - final int serVer = extractSerVer(seg); - - // Flags - final int flags = extractFlags(seg); - final String flagsStr = zeroPad(Integer.toBinaryString(flags), 8) + ", " + (flags); - //final boolean readOnly = (flags & READ_ONLY_FLAG_MASK) > 0; - final boolean isEmpty = (flags & EMPTY_FLAG_MASK) > 0; - final boolean isGadget = (flags & GADGET_FLAG_MASK) > 0; - - final int k; - if (serVer == 1) { - final short encK = extractEncodedReservoirSize(seg); - k = ReservoirSize.decodeValue(encK); - } else { - k = extractK(seg); - } - - long n = 0; - if (!isEmpty) { - n = extractN(seg); - } - final long dataBytes = seg.byteSize() - (preLongs << 3); - - final StringBuilder sb = new StringBuilder(); - sb.append(LS) - .append("### END ") - .append(family.getFamilyName().toUpperCase(Locale.US)) - .append(" PREAMBLE SUMMARY").append(LS) - .append("Byte 0: Preamble Longs : ").append(preLongs).append(LS) - .append("Byte 0: ResizeFactor : ").append(rf.toString()).append(LS) - .append("Byte 1: Serialization Version: ").append(serVer).append(LS) - .append("Byte 2: Family : ").append(family.toString()).append(LS) - .append("Byte 3: Flags Field : ").append(flagsStr).append(LS) - //.append(" READ_ONLY : ").append(readOnly).append(LS) - .append(" EMPTY : ").append(isEmpty).append(LS); - if (family == Family.VAROPT) { - sb.append(" GADGET : ").append(isGadget).append(LS); - } - sb.append("Bytes 4-7: Sketch Size (k) : ").append(k).append(LS); - if (!isEmpty) { - sb.append("Bytes 8-15: Items Seen (n) : ").append(n).append(LS); - } - if ((family == Family.VAROPT) && !isEmpty) { - final int hCount = extractHRegionItemCount(seg); - final int rCount = extractRRegionItemCount(seg); - final double totalRWeight = extractTotalRWeight(seg); - sb.append("Bytes 16-19: H region count : ").append(hCount).append(LS) - .append("Bytes 20-23: R region count : ").append(rCount).append(LS); - if (rCount > 0) { - sb.append("Bytes 24-31: R region weight : ").append(totalRWeight).append(LS); - } - } - - sb.append("TOTAL Sketch Bytes : ").append(seg.byteSize()).append(LS) - .append(" Preamble Bytes : ").append(preLongs << 3).append(LS) - .append(" Data Bytes : ").append(dataBytes).append(LS) - .append("### END ") - .append(family.getFamilyName().toUpperCase(Locale.US)) - .append(" PREAMBLE SUMMARY").append(LS); - return sb.toString(); - } - - private static String unionPreambleToString(final MemorySegment seg, - final Family family, - final int preLongs) { - final ResizeFactor rf = ResizeFactor.getRF(extractResizeFactor(seg)); - final int serVer = extractSerVer(seg); - - // Flags - final int flags = extractFlags(seg); - final String flagsStr = zeroPad(Integer.toBinaryString(flags), 8) + ", " + (flags); - //final boolean readOnly = (flags & READ_ONLY_FLAG_MASK) > 0; - final boolean isEmpty = (flags & EMPTY_FLAG_MASK) > 0; - - final int k; - if (serVer == 1) { - final short encK = extractEncodedReservoirSize(seg); - k = ReservoirSize.decodeValue(encK); - } else { - k = extractK(seg); - } - - final long dataBytes = seg.byteSize() - (preLongs << 3); - - return LS - + "### END " + family.getFamilyName().toUpperCase(Locale.US) + " PREAMBLE SUMMARY" + LS - + "Byte 0: Preamble Longs : " + preLongs + LS - + "Byte 0: ResizeFactor : " + rf.toString() + LS - + "Byte 1: Serialization Version : " + serVer + LS - + "Byte 2: Family : " + family.toString() + LS - + "Byte 3: Flags Field : " + flagsStr + LS - //+ " READ_ONLY : " + readOnly + LS - + " EMPTY : " + isEmpty + LS - + "Bytes 4-7: Max Sketch Size (maxK): " + k + LS - + "TOTAL Sketch Bytes : " + seg.byteSize() + LS - + " Preamble Bytes : " + (preLongs << 3) + LS - + " Sketch Bytes : " + dataBytes + LS - + "### END " + family.getFamilyName().toUpperCase(Locale.US) + " PREAMBLE SUMMARY" + LS; - } - - // Extraction methods - - static int extractPreLongs(final MemorySegment seg) { - return seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE) & 0x3F; - } - - static int extractResizeFactor(final MemorySegment seg) { - return (seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE) >>> LG_RESIZE_FACTOR_BIT) & 0x3; - } - - static int extractSerVer(final MemorySegment seg) { - return seg.get(JAVA_BYTE, SER_VER_BYTE) & 0xFF; - } - - static int extractFamilyID(final MemorySegment seg) { - return seg.get(JAVA_BYTE, FAMILY_BYTE) & 0xFF; - } - - static int extractFlags(final MemorySegment seg) { - return seg.get(JAVA_BYTE, FLAGS_BYTE) & 0xFF; - } - - static short extractEncodedReservoirSize(final MemorySegment seg) { - return seg.get(JAVA_SHORT_UNALIGNED, RESERVOIR_SIZE_SHORT); - } - - static int extractK(final MemorySegment seg) { - return seg.get(JAVA_INT_UNALIGNED, RESERVOIR_SIZE_INT); - } - - static int extractMaxK(final MemorySegment seg) { - return extractK(seg); - } - - static long extractN(final MemorySegment seg) { - return seg.get(JAVA_LONG_UNALIGNED, ITEMS_SEEN_LONG); - } - - static int extractHRegionItemCount(final MemorySegment seg) { - return seg.get(JAVA_INT_UNALIGNED, ITEM_COUNT_H_INT); - } - - static int extractRRegionItemCount(final MemorySegment seg) { - return seg.get(JAVA_INT_UNALIGNED, ITEM_COUNT_R_INT); - } - - static double extractTotalRWeight(final MemorySegment seg) { - return seg.get(JAVA_DOUBLE_UNALIGNED, TOTAL_WEIGHT_R_DOUBLE); - } - - static double extractOuterTauNumerator(final MemorySegment seg) { - return seg.get(JAVA_DOUBLE_UNALIGNED, OUTER_TAU_NUM_DOUBLE); - } - - static long extractOuterTauDenominator(final MemorySegment seg) { - return seg.get(JAVA_LONG_UNALIGNED, OUTER_TAU_DENOM_LONG); - } - - static double extractEbppsCumulativeWeight(final MemorySegment seg) { - return seg.get(JAVA_DOUBLE_UNALIGNED, EBPPS_CUM_WT_DOUBLE); - } - - static double extractEbppsMaxWeight(final MemorySegment seg) { - return seg.get(JAVA_DOUBLE_UNALIGNED, EBPPS_MAX_WT_DOUBLE); - } - - static double extractEbppsRho(final MemorySegment seg) { - return seg.get(JAVA_DOUBLE_UNALIGNED, EBPPS_RHO_DOUBLE); - } - - // Insertion methods - - static void insertPreLongs(final MemorySegment wseg, final int preLongs) { - final int curByte = wseg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE); - final int mask = 0x3F; - final byte newByte = (byte) ((preLongs & mask) | (~mask & curByte)); - wseg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, newByte); - } - - static void insertLgResizeFactor(final MemorySegment wseg, final int rf) { - final int curByte = wseg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE); - final int shift = LG_RESIZE_FACTOR_BIT; // shift in bits - final int mask = 3; - final byte newByte = (byte) (((rf & mask) << shift) | (~(mask << shift) & curByte)); - wseg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, newByte); - } - - static void insertSerVer(final MemorySegment wseg, final int serVer) { - wseg.set(JAVA_BYTE, SER_VER_BYTE, (byte) serVer); - } - - static void insertFamilyID(final MemorySegment wseg, final int famId) { - wseg.set(JAVA_BYTE, FAMILY_BYTE, (byte) famId); - } - - static void insertFlags(final MemorySegment wseg, final int flags) { - wseg.set(JAVA_BYTE, FLAGS_BYTE, (byte) flags); - } - - static void insertK(final MemorySegment wseg, final int k) { - wseg.set(JAVA_INT_UNALIGNED, RESERVOIR_SIZE_INT, k); - } - - static void insertMaxK(final MemorySegment wseg, final int maxK) { - insertK(wseg, maxK); - } - - static void insertN(final MemorySegment wseg, final long totalSeen) { - wseg.set(JAVA_LONG_UNALIGNED, ITEMS_SEEN_LONG, totalSeen); - } - - static void insertHRegionItemCount(final MemorySegment wseg, final int hCount) { - wseg.set(JAVA_INT_UNALIGNED, ITEM_COUNT_H_INT, hCount); - } - - static void insertRRegionItemCount(final MemorySegment wseg, final int rCount) { - wseg.set(JAVA_INT_UNALIGNED, ITEM_COUNT_R_INT, rCount); - } - - static void insertTotalRWeight(final MemorySegment wseg, final double weight) { - wseg.set(JAVA_DOUBLE_UNALIGNED, TOTAL_WEIGHT_R_DOUBLE, weight); - } - - static void insertOuterTauNumerator(final MemorySegment wseg, final double numer) { - wseg.set(JAVA_DOUBLE_UNALIGNED, OUTER_TAU_NUM_DOUBLE, numer); - } - - static void insertOuterTauDenominator(final MemorySegment wseg, final long denom) { - wseg.set(JAVA_LONG_UNALIGNED, OUTER_TAU_DENOM_LONG, denom); - } - - static void insertEbppsCumulativeWeight(final MemorySegment wseg, final double cumWt) { - wseg.set(JAVA_DOUBLE_UNALIGNED, EBPPS_CUM_WT_DOUBLE, cumWt); - } - - static void insertEbppsMaxWeight(final MemorySegment wseg, final double maxWt) { - wseg.set(JAVA_DOUBLE_UNALIGNED, EBPPS_MAX_WT_DOUBLE, maxWt); - } - - static void insertEbppsRho(final MemorySegment wseg, final double rho) { - wseg.set(JAVA_DOUBLE_UNALIGNED, EBPPS_RHO_DOUBLE, rho); - } - - /** - * Checks MemorySegment for capacity to hold the preamble and returns the extracted preLongs. - * @param seg the given MemorySegment - * @return the extracted prelongs value. - */ - static int getAndCheckPreLongs(final MemorySegment seg) { - final long cap = seg.byteSize(); - if (cap < 8) { throwNotBigEnough(cap, 8); } - final int preLongs = seg.get(JAVA_BYTE, 0) & 0x3F; - final int required = Math.max(preLongs << 3, 8); - if (cap < required) { throwNotBigEnough(cap, required); } - return preLongs; - } - - private static void throwNotBigEnough(final long cap, final int required) { - throw new SketchesArgumentException( - "Possible Corruption: Size of byte array or MemorySegment not large enough: Size: " + cap - + ", Required: " + required); - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/ReservoirItemsSketch.java b/src/main/java/org/apache/datasketches/sampling/ReservoirItemsSketch.java deleted file mode 100644 index e8ad5f23b..000000000 --- a/src/main/java/org/apache/datasketches/sampling/ReservoirItemsSketch.java +++ /dev/null @@ -1,646 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.sampling.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.sampling.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SER_VER; -import static org.apache.datasketches.sampling.PreambleUtil.extractEncodedReservoirSize; -import static org.apache.datasketches.sampling.PreambleUtil.extractFlags; -import static org.apache.datasketches.sampling.PreambleUtil.extractK; -import static org.apache.datasketches.sampling.PreambleUtil.extractN; -import static org.apache.datasketches.sampling.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.sampling.PreambleUtil.extractResizeFactor; -import static org.apache.datasketches.sampling.PreambleUtil.extractSerVer; -import static org.apache.datasketches.sampling.SamplingUtil.pseudoHypergeometricLBonP; -import static org.apache.datasketches.sampling.SamplingUtil.pseudoHypergeometricUBonP; - -import java.lang.foreign.MemorySegment; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.function.Predicate; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.Util; - -/** - * This sketch provides a reservoir sample over an input stream of items. The sketch contains a - * uniform random sample of unweighted items from the stream. - * - * @param The type of object held in the reservoir. - * - * @author Jon Malkin - * @author Kevin Lang - */ -public final class ReservoirItemsSketch { - - /** - * The smallest sampling array allocated: 16 - */ - private static final int MIN_LG_ARR_ITEMS = 4; - - /** - * Using 48 bits to capture number of items seen, so sketch cannot process more after this - * many items capacity - */ - private static final long MAX_ITEMS_SEEN = 0xFFFFFFFFFFFFL; - - /** - * Default sampling size multiple when reallocating storage: 8 - */ - private static final ResizeFactor DEFAULT_RESIZE_FACTOR = ResizeFactor.X8; - - private final int reservoirSize_; // max size of reservoir - private int currItemsAlloc_; // currently allocated array size - private long itemsSeen_; // number of items presented to sketch - private final ResizeFactor rf_; // resize factor - private ArrayList data_; // stored sampled items - - private ReservoirItemsSketch(final int k, final ResizeFactor rf) { - // required due to a theorem about lightness during merging - if (k < 2) { - throw new SketchesArgumentException("k must be at least 2"); - } - - reservoirSize_ = k; - rf_ = rf; - - itemsSeen_ = 0; - - final int ceilingLgK = Util.exactLog2OfInt(Util.ceilingPowerOf2(reservoirSize_), "reservoirSize_"); - final int initialLgSize = - SamplingUtil.startingSubMultiple(ceilingLgK, rf_.lg(), MIN_LG_ARR_ITEMS); - - currItemsAlloc_ = SamplingUtil.getAdjustedSize(reservoirSize_, 1 << initialLgSize); - data_ = new ArrayList<>(currItemsAlloc_); - } - - /** - * Creates a fully-populated sketch. Used internally to avoid extraneous array allocation - * when deserializing. - * Uses size of items array to as initial array allocation. - * - * @param data Reservoir items as an ArrayList<T> - * @param itemsSeen Number of items presented to the sketch so far - * @param rf See Resize Factor - * @param k Maximum size of reservoir - */ - private ReservoirItemsSketch(final ArrayList data, final long itemsSeen, - final ResizeFactor rf, final int k) { - if (data == null) { - throw new SketchesArgumentException("Instantiating sketch with null reservoir"); - } - if (k < 2) { - throw new SketchesArgumentException("Cannot instantiate sketch with reservoir size less than 2"); - } - if (k < data.size()) { - throw new SketchesArgumentException("Instantiating sketch with max size less than array length: " - + k + " max size, array of length " + data.size()); - } - if (((itemsSeen >= k) && (data.size() < k)) - || ((itemsSeen < k) && (data.size() < itemsSeen))) { - throw new SketchesArgumentException("Instantiating sketch with too few samples. Items seen: " - + itemsSeen + ", max reservoir size: " + k - + ", items array length: " + data.size()); - } - - // Should we compute target current allocation to validate? - reservoirSize_ = k; - currItemsAlloc_ = data.size(); - itemsSeen_ = itemsSeen; - rf_ = rf; - data_ = data; - } - - /** - * Fast constructor for fully-specified sketch with no encoded/decoding size and no - * validation. Used with copy(). - * - * @param k Maximum reservoir capacity - * @param currItemsAlloc Current array size (assumed equal to items.length) - * @param itemsSeen Total items seen by this sketch - * @param rf See Resize Factor - * @param data Data ArrayList backing the reservoir, will not be copied - */ - private ReservoirItemsSketch(final int k, final int currItemsAlloc, final long itemsSeen, - final ResizeFactor rf, final ArrayList data) { - reservoirSize_ = k; - currItemsAlloc_ = currItemsAlloc; - itemsSeen_ = itemsSeen; - rf_ = rf; - data_ = data; - } - - /** - * Construct a mergeable sampling sketch with up to k samples using the default resize - * factor (8). - * - * @param k Maximum size of sampling. Allocated size may be smaller until reservoir fills. - * Unlike many sketches in this package, this value does not need to be a - * power of 2. - * @param The type of object held in the reservoir. - * @return A ReservoirLongsSketch initialized with maximum size k and the default resize factor. - */ - public static ReservoirItemsSketch newInstance(final int k) { - return new ReservoirItemsSketch<>(k, DEFAULT_RESIZE_FACTOR); - } - - /** - * Construct a mergeable sampling sketch with up to k samples using a specified resize factor. - * - * @param k Maximum size of sampling. Allocated size may be smaller until reservoir fills. - * Unlike many sketches in this package, this value does not need to be a - * power of 2. - * @param rf See Resize Factor - * @param The type of object held in the reservoir. - * @return A ReservoirLongsSketch initialized with maximum size k and resize factor rf. - */ - public static ReservoirItemsSketch newInstance(final int k, final ResizeFactor rf) { - return new ReservoirItemsSketch<>(k, rf); - } - - /** - * Thin wrapper around private constructor - * - * @param data type - * @param data Reservoir items as ArrayList<T> - * @param itemsSeen Number of items presented to the sketch so far - * @param rf See Resize Factor - * @param k Compact encoding of reservoir size - * @return New sketch built with the provided inputs - */ - static ReservoirItemsSketch newInstance(final ArrayList data, final long itemsSeen, - final ResizeFactor rf, final int k) { - return new ReservoirItemsSketch<>(data, itemsSeen, rf, k); - } - - /** - * Returns a sketch instance of this class from the given srcSeg, - * which must be a MemorySegment representation of this sketch class. - * - * @param The type of item this sketch contains - * @param srcSeg a MemorySegment representation of a sketch of this class. - * @param serDe An instance of ArrayOfItemsSerDe - * @return a sketch instance of this class - */ - public static ReservoirItemsSketch heapify(final MemorySegment srcSeg, - final ArrayOfItemsSerDe serDe) { - Family.RESERVOIR.checkFamilyID(srcSeg.get(JAVA_BYTE, FAMILY_BYTE)); - - final int numPreLongs = extractPreLongs(srcSeg); - final ResizeFactor rf = ResizeFactor.getRF(extractResizeFactor(srcSeg)); - final int serVer = extractSerVer(srcSeg); - final boolean isEmpty = (extractFlags(srcSeg) & EMPTY_FLAG_MASK) != 0; - final long itemsSeen = (isEmpty ? 0 : extractN(srcSeg)); - int k = extractK(srcSeg); - - // Check values - final boolean preLongsEqMin = (numPreLongs == Family.RESERVOIR.getMinPreLongs()); - final boolean preLongsEqMax = (numPreLongs == Family.RESERVOIR.getMaxPreLongs()); - - if (!preLongsEqMin && !preLongsEqMax) { - throw new SketchesArgumentException( - "Possible corruption: Non-empty sketch with only " - + Family.RESERVOIR.getMinPreLongs() + " preLong(s)"); - } - - if (serVer != RESERVOIR_SER_VER) { - if (serVer == 1) { - final short encK = extractEncodedReservoirSize(srcSeg); - k = ReservoirSize.decodeValue(encK); - } else { - throw new SketchesArgumentException( - "Possible Corruption: Ser Ver must be " + RESERVOIR_SER_VER + ": " + serVer); - } - } - - if (isEmpty) { - return new ReservoirItemsSketch<>(k, rf); - } - - final int preLongBytes = numPreLongs << 3; - int allocatedItems = k; // default to full reservoir - - if (itemsSeen < k) { - // under-full so determine size to allocate, using ceilingLog2(totalSeen) as minimum - // casts to int are safe since under-full - final int ceilingLgK = Util.exactLog2OfInt(Util.ceilingPowerOf2(k), "heapify"); - final int minLgSize = Util.exactLog2OfInt(Util.ceilingPowerOf2((int) itemsSeen), "heapify"); - final int initialLgSize = SamplingUtil.startingSubMultiple(ceilingLgK, rf.lg(), - Math.max(minLgSize, MIN_LG_ARR_ITEMS)); - - allocatedItems = SamplingUtil.getAdjustedSize(k, 1 << initialLgSize); - } - - final int itemsToRead = (int) Math.min(k, itemsSeen); - final T[] data = serDe.deserializeFromMemorySegment(srcSeg, preLongBytes, itemsToRead); - final ArrayList dataList = new ArrayList<>(Arrays.asList(data)); - - final ReservoirItemsSketch ris = new ReservoirItemsSketch<>(dataList, itemsSeen, rf, k); - ris.data_.ensureCapacity(allocatedItems); - ris.currItemsAlloc_ = allocatedItems; - - return ris; - } - - /** - * Returns the sketch's value of k, the maximum number of samples stored in the - * reservoir. The current number of items in the sketch may be lower. - * - * @return k, the maximum number of samples in the reservoir - */ - public int getK() { - return reservoirSize_; - } - - /** - * Returns the number of items processed from the input stream - * - * @return n, the number of stream items the sketch has seen - */ - public long getN() { - return itemsSeen_; - } - - /** - * Returns the current number of items in the reservoir, which may be smaller than the - * reservoir capacity. - * - * @return the number of items currently in the reservoir - */ - public int getNumSamples() { - return (int) Math.min(reservoirSize_, itemsSeen_); - } - - /** - * Randomly decide whether or not to include an item in the sample set. - * - * @param item a unit-weight (equivalently, unweighted) item of the set being sampled from - */ - public void update(final T item) { - if (itemsSeen_ == MAX_ITEMS_SEEN) { - throw new SketchesStateException("Sketch has exceeded capacity for total items seen: " - + MAX_ITEMS_SEEN); - } - if (item == null) { - return; - } - - if (itemsSeen_ < reservoirSize_) { // initial phase, take the first reservoirSize_ items - if (itemsSeen_ >= currItemsAlloc_) { - growReservoir(); - } - assert itemsSeen_ < currItemsAlloc_; - // we'll randomize replacement positions, so in-order should be valid for now - data_.add(item); - ++itemsSeen_; - } else { // code for steady state where we sample randomly - ++itemsSeen_; - // prob(keep_item) < k / n = reservoirSize_ / itemsSeen_ - // so multiply to get: keep if rand * itemsSeen_ < reservoirSize_ - if ((SamplingUtil.rand().nextDouble() * itemsSeen_) < reservoirSize_) { - final int newSlot = SamplingUtil.rand().nextInt(reservoirSize_); - data_.set(newSlot, item); - } - } - } - - /** - * Resets this sketch to the empty state, but retains the original value of k. - */ - public void reset() { - final int ceilingLgK = Util.exactLog2OfInt(Util.ceilingPowerOf2(reservoirSize_), "ReservoirItemsSketch"); - final int initialLgSize = - SamplingUtil.startingSubMultiple(ceilingLgK, rf_.lg(), MIN_LG_ARR_ITEMS); - - currItemsAlloc_ = SamplingUtil.getAdjustedSize(reservoirSize_, 1 << initialLgSize); - data_ = new ArrayList<>(currItemsAlloc_); - itemsSeen_ = 0; - } - - /** - * Returns a copy of the items in the reservoir, or null if empty. The returned array length - * may be smaller than the reservoir capacity. - * - *

In order to allocate an array of generic type T, uses the class of the first item in - * the array. This method method may throw an ArrayAssignmentException if the - * reservoir stores instances of a polymorphic base class.

- * - * @return A copy of the reservoir array - */ - @SuppressWarnings("unchecked") - public T[] getSamples() { - if (itemsSeen_ == 0) { - return null; - } - - final Class clazz = data_.get(0).getClass(); - return data_.toArray((T[]) Array.newInstance(clazz, 0)); - } - - /** - * Returns a copy of the items in the reservoir as members of Class clazz, or null - * if empty. The returned array length may be smaller than the reservoir capacity. - * - *

This method allocates an array of class clazz, which must either match or - * extend T. This method should be used when objects in the array are all instances of T but - * are not necessarily instances of the base class.

- * - * @param clazz A class to which the items are cast before returning - * @return A copy of the reservoir array - */ - @SuppressWarnings("unchecked") - public T[] getSamples(final Class clazz) { - if (itemsSeen_ == 0) { - return null; - } - - return data_.toArray((T[]) Array.newInstance(clazz, 0)); - } - - /** - * Returns the actual List backing the reservoir. Any changes to this List will corrupt - * the reservoir sample. - * - *

This method should be used only when making a copy of the returned samples, to avoid - * an extraneous array copy.

- * - * @return The raw array backing this reservoir. - */ - ArrayList getRawSamplesAsList() { - return data_; - } - - /** - * Returns a human-readable summary of the sketch, without items. - * - * @return A string version of the sketch summary - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - - final String thisSimpleName = this.getClass().getSimpleName(); - - sb.append(LS); - sb.append("### ").append(thisSimpleName).append(" SUMMARY: ").append(LS); - sb.append(" k : ").append(reservoirSize_).append(LS); - sb.append(" n : ").append(itemsSeen_).append(LS); - sb.append(" Current size : ").append(currItemsAlloc_).append(LS); - sb.append(" Resize factor: ").append(rf_).append(LS); - sb.append("### END SKETCH SUMMARY").append(LS); - - return sb.toString(); - } - - /** - * Returns a human readable string of the preamble of a byte array image of a ReservoirItemsSketch. - * @param byteArr the given byte array - * @return a human readable string of the preamble of a byte array image of a ReservoirItemsSketch. - */ - public static String toString(final byte[] byteArr) { - return PreambleUtil.preambleToString(byteArr); - } - - /** - * Returns a human readable string of the preamble of a MemorySegment image of a ReservoirItemsSketch. - * @param seg the given MemorySegment - * @return a human readable string of the preamble of a MemorySegment image of a ReservoirItemsSketch. - */ - public static String toString(final MemorySegment seg) { - return PreambleUtil.preambleToString(seg); - } - - /** - * Returns a byte array representation of this sketch. May fail for polymorphic item types. - * - * @param serDe An instance of ArrayOfItemsSerDe - * @return a byte array representation of this sketch - */ - public byte[] toByteArray(final ArrayOfItemsSerDe serDe) { - if (itemsSeen_ == 0) { - // null class is ok since empty -- no need to call serDe - return toByteArray(serDe, null); - } else { - return toByteArray(serDe, data_.get(0).getClass()); - } - } - - /** - * Returns a byte array representation of this sketch. Copies contents into an array of the - * specified class for serialization to allow for polymorphic types. - * - * @param serDe An instance of ArrayOfItemsSerDe - * @param clazz The class represented by <T> - * @return a byte array representation of this sketch - */ - // bytes will be null only if empty == true - public byte[] toByteArray(final ArrayOfItemsSerDe serDe, final Class clazz) { - final int preLongs, outBytes; - final boolean empty = itemsSeen_ == 0; - byte[] bytes = null; // for serialized items from serDe - - if (empty) { - preLongs = 1; - outBytes = 8; - } else { - preLongs = Family.RESERVOIR.getMaxPreLongs(); - bytes = serDe.serializeToByteArray(getSamples(clazz)); - outBytes = (preLongs << 3) + bytes.length; - } - final byte[] outArr = new byte[outBytes]; - final MemorySegment seg = MemorySegment.ofArray(outArr); - - // Common header elements - PreambleUtil.insertPreLongs(seg, preLongs); // Byte 0 - PreambleUtil.insertLgResizeFactor(seg, rf_.lg()); - PreambleUtil.insertSerVer(seg, RESERVOIR_SER_VER); // Byte 1 - PreambleUtil.insertFamilyID(seg, Family.RESERVOIR.getID()); // Byte 2 - if (empty) { - PreambleUtil.insertFlags(seg, EMPTY_FLAG_MASK); // Byte 3 - } else { - PreambleUtil.insertFlags(seg, 0); - } - PreambleUtil.insertK(seg, reservoirSize_); // Bytes 4-7 - - // conditional elements - if (!empty) { - PreambleUtil.insertN(seg, itemsSeen_); - - // insert the byteArray of serialized samples, offset by the preamble size - final int preBytes = preLongs << 3; - MemorySegment.copy(bytes, 0, seg, JAVA_BYTE, preBytes, bytes.length); - } - - return outArr; - } - - /** - * Computes an estimated subset sum from the entire stream for objects matching a given - * predicate. Provides a lower bound, estimate, and upper bound using a target of 2 standard - * deviations. - * - *

This is technically a heuristic method, and tries to err on the conservative side.

- * - * @param predicate A predicate to use when identifying items. - * @return A summary object containing the estimate, upper and lower bounds, and the total - * sketch weight. - */ - public SampleSubsetSummary estimateSubsetSum(final Predicate predicate) { - if (itemsSeen_ == 0) { - return new SampleSubsetSummary(0.0, 0.0, 0.0, 0.0); - } - - final int numSamples = getNumSamples(); - final double samplingRate = numSamples / (double) itemsSeen_; - assert samplingRate >= 0.0; - assert samplingRate <= 1.0; - - int trueCount = 0; - for (int i = 0; i < numSamples; ++i) { - if (predicate.test(data_.get(i))) { - ++trueCount; - } - } - - // if in exact mode, we can return an exact answer - if (itemsSeen_ <= reservoirSize_) { - return new SampleSubsetSummary(trueCount, trueCount, trueCount, numSamples); - } - - final double lbTrueFraction = pseudoHypergeometricLBonP(numSamples, trueCount, samplingRate); - final double estimatedTrueFraction = (1.0 * trueCount) / numSamples; - final double ubTrueFraction = pseudoHypergeometricUBonP(numSamples, trueCount, samplingRate); - return new SampleSubsetSummary( - itemsSeen_ * lbTrueFraction, - itemsSeen_ * estimatedTrueFraction, - itemsSeen_ * ubTrueFraction, - itemsSeen_); - } - - double getImplicitSampleWeight() { - if (itemsSeen_ < reservoirSize_) { - return 1.0; - } else { - return ((1.0 * itemsSeen_) / reservoirSize_); - } - } - - /** - * Useful during union operations to avoid copying the items array around if only updating a - * few points. - * - * @param pos The position from which to retrieve the element - * @return The value in the reservoir at position pos - */ - T getValueAtPosition(final int pos) { - if (itemsSeen_ == 0) { - throw new SketchesArgumentException("Requested element from empty reservoir."); - } else if ((pos < 0) || (pos >= getNumSamples())) { - throw new SketchesArgumentException("Requested position must be between 0 and " - + getNumSamples() + ", " + "inclusive. Received: " + pos); - } - - return data_.get(pos); - } - - /** - * Useful during union operation to force-insert a value into the union gadget. Does - * NOT increment count of items seen. - * - * @param value The entry to store in the reservoir - * @param pos The position at which to store the entry - */ - void insertValueAtPosition(final T value, final int pos) { - if ((pos < 0) || (pos >= getNumSamples())) { - throw new SketchesArgumentException("Insert position must be between 0 and " - + getNumSamples() + ", " + "inclusive. Received: " + pos); - } - - data_.set(pos, value); - } - - /** - * Used during union operations to update count of items seen. Does NOT check sign, - * but will throw an exception if the final result exceeds the maximum possible items seen - * value. - * - * @param inc The value added - */ - void forceIncrementItemsSeen(final long inc) { - itemsSeen_ += inc; - - if (itemsSeen_ > MAX_ITEMS_SEEN) { - throw new SketchesStateException("Sketch has exceeded capacity for total items seen. " - + "Limit: " + MAX_ITEMS_SEEN + ", found: " + itemsSeen_); - } - } - - /** - * Used during union operations to ensure we do not overwrite an existing reservoir. Creates a - * shallow copy of the reservoir. - * - * @return A copy of the current sketch - */ - @SuppressWarnings("unchecked") - ReservoirItemsSketch copy() { - return new ReservoirItemsSketch<>(reservoirSize_, currItemsAlloc_, - itemsSeen_, rf_, (ArrayList) data_.clone()); - } - - // Note: the downsampling approach may appear strange but avoids several edge cases - // Q1: Why not just permute samples and then take the first "newK" of them? - // A1: We're assuming the sketch source is read-only - // Q2: Why not copy the source sketch, permute samples, then truncate the sample array and - // reduce k? - // A2: That would involve allocating a MemorySegment proportional to the old k. Even if only a - // temporary violation of maxK, we're avoiding violating it at all. - ReservoirItemsSketch downsampledCopy(final int maxK) { - final ReservoirItemsSketch ris = new ReservoirItemsSketch<>(maxK, rf_); - for (final T item : getSamples()) { - // Pretending old implicit weights are all 1. Not true in general, but they're all - // equal so update should work properly as long as we update itemsSeen_ at the end. - ris.update(item); - } - - // need to adjust number seen to get correct new implicit weights - if (ris.getN() < itemsSeen_) { - ris.forceIncrementItemsSeen(itemsSeen_ - ris.getN()); - } - - return ris; - } - - /** - * Increases allocated sampling size by (adjusted) ResizeFactor and copies items from old - * sampling. - */ - private void growReservoir() { - currItemsAlloc_ = SamplingUtil.getAdjustedSize(reservoirSize_, currItemsAlloc_ << rf_.lg()); - data_.ensureCapacity(currItemsAlloc_); - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/ReservoirItemsUnion.java b/src/main/java/org/apache/datasketches/sampling/ReservoirItemsUnion.java deleted file mode 100644 index 424388581..000000000 --- a/src/main/java/org/apache/datasketches/sampling/ReservoirItemsUnion.java +++ /dev/null @@ -1,435 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.sampling.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.sampling.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SER_VER; -import static org.apache.datasketches.sampling.PreambleUtil.extractEncodedReservoirSize; -import static org.apache.datasketches.sampling.PreambleUtil.extractFlags; -import static org.apache.datasketches.sampling.PreambleUtil.extractMaxK; -import static org.apache.datasketches.sampling.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.sampling.PreambleUtil.extractSerVer; - -import java.lang.foreign.MemorySegment; -import java.util.ArrayList; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Class to union reservoir samples of generic items. - * - *

For efficiency reasons, the unioning process picks one of the two sketches to use as the - * base. As a result, we provide only a stateful union. Using the same approach for a merge would - * result in unpredictable side effects on the underlying sketches.

- * - *

A union object is created with a maximum value of k, represented using the - * ReservoirSize class. The unioning process may cause the actual number of samples to fall below - * that maximum value, but never to exceed it. The result of a union will be a reservoir where - * each item from the global input has a uniform probability of selection, but there are no - * claims about higher order statistics. For instance, in general all possible permutations of - * the global input are not equally likely.

- * - *

If taking the union of two reservoirs of different sizes, the output sample will contain no more - * than MIN(k_1, k_2) samples.

- * - * @param The specific Java type for this sketch - * - * @author Jon Malkin - * @author Kevin Lang - */ -public final class ReservoirItemsUnion { - private ReservoirItemsSketch gadget_; - private final int maxK_; - - /** - * Empty constructor using ReservoirSize-encoded maxK value - * - * @param maxK Maximum allowed reservoir capacity for this union - */ - private ReservoirItemsUnion(final int maxK) { - maxK_ = maxK; - } - - /** - * Creates an empty Union with a maximum reservoir capacity of size k. - * - * @param The type of item this sketch contains - * @param maxK The maximum allowed reservoir capacity for any sketches in the union - * @return A new ReservoirItemsUnion - */ - public static ReservoirItemsUnion newInstance(final int maxK) { - return new ReservoirItemsUnion<>(maxK); - } - - /** - * Instantiates a Union from MemorySegment - * - * @param The type of item this sketch contains - * @param srcSeg MemorySegment object containing a serialized union - * @param serDe An instance of ArrayOfItemsSerDe - * @return A ReservoirItemsUnion created from the provided MemorySegment - */ - public static ReservoirItemsUnion heapify(final MemorySegment srcSeg, - final ArrayOfItemsSerDe serDe) { - Family.RESERVOIR_UNION.checkFamilyID(srcSeg.get(JAVA_BYTE, FAMILY_BYTE)); - - final int numPreLongs = extractPreLongs(srcSeg); - final int serVer = extractSerVer(srcSeg); - final boolean isEmpty = (extractFlags(srcSeg) & EMPTY_FLAG_MASK) != 0; - int maxK = extractMaxK(srcSeg); - - final boolean preLongsEqMin = (numPreLongs == Family.RESERVOIR_UNION.getMinPreLongs()); - final boolean preLongsEqMax = (numPreLongs == Family.RESERVOIR_UNION.getMaxPreLongs()); - - if (!preLongsEqMin && !preLongsEqMax) { - throw new SketchesArgumentException("Possible corruption: Non-empty union with only " - + Family.RESERVOIR_UNION.getMinPreLongs() + "preLongs"); - } - - if (serVer != RESERVOIR_SER_VER) { - if (serVer == 1) { - final short encMaxK = extractEncodedReservoirSize(srcSeg); - maxK = ReservoirSize.decodeValue(encMaxK); - } else { - throw new SketchesArgumentException( - "Possible Corruption: Ser Ver must be " + RESERVOIR_SER_VER + ": " + serVer); - } - } - - final ReservoirItemsUnion riu = new ReservoirItemsUnion<>(maxK); - - if (!isEmpty) { - final int preLongBytes = numPreLongs << 3; - final MemorySegment sketchSeg = srcSeg.asSlice(preLongBytes); - riu.update(sketchSeg, serDe); - } - - return riu; - } - - /** - * Returns the maximum allowed reservoir capacity in this union. The current reservoir capacity - * may be lower. - * - * @return The maximum allowed reservoir capacity in this union. - */ - public int getMaxK() { return maxK_; } - - /** - * Union the given sketch. This method can be repeatedly called. If the given sketch is null it is - * interpreted as an empty sketch. - * - * @param sketchIn The incoming sketch. - */ - public void update(final ReservoirItemsSketch sketchIn) { - if (sketchIn == null) { - return; - } - - final ReservoirItemsSketch ris = - (sketchIn.getK() <= maxK_ ? sketchIn : sketchIn.downsampledCopy(maxK_)); - - // can modify the sketch if we downsampled, otherwise may need to copy it - final boolean isModifiable = (sketchIn != ris); - if (gadget_ == null) { - createNewGadget(ris, isModifiable); - } else { - twoWayMergeInternal(ris, isModifiable); - } - } - - /** - * Union the given MemorySegment image of the sketch. - * - *

This method can be repeatedly called. If the given sketch is null it is interpreted as an - * empty sketch.

- * - * @param seg MemorySegment image of sketch to be merged - * @param serDe An instance of ArrayOfItemsSerDe - */ - public void update(final MemorySegment seg, final ArrayOfItemsSerDe serDe) { - if (seg == null) { - return; - } - - ReservoirItemsSketch ris = ReservoirItemsSketch.heapify(seg, serDe); - ris = (ris.getK() <= maxK_ ? ris : ris.downsampledCopy(maxK_)); - - if (gadget_ == null) { - createNewGadget(ris, true); - } else { - twoWayMergeInternal(ris, true); - } - } - - /** - * Present this union with a single item to be added to the union. - * - * @param datum The given datum of type T. - */ - public void update(final T datum) { - if (datum == null) { - return; - } - - if (gadget_ == null) { - gadget_ = ReservoirItemsSketch.newInstance(maxK_); - } - gadget_.update(datum); - } - - /** - * Present this union with raw elements of a sketch. Useful when operating in a distributed - * environment like Pig Latin scripts, where an explicit SerDe may be overly complicated but - * keeping raw values is simple. Values are not copied and the input array may be - * modified. - * - * @param n Total items seen - * @param k Reservoir size - * @param input Reservoir samples - */ - public void update(final long n, final int k, final ArrayList input) { - ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(input, n, - ResizeFactor.X8, k); // forcing a resize factor - ris = (ris.getK() <= maxK_ ? ris : ris.downsampledCopy(maxK_)); - - if (gadget_ == null) { - createNewGadget(ris, true); - } else { - twoWayMergeInternal(ris, true); - } - } - - /** - * Resets this Union. MaxK remains intact, otherwise reverts back to its virgin state. - */ - void reset() { - gadget_.reset(); - } - - /** - * Returns a sketch representing the current state of the union. - * - * @return The result of any unions already processed. - */ - public ReservoirItemsSketch getResult() { - return (gadget_ != null ? gadget_.copy() : null); - } - - /** - * Returns a byte array representation of this union - * - * @param serDe An instance of ArrayOfItemsSerDe - * @return a byte array representation of this union - */ - public byte[] toByteArray(final ArrayOfItemsSerDe serDe) { - if ((gadget_ == null) || (gadget_.getNumSamples() == 0)) { - return toByteArray(serDe, null); - } else { - return toByteArray(serDe, gadget_.getValueAtPosition(0).getClass()); - } - } - - /** - * Returns a human-readable summary of the sketch, without items. - * - * @return A string version of the sketch summary - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - - final String thisSimpleName = this.getClass().getSimpleName(); - - sb.append(LS); - sb.append("### ").append(thisSimpleName).append(" SUMMARY: ").append(LS); - sb.append(" Max k: ").append(maxK_).append(LS); - if (gadget_ == null) { - sb.append(" Gadget is null").append(LS); - } else { - sb.append(" Gadget summary: ").append(gadget_.toString()); - } - sb.append("### END UNION SUMMARY").append(LS); - - return sb.toString(); - } - - /** - * Returns a byte array representation of this union. This method should be used when the array - * elements are subclasses of a common base class. - * - * @param serDe An instance of ArrayOfItemsSerDe - * @param clazz A class to which the items are cast before serialization - * @return a byte array representation of this union - */ - // gadgetBytes will be null only if gadget_ == null AND empty == true - public byte[] toByteArray(final ArrayOfItemsSerDe serDe, final Class clazz) { - final int preLongs, outBytes; - final boolean empty = gadget_ == null; - final byte[] gadgetBytes = (gadget_ != null ? gadget_.toByteArray(serDe, clazz) : null); - - if (empty) { - preLongs = Family.RESERVOIR_UNION.getMinPreLongs(); - outBytes = 8; - } else { - preLongs = Family.RESERVOIR_UNION.getMaxPreLongs(); - outBytes = (preLongs << 3) + gadgetBytes.length; // for longs, we know the size - } - final byte[] outArr = new byte[outBytes]; - final MemorySegment seg = MemorySegment.ofArray(outArr); - - // build preLong - PreambleUtil.insertPreLongs(seg, preLongs); // Byte 0 - PreambleUtil.insertSerVer(seg, RESERVOIR_SER_VER); // Byte 1 - PreambleUtil.insertFamilyID(seg, Family.RESERVOIR_UNION.getID()); // Byte 2 - if (empty) { - PreambleUtil.insertFlags(seg, EMPTY_FLAG_MASK); - } else { - PreambleUtil.insertFlags(seg, 0); // Byte 3 - } - PreambleUtil.insertMaxK(seg, maxK_); // Bytes 4-5 - - if (!empty) { - final int preBytes = preLongs << 3; - MemorySegment.copy(gadgetBytes, 0, seg, JAVA_BYTE, preBytes, gadgetBytes.length); - } - - return outArr; - } - - private void createNewGadget(final ReservoirItemsSketch sketchIn, - final boolean isModifiable) { - if ((sketchIn.getK() < maxK_) && (sketchIn.getN() <= sketchIn.getK())) { - // incoming sketch is in exact mode with sketch's k < maxK, - // so we can create a gadget at size maxK and keep everything - //Assumes twoWayMergeInternal first checks if sketchIn is in exact mode - gadget_ = ReservoirItemsSketch.newInstance(maxK_); - twoWayMergeInternal(sketchIn, isModifiable); // isModifiable could be fixed to false here - } else { - // use the input sketch as gadget, copying if needed - gadget_ = (isModifiable ? sketchIn : sketchIn.copy()); - } - } - - // We make a three-way classification of sketch states. - // "uni" when (n < k); source of unit weights, can only accept unit weights - // "mid" when (n == k); source of unit weights, can accept "light" general weights. - // "gen" when (n > k); source of general weights, can accept "light" general weights. - - // source target status update notes - // ---------------------------------------------------------------------------------------------- - // uni,mid uni okay standard target might transition to mid and gen - // uni,mid mid,gen okay standard target might transition to gen - // gen uni must swap N/A - // gen mid,gen maybe swap weighted N assumes fractional values during merge - // ---------------------------------------------------------------------------------------------- - - // Here is why in the (gen, gen) merge case, the items will be light enough in at least one - // direction: - // Obviously either (n_s/k_s <= n_t/k_t) OR (n_s/k_s >= n_t/k_t). - // WLOG say its the former, then (n_s/k_s < n_t/(k_t - 1)) provided n_t > 0 and k_t > 1 - - /** - * This either merges sketchIn into gadget_ or gadget_ into sketchIn. If merging into sketchIn - * with isModifiable set to false, copies elements from sketchIn first, leaving original - * unchanged. - * - * @param sketchIn Sketch with new samples from which to draw - * @param isModifiable Flag indicating whether sketchIn can be modified (e.g. if it was rebuild - * from MemorySegment) - */ - private void twoWayMergeInternal(final ReservoirItemsSketch sketchIn, - final boolean isModifiable) { - if (sketchIn.getN() <= sketchIn.getK()) { - twoWayMergeInternalStandard(sketchIn); - } else if (gadget_.getN() < gadget_.getK()) { - // merge into sketchIn, so swap first - final ReservoirItemsSketch tmpSketch = gadget_; - gadget_ = (isModifiable ? sketchIn : sketchIn.copy()); - twoWayMergeInternalStandard(tmpSketch); - } else if (sketchIn.getImplicitSampleWeight() < (gadget_.getN() - / ((double) (gadget_.getK() - 1)))) { - // implicit weights in sketchIn are light enough to merge into gadget - twoWayMergeInternalWeighted(sketchIn); - } else { - // Use next line as an assert/exception? - // gadget_.getImplicitSampleWeight() < sketchIn.getN() / ((double) (sketchIn.getK() - 1))) { - // implicit weights in gadget are light enough to merge into sketchIn - // merge into sketchIn, so swap first - final ReservoirItemsSketch tmpSketch = gadget_; - gadget_ = (isModifiable ? sketchIn : sketchIn.copy()); - twoWayMergeInternalWeighted(tmpSketch); - } - } - - // should be called ONLY by twoWayMergeInternal - private void twoWayMergeInternalStandard(final ReservoirItemsSketch source) { - assert (source.getN() <= source.getK()); - final int numInputSamples = source.getNumSamples(); - for (int i = 0; i < numInputSamples; ++i) { - gadget_.update(source.getValueAtPosition(i)); - } - } - - // should be called ONLY by twoWayMergeInternal - private void twoWayMergeInternalWeighted(final ReservoirItemsSketch source) { - // gadget_ capable of accepting (light) general weights - assert (gadget_.getN() >= gadget_.getK()); - - final int numSourceSamples = source.getK(); - - final double sourceItemWeight = (source.getN() / (double) numSourceSamples); - final double rescaled_prob = gadget_.getK() * sourceItemWeight; // K * weight - double targetTotal = gadget_.getN(); // assumes fractional values during merge - - final int tgtK = gadget_.getK(); - - for (int i = 0; i < numSourceSamples; ++i) { - // inlining the update procedure, using targetTotal for the fractional N values - // similar to ReservoirLongsSketch.update() - // p(keep_new_item) = (k * w) / newTotal - // require p(keep_new_item) < 1.0, meaning strict lightness - - targetTotal += sourceItemWeight; - - final double rescaled_one = targetTotal; - assert (rescaled_prob < rescaled_one); // Use an exception to enforce strict lightness? - final double rescaled_flip = rescaled_one * SamplingUtil.rand().nextDouble(); - if (rescaled_flip < rescaled_prob) { - // Intentionally NOT doing optimization to extract slot number from rescaled_flip. - // Grabbing new random bits to ensure all slots in play - final int slotNo = SamplingUtil.rand().nextInt(tgtK); - gadget_.insertValueAtPosition(source.getValueAtPosition(i), slotNo); - } // end of inlined weight update - } // end of loop over source samples - - // targetTotal was fractional but should now be an integer again. Could validate with low - // tolerance, but for now just round to check. - final long checkN = (long) Math.floor(0.5 + targetTotal); - gadget_.forceIncrementItemsSeen(source.getN()); - assert (checkN == gadget_.getN()); - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/ReservoirLongsSketch.java b/src/main/java/org/apache/datasketches/sampling/ReservoirLongsSketch.java deleted file mode 100644 index a73210f56..000000000 --- a/src/main/java/org/apache/datasketches/sampling/ReservoirLongsSketch.java +++ /dev/null @@ -1,566 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.sampling.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.sampling.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SER_VER; -import static org.apache.datasketches.sampling.PreambleUtil.extractEncodedReservoirSize; -import static org.apache.datasketches.sampling.PreambleUtil.extractFlags; -import static org.apache.datasketches.sampling.PreambleUtil.extractK; -import static org.apache.datasketches.sampling.PreambleUtil.extractN; -import static org.apache.datasketches.sampling.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.sampling.PreambleUtil.extractResizeFactor; -import static org.apache.datasketches.sampling.PreambleUtil.extractSerVer; -import static org.apache.datasketches.sampling.SamplingUtil.pseudoHypergeometricLBonP; -import static org.apache.datasketches.sampling.SamplingUtil.pseudoHypergeometricUBonP; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.function.Predicate; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.Util; - -/** - * This sketch provides a reservoir sample over an input stream of longs. The sketch - * contains a uniform random sample of items from the stream. - * - * @author Jon Malkin - * @author Kevin Lang - */ -public final class ReservoirLongsSketch { - - /** - * The smallest sampling array allocated: 16 - */ - private static final int MIN_LG_ARR_LONGS = 4; - - /** - * Using 48 bits to capture number of items seen, so sketch cannot process more after this many - * items capacity - */ - private static final long MAX_ITEMS_SEEN = 0xFFFFFFFFFFFFL; - - /** - * Default sampling size multiple when reallocating storage: 8 - */ - private static final ResizeFactor DEFAULT_RESIZE_FACTOR = ResizeFactor.X8; - - private final int reservoirSize_; // max size of sampling - private int currItemsAlloc_; // currently allocated array size - private long itemsSeen_; // number of items presented to sketch - private final ResizeFactor rf_; // resize factor - private long[] data_; // stored sampling items - - /** - * The basic constructor for building an empty sketch. - * - * @param k Target maximum reservoir size - * @param rf See Resize Factor - */ - private ReservoirLongsSketch(final int k, final ResizeFactor rf) { - // required due to a theorem about lightness during merging - if (k < 2) { - throw new SketchesArgumentException("k must be at least 2"); - } - - reservoirSize_ = k; - rf_ = rf; - - itemsSeen_ = 0; - - final int ceilingLgK = Util.exactLog2OfInt(Util.ceilingPowerOf2(reservoirSize_), "ReservoirLongsSketch"); - final int initialLgSize = - SamplingUtil.startingSubMultiple(ceilingLgK, rf_.lg(), MIN_LG_ARR_LONGS); - - currItemsAlloc_ = SamplingUtil.getAdjustedSize(reservoirSize_, 1 << initialLgSize); - data_ = new long[currItemsAlloc_]; - java.util.Arrays.fill(data_, 0L); - } - - /** - * Creates a fully-populated sketch. Used internally to avoid extraneous array allocation when - * deserializing. Uses size of items array to as initial array allocation. - * - * @param data Reservoir items as long[] - * @param itemsSeen Number of items presented to the sketch so far - * @param rf See Resize Factor - * @param k Maximum reservoir size - */ - private ReservoirLongsSketch(final long[] data, final long itemsSeen, final ResizeFactor rf, - final int k) { - if (data == null) { - throw new SketchesArgumentException("Instantiating sketch with null reservoir"); - } - if (k < 2) { - throw new SketchesArgumentException( - "Cannot instantiate sketch with reservoir size less than 2"); - } - if (k < data.length) { - throw new SketchesArgumentException( - "Instantiating sketch with max size less than array length: " + k - + " max size, array of length " + data.length); - } - if (((itemsSeen >= k) ? (data.length < k) : (data.length < itemsSeen))) { - throw new SketchesArgumentException("Instantiating sketch with too few samples. " - + "Items seen: " + itemsSeen + ", max reservoir size: " + k + ", " - + "items array length: " + data.length); - } - - reservoirSize_ = k; - currItemsAlloc_ = data.length; - itemsSeen_ = itemsSeen; - rf_ = rf; - data_ = data; - } - - /** - * Fast constructor for full-specified sketch with no encoded/decoding size and no validation. - * Used with copy(). - * - * @param k Maximum reservoir capacity - * @param currItemsAlloc Current array size (assumed equal to items.length) - * @param itemsSeen Total items seen by this sketch - * @param rf See Resize Factor - * @param data Data array backing the reservoir, will not be copied - */ - private ReservoirLongsSketch(final int k, final int currItemsAlloc, - final long itemsSeen, final ResizeFactor rf, final long[] data) { - reservoirSize_ = k; - currItemsAlloc_ = currItemsAlloc; - itemsSeen_ = itemsSeen; - rf_ = rf; - data_ = data; - } - - /** - * Construct a mergeable reservoir sampling sketch with up to k samples using the default resize - * factor (8). - * - * @param k Maximum size of sampling. Allocated size may be smaller until sampling fills. Unlike - * many sketches in this package, this value does not need to be a power of 2. - * @return A ReservoirLongsSketch initialized with maximum size k and the default resize factor. - */ - public static ReservoirLongsSketch newInstance(final int k) { - return new ReservoirLongsSketch(k, DEFAULT_RESIZE_FACTOR); - } - - /** - * Construct a mergeable reservoir sampling sketch with up to k samples using the default resize - * factor (8). - * - * @param k Maximum size of sampling. Allocated size may be smaller until sampling fills. Unlike - * many sketches in this package, this value does not need to be a power of 2. - * @param rf See Resize Factor - * @return A ReservoirLongsSketch initialized with maximum size k and ResizeFactor rf. - */ - public static ReservoirLongsSketch newInstance(final int k, final ResizeFactor rf) { - return new ReservoirLongsSketch(k, rf); - } - - /** - * Returns a sketch instance of this class from the given srcSeg, which must be a MemorySegment - * representation of this sketch class. - * - * @param srcSeg a MemorySegment representation of a sketch of this class. - * @return a sketch instance of this class - */ - public static ReservoirLongsSketch heapify(final MemorySegment srcSeg) { - Family.RESERVOIR.checkFamilyID(srcSeg.get(JAVA_BYTE, FAMILY_BYTE)); - - final int numPreLongs = extractPreLongs(srcSeg); - final ResizeFactor rf = ResizeFactor.getRF(extractResizeFactor(srcSeg)); - final int serVer = extractSerVer(srcSeg); - final boolean isEmpty = (extractFlags(srcSeg) & EMPTY_FLAG_MASK) != 0; - final long itemsSeen = (isEmpty ? 0 : extractN(srcSeg)); - int k = extractK(srcSeg); - - // Check values - final boolean preLongsEqMin = (numPreLongs == Family.RESERVOIR.getMinPreLongs()); - final boolean preLongsEqMax = (numPreLongs == Family.RESERVOIR.getMaxPreLongs()); - - if (!preLongsEqMin && !preLongsEqMax) { - throw new SketchesArgumentException("Possible corruption: Non-empty sketch with only " - + Family.RESERVOIR.getMinPreLongs() + "preLongs"); - } - - if (serVer != RESERVOIR_SER_VER) { - if (serVer == 1) { - final short encK = extractEncodedReservoirSize(srcSeg); - k = ReservoirSize.decodeValue(encK); - } else { - throw new SketchesArgumentException( - "Possible Corruption: Ser Ver must be " + RESERVOIR_SER_VER + ": " + serVer); - } - } - - if (isEmpty) { - return new ReservoirLongsSketch(k, rf); - } - - final int preLongBytes = numPreLongs << 3; - final int numSketchLongs = (int) Math.min(itemsSeen, k); - int allocatedSize = k; // default to full reservoir - if (itemsSeen < k) { - // under-full so determine size to allocate, using ceilingLog2(totalSeen) as minimum - // casts to int are safe since under-full - final int ceilingLgK = Util.exactLog2OfInt(Util.ceilingPowerOf2(k), "k"); - final int minLgSize = Util.exactLog2OfInt(Util.ceilingPowerOf2((int) itemsSeen), "heapify"); - final int initialLgSize = SamplingUtil.startingSubMultiple(ceilingLgK, rf.lg(), - Math.max(minLgSize, MIN_LG_ARR_LONGS)); - - allocatedSize = SamplingUtil.getAdjustedSize(k, 1 << initialLgSize); - } - - final long[] data = new long[allocatedSize]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, preLongBytes, data, 0, numSketchLongs); - - return new ReservoirLongsSketch(data, itemsSeen, rf, k); - } - - /** - * Thin wrapper around private constructor - * - * @param data Reservoir items as long[] - * @param itemsSeen Number of items presented to the sketch so far - * @param rf See Resize Factor - * @param k Maximum reservoir size - * @return New sketch built with the provided inputs - */ - static ReservoirLongsSketch getInstance(final long[] data, final long itemsSeen, - final ResizeFactor rf, final int k) { - return new ReservoirLongsSketch(data, itemsSeen, rf, k); - } - - /** - * Returns the sketch's value of k, the maximum number of samples stored in the reservoir. - * The current number of items in the sketch may be lower. - * - * @return k, the maximum number of samples in the reservoir - */ - public int getK() { - return reservoirSize_; - } - - /** - * Returns the number of items processed from the input stream - * - * @return n, the number of stream items the sketch has seen - */ - public long getN() { - return itemsSeen_; - } - - /** - * Returns the current number of items in the reservoir, which may be smaller than the reservoir - * capacity. - * - * @return the number of items currently in the reservoir - */ - public int getNumSamples() { - return (int) Math.min(reservoirSize_, itemsSeen_); - } - - /** - * Returns a copy of the items in the reservoir. The returned array length may be smaller than the - * reservoir capacity. - * - * @return A copy of the reservoir array - */ - public long[] getSamples() { - if (itemsSeen_ == 0) { - return null; - } - final int numSamples = (int) Math.min(reservoirSize_, itemsSeen_); - return java.util.Arrays.copyOf(data_, numSamples); - } - - /** - * Randomly decide whether or not to include an item in the sample set. - * - * @param item a unit-weight (equivalently, unweighted) item of the set being sampled from - */ - public void update(final long item) { - if (itemsSeen_ == MAX_ITEMS_SEEN) { - throw new SketchesStateException( - "Sketch has exceeded capacity for total items seen: " + MAX_ITEMS_SEEN); - } - - if (itemsSeen_ < reservoirSize_) { // initial phase, take the first reservoirSize_ items - if (itemsSeen_ >= currItemsAlloc_) { - growReservoir(); - } - assert itemsSeen_ < currItemsAlloc_; - // we'll randomize replacement positions, so in-order should be valid for now - data_[(int) itemsSeen_] = item; // since less than reservoir size, cast is safe - ++itemsSeen_; - } else { // code for steady state where we sample randomly - ++itemsSeen_; - // prob(keep_item) < k / n = reservoirSize_ / itemsSeen_ - // so multiply to get: keep if rand * itemsSeen_ < reservoirSize_ - if ((SamplingUtil.rand().nextDouble() * itemsSeen_) < reservoirSize_) { - final int newSlot = SamplingUtil.rand().nextInt(reservoirSize_); - data_[newSlot] = item; - } - } - } - - /** - * Resets this sketch to the empty state, but retains the original value of k. - */ - public void reset() { - final int ceilingLgK = Util.exactLog2OfInt(Util.ceilingPowerOf2(reservoirSize_), - "ReservoirLongsSketch"); - final int initialLgSize = - SamplingUtil.startingSubMultiple(ceilingLgK, rf_.lg(), MIN_LG_ARR_LONGS); - - currItemsAlloc_ = SamplingUtil.getAdjustedSize(reservoirSize_, 1 << initialLgSize); - data_ = new long[currItemsAlloc_]; - itemsSeen_ = 0; - } - - /** - * Returns a human-readable summary of the sketch, without items. - * - * @return A string version of the sketch summary - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - - final String thisSimpleName = this.getClass().getSimpleName(); - - sb.append(LS); - sb.append("### ").append(thisSimpleName).append(" SUMMARY: ").append(LS); - sb.append(" k : ").append(reservoirSize_).append(LS); - sb.append(" n : ").append(itemsSeen_).append(LS); - sb.append(" Current size : ").append(currItemsAlloc_).append(LS); - sb.append(" Resize factor: ").append(rf_).append(LS); - sb.append("### END SKETCH SUMMARY").append(LS); - - return sb.toString(); - } - - /** - * Returns a human readable string of the preamble of a byte array image of a ReservoirLongsSketch. - * @param byteArr the given byte array - * @return a human readable string of the preamble of a byte array image of a ReservoirLongsSketch. - */ - public static String toString(final byte[] byteArr) { - return PreambleUtil.preambleToString(byteArr); - } - - /** - * Returns a human readable string of the preamble of a MemorySegment image of a ReservoirLongsSketch. - * @param seg the given MemorySegment - * @return a human readable string of the preamble of a MemorySegment image of a ReservoirLongsSketch. - */ - public static String toString(final MemorySegment seg) { - return PreambleUtil.preambleToString(seg); - } - - /** - * Returns a byte array representation of this sketch - * - * @return a byte array representation of this sketch - */ - public byte[] toByteArray() { - final int preLongs, outBytes; - final boolean empty = itemsSeen_ == 0; - final int numItems = (int) Math.min(reservoirSize_, itemsSeen_); - - if (empty) { - preLongs = 1; - outBytes = 8; - } else { - preLongs = Family.RESERVOIR.getMaxPreLongs(); - outBytes = (preLongs + numItems) << 3; // for longs, we know the size - } - final byte[] outArr = new byte[outBytes]; - final MemorySegment seg = MemorySegment.ofArray(outArr); - - // build first preLong - PreambleUtil.insertPreLongs(seg, preLongs); // Byte 0 - PreambleUtil.insertLgResizeFactor(seg, rf_.lg()); - PreambleUtil.insertSerVer(seg, RESERVOIR_SER_VER); // Byte 1 - PreambleUtil.insertFamilyID(seg, Family.RESERVOIR.getID()); // Byte 2 - if (empty) { - PreambleUtil.insertFlags(seg, EMPTY_FLAG_MASK); // Byte 3 - } else { - PreambleUtil.insertFlags(seg, 0); - } - PreambleUtil.insertK(seg, reservoirSize_); // Bytes 4-7 - - if (!empty) { - // second preLong, only if non-empty - PreambleUtil.insertN(seg, itemsSeen_); - - // insert the serialized samples, offset by the preamble size - final int preBytes = preLongs << 3; - MemorySegment.copy(data_, 0, seg, JAVA_LONG_UNALIGNED, preBytes, numItems); - } - - return outArr; - } - - /** - * Computes an estimated subset sum from the entire stream for objects matching a given - * predicate. Provides a lower bound, estimate, and upper bound using a target of 2 standard - * deviations. - * - *

This is technically a heuristic method, and tries to err on the conservative side.

- * - * @param predicate A predicate to use when identifying items. - * @return A summary object containing the estimate, upper and lower bounds, and the total - * sketch weight. - */ - public SampleSubsetSummary estimateSubsetSum(final Predicate predicate) { - if (itemsSeen_ == 0) { - return new SampleSubsetSummary(0.0, 0.0, 0.0, 0.0); - } - - final int numSamples = getNumSamples(); - final double samplingRate = numSamples / (double) itemsSeen_; - assert samplingRate >= 0.0; - assert samplingRate <= 1.0; - - int predTrueCount = 0; - for (int i = 0; i < numSamples; ++i) { - if (predicate.test(data_[i])) { - ++predTrueCount; - } - } - - // if in exact mode, we can return an exact answer - if (itemsSeen_ <= reservoirSize_) { - return new SampleSubsetSummary(predTrueCount, predTrueCount, predTrueCount, numSamples); - } - - final double lbTrueFraction = pseudoHypergeometricLBonP(numSamples, predTrueCount, samplingRate); - final double estimatedTrueFraction = (1.0 * predTrueCount) / numSamples; - final double ubTrueFraction = pseudoHypergeometricUBonP(numSamples, predTrueCount, samplingRate); - return new SampleSubsetSummary( - itemsSeen_ * lbTrueFraction, - itemsSeen_ * estimatedTrueFraction, - itemsSeen_ * ubTrueFraction, - itemsSeen_); - } - - double getImplicitSampleWeight() { - if (itemsSeen_ < reservoirSize_) { - return 1.0; - } else { - return ((1.0 * itemsSeen_) / reservoirSize_); - } - } - - /** - * Useful during union operations to avoid copying the items array around if only updating a few - * points. - * - * @param pos The position from which to retrieve the element - * @return The value in the reservoir at position pos - */ - long getValueAtPosition(final int pos) { - if (itemsSeen_ == 0) { - throw new SketchesArgumentException("Requested element from empty reservoir."); - } else if ((pos < 0) || (pos >= getNumSamples())) { - throw new SketchesArgumentException("Requested position must be between 0 and " - + (getNumSamples() - 1) + ", inclusive. Received: " + pos); - } - - return data_[pos]; - } - - /** - * Useful during union operation to force-insert a value into the union gadget. Does NOT - * increment count of items seen. Cannot insert beyond current number of samples; if reservoir is - * not full, use update(). - * - * @param value The entry to store in the reservoir - * @param pos The position at which to store the entry - */ - void insertValueAtPosition(final long value, final int pos) { - if ((pos < 0) || (pos >= getNumSamples())) { - throw new SketchesArgumentException("Insert position must be between 0 and " + getNumSamples() - + ", inclusive. Received: " + pos); - } - - data_[pos] = value; - } - - /** - * Used during union operations to update count of items seen. Does NOT check sign, but - * will throw an exception if the final result exceeds the maximum possible items seen value. - * - * @param inc The value added - */ - void forceIncrementItemsSeen(final long inc) { - itemsSeen_ += inc; - - if (itemsSeen_ > MAX_ITEMS_SEEN) { - throw new SketchesStateException("Sketch has exceeded capacity for total items seen. " - + "Limit: " + MAX_ITEMS_SEEN + ", found: " + itemsSeen_); - } - } - - ReservoirLongsSketch copy() { - final long[] dataCopy = Arrays.copyOf(data_, currItemsAlloc_); - return new ReservoirLongsSketch(reservoirSize_, currItemsAlloc_, itemsSeen_, rf_, dataCopy); - } - - // Note: the downsampling approach may appear strange but avoids several edge cases - // Q1: Why not just permute samples and then take the first "newK" of them? - // A1: We're assuming the sketch source is read-only - // Q2: Why not copy the source sketch, permute samples, then truncate the sample array and - // reduce k? - // A2: That would involve allocating MemorySegment proportional to the old k. Even if only a - // temporary violation of maxK, we're avoiding violating it at all. - ReservoirLongsSketch downsampledCopy(final int maxK) { - final ReservoirLongsSketch rls = new ReservoirLongsSketch(maxK, rf_); - for (final long l: getSamples()) { - // Pretending old implicit weights are all 1. Not true in general, but they're all - // equal so update should work properly as long as we update itemsSeen_ at the end. - rls.update(l); - } - - // need to adjust number seen to get correct new implicit weights - if (rls.getN() < itemsSeen_) { - rls.forceIncrementItemsSeen(itemsSeen_ - rls.getN()); - } - - return rls; - } - - /** - * Increases allocated sampling size by (adjusted) ResizeFactor and copies items from old sampling. - */ - private void growReservoir() { - currItemsAlloc_ = SamplingUtil.getAdjustedSize(reservoirSize_, currItemsAlloc_ * rf_.getValue()); - data_ = java.util.Arrays.copyOf(data_, currItemsAlloc_); - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/ReservoirLongsUnion.java b/src/main/java/org/apache/datasketches/sampling/ReservoirLongsUnion.java deleted file mode 100644 index 37129a299..000000000 --- a/src/main/java/org/apache/datasketches/sampling/ReservoirLongsUnion.java +++ /dev/null @@ -1,389 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.sampling.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.sampling.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SER_VER; -import static org.apache.datasketches.sampling.PreambleUtil.extractEncodedReservoirSize; -import static org.apache.datasketches.sampling.PreambleUtil.extractFlags; -import static org.apache.datasketches.sampling.PreambleUtil.extractMaxK; -import static org.apache.datasketches.sampling.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.sampling.PreambleUtil.extractSerVer; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Class to union reservoir samples of longs. - * - *

- * For efficiency reasons, the unioning process picks one of the two sketches to use as the base. As - * a result, we provide only a stateful union. Using the same approach for a merge would result in - * unpredictable side effects on the underlying sketches. - *

- * - *

- * A union object is created with a maximum value of k, represented using the ReservoirSize - * class. The unioning process may cause the actual number of samples to fall below that maximum - * value, but never to exceed it. The result of a union will be a reservoir where each item from the - * global input has a uniform probability of selection, but there are no claims about higher order - * statistics. For instance, in general all possible permutations of the global input are not - * equally likely. - *

- * - * @author Jon Malkin - * @author Kevin Lang - */ -public final class ReservoirLongsUnion { - private ReservoirLongsSketch gadget_; - private final int maxK_; - - /** - * Empty constructor using ReservoirSize-encoded maxK value - * - * @param maxK Maximum allowed reservoir capacity for this union - */ - private ReservoirLongsUnion(final int maxK) { - maxK_ = maxK; - } - - /** - * Creates an empty Union with a maximum reservoir capacity of size k. - * - * @param maxK The maximum allowed reservoir capacity for any sketches in the union - * @return A new ReservoirLongsUnion - */ - public static ReservoirLongsUnion newInstance(final int maxK) { - return new ReservoirLongsUnion(maxK); - } - - /** - * Instantiates a Union from MemorySegment - * - * @param srcSeg MemorySegment object containing a serialized union - * @return A ReservoirLongsUnion created from the provided MemorySegment - */ - public static ReservoirLongsUnion heapify(final MemorySegment srcSeg) { - Family.RESERVOIR_UNION.checkFamilyID(srcSeg.get(JAVA_BYTE, FAMILY_BYTE)); - - final int numPreLongs = extractPreLongs(srcSeg); - final int serVer = extractSerVer(srcSeg); - final boolean isEmpty = (extractFlags(srcSeg) & EMPTY_FLAG_MASK) != 0; - int maxK = extractMaxK(srcSeg); - - final boolean preLongsEqMin = (numPreLongs == Family.RESERVOIR_UNION.getMinPreLongs()); - final boolean preLongsEqMax = (numPreLongs == Family.RESERVOIR_UNION.getMaxPreLongs()); - - if (!preLongsEqMin && !preLongsEqMax) { - throw new SketchesArgumentException("Possible corruption: Non-empty union with only " - + Family.RESERVOIR_UNION.getMinPreLongs() + "preLongs"); - } - - if (serVer != RESERVOIR_SER_VER) { - if (serVer == 1) { - final short encMaxK = extractEncodedReservoirSize(srcSeg); - maxK = ReservoirSize.decodeValue(encMaxK); - } else { - throw new SketchesArgumentException( - "Possible Corruption: Ser Ver must be " + RESERVOIR_SER_VER + ": " + serVer); - } - } - - final ReservoirLongsUnion rlu = new ReservoirLongsUnion(maxK); - - if (!isEmpty) { - final int preLongBytes = numPreLongs << 3; - final MemorySegment sketchSeg = srcSeg.asSlice(preLongBytes); - rlu.update(sketchSeg); - } - - return rlu; - } - - /** - * Returns the maximum allowed reservoir capacity in this union. The current reservoir capacity - * may be lower. - * - * @return The maximum allowed reservoir capacity in this union. - */ - public int getMaxK() { return maxK_; } - - /** - * Union the given sketch. - * - *

This method can be repeatedly called. If the given sketch is null it is interpreted as an empty - * sketch.

- * - * @param sketchIn The incoming sketch. - */ - public void update(final ReservoirLongsSketch sketchIn) { - if (sketchIn == null) { - return; - } - - final ReservoirLongsSketch rls = - (sketchIn.getK() <= maxK_ ? sketchIn : sketchIn.downsampledCopy(maxK_)); - - // can modify the sketch if we downsampled, otherwise may need to copy it - final boolean isModifiable = (sketchIn != rls); - if (gadget_ == null) { - createNewGadget(rls, isModifiable); - } else { - twoWayMergeInternal(rls, isModifiable); - } - } - - /** - * Union the given MemorySegment image of the sketch. - * - *

- * This method can be repeatedly called. If the given sketch is null it is interpreted as an empty - * sketch. - *

- * - * @param seg MemorySegment image of sketch to be merged - */ - public void update(final MemorySegment seg) { - if (seg == null) { - return; - } - - ReservoirLongsSketch rls = ReservoirLongsSketch.heapify(seg); - - rls = (rls.getK() <= maxK_ ? rls : rls.downsampledCopy(maxK_)); - - if (gadget_ == null) { - createNewGadget(rls, true); - } else { - twoWayMergeInternal(rls, true); - } - } - - /** - * Present this union with a long. - * - * @param datum The given long datum. - */ - public void update(final long datum) { - if (gadget_ == null) { - gadget_ = ReservoirLongsSketch.newInstance(maxK_); - } - gadget_.update(datum); - } - - /** - * Resets this Union. MaxK remains intact, otherwise reverts back to its virgin state. - */ - void reset() { - gadget_.reset(); - } - - /** - * Returns a sketch representing the current state of the union. - * - * @return The result of any unions already processed. - */ - public ReservoirLongsSketch getResult() { - return (gadget_ != null ? gadget_.copy() : null); - } - - /** - * Returns a human-readable summary of the sketch, without items. - * - * @return A string version of the sketch summary - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - - final String thisSimpleName = this.getClass().getSimpleName(); - - sb.append(LS); - sb.append("### ").append(thisSimpleName).append(" SUMMARY: ").append(LS); - sb.append("Max k: ").append(maxK_).append(LS); - if (gadget_ == null) { - sb.append("Gadget is null").append(LS); - } else { - sb.append("Gadget summary: ").append(gadget_.toString()); - } - sb.append("### END UNION SUMMARY").append(LS); - - return sb.toString(); - } - - /** - * Returns a byte array representation of this union - * - * @return a byte array representation of this union - */ - // gadgetBytes will be null only if gadget_ == null AND empty == true - public byte[] toByteArray() { - final int preLongs, outBytes; - final boolean empty = gadget_ == null; - final byte[] gadgetBytes = (gadget_ != null ? gadget_.toByteArray() : null); - - if (empty) { - preLongs = Family.RESERVOIR_UNION.getMinPreLongs(); - outBytes = 8; - } else { - preLongs = Family.RESERVOIR_UNION.getMaxPreLongs(); - outBytes = (preLongs << 3) + gadgetBytes.length; // longs, so we know the size - } - final byte[] outArr = new byte[outBytes]; - final MemorySegment seg = MemorySegment.ofArray(outArr); - - // construct header - PreambleUtil.insertPreLongs(seg, preLongs); // Byte 0 - PreambleUtil.insertSerVer(seg, RESERVOIR_SER_VER); // Byte 1 - PreambleUtil.insertFamilyID(seg, Family.RESERVOIR_UNION.getID()); // Byte 2 - if (empty) { - PreambleUtil.insertFlags(seg, EMPTY_FLAG_MASK); // Byte 3 - } else { - PreambleUtil.insertFlags(seg, 0); - } - PreambleUtil.insertMaxK(seg, maxK_); // Bytes 4-7 - - if (!empty) { - final int preBytes = preLongs << 3; - MemorySegment.copy(gadgetBytes, 0, seg, JAVA_BYTE, preBytes, gadgetBytes.length); - - - } - - return outArr; - } - - private void createNewGadget(final ReservoirLongsSketch sketchIn, - final boolean isModifiable) { - if ((sketchIn.getK() < maxK_) && (sketchIn.getN() <= sketchIn.getK())) { - // incoming sketch is in exact mode with sketch's k < maxK, - // so we can create a gadget at size maxK and keep everything - // NOTE: assumes twoWayMergeInternal first checks if sketchIn is in exact mode - gadget_ = ReservoirLongsSketch.newInstance(maxK_); - twoWayMergeInternal(sketchIn, isModifiable); // isModifiable could be fixed to false here - } else { - // use the input sketch as gadget, copying if needed - gadget_ = (isModifiable ? sketchIn : sketchIn.copy()); - } - } - - // We make a three-way classification of sketch states. - // "uni" when (n < k); source of unit weights, can only accept unit weights - // "mid" when (n == k); source of unit weights, can accept "light" general weights. - // "gen" when (n > k); source of general weights, can accept "light" general weights. - - // source target status update notes - // ---------------------------------------------------------------------------------------------- - // uni,mid uni okay standard target might transition to mid and gen - // uni,mid mid,gen okay standard target might transition to gen - // gen uni must swap N/A - // gen mid,gen maybe swap weighted N assumes fractional values during merge - // ---------------------------------------------------------------------------------------------- - - // Here is why in the (gen, gen) merge case, the items will be light enough in at least one - // direction: - // Obviously either (n_s/k_s <= n_t/k_t) OR (n_s/k_s >= n_t/k_t). - // WLOG say its the former, then (n_s/k_s < n_t/(k_t - 1)) provided n_t > 0 and k_t > 1 - - /** - * This either merges sketchIn into gadget_ or gadget_ into sketchIn. If merging into sketchIn - * with isModifiable set to false, copies elements from sketchIn first, leaving original - * unchanged. - * - * @param sketchIn Sketch with new samples from which to draw - * @param isModifiable Flag indicating whether sketchIn can be modified (e.g. if it was rebuild - * from MemorySegment) - */ - private void twoWayMergeInternal(final ReservoirLongsSketch sketchIn, - final boolean isModifiable) { - if (sketchIn.getN() <= sketchIn.getK()) { - twoWayMergeInternalStandard(sketchIn); - } else if (gadget_.getN() < gadget_.getK()) { - // merge into sketchIn, so swap first - final ReservoirLongsSketch tmpSketch = gadget_; - gadget_ = (isModifiable ? sketchIn : sketchIn.copy()); - twoWayMergeInternalStandard(tmpSketch); - } else if (sketchIn.getImplicitSampleWeight() < (gadget_.getN() - / ((double) (gadget_.getK() - 1)))) { - // implicit weights in sketchIn are light enough to merge into gadget - twoWayMergeInternalWeighted(sketchIn); - } else { - // Use next next line for an assert/exception? - // gadget_.getImplicitSampleWeight() < sketchIn.getN() / ((double) (sketchIn.getK() - 1))) - // implicit weights in gadget are light enough to merge into sketchIn, so swap first - final ReservoirLongsSketch tmpSketch = gadget_; - gadget_ = (isModifiable ? sketchIn : sketchIn.copy()); - twoWayMergeInternalWeighted(tmpSketch); - } - } - - // should be called ONLY by twoWayMergeInternal - private void twoWayMergeInternalStandard(final ReservoirLongsSketch source) { - assert (source.getN() <= source.getK()); - final int numInputSamples = source.getNumSamples(); - for (int i = 0; i < numInputSamples; ++i) { - gadget_.update(source.getValueAtPosition(i)); - } - } - - // should be called ONLY by twoWayMergeInternal - private void twoWayMergeInternalWeighted(final ReservoirLongsSketch source) { - // gadget_ capable of accepting (light) general weights - assert (gadget_.getN() >= gadget_.getK()); - - final int numSourceSamples = source.getK(); - - final double sourceItemWeight = (source.getN() / (double) numSourceSamples); - final double rescaled_prob = gadget_.getK() * sourceItemWeight; // K * weight - double targetTotal = gadget_.getN(); // assumes fractional values during merge - - final int tgtK = gadget_.getK(); - - for (int i = 0; i < numSourceSamples; ++i) { - // inlining the update procedure, using targetTotal for the fractional N values - // similar to ReservoirLongsSketch.update() - // p(keep_new_item) = (k * w) / newTotal - // require p(keep_new_item) < 1.0, meaning strict lightness - - targetTotal += sourceItemWeight; - - final double rescaled_one = targetTotal; - assert (rescaled_prob < rescaled_one); // Use an exception to enforce strict lightness? - final double rescaled_flip = rescaled_one * SamplingUtil.rand().nextDouble(); - if (rescaled_flip < rescaled_prob) { - // Intentionally NOT doing optimization to extract slot number from rescaled_flip. - // Grabbing new random bits to ensure all slots in play - final int slotNo = SamplingUtil.rand().nextInt(tgtK); - gadget_.insertValueAtPosition(source.getValueAtPosition(i), slotNo); - } // end of inlined weight update - } // end of loop over source samples - - // targetTotal was fractional but should now be an integer again. Could validate with - // low tolerance, but for now just round to check. - final long checkN = (long) Math.floor(0.5 + targetTotal); - gadget_.forceIncrementItemsSeen(source.getN()); - assert (checkN == gadget_.getN()); - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/ReservoirSize.java b/src/main/java/org/apache/datasketches/sampling/ReservoirSize.java deleted file mode 100644 index e12d31aa9..000000000 --- a/src/main/java/org/apache/datasketches/sampling/ReservoirSize.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; - -/** - * This class provides a compact representation of reservoir size by encoding it into a - * fixed-point 16-bit value. - * - *

The value itself is a fractional power of 2, with 5 bits of exponent and 11 bits of - * mantissa. The exponent allows a choice of anywhere from 0-30, and there are 2048 possible - * reservoir size values within each octave. Because reservoir size must be an integer, this - * means that some sizes below 2048 may have multiple valid encodings.

- * - *

Reservoir sizes can be specified exactly to 4096, and may be off by up to 0.03% thereafter. - * The value returned is always at least as large as the requested size, but may be larger. - *

- * - *

NOTE: Numerical instability may cause an off-by-one error on reservoir size, causing a - * slight increase in storage over the optimal value.

- * - * @author Jon Malkin - */ -final class ReservoirSize { - /** - * Number of bins per power of two. - */ - static final int BINS_PER_OCTAVE = 2048; - - /** - * Precomputed inverse values for efficiency - */ - private static final double INV_BINS_PER_OCTAVE = 1.0 / BINS_PER_OCTAVE; - private static final double INV_LN_2 = 1.0 / Math.log(2.0); - - /** - * Values for encoding/decoding - */ - private static final int EXPONENT_MASK = 0x1F; - private static final int EXPONENT_SHIFT = 11; - private static final int INDEX_MASK = 0x07FF; - private static final int OUTPUT_MASK = 0xFFFF; - private static final int MAX_ABS_VALUE = 2146959360; - private static final int MAX_ENC_VALUE = 0xF7FF; // p=30, i=2047 - - private ReservoirSize() {} - - /** - * Given target reservoir size k, computes the smallest representable reservoir size that can - * hold k entries and returns it in a 16-bit fixed-point format as a short. - * - * @param k target reservoir size - * @return reservoir size as 16-bit encoded value - */ - public static short computeSize(final int k) { - if ((k < 1) || (k > MAX_ABS_VALUE)) { - throw new SketchesArgumentException("Can only encode strictly positive sketch sizes " - + "less than " + MAX_ABS_VALUE + ", found: " + k); - } - - final int p = Util.exactLog2OfInt(Util.floorPowerOf2(k), "computeSize: p"); - - // because of floor() + 1 below, need to check power of 2 here - if (Util.isPowerOf2(k)) { - return (short) (((p & EXPONENT_MASK) << EXPONENT_SHIFT) & OUTPUT_MASK); - } - - // mantissa is scalar in range [1,2); can reconstruct k as m * 2^p - final double m = Math.pow(2.0, (Math.log(k) * INV_LN_2) - p); - - // Convert to index offset: ceil(m * BPO) - BPO - // Typically in range range 0-(BINS_PER_OCTAVE-1) (but see note below) - final int i = ((int) Math.floor(m * BINS_PER_OCTAVE) - BINS_PER_OCTAVE) + 1; - - // Due to ceiling, possible to overflow BINS_PER_OCTAVE - // E.g., if BPO = 2048 then for k=32767 we have p=14. Except that 32767 > decodeValue - // (p=14, i=2047)=32756, so we encode and return p+1 - if (i == BINS_PER_OCTAVE) { - return (short) ((((p + 1) & EXPONENT_MASK) << EXPONENT_SHIFT) & OUTPUT_MASK); - } - - return (short) (((p & EXPONENT_MASK) << EXPONENT_SHIFT) | ((i & INDEX_MASK) & OUTPUT_MASK)); - } - - /** - * Decodes the 16-bit reservoir size value into an int. - * - * @param encodedSize Encoded 16-bit value - * @return int represented by encodedSize - */ - public static int decodeValue(final short encodedSize) { - final int value = encodedSize & 0xFFFF; - - if (value > MAX_ENC_VALUE) { - throw new SketchesArgumentException("Maximum valid encoded value is " - + Integer.toHexString(MAX_ENC_VALUE) + ", found: " + value); - } - - final int p = (value >>> EXPONENT_SHIFT) & EXPONENT_MASK; - final int i = value & INDEX_MASK; - - return (int) ((1 << p) * ((i * INV_BINS_PER_OCTAVE) + 1.0)); - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/SampleSubsetSummary.java b/src/main/java/org/apache/datasketches/sampling/SampleSubsetSummary.java deleted file mode 100644 index 1504542f7..000000000 --- a/src/main/java/org/apache/datasketches/sampling/SampleSubsetSummary.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -/** - * A simple object o capture the results of a subset sum query on a sampling sketch. - * - * @author Jon Malkin - */ -public class SampleSubsetSummary { - private double lowerBound; - private double estimate; - private double upperBound; - private double totalSketchWeight; - - SampleSubsetSummary(final double lowerBound, - final double estimate, - final double upperBound, - final double totalSketchWeight) { - this.lowerBound = lowerBound; - this.estimate = estimate; - this.upperBound = upperBound; - this.totalSketchWeight = totalSketchWeight; - } - - /** - * Returns the lower bound - * @return the lower bound - */ - public double getLowerBound() { - return lowerBound; - } - - /** - * Returns the total sketch weight - * @return the total sketch weight - */ - public double getTotalSketchWeight() { - return totalSketchWeight; - } - - /** - * Returns the upper bound - * @return the upper bound - */ - public double getUpperBound() { - return upperBound; - } - - /** - * Returns the unique count estimate - * @return the unique count estimate - */ - public double getEstimate() { - return estimate; - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/SamplingUtil.java b/src/main/java/org/apache/datasketches/sampling/SamplingUtil.java deleted file mode 100644 index 4fa96c7bc..000000000 --- a/src/main/java/org/apache/datasketches/sampling/SamplingUtil.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static org.apache.datasketches.common.BoundsOnBinomialProportions.approximateLowerBoundOnP; -import static org.apache.datasketches.common.BoundsOnBinomialProportions.approximateUpperBoundOnP; - -import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; - -/** - * Common utility functions for the sampling family of sketches. - * - * @author Jon Malkin - */ -final class SamplingUtil { - - /** - * Number of standard deviations to use for subset sum error bounds - */ - private static final double DEFAULT_KAPPA = 2.0; - - private SamplingUtil() {} - - /** - * Checks if target sampling allocation is more than 50% of max sampling size. If so, returns - * max sampling size, otherwise passes through the target size. - * - * @param maxSize Maximum allowed reservoir size, as from getK() - * @param resizeTarget Next size based on a pure ResizeFactor scaling - * @return (reservoirSize_ < 2*resizeTarget ? reservoirSize_ : resizeTarget) - */ - static int getAdjustedSize(final int maxSize, final int resizeTarget) { - if (maxSize - (resizeTarget << 1) < 0L) { - return maxSize; - } - return resizeTarget; - } - - static double nextDoubleExcludeZero() { - double r = rand().nextDouble(); - while (r == 0.0) { - r = rand().nextDouble(); - } - return r; - } - - static int startingSubMultiple(final int lgTarget, final int lgRf, final int lgMin) { - return (lgTarget <= lgMin) - ? lgMin : (lgRf == 0) ? lgTarget - : (lgTarget - lgMin) % lgRf + lgMin; - } - - static double pseudoHypergeometricUBonP(final long n, final int k, final double samplingRate) { - final double adjustedKappa = DEFAULT_KAPPA * Math.sqrt(1 - samplingRate); - return approximateUpperBoundOnP(n, k, adjustedKappa); - } - - static double pseudoHypergeometricLBonP(final long n, final int k, final double samplingRate) { - final double adjustedKappa = DEFAULT_KAPPA * Math.sqrt(1 - samplingRate); - return approximateLowerBoundOnP(n, k, adjustedKappa); - } - - public static Random rand() { - return ThreadLocalRandom.current(); - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/VarOptItemsSamples.java b/src/main/java/org/apache/datasketches/sampling/VarOptItemsSamples.java deleted file mode 100644 index 00ad3fd6f..000000000 --- a/src/main/java/org/apache/datasketches/sampling/VarOptItemsSamples.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Objects; - -/** - * This class provides access to the samples contained in a VarOptItemsSketch. It provides two - * mechanisms for access: - *
    - *
  • An Iterator over WeightedSample objects which can can be used to - * access both the items and weights in the sample, and which avoids copying data from the - * sketch.
  • - *
  • Getter methods to obtain items or weights as arrays, or individual items. These - * methods create a (shallow) copy of data from the sketch on the first call to any get - * method.
  • - *
- * - *

If using getters with a sketch storing heterogeneous items from a polymorphic base class, you - * must call setClass() prior to calling one of the getter methods. This is not - * necessary if using the iterator.

- * - *

The class also implements Iterable to allow the use of forEach loops for - * convenience.

- * - * @param an item of type T - * - * @author Jon Malkin - */ -public class VarOptItemsSamples implements Iterable.WeightedSample> { - - final VarOptItemsSketch sketch_; - VarOptItemsSketch.Result sampleLists; - final long n_; - final int h_; - final double rWeight_; - - /** - * A convenience class to allow easy iterator access to a VarOpt sample. - */ - //@SuppressWarnings("synthetic-access") - public final class WeightedSample { - private final int idx_; - private double adjustedWeight_; - - WeightedSample(final int i) { - idx_ = i; - adjustedWeight_ = Double.NaN; - } - - WeightedSample(final int i, final double adjustedWeight) { - idx_ = i; - adjustedWeight_ = adjustedWeight; - } - - /** - * Accesses the iterator's current object - * @return An item from the sketch's data sample - */ - public T getItem() { - return sketch_.getItem(idx_); - } - - /** - * Accesses the iterator's current weight value - * @return A weight from the sketch's data sample - */ - public double getWeight() { - if (idx_ > h_) { - return Double.isNaN(adjustedWeight_) ? rWeight_ : adjustedWeight_; - } else { - return sketch_.getWeight(idx_); - } - } - - // only used in resolving union gadget - boolean getMark() { return sketch_.getMark(idx_); } - } - - /** - * The standard iterator - */ - //@SuppressWarnings("synthetic-access") - public class VarOptItemsIterator implements Iterator { - int currIdx_; - int finalIdx_; // inclusive final index - - VarOptItemsIterator() { - currIdx_ = h_ == 0 ? 1 : 0; - final int k = sketch_.getK(); - finalIdx_ = (int) (n_ <= k ? n_ - 1 : k); // -1 since finalIdx_ is inclusive - } - - // package private iterator to crawl only H or only R region values - VarOptItemsIterator(final boolean useRRegion) { - if (useRRegion) { - currIdx_ = h_ + 1; // to handle the gap - finalIdx_ = sketch_.getNumSamples(); // no +1 since inclusive - } else { - currIdx_ = 0; - finalIdx_ = h_ - 1; // need stop before h_ since incluside - } - } - - @Override - public boolean hasNext() { - // If sketch is in exact mode, we'll have a next item as long as index < k. - // If in sampling mode, the last index is k (array length k+1) but there will always be at - // least one item in R, so no need to check if the last element is null. - return currIdx_ <= finalIdx_; - } - - @Override - public WeightedSample next() { - if (n_ != sketch_.getN()) { - throw new ConcurrentModificationException(); - } else if (currIdx_ > finalIdx_) { - throw new NoSuchElementException(); - } - - // grab current index, apply logic to update currIdx_ for the next call - final int tgt = currIdx_; - - ++currIdx_; - if ((currIdx_ == h_) && (h_ != n_)) { - ++currIdx_; - } - - return new WeightedSample(tgt); - } - } - - //@SuppressWarnings("synthetic-access") - class WeightCorrectingRRegionIterator extends VarOptItemsIterator { - private double cumWeight = 0.0; - - WeightCorrectingRRegionIterator() { - super(true); - } - - @Override - public WeightedSample next() { - if (n_ != sketch_.getN()) { - throw new ConcurrentModificationException(); - } else if (currIdx_ > finalIdx_) { - throw new NoSuchElementException(); - } - - // grab current index, apply logic to update currIdx_ for the next call - final int tgt = currIdx_; - - ++currIdx_; - // only covers R region, no need to check for gap - - final WeightedSample sample; - if (tgt == finalIdx_) { - sample = new WeightedSample(tgt, sketch_.getTotalWtR() - cumWeight); - } else { - sample = new WeightedSample(tgt); - cumWeight += rWeight_; - } - - return sample; - } - } - - VarOptItemsSamples(final VarOptItemsSketch sketch) { - Objects.requireNonNull(sketch, "sketch must not be null"); - sketch_ = sketch; - n_ = sketch.getN(); - h_ = sketch.getHRegionCount(); - rWeight_ = sketch.getTau(); - } - - @Override - public Iterator iterator() { - return new VarOptItemsIterator(); - } - - Iterator getHIterator() { return new VarOptItemsIterator(false); } - - Iterator getRIterator() { return new VarOptItemsIterator(true); } - - Iterator getWeightCorrRIter() { return new WeightCorrectingRRegionIterator(); } - - /** - * Specifies the class to use when copying the item array from the sketch. This method is - * required if the sketch stores heterogeneous item types of some base class, for instance a - * sketch over Numbers. - * - * @param clazz The class to use when creating the item array result - */ - public void setClass(final Class clazz) { - if (sampleLists == null) { - sampleLists = sketch_.getSamplesAsArrays(clazz); - } - } - - /** - * Returns the length Copies items and weights from the sketch, if necessary, and returns the - * length of - * any - * resulting array. The result will be 0 for an empty sketch. - * - * @return The number of items and weights in the sketch - */ - public int getNumSamples() { - loadArrays(); - return (sampleLists == null || sampleLists.weights == null ? 0 : sampleLists.weights.length); - } - - /** - * Returns a shallow copy of the array of sample items contained in the sketch. If this is the - * first getter call, copies data arrays from the sketch. - * @return The number of samples contained in the sketch. - */ - public T[] items() { - loadArrays(); - return (sampleLists == null ? null : sampleLists.items); - } - - /** - * Returns a single item from the samples contained in the sketch. Does not perform bounds - * checking on the input. If this is the first getter call, copies data arrays from the sketch. - * @param i An index into the list of samples - * @return The sample at array position i - */ - public T items(final int i) { - loadArrays(); - return (sampleLists == null || sampleLists.items == null ? null : sampleLists.items[i]); - } - - /** - * Returns a copy of the array of weights contained in the sketch. If this is the first - * getter call, copies data arrays from the sketch. - * @return The number of samples contained in the sketch. - */ - public double[] weights() { - loadArrays(); - return (sampleLists == null ? null : sampleLists.weights); - } - - /** - * Returns a single weight from the samples contained in the sketch. Does not perform bounds - * checking on the input. If this is the first getter call, copies data arrays from the sketch. - * @param i An index into the list of weights - * @return The weight at array position i - */ - public double weights(final int i) { - loadArrays(); - return (sampleLists == null || sampleLists.weights == null ? Double.NaN : sampleLists.weights[i]); - } - - private void loadArrays() { - if (sampleLists == null) { - sampleLists = sketch_.getSamplesAsArrays(); - } - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/VarOptItemsSketch.java b/src/main/java/org/apache/datasketches/sampling/VarOptItemsSketch.java deleted file mode 100644 index 121b6678a..000000000 --- a/src/main/java/org/apache/datasketches/sampling/VarOptItemsSketch.java +++ /dev/null @@ -1,1313 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.sampling.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.sampling.PreambleUtil.GADGET_FLAG_MASK; -import static org.apache.datasketches.sampling.PreambleUtil.TOTAL_WEIGHT_R_DOUBLE; -import static org.apache.datasketches.sampling.PreambleUtil.VAROPT_SER_VER; -import static org.apache.datasketches.sampling.PreambleUtil.VO_PRELONGS_EMPTY; -import static org.apache.datasketches.sampling.PreambleUtil.VO_PRELONGS_FULL; -import static org.apache.datasketches.sampling.PreambleUtil.VO_PRELONGS_WARMUP; -import static org.apache.datasketches.sampling.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.sampling.PreambleUtil.extractFlags; -import static org.apache.datasketches.sampling.PreambleUtil.extractHRegionItemCount; -import static org.apache.datasketches.sampling.PreambleUtil.extractK; -import static org.apache.datasketches.sampling.PreambleUtil.extractN; -import static org.apache.datasketches.sampling.PreambleUtil.extractRRegionItemCount; -import static org.apache.datasketches.sampling.PreambleUtil.extractResizeFactor; -import static org.apache.datasketches.sampling.PreambleUtil.extractSerVer; -import static org.apache.datasketches.sampling.PreambleUtil.extractTotalRWeight; -import static org.apache.datasketches.sampling.PreambleUtil.getAndCheckPreLongs; -import static org.apache.datasketches.sampling.SamplingUtil.pseudoHypergeometricLBonP; -import static org.apache.datasketches.sampling.SamplingUtil.pseudoHypergeometricUBonP; - -import java.lang.foreign.MemorySegment; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.function.Predicate; - -import org.apache.datasketches.common.ArrayOfBooleansSerDe; -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.Util; - -/** - * This sketch provides a variance optimal sample over an input stream of weighted items. The - * sketch can be used to compute subset sums over predicates, producing estimates with optimal - * variance for a given sketch size. - * - *

Using this sketch with uniformly constant item weights (e.g. 1.0) will produce a standard - * reservoir sample over the steam.

- * - * @param The type of object held in the sketch. - * - * @author Jon Malkin - * @author Kevin Lang - */ -public final class VarOptItemsSketch { - /** - * The smallest sampling array allocated: 16 - */ - private static final int MIN_LG_ARR_ITEMS = 4; - - /** - * Default sampling size multiple when reallocating storage: 8 - */ - private static final ResizeFactor DEFAULT_RESIZE_FACTOR = ResizeFactor.X8; - - private static final ArrayOfBooleansSerDe MARK_SERDE = new ArrayOfBooleansSerDe(); - - private int k_; // max size of sketch, in items - private int currItemsAlloc_; // currently allocated array size - private final ResizeFactor rf_; // resize factor - private ArrayList data_; // stored sampled items - private ArrayList weights_; // weights for sampled items - - private long n_; // total number of items processed by the sketch - private int h_; // number of items in heap - private int m_; // number of items in middle region - private int r_; // number of items in reservoir-like area - private double totalWtR_; // total weight of items in reservoir-like area - - // The next two fields are hidden from the user because they are part of the state of the - // unioning algorithm, NOT part of a varopt sketch, or even of a varopt "gadget" (our name for - // the potentially invalid sketch that is maintained by the unioning algorithm). It would make - // more sense logically for these fields to be declared in the unioning object (whose entire - // purpose is storing the state of the unioning algorithm) but for reasons of programming - // convenience we are currently declaring them here. However, that could change in the future. - - // Following int is: - // 1. Zero (for a varopt sketch) - // 2. Count of marked items in H region, if part of a unioning algo's gadget - private int numMarksInH_; - - // The following array is absent in a varopt sketch, and notionally present in a gadget - // [although it really belongs in the unioning object]. If the array were to be made explicit, - // some additional coding would need to be done to ensure that all of the necessary data motion - // occurs and is properly tracked. - private ArrayList marks_; - - // used to return a shallow copy of the sketch's samples to a VarOptItemsSamples, as arrays - // with any null value stripped and the R region weight computed - class Result { - T[] items; - double[] weights; - } - - private VarOptItemsSketch(final int k, final ResizeFactor rf) { - // required due to a theorem about lightness during merging - if ((k < 1) || (k > (Integer.MAX_VALUE - 1))) { - throw new SketchesArgumentException("k must be at least 1 and less than " + Integer.MAX_VALUE - + ". Found: " + k); - } - - k_ = k; - n_ = 0; - rf_ = rf; - - h_ = 0; - m_ = 0; - r_ = 0; - totalWtR_ = 0; - numMarksInH_ = 0; - - final int ceilingLgK = Util.exactLog2OfInt(Util.ceilingPowerOf2(k_), "VarOptItemsSketch"); - final int initialLgSize = - SamplingUtil.startingSubMultiple(ceilingLgK, rf_.lg(), MIN_LG_ARR_ITEMS); - - currItemsAlloc_ = SamplingUtil.getAdjustedSize(k_, 1 << initialLgSize); - if (currItemsAlloc_ == k_) { - ++currItemsAlloc_; - } - - data_ = new ArrayList<>(currItemsAlloc_); - weights_ = new ArrayList<>(currItemsAlloc_); - marks_ = null; - } - - private VarOptItemsSketch(final ArrayList dataList, - final ArrayList weightList, - final int k, - final long n, - final int currItemsAlloc, - final ResizeFactor rf, - final int hCount, - final int rCount, - final double totalWtR) { - assert dataList != null; - assert weightList != null; - assert dataList.size() == weightList.size(); - assert currItemsAlloc >= dataList.size(); - assert k >= 2; - assert n >= 0; - assert hCount >= 0; - assert rCount >= 0; - assert ((rCount == 0) && (dataList.size() == hCount)) || ((rCount > 0) && (dataList.size() == (k + 1))); - - k_ = k; - n_ = n; - h_ = hCount; - r_ = rCount; - m_ = 0; - totalWtR_ = totalWtR; - currItemsAlloc_ = currItemsAlloc; - rf_ = rf; - data_ = dataList; - weights_ = weightList; - - numMarksInH_ = 0; - marks_ = null; - } - - /** - * Construct a varopt sampling sketch with up to k samples using the default resize factor (8). - * - * @param k Maximum size of sampling. Allocated size may be smaller until sketch fills. - * Unlike many sketches in this package, this value does not need to be a - * power of 2. - * @param The type of object held in the sketch. - * @return A VarOptItemsSketch initialized with maximum size k and resize factor rf. - */ - public static VarOptItemsSketch newInstance(final int k) { - return new VarOptItemsSketch<>(k, DEFAULT_RESIZE_FACTOR); - } - - /** - * Construct a varopt sampling sketch with up to k samples using the specified resize factor. - * - * @param k Maximum size of sampling. Allocated size may be smaller until sketch fills. - * Unlike many sketches in this package, this value does not need to be a - * power of 2. The maximum size is Integer.MAX_VALUE-1. - * @param rf See Resize Factor - * @param The type of object held in the sketch. - * @return A VarOptItemsSketch initialized with maximum size k and resize factor rf. - */ - public static VarOptItemsSketch newInstance(final int k, final ResizeFactor rf) { - return new VarOptItemsSketch<>(k, rf); - } - - /** - * Construct a varopt sketch for use as a unioning gadget, meaning the array of marked elements - * is also initialized. - * - * @param k Maximum size of sampling. Allocated size may be smaller until sketch fills. - * Unlike many sketches in this package, this value does not need to be a - * power of 2. - * @param The type of object held in the sketch. - * @return A VarOptItemsSketch initialized with maximum size k and a valid array of marks. - */ - static VarOptItemsSketch newInstanceAsGadget(final int k) { - final VarOptItemsSketch sketch = new VarOptItemsSketch<>(k, DEFAULT_RESIZE_FACTOR); - sketch.marks_ = new ArrayList<>(sketch.currItemsAlloc_); - return sketch; - } - - /** - * Construct a varopt sketch as the output of a union's getResult() method. Because this method - * is package-private, we do not perform checks on the input values. - * - *

Assumes dataList.size() is the correct allocated size but does not check.

- * - * @param The type of object held in the sketch. - * @param dataList an ArrayList of data - * @param weightList an ArrayList of weights - * @param k Maximum size of sampling. Allocated size may be smaller until sketch fills. - * Unlike many sketches in this package, this value does not need to be a - * power of 2. - * @param n The current count of items seen by the sketch - * @param hCount the count of heavy items - * @param rCount the reservoir count of (non-heavy) items - * @param totalWtR the sum of the reservoir weights. - * @return A VarOptItemsSketch initialized with maximum size k and a valid array of marks. - */ - static VarOptItemsSketch newInstanceFromUnionResult(final ArrayList dataList, - final ArrayList weightList, - final int k, - final long n, - final int hCount, - final int rCount, - final double totalWtR) { - final VarOptItemsSketch sketch = new VarOptItemsSketch<>(dataList, weightList, k, n, - dataList.size(), DEFAULT_RESIZE_FACTOR, hCount, rCount, totalWtR); - sketch.convertToHeap(); - return sketch; - } - - /** - * Returns a sketch instance of this class from the given srcSeg, - * which must be a MemorySegment representation of this sketch class. - * - * @param The type of item this sketch contains - * @param srcSeg a MemorySegment representation of a sketch of this class. - * @param serDe An instance of ArrayOfItemsSerDe - * @return a sketch instance of this class - */ - public static VarOptItemsSketch heapify(final MemorySegment srcSeg, - final ArrayOfItemsSerDe serDe) { - final int numPreLongs = getAndCheckPreLongs(srcSeg); - final ResizeFactor rf = ResizeFactor.getRF(extractResizeFactor(srcSeg)); - final int serVer = extractSerVer(srcSeg); - final int familyId = extractFamilyID(srcSeg); - final int flags = extractFlags(srcSeg); - final boolean isEmpty = (flags & EMPTY_FLAG_MASK) != 0; - final boolean isGadget = (flags & GADGET_FLAG_MASK) != 0; - - // Check values - if (isEmpty) { - if (numPreLongs != VO_PRELONGS_EMPTY) { - throw new SketchesArgumentException("Possible corruption: Must be " + VO_PRELONGS_EMPTY - + " for an empty sketch. Found: " + numPreLongs); - } - } else if ((numPreLongs != VO_PRELONGS_WARMUP) - && (numPreLongs != VO_PRELONGS_FULL)) { - throw new SketchesArgumentException("Possible corruption: Must be " + VO_PRELONGS_WARMUP - + " or " + VO_PRELONGS_FULL + " for a non-empty sketch. Found: " + numPreLongs); - } - if (serVer != VAROPT_SER_VER) { - throw new SketchesArgumentException( - "Possible Corruption: Ser Ver must be " + VAROPT_SER_VER + ": " + serVer); - } - final int reqFamilyId = Family.VAROPT.getID(); - if (familyId != reqFamilyId) { - throw new SketchesArgumentException( - "Possible Corruption: FamilyID must be " + reqFamilyId + ": " + familyId); - } - - final int k = extractK(srcSeg); - if (k < 1) { - throw new SketchesArgumentException("Possible Corruption: k must be at least 1: " + k); - } - - if (isEmpty) { - assert numPreLongs == Family.VAROPT.getMinPreLongs(); - return new VarOptItemsSketch<>(k, rf); - } - - final long n = extractN(srcSeg); - if (n < 0) { - throw new SketchesArgumentException("Possible Corruption: n cannot be negative: " + n); - } - - // get rest of preamble - final int hCount = extractHRegionItemCount(srcSeg); - final int rCount = extractRRegionItemCount(srcSeg); - - if (hCount < 0) { - throw new SketchesArgumentException("Possible Corruption: H region count cannot be " - + "negative: " + hCount); - } - if (rCount < 0) { - throw new SketchesArgumentException("Possible Corruption: R region count cannot be " - + "negative: " + rCount); - } - - double totalRWeight = 0.0; - if (numPreLongs == Family.VAROPT.getMaxPreLongs()) { - if (rCount > 0) { - totalRWeight = extractTotalRWeight(srcSeg); - if (Double.isNaN(totalRWeight) || (totalRWeight <= 0.0)) { - throw new SketchesArgumentException("Possible Corruption: deserializing in full mode " - + "but invalid R region weight. Found r = " + rCount - + ", R region weight = " + totalRWeight); - } - } else { - throw new SketchesArgumentException( - "Possible Corruption: " - + Family.VAROPT.getMaxPreLongs() + " preLongs but no items in R region"); - } - } - - final int preLongBytes = numPreLongs << 3; - - final int totalItems = hCount + rCount; - int allocatedItems = k + 1; // default to full - - if (rCount == 0) { - // Not in sampling mode, so determine size to allocate, using ceilingLog2(hCount) as minimum - final int ceilingLgK = Util.exactLog2OfInt(Util.ceilingPowerOf2(k), "heapify"); - final int minLgSize = Util.exactLog2OfInt(Util.ceilingPowerOf2(hCount), "heapify"); - final int initialLgSize = SamplingUtil.startingSubMultiple(ceilingLgK, rf.lg(), - Math.max(minLgSize, MIN_LG_ARR_ITEMS)); - - allocatedItems = SamplingUtil.getAdjustedSize(k, 1 << initialLgSize); - if (allocatedItems == k) { - ++allocatedItems; - } - } - - // allocate full-sized ArrayLists, but we store only hCount weights at any moment - final long weightOffsetBytes = TOTAL_WEIGHT_R_DOUBLE + (rCount > 0 ? Double.BYTES : 0); - final ArrayList weightList = new ArrayList<>(allocatedItems); - final double[] wts = new double[allocatedItems]; - MemorySegment.copy(srcSeg, JAVA_DOUBLE_UNALIGNED, weightOffsetBytes, wts, 0, hCount); - - // can't use Arrays.asList(wts) since double[] rather than Double[] - for (int i = 0; i < hCount; ++ i) { - if (wts[i] <= 0.0) { - throw new SketchesArgumentException("Possible Corruption: " - + "Non-positive weight in heapify(): " + wts[i]); - } - weightList.add(wts[i]); - } - - // marks, if we have a gadget - long markBytes = 0; - int markCount = 0; - ArrayList markList = null; - if (isGadget) { - final long markOffsetBytes = preLongBytes + ((long) hCount * Double.BYTES); - markBytes = ArrayOfBooleansSerDe.computeBytesNeeded(hCount); - markList = new ArrayList<>(allocatedItems); - - final ArrayOfBooleansSerDe booleansSerDe = new ArrayOfBooleansSerDe(); - final Boolean[] markArray = booleansSerDe.deserializeFromMemorySegment( - srcSeg.asSlice(markOffsetBytes, (hCount >>> 3) + 1), 0, hCount); - - for (final Boolean mark : markArray) { - if (mark) { ++markCount; } - } - markList.addAll(Arrays.asList(markArray)); - } - - final long offsetBytes = preLongBytes + ((long) hCount * Double.BYTES) + markBytes; - final T[] data = serDe.deserializeFromMemorySegment(srcSeg.asSlice(offsetBytes), 0, totalItems); - final List wrappedData = Arrays.asList(data); - final ArrayList dataList = new ArrayList<>(allocatedItems); - dataList.addAll(wrappedData.subList(0, hCount)); - - // Load items in R as needed - if (rCount > 0) { - weightList.add(-1.0); // the gap - if (isGadget) { markList.add(false); } // the gap - for (int i = 0; i < rCount; ++i) { - weightList.add(-1.0); - if (isGadget) { markList.add(false); } - } - - dataList.add(null); // the gap - dataList.addAll(wrappedData.subList(hCount, totalItems)); - } - - final VarOptItemsSketch sketch = - new VarOptItemsSketch<>(dataList, weightList, k, n, - allocatedItems, rf, hCount, rCount, totalRWeight); - - if (isGadget) { - sketch.marks_ = markList; - sketch.numMarksInH_ = markCount; - } - - return sketch; - } - - /** - * Returns the sketch's value of k, the maximum number of samples stored in the - * sketch. The current number of items in the sketch may be lower. - * - * @return k, the maximum number of samples in the sketch - */ - public int getK() { - return k_; - } - - /** - * Returns the number of items processed from the input stream - * - * @return n, the number of stream items the sketch has seen - */ - public long getN() { - return n_; - } - - /** - * Returns the current number of items in the sketch, which may be smaller than the - * sketch capacity. - * - * @return the number of items currently in the sketch - */ - public int getNumSamples() { - return Math.min(k_, h_ + r_); - } - - /** - * Gets a result iterator object. - * @return An object with an iterator over the results - */ - public VarOptItemsSamples getSketchSamples() { - return new VarOptItemsSamples<>(this); - } - - /** - * Randomly decide whether or not to include an item in the sample set. - * - * @param item an item of the set being sampled from - * @param weight a strictly positive weight associated with the item - */ - public void update(final T item, final double weight) { - update(item, weight, false); - } - - /** - * Resets this sketch to the empty state, but retains the original value of k. - */ - public void reset() { - final int ceilingLgK = Util.exactLog2OfInt(Util.ceilingPowerOf2(k_), "VarOptItemsSketch"); - final int initialLgSize = - SamplingUtil.startingSubMultiple(ceilingLgK, rf_.lg(), MIN_LG_ARR_ITEMS); - - currItemsAlloc_ = SamplingUtil.getAdjustedSize(k_, 1 << initialLgSize); - if (currItemsAlloc_ == k_) { - ++currItemsAlloc_; - } - - data_ = new ArrayList<>(currItemsAlloc_); - weights_ = new ArrayList<>(currItemsAlloc_); - if (marks_ != null) { - marks_ = new ArrayList<>(currItemsAlloc_); - } - - n_ = 0; - h_ = 0; - m_ = 0; - r_ = 0; - numMarksInH_ = 0; - totalWtR_ = 0.0; - } - - /** - * Returns a human-readable summary of the sketch. - * - * @return A string version of the sketch summary - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - - final String thisSimpleName = this.getClass().getSimpleName(); - - sb.append(LS); - sb.append("### ").append(thisSimpleName).append(" SUMMARY: ").append(LS); - sb.append(" k : ").append(k_).append(LS); - sb.append(" h : ").append(h_).append(LS); - sb.append(" r : ").append(r_).append(LS); - sb.append(" weight_r : ").append(totalWtR_).append(LS); - sb.append(" Current size : ").append(currItemsAlloc_).append(LS); - sb.append(" Resize factor: ").append(rf_).append(LS); - sb.append("### END SKETCH SUMMARY").append(LS); - - return sb.toString(); - } - - /** - * Returns a human readable string of the preamble of a byte array image of a VarOptItemsSketch. - * @param byteArr the given byte array - * @return a human readable string of the preamble of a byte array image of a VarOptItemsSketch. - */ - public static String toString(final byte[] byteArr) { - return PreambleUtil.preambleToString(byteArr); - } - - /** - * Returns a human readable string of the preamble of a MemorySegment image of a VarOptItemsSketch. - * @param seg the given MemorySegment - * @return a human readable string of the preamble of a MemorySegment image of a VarOptItemsSketch. - */ - public static String toString(final MemorySegment seg) { - return PreambleUtil.preambleToString(seg); - } - - /** - * Returns a byte array representation of this sketch. May fail for polymorphic item types. - * - * @param serDe An instance of ArrayOfItemsSerDe - * @return a byte array representation of this sketch - */ - public byte[] toByteArray(final ArrayOfItemsSerDe serDe) { - if ((r_ == 0) && (h_ == 0)) { - // null class is ok since empty -- no need to call serDe - return toByteArray(serDe, null); - } else { - final int validIndex = (h_ == 0 ? 1 : 0); - final Class clazz = data_.get(validIndex).getClass(); - return toByteArray(serDe, clazz); - } - } - - /** - * Returns a byte array representation of this sketch. Copies contents into an array of the - * specified class for serialization to allow for polymorphic types. - * - * @param serDe An instance of ArrayOfItemsSerDe - * @param clazz The class represented by <T> - * @return a byte array representation of this sketch - */ - // bytes will be null only if empty == true - public byte[] toByteArray(final ArrayOfItemsSerDe serDe, final Class clazz) { - final int preLongs, numMarkBytes, outBytes; - final boolean empty = (r_ == 0) && (h_ == 0); - byte[] itemBytes = null; // for serialized items from serDe - int flags = marks_ == null ? 0 : GADGET_FLAG_MASK; - - if (empty) { - preLongs = Family.VAROPT.getMinPreLongs(); - outBytes = Family.VAROPT.getMinPreLongs() << 3; // only contains the minimum header info - flags |= EMPTY_FLAG_MASK; - } else { - preLongs = (r_ == 0 ? PreambleUtil.VO_PRELONGS_WARMUP : Family.VAROPT.getMaxPreLongs()); - itemBytes = serDe.serializeToByteArray(getDataSamples(clazz)); - numMarkBytes = marks_ == null ? 0 : ArrayOfBooleansSerDe.computeBytesNeeded(h_); - outBytes = (preLongs << 3) + (h_ * Double.BYTES) + numMarkBytes + itemBytes.length; - } - final byte[] outArr = new byte[outBytes]; - final MemorySegment seg = MemorySegment.ofArray(outArr); - - // build first preLong - PreambleUtil.insertPreLongs(seg, preLongs); // Byte 0 - PreambleUtil.insertLgResizeFactor(seg, rf_.lg()); - PreambleUtil.insertSerVer(seg, VAROPT_SER_VER); // Byte 1 - PreambleUtil.insertFamilyID(seg, Family.VAROPT.getID()); // Byte 2 - PreambleUtil.insertFlags(seg, flags); // Byte 3 - PreambleUtil.insertK(seg, k_); // Bytes 4-7 - - if (!empty) { - PreambleUtil.insertN(seg, n_); // Bytes 8-15 - PreambleUtil.insertHRegionItemCount(seg, h_); // Bytes 16-19 - PreambleUtil.insertRRegionItemCount(seg, r_); // Bytes 20-23 - if (r_ > 0) { - PreambleUtil.insertTotalRWeight(seg, totalWtR_); // Bytes 24-31 - } - - // write the first h_ weights - int offset = preLongs << 3; - for (int i = 0; i < h_; ++i) { - seg.set(JAVA_DOUBLE_UNALIGNED, offset, weights_.get(i)); - offset += Double.BYTES; - } - - // write the first h_ marks, iff we have a gadget - if (marks_ != null) { - final byte[] markBytes; - markBytes = MARK_SERDE.serializeToByteArray(marks_.subList(0, h_).toArray(new Boolean[0])); - MemorySegment.copy(markBytes, 0, seg, JAVA_BYTE, offset, markBytes.length); - - offset += markBytes.length; - } - - // write the sample items, using offset from earlier - MemorySegment.copy(itemBytes, 0, seg, JAVA_BYTE, offset, itemBytes.length); - } - - return outArr; - } - - /** - * Computes an estimated subset sum from the entire stream for objects matching a given - * predicate. Provides a lower bound, estimate, and upper bound using a target of 2 standard - * deviations. - * - *

This is technically a heuristic method, and tries to err on the conservative side.

- * - * @param predicate A predicate to use when identifying items. - * @return A summary object containing the estimate, upper and lower bounds, and the total - * sketch weight. - */ - public SampleSubsetSummary estimateSubsetSum(final Predicate predicate) { - - if (n_ == 0) { - return new SampleSubsetSummary(0.0, 0.0, 0.0, 0.0); - } - - double totalWtH = 0.0; - double hTrueWeight = 0.0; - int idx = 0; - for (; idx < h_; ++idx) { - final double wt = weights_.get(idx); - totalWtH += wt; - if (predicate.test(data_.get(idx))) { - hTrueWeight += wt; - } - } - - // if only heavy items, we have an exact answer - if (r_ == 0) { - return new SampleSubsetSummary(hTrueWeight, hTrueWeight, hTrueWeight, hTrueWeight); - } - - final long numSampled = n_ - h_; - assert numSampled > 0; - final double effectiveSamplingRate = r_ / (double) numSampled; - assert effectiveSamplingRate >= 0.0; - assert effectiveSamplingRate <= 1.0; - - int rTrueCount = 0; - ++idx; // skip the gap - for (; idx < (k_ + 1); ++idx) { - if (predicate.test(data_.get(idx))) { - ++rTrueCount; - } - } - - final double lbTrueFraction = pseudoHypergeometricLBonP(r_, rTrueCount, effectiveSamplingRate); - final double estimatedTrueFraction = (1.0 * rTrueCount) / r_; - final double ubTrueFraction = pseudoHypergeometricUBonP(r_, rTrueCount, effectiveSamplingRate); - return new SampleSubsetSummary( - hTrueWeight + (totalWtR_ * lbTrueFraction), - hTrueWeight + (totalWtR_ * estimatedTrueFraction), - hTrueWeight + (totalWtR_ * ubTrueFraction), - totalWtH + totalWtR_); - } - - /** - * Returns a VarOptItemsSketch.Result structure containing the items and weights in separate - * lists. The returned list lengths may be smaller than the total capacity. - * - * @return A Result object containing items and weights. - */ - Result getSamplesAsArrays() { - if ((r_ + h_) == 0) { - return null; - } - - final int validIndex = (h_ == 0 ? 1 : 0); - final Class clazz = data_.get(validIndex).getClass(); - return getSamplesAsArrays(clazz); - } - - /** - * Creates a copy of the sketch, optionally discarding any information about marks that would - * indicate the class's use as a union gadget as opposed to a valid sketch. - * - * @param asSketch If true, copies as a sketch; if false, copies as a union gadget - * @param adjustedN Target value of n for the resulting sketch. Ignored if negative. - * @return A copy of the sketch. - */ - VarOptItemsSketch copyAndSetN(final boolean asSketch, final long adjustedN) { - final VarOptItemsSketch sketch; - sketch = new VarOptItemsSketch<>(data_, weights_, k_,n_, - currItemsAlloc_, rf_, h_, r_, totalWtR_); - - if (!asSketch) { - sketch.marks_ = marks_; - sketch.numMarksInH_ = numMarksInH_; - } - - if (adjustedN >= 0) { - sketch.n_ = adjustedN; - } - - return sketch; - } - - /** - * Strips the mark array from the object, making what had been a gadget indistinguishable form - * a sketch. Avoids an extra copy. - */ - void stripMarks() { - assert marks_ != null; - numMarksInH_ = 0; - marks_ = null; - } - - /** - * Returns a VarOptItemsSketch.Result structure containing the items and weights in separate - * lists. The returned list lengths may be smaller than the total capacity. - * - *

This method allocates an array of class clazz, which must either match or - * be parent of T. This method should be used when objects in the array are all instances of T - * but are not necessarily instances of the base class.

- * - * @param clazz A class to which the items are cast before returning - * @return A Result object containing items and weights. - */ - @SuppressWarnings("unchecked") - Result getSamplesAsArrays(final Class clazz) { - if ((r_ + h_) == 0) { - return null; - } - - // are Array.asList(data_.subList()) copies better? - final int numSamples = getNumSamples(); - final T[] prunedItems = (T[]) Array.newInstance(clazz, numSamples); - final double[] prunedWeights = new double[numSamples]; - int j = 0; - final double rWeight = totalWtR_ / r_; - for (int i = 0; j < numSamples; ++i) { - final T item = data_.get(i); - if (item != null) { - prunedItems[j] = item; - prunedWeights[j] = (weights_.get(i) > 0 ? weights_.get(i) : rWeight); - ++j; - } - } - - final Result output = new Result(); - output.items = prunedItems; - output.weights = prunedWeights; - - return output; - } - - // package-private getters - - // package-private: Relies on ArrayList for bounds checking and assumes caller knows how to handle - // a null from the middle of the list - T getItem(final int idx) { - return data_.get(idx); - } - - // package-private: Relies on ArrayList for bounds checking and assumes caller knows how to handle - // a negative value (whether from the null in the middle or an R-region item) - double getWeight(final int idx) { - return weights_.get(idx); - } - - // package-private: Relies on ArrayList for bounds checking and assumes caller knows how to - // handle a null from the middle of the list. - boolean getMark(final int idx) { return marks_.get(idx); } - - int getHRegionCount() { - return h_; - } - - int getRRegionCount() { return r_; } - - int getNumMarksInH() { return numMarksInH_; } - - // Needed by result object and for unioning - double getTau() { - return r_ == 0 ? Double.NaN : (totalWtR_ / r_); - } - - double getTotalWtR() { - return totalWtR_; - } - - // package-private setter, used to resolve gadget into sketch during union - void forceSetK(final int k) { - assert k > 0; - k_ = k; - } - - /** - * Internal implementation of update() which requires the user to know if an item is - * marked as coming from the reservoir region of a sketch. The marks are used only in - * merging. - * - * @param item an item of the set being sampled from - * @param weight a strictly positive weight associated with the item - * @param mark true if an item comes from a sketch's reservoir region - */ - void update(final T item, final double weight, final boolean mark) { - if (item == null) { - return; - } - if (weight <= 0.0 || Double.isNaN(weight) || Double.isInfinite(weight)) { - throw new SketchesArgumentException("Item weights must be strictly positive and finite number: " - + weight + ", for item " + item.toString()); - } - ++n_; - - if (r_ == 0) { - // exact mode - updateWarmupPhase(item, weight, mark); - } else { - // sketch is in estimation mode, so we can make the following check - assert (h_ == 0) || (peekMin() >= getTau()); - - // what tau would be if deletion candidates turn out to be R plus the new item - // note: (r_ + 1) - 1 is intentional - final double hypotheticalTau = (weight + totalWtR_) / ((r_ + 1) - 1); - - // is new item's turn to be considered for reservoir? - final boolean condition1 = (h_ == 0) || (weight <= peekMin()); - - // is new item light enough for reservoir? - final boolean condition2 = weight < hypotheticalTau; - - if (condition1 && condition2) { - updateLight(item, weight, mark); - } else if (r_ == 1) { - updateHeavyREq1(item, weight, mark); - } else { - updateHeavyGeneral(item, weight, mark); - } - } - } - - /** - * Decreases sketch's value of k by 1, updating stored values as needed. - * - *

Subject to certain pre-conditions, decreasing k causes tau to increase. This fact is used by - * the unioning algorithm to force "marked" items out of H and into the reservoir region.

- */ - void decreaseKBy1() { - if (k_ <= 1) { - throw new SketchesStateException("Cannot decrease k below 1 in union"); - } - - if ((h_ == 0) && (r_ == 0)) { - // exact mode, but no data yet; this reduction is somewhat gratuitous - --k_; - } else if ((h_ > 0) && (r_ == 0)) { - // exact mode, but we have some data - --k_; - if (h_ > k_) { - transitionFromWarmup(); - } - } else if ((h_ > 0) && (r_ > 0)) { - // reservoir mode, but we have some exact samples. - // Our strategy will be to pull an item out of H (which we are allowed to do since it's - // still just data), reduce k, and then re-insert the item - - // first, slide the R zone to the left by 1, temporarily filling the gap - final int oldGapIdx = h_; - final int oldFinalRIdx = (h_ + 1 + r_) - 1; - - assert oldFinalRIdx == k_; - swapValues(oldFinalRIdx, oldGapIdx); - - // now we pull an item out of H; any item is ok, but if we grab the rightmost and then - // reduce h_, the heap invariant will be preserved (and the gap will be restored), plus - // the push() of the item that will probably happen later will be cheap. - - final int pulledIdx = h_ - 1; - final T pulledItem = data_.get(pulledIdx); - final double pulledWeight = weights_.get(pulledIdx); - final boolean pulledMark = marks_.get(pulledIdx); - - if (pulledMark) { --numMarksInH_; } - weights_.set(pulledIdx, -1.0); // to make bugs easier to spot - - --h_; - --k_; - --n_; // will be re-incremented with the update - - update(pulledItem, pulledWeight, pulledMark); - } else if ((h_ == 0) && (r_ > 0)) { - // pure reservoir mode, so can simply eject a randomly chosen sample from the reservoir - assert r_ >= 2; - - final int rIdxToDelete = 1 + SamplingUtil.rand().nextInt(r_); // 1 for the gap - final int rightmostRIdx = (1 + r_) - 1; - swapValues(rIdxToDelete, rightmostRIdx); - weights_.set(rightmostRIdx, -1.0); - - --k_; - --r_; - } - } - - /* In the "light" case the new item has weight <= old_tau, so - would appear to the right of the R items in a hypothetical reverse-sorted - list. It is easy to prove that it is light enough to be part of this - round's downsampling */ - private void updateLight(final T item, final double weight, final boolean mark) { - assert r_ >= 1; - assert (r_ + h_) == k_; - - final int mSlot = h_; // index of the gap, which becomes the M region - data_.set(mSlot, item); - weights_.set(mSlot, weight); - if (marks_ != null) { marks_.set(mSlot, mark); } - ++m_; - - growCandidateSet(totalWtR_ + weight, r_ + 1); - } - - /* In the "heavy" case the new item has weight > old_tau, so would - appear to the left of items in R in a hypothetical reverse-sorted list and - might or might not be light enough be part of this round's downsampling. - [After first splitting off the R=1 case] we greatly simplify the code by - putting the new item into the H heap whether it needs to be there or not. - In other words, it might go into the heap and then come right back out, - but that should be okay because pseudo_heavy items cannot predominate - in long streams unless (max wt) / (min wt) > o(exp(N)) */ - private void updateHeavyGeneral(final T item, final double weight, final boolean mark) { - assert m_ == 0; - assert r_ >= 2; - assert (r_ + h_) == k_; - - // put into H, although may come back out momentarily - push(item, weight, mark); - - growCandidateSet(totalWtR_, r_); - } - - /* The analysis of this case is similar to that of the general heavy case. - The one small technical difference is that since R < 2, we must grab an M item - to have a valid starting point for continue_by_growing_candidate_set () */ - private void updateHeavyREq1(final T item, final double weight, final boolean mark) { - assert m_ == 0; - assert r_ == 1; - assert (r_ + h_) == k_; - - push(item, weight, mark); // new item into H - popMinToMRegion(); // pop lightest back into M - - // Any set of two items is downsample-able to one item, - // so the two lightest items are a valid starting point for the following - final int mSlot = k_ - 1; // array is k+1, 1 in R, so slot before is M - growCandidateSet(weights_.get(mSlot) + totalWtR_, 2); - } - - private void updateWarmupPhase(final T item, final double wt, final boolean mark) { - assert r_ == 0; - assert m_ == 0; - assert h_ <= k_; - - if (h_ >= currItemsAlloc_) { - growDataArrays(); - } - - // store items as they come in, until full - data_.add(h_, item); - weights_.add(h_, wt); - if (marks_ != null) { marks_.add(h_, mark); } - ++h_; - numMarksInH_ += mark ? 1 : 0; - - // check if need to heapify - if (h_ > k_) { - transitionFromWarmup(); - } - } - - private void transitionFromWarmup() { - // Move 2 lightest items from H to M - // But the lighter really belongs in R, so update counts to reflect that - convertToHeap(); - popMinToMRegion(); - popMinToMRegion(); - --m_; - ++r_; - - assert h_ == (k_ - 1); - assert m_ == 1; - assert r_ == 1; - - // Update total weight in R then, having grabbed the value, overwrite in - // weight_ array to help make bugs more obvious - totalWtR_ = weights_.get(k_); // only one item, known location - weights_.set(k_, -1.0); - - // The two lightest items are necessarily downsample-able to one item, and are therefore a - // valid initial candidate set. - growCandidateSet(weights_.get(k_ - 1) + totalWtR_, 2); - } - - /* Validates the heap condition for the weight array */ - /* - private void validateHeap() { - for (int j = h_ - 1; j >= 1; --j) { - final int p = ((j + 1) / 2) - 1; - assert weights_.get(p) <= weights_.get(j); - } - } - */ - - /* Converts the data_ and weights_ arrays to heaps. In contrast to other parts - of the library, this has nothing to do with on- or off-heap storage or the - MemorySegment package. - */ - private void convertToHeap() { - if (h_ < 2) { - return; // nothing to do - } - - final int lastSlot = h_ - 1; - final int lastNonLeaf = ((lastSlot + 1) / 2) - 1; - - for (int j = lastNonLeaf; j >= 0; --j) { - restoreTowardsLeaves(j); - } - - //validateHeap(); - } - - private void restoreTowardsLeaves(final int slotIn) { - assert h_ > 0; - final int lastSlot = h_ - 1; - assert slotIn <= lastSlot; - - int slot = slotIn; - int child = (2 * slotIn) + 1; // might be invalid, need to check - - while (child <= lastSlot) { - final int child2 = child + 1; // might also be invalid - if ((child2 <= lastSlot) && (weights_.get(child2) < weights_.get(child))) { - // switch to other child if it's both valid and smaller - child = child2; - } - - if (weights_.get(slot) <= weights_.get(child)) { - // invariant holds so we're done - break; - } - - // swap and continue - swapValues(slot, child); - - slot = child; - child = (2 * slot) + 1; // might be invalid, checked on next loop - } - } - - private void restoreTowardsRoot(final int slotIn) { - int slot = slotIn; - int p = (((slot + 1) / 2) - 1); // valid if slot >= 1 - while ((slot > 0) && (weights_.get(slot) < weights_.get(p))) { - swapValues(slot, p); - slot = p; - p = (((slot + 1) / 2) - 1); // valid if slot >= 1 - } - } - - private void push(final T item, final double wt, final boolean mark) { - data_.set(h_, item); - weights_.set(h_, wt); - if (marks_ != null) { - marks_.set(h_, mark); - numMarksInH_ += (mark ? 1 : 0); - } - ++h_; - - restoreTowardsRoot(h_ - 1); // need use old h_, but want accurate h_ - } - - private double peekMin() { - assert h_ > 0; - return weights_.get(0); - } - - private void popMinToMRegion() { - assert h_ > 0; - assert (h_ + m_ + r_) == (k_ + 1); - - if (h_ == 1) { - // just update bookkeeping - ++m_; - --h_; - } else { - // main case - final int tgt = h_ - 1; // last slot, will swap with root - swapValues(0, tgt); - ++m_; - --h_; - - restoreTowardsLeaves(0); - } - - if (isMarked(h_)) { - --numMarksInH_; - } - } - - /* When entering here we should be in a well-characterized state where the - new item has been placed in either h or m and we have a valid but not necessarily - maximal sampling plan figured out. The array is completely full at this point. - Everyone in h and m has an explicit weight. The candidates are right-justified - and are either just the r set or the r set + exactly one m item. The number - of cands is at least 2. We will now grow the candidate set as much as possible - by pulling sufficiently light items from h to m. - */ - private void growCandidateSet(double wtCands, int numCands) { - assert (h_ + m_ + r_) == (k_ + 1); - assert numCands >= 2; // essential - assert numCands == (m_ + r_); // essential - assert (m_ == 0) || (m_ == 1); - - while (h_ > 0) { - final double nextWt = peekMin(); - final double nextTotWt = wtCands + nextWt; - - // test for strict lightness of next prospect (denominator multiplied through) - // ideally: (nextWt * (nextNumCands-1) < nextTotWt) but can just - // use numCands directly - if ((nextWt * numCands) < nextTotWt) { - wtCands = nextTotWt; - ++numCands; - popMinToMRegion(); // adjusts h_ and m_ - } else { - break; - } - } - - downsampleCandidateSet(wtCands, numCands); - } - - private int pickRandomSlotInR() { - assert r_ > 0; - final int offset = h_ + m_; - if (r_ == 1) { - return offset; - } else { - return offset + SamplingUtil.rand().nextInt(r_); - } - } - - private int chooseDeleteSlot(final double wtCand, final int numCand) { - assert r_ > 0; - - if (m_ == 0) { - // this happens if we insert a really heavy item - return pickRandomSlotInR(); - } else if (m_ == 1) { - // check if we keep the item in M or pick one from R - // p(keep) = (numCand - 1) * wt_M / wt_cand - final double wtMCand = weights_.get(h_); // slot of item in M is h_ - if ((wtCand * SamplingUtil.nextDoubleExcludeZero()) < ((numCand - 1) * wtMCand)) { - return pickRandomSlotInR(); // keep item in M - } else { - return h_; // index of item in M - } - } else { - // general case - final int deleteSlot = chooseWeightedDeleteSlot(wtCand, numCand); - final int firstRSlot = h_ + m_; - if (deleteSlot == firstRSlot) { - return pickRandomSlotInR(); - } else { - return deleteSlot; - } - } - } - - private int chooseWeightedDeleteSlot(final double wtCand, final int numCand) { - assert m_ >= 1; - - final int offset = h_; - final int finalM = (offset + m_) - 1; - final int numToKeep = numCand - 1; - - double leftSubtotal = 0.0; - double rightSubtotal = -1.0 * wtCand * SamplingUtil.nextDoubleExcludeZero(); - - for (int i = offset; i <= finalM; ++i) { - leftSubtotal += numToKeep * weights_.get(i); - rightSubtotal += wtCand; - - if (leftSubtotal < rightSubtotal) { - return i; - } - } - - // this slot tells caller that we need to delete out of R - return finalM + 1; - } - - private void downsampleCandidateSet(final double wtCands, final int numCands) { - assert numCands >= 2; - assert (h_ + numCands) == (k_ + 1); - - // need this before overwriting anything - final int deleteSlot = chooseDeleteSlot(wtCands, numCands); - final int leftmostCandSlot = h_; - assert deleteSlot >= leftmostCandSlot; - assert deleteSlot <= k_; - - // overwrite weights for items from M moving into R, to make bugs more obvious - final int stopIdx = leftmostCandSlot + m_; - for (int j = leftmostCandSlot; j < stopIdx; ++j) { - weights_.set(j, -1.0); - } - - // The next two lines work even when deleteSlot == leftmostCandSlot - data_.set(deleteSlot, data_.get(leftmostCandSlot)); - data_.set(leftmostCandSlot, null); - - m_ = 0; - r_ = numCands - 1; - totalWtR_ = wtCands; - } - - /* swap values of data_, weights_, and marks between src and dst indices */ - private void swapValues(final int src, final int dst) { - final T item = data_.get(src); - data_.set(src, data_.get(dst)); - data_.set(dst, item); - - final Double wt = weights_.get(src); - weights_.set(src, weights_.get(dst)); - weights_.set(dst, wt); - - if (marks_ != null) { - final Boolean mark = marks_.get(src); - marks_.set(src, marks_.get(dst)); - marks_.set(dst, mark); - } - } - - private boolean isMarked(final int idx) { - return marks_ != null ? marks_.get(idx) : false; - } - - /** - * Returns a copy of the items (no weights) in the sketch as members of Class clazz, - * or null if empty. The returned array length may be smaller than the total capacity. - * - *

This method allocates an array of class clazz, which must either match or - * extend T. This method should be used when objects in the array are all instances of T but - * are not necessarily instances of the base class.

- * - * @param clazz A class to which the items are cast before returning - * @return A copy of the sample array - */ - @SuppressWarnings("unchecked") - private T[] getDataSamples(final Class clazz) { - assert (h_ + r_) > 0; - - // are 2 Array.asList(data_.subList()) copies better? - final T[] prunedList = (T[]) Array.newInstance(clazz, getNumSamples()); - int i = 0; - for (final T item : data_) { - if (item != null) { - prunedList[i++] = item; - } - } - return prunedList; - } - - /** - * Increases allocated sampling size by (adjusted) ResizeFactor and copies items from old - * sampling. Only happens when buffer is not full, so don't need to worry about blindly copying - * the array items. - */ - private void growDataArrays() { - currItemsAlloc_ = SamplingUtil.getAdjustedSize(k_, currItemsAlloc_ << rf_.lg()); - if (currItemsAlloc_ == k_) { - ++currItemsAlloc_; - } - - data_.ensureCapacity(currItemsAlloc_); - weights_.ensureCapacity(currItemsAlloc_); - if (marks_ != null) { - marks_.ensureCapacity(currItemsAlloc_); - } - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/VarOptItemsUnion.java b/src/main/java/org/apache/datasketches/sampling/VarOptItemsUnion.java deleted file mode 100644 index 40d573f3f..000000000 --- a/src/main/java/org/apache/datasketches/sampling/VarOptItemsUnion.java +++ /dev/null @@ -1,628 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.sampling.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.sampling.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.VAROPT_SER_VER; -import static org.apache.datasketches.sampling.PreambleUtil.extractFlags; -import static org.apache.datasketches.sampling.PreambleUtil.extractMaxK; -import static org.apache.datasketches.sampling.PreambleUtil.extractN; -import static org.apache.datasketches.sampling.PreambleUtil.extractOuterTauDenominator; -import static org.apache.datasketches.sampling.PreambleUtil.extractOuterTauNumerator; -import static org.apache.datasketches.sampling.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.sampling.PreambleUtil.extractSerVer; -import static org.apache.datasketches.sampling.VarOptItemsSketch.newInstanceFromUnionResult; - -import java.lang.foreign.MemorySegment; -import java.util.ArrayList; -import java.util.Iterator; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Provides a unioning operation over varopt sketches. This union allows the sample size k to float, - * possibly increasing or decreasing as warranted by the available data. - * - * @author Jon Malkin - * @author Kevin Lang - * @param Type of items - */ -public final class VarOptItemsUnion { - private VarOptItemsSketch gadget_; - private final int maxK_; - private long n_; // cumulative over all input sketches - - // outer tau is the largest tau of any input sketch - private double outerTauNumer; // total weight of all input R-zones where tau = outerTau - - // total cardinality of the same R-zones, or zero if no input sketch was in estimation mode - private long outerTauDenom; - - /* - IMPORTANT NOTE: the "gadget" in the union object appears to be a varopt sketch, - but in fact is NOT because it doesn't satisfy the mathematical definition - of a varopt sketch of the concatenated input streams. Therefore it could be different - from a true varopt sketch with that value of K, in which case it could easily provide - worse estimation accuracy for subset-sum queries. - - This should not surprise you; the approximation guarantees of varopt sketches - do not apply to things that merely resemble varopt sketches. - - However, even though the gadget is not a varopt sketch, the result - of the unioning process IS a varopt sketch. It is constructed by a - somewhat complicated "resolution" process which determines the largest K - that a valid varopt sketch could have given the available information, - then constructs a varopt sketch of that size and returns it. - - However, the gadget itself is not touched during the resolution process, - and additional sketches could subsequently be merged into the union, - at which point a varopt result could again be requested. - */ - - /* - Explanation of "marked items" in the union's gadget: - - The boolean value "true" in an pair indicates that the item - came from an input sketch's R zone, so it is already the result of sampling. - - Therefore it must not wind up in the H zone of the final result, because - that would imply that the item is "exact". - - However, it is okay for a marked item to hang out in the gadget's H zone for a while. - - And once the item has moved to the gadget's R zone, the mark is never checked again, - so no effort is made to ensure that its value is preserved or even makes sense. - */ - - /* - Note: if the computer could perform exact real-valued arithmetic, the union could finalize - its result by reducing k until inner_tau > outer_tau. [Due to the vagaries of floating point - arithmetic, we won't attempt to detect and specially handle the inner_tau = outer_tau special - case.] - - In fact, we won't even look at tau while while reducing k. Instead the logic will be based - on the more robust integer quantity num_marks_in_h_ in the gadget. It is conceivable that due - to round-off error we could end up with inner_tau slightly less than outer_tau, but that should - be fairly harmless since we will have achieved our goal of getting the marked items out of H. - - Also, you might be wondering why we are bothering to maintain the numerator and denominator - separately instead of just having a single variable outer_tau. This allows us (in certain - cases) to add an input's entire R-zone weight into the result sketch, as opposed to subdividing - it then adding it back up. That would be a source of numerical inaccuracy. And even - more importantly, this design choice allows us to exactly re-construct the input sketch - when there is only one of them. - */ - - /** - * Empty constructor - * - * @param maxK Maximum allowed reservoir capacity for this union - */ - private VarOptItemsUnion(final int maxK) { - maxK_ = maxK; - n_ = 0; - outerTauNumer = 0.0; - outerTauDenom = 0; - gadget_ = VarOptItemsSketch.newInstanceAsGadget(maxK); - } - - /** - * Creates an empty Union with a maximum capacity of size k. - * - * @param The type of item this union contains - * @param maxK The maximum allowed capacity of the unioned result - * @return A new VarOptItemsUnion - */ - public static VarOptItemsUnion newInstance(final int maxK) { - return new VarOptItemsUnion<>(maxK); - } - - /** - * Instantiates a Union from MemorySegment - * - * @param The type of item this sketch contains - * @param srcSeg MemorySegment object containing a serialized union - * @param serDe An instance of ArrayOfItemsSerDe - * @return A VarOptItemsUnion created from the provided MemorySegment - */ - public static VarOptItemsUnion heapify(final MemorySegment srcSeg, - final ArrayOfItemsSerDe serDe) { - Family.VAROPT_UNION.checkFamilyID(srcSeg.get(JAVA_BYTE, FAMILY_BYTE)); - - long n = 0; - double outerTauNum = 0.0; - long outerTauDenom = 0; - - final int numPreLongs = extractPreLongs(srcSeg); - final int serVer = extractSerVer(srcSeg); - final boolean isEmpty = (extractFlags(srcSeg) & EMPTY_FLAG_MASK) != 0; - final int maxK = extractMaxK(srcSeg); - if (!isEmpty) { - n = extractN(srcSeg); - outerTauNum = extractOuterTauNumerator(srcSeg); - outerTauDenom = extractOuterTauDenominator(srcSeg); - } - - if (serVer != VAROPT_SER_VER) { - throw new SketchesArgumentException( - "Possible Corruption: Ser Ver must be " + VAROPT_SER_VER + ": " + serVer); - } - - final boolean preLongsEqMin = (numPreLongs == Family.VAROPT_UNION.getMinPreLongs()); - final boolean preLongsEqMax = (numPreLongs == Family.VAROPT_UNION.getMaxPreLongs()); - - if (!preLongsEqMin && !preLongsEqMax) { - throw new SketchesArgumentException("Possible corruption: Non-empty union with only " - + Family.VAROPT_UNION.getMinPreLongs() + "preLongs"); - } - - final VarOptItemsUnion viu = new VarOptItemsUnion<>(maxK); - - if (isEmpty) { - viu.gadget_ = VarOptItemsSketch.newInstanceAsGadget(maxK); - } else { - viu.n_ = n; - viu.outerTauNumer = outerTauNum; - viu.outerTauDenom = outerTauDenom; - - final int preLongBytes = numPreLongs << 3; - final MemorySegment sketchSeg = srcSeg.asSlice(preLongBytes); - viu.gadget_ = VarOptItemsSketch.heapify(sketchSeg, serDe); - } - - return viu; - } - - /** - * Union the given sketch. - * - *

This method can be repeatedly called.

- * - * @param sketchIn The sketch to be merged - */ - public void update(final VarOptItemsSketch sketchIn) { - if (sketchIn != null) { - mergeInto(sketchIn); - } - } - - /** - * Union the given MemorySegment image of the sketch. - * - *

This method can be repeatedly called.

- * - * @param seg MemorySegment image of sketch to be merged - * @param serDe An instance of ArrayOfItemsSerDe - */ - public void update(final MemorySegment seg, final ArrayOfItemsSerDe serDe) { - if (seg != null) { - final VarOptItemsSketch vis = VarOptItemsSketch.heapify(seg, serDe); - mergeInto(vis); - } - } - - /** - * Union a reservoir sketch. The reservoir sample is treated as if all items were added with a - * weight of 1.0. - * - * @param reservoirIn The reservoir sketch to be merged - */ - public void update(final ReservoirItemsSketch reservoirIn) { - if (reservoirIn != null) { - mergeReservoirInto(reservoirIn); - } - } - - /** - * Gets the varopt sketch resulting from the union of any input sketches. - * - * @return A varopt sketch - */ - public VarOptItemsSketch getResult() { - // If no marked items in H, gadget is already valid mathematically. We can return what is - // basically just a copy of the gadget. - if (gadget_.getNumMarksInH() == 0) { - return simpleGadgetCoercer(); - } else { - // At this point, we know that marked items are present in H. So: - // 1. Result will necessarily be in estimation mode - // 2. Marked items currently in H need to be absorbed into reservoir (R) - final VarOptItemsSketch tmp = detectAndHandleSubcaseOfPseudoExact(); - if (tmp != null) { - // sub-case detected and handled, so return the result - return tmp; - } else { - // continue with main logic - return migrateMarkedItemsByDecreasingK(); - } - } - } - - /** - * Resets this sketch to the empty state, but retains the original value of max k. - */ - public void reset() { - gadget_.reset(); - n_ = 0; - outerTauNumer = 0.0; - outerTauDenom = 0; - } - - /** - * Returns a human-readable summary of the sketch, without items. - * - * @return A string version of the sketch summary - */ - @Override - public String toString() { - assert gadget_ != null; - final StringBuilder sb = new StringBuilder(); - - final String thisSimpleName = this.getClass().getSimpleName(); - - sb.append(LS) - .append("### ").append(thisSimpleName).append(" SUMMARY: ").append(LS) - .append(" Max k: ").append(maxK_).append(LS) - .append(" Gadget summary: ").append(gadget_.toString()) - .append("### END UNION SUMMARY").append(LS); - - return sb.toString(); - } - - /** - * Returns a byte array representation of this union - * - * @param serDe An instance of ArrayOfItemsSerDe - * @return a byte array representation of this union - */ - public byte[] toByteArray(final ArrayOfItemsSerDe serDe) { - assert gadget_ != null; - if (gadget_.getNumSamples() == 0) { - return toByteArray(serDe, null); - } else { - return toByteArray(serDe, gadget_.getItem(0).getClass()); - } - } - - /** - * Returns a byte array representation of this union. This method should be used when the array - * elements are subclasses of a common base class. - * - * @param serDe An instance of ArrayOfItemsSerDe - * @param clazz A class to which the items are cast before serialization - * @return a byte array representation of this union - */ - // gadgetBytes will be null only if gadget_ == null AND empty == true - public byte[] toByteArray(final ArrayOfItemsSerDe serDe, final Class clazz) { - final int preLongs, outBytes; - final boolean empty = gadget_.getNumSamples() == 0; - final byte[] gadgetBytes = (empty ? null : gadget_.toByteArray(serDe, clazz)); - - if (empty) { - preLongs = Family.VAROPT_UNION.getMinPreLongs(); - outBytes = 8; - } else { - preLongs = Family.VAROPT_UNION.getMaxPreLongs(); - outBytes = (preLongs << 3) + gadgetBytes.length; // for longs, we know the size - } - final byte[] outArr = new byte[outBytes]; - final MemorySegment seg = MemorySegment.ofArray(outArr); - - // build preLong - PreambleUtil.insertPreLongs(seg, preLongs); // Byte 0 - PreambleUtil.insertSerVer(seg, VAROPT_SER_VER); // Byte 1 - PreambleUtil.insertFamilyID(seg, Family.VAROPT_UNION.getID()); // Byte 2 - if (empty) { - PreambleUtil.insertFlags(seg, EMPTY_FLAG_MASK); - } else { - PreambleUtil.insertFlags(seg, 0); // Byte 3 - } - PreambleUtil.insertMaxK(seg, maxK_); // Bytes 4-7 - - if (!empty) { - PreambleUtil.insertN(seg, n_); // Bytes 8-15 - PreambleUtil.insertOuterTauNumerator(seg, outerTauNumer); // Bytes 16-23 - PreambleUtil.insertOuterTauDenominator(seg, outerTauDenom); // Bytes 24-31 - - final int preBytes = preLongs << 3; - MemorySegment.copy(gadgetBytes, 0, seg, JAVA_BYTE, preBytes, gadgetBytes.length); - } - - return outArr; - } - - // package-private for testing - double getOuterTau() { - if (outerTauDenom == 0) { - return 0.0; - } else { - return outerTauNumer / outerTauDenom; - } - } - - private void mergeInto(final VarOptItemsSketch sketch) { - final long sketchN = sketch.getN(); - if (sketchN == 0) { - return; - } - - n_ += sketchN; - - final VarOptItemsSamples sketchSamples = sketch.getSketchSamples(); - - // insert H region items - Iterator.WeightedSample> sketchIterator; - sketchIterator = sketchSamples.getHIterator(); - while (sketchIterator.hasNext()) { - final VarOptItemsSamples.WeightedSample ws = sketchIterator.next(); - gadget_.update(ws.getItem(), ws.getWeight(), false); - } - - // insert R region items - sketchIterator = sketchSamples.getWeightCorrRIter(); - while (sketchIterator.hasNext()) { - final VarOptItemsSamples.WeightedSample ws = sketchIterator.next(); - gadget_.update(ws.getItem(), ws.getWeight(), true); - } - - // resolve tau - if (sketch.getRRegionCount() > 0) { - final double sketchTau = sketch.getTau(); - final double outerTau = getOuterTau(); - - if (outerTauDenom == 0) { - // detect first estimation mode sketch and grab its tau - outerTauNumer = sketch.getTotalWtR(); - outerTauDenom = sketch.getRRegionCount(); - } else if (sketchTau > outerTau) { - // switch to a bigger value of outerTau - outerTauNumer = sketch.getTotalWtR(); - outerTauDenom = sketch.getRRegionCount(); - } else if (sketchTau == outerTau) { - // Ok if previous equality test isn't quite perfect. Mistakes in either direction should - // be fairly benign. - // Without conceptually changing outerTau, update number and denominator. In particular, - // add the total weight of the incoming reservoir to the running total. - outerTauNumer += sketch.getTotalWtR(); - outerTauDenom += sketch.getRRegionCount(); - } - - // do nothing if sketch's tau is smaller than outerTau - } - } - - /** - * Used to merge a reservoir sample into varopt, assuming the reservoir was built with items - * of weight 1.0. Logic is very similar to mergeInto() for a sketch with no heavy items. - * @param reservoir Reservoir sketch to merge into this union - */ - private void mergeReservoirInto(final ReservoirItemsSketch reservoir) { - final long reservoirN = reservoir.getN(); - if (reservoirN == 0) { - return; - } - - n_ += reservoirN; - - final int reservoirK = reservoir.getK(); - if (reservoir.getN() <= reservoirK) { - // exact mode, so just insert and be done - for (T item : reservoir.getRawSamplesAsList()) { - gadget_.update(item, 1.0, false); - } - } else { - // sampling mode. We'll replicate a weight-correcting iterator - final double reservoirTau = reservoir.getImplicitSampleWeight(); - - double cumWeight = 0.0; - final ArrayList samples = reservoir.getRawSamplesAsList(); - for (int i = 0; i < (reservoirK - 1); ++i) { - gadget_.update(samples.get(i), reservoirTau, true); - cumWeight += reservoirTau; - } - // correct for any numerical discrepancies with the last item - gadget_.update(samples.get(reservoirK - 1), reservoir.getN() - cumWeight, true); - - // resolve tau - final double outerTau = getOuterTau(); - - if (outerTauDenom == 0) { - // detect first estimation mode sketch and grab its tau - outerTauNumer = reservoirN; - outerTauDenom = reservoirK; - } else if (reservoirTau > outerTau) { - // switch to a bigger value of outerTau - outerTauNumer = reservoirN; - outerTauDenom = reservoirK; - } else if (reservoirTau == outerTau) { - // Ok if previous equality test isn't quite perfect. Mistakes in either direction should - // be fairly benign. - // Without conceptually changing outerTau, update number and denominator. In particular, - // add the total weight of the incoming reservoir to the running total. - outerTauNumer += reservoirN; - outerTauDenom += reservoirK; - } - // do nothing if reservoir "tau" is no smaller than outerTau - } - } - - /** - * When there are no marked items in H, teh gadget is mathematically equivalent to a valid - * varopt sketch. This method simply returns a copy (without perserving marks). - * - * @return A shallow copy of the gadget as valid varopt sketch - */ - private VarOptItemsSketch simpleGadgetCoercer() { - assert gadget_.getNumMarksInH() == 0; - return gadget_.copyAndSetN(true, n_); - } - - /** - * This coercer directly transfers marked items from the gadget's H into the result's R. - * Deciding whether that is a valid thing to do is the responsibility of the caller. Currently, - * this is only used for a subcase of pseudo-exact, but later it might be used by other - * subcases as well. - * - * @return A sketch derived from the gadget, with marked items moved to the reservoir - */ - private VarOptItemsSketch markMovingGadgetCoercer() { - final int resultK = gadget_.getHRegionCount() + gadget_.getRRegionCount(); - - int resultH = 0; - int resultR = 0; - int nextRPos = resultK; // = (resultK+1)-1, to fill R region from back to front - - final ArrayList data = new ArrayList<>(resultK + 1); - final ArrayList weights = new ArrayList<>(resultK + 1); - - // Need arrays filled to use set() and be able to fill from end forward. - // Ideally would create as arrays but trying to avoid forcing user to pass a Class - for (int i = 0; i < (resultK + 1); ++i) { - data.add(null); - weights.add(null); - } - - final VarOptItemsSamples sketchSamples = gadget_.getSketchSamples(); - // insert R region items, ignoring weights - // Currently (May 2017) this next block is unreachable; this coercer is used only in the - // pseudo-exact case in which case there are no items natively in R, only marked items in H - // that will be moved into R as part of the coercion process. - Iterator.WeightedSample> sketchIterator; - sketchIterator = sketchSamples.getRIterator(); - while (sketchIterator.hasNext()) { - final VarOptItemsSamples.WeightedSample ws = sketchIterator.next(); - data.set(nextRPos, ws.getItem()); - weights.set(nextRPos, -1.0); - ++resultR; - --nextRPos; - } - double transferredWeight = 0; - - // insert H region items - sketchIterator = sketchSamples.getHIterator(); - while (sketchIterator.hasNext()) { - final VarOptItemsSamples.WeightedSample ws = sketchIterator.next(); - if (ws.getMark()) { - data.set(nextRPos, ws.getItem()); - weights.set(nextRPos, -1.0); - transferredWeight += ws.getWeight(); - ++resultR; - --nextRPos; - } else { - data.set(resultH, ws.getItem()); - weights.set(resultH, ws.getWeight()); - ++resultH; - } - } - - assert (resultH + resultR) == resultK; - assert Math.abs(transferredWeight - outerTauNumer) < 1e-10; - - final double resultRWeight = gadget_.getTotalWtR() + transferredWeight; - final long resultN = n_; - - // explicitly set values for the gap - data.set(resultH, null); - weights.set(resultH, -1.0); - - // create sketch with the new values - return newInstanceFromUnionResult(data, weights, resultK, resultN, resultH, resultR, resultRWeight); - } - - private VarOptItemsSketch detectAndHandleSubcaseOfPseudoExact() { - // gadget is seemingly exact - final boolean condition1 = gadget_.getRRegionCount() == 0; - - // but there are marked items in H, so only _pseudo_ exact - final boolean condition2 = gadget_.getNumMarksInH() > 0; - - // if gadget is pseudo-exact and the number of marks equals outerTauDenom, then we can deduce - // from the bookkeeping logic of mergeInto() that all estimation mode input sketches must - // have had the same tau, so we can throw all of the marked items into a common reservoir. - final boolean condition3 = gadget_.getNumMarksInH() == outerTauDenom; - - if (!(condition1 && condition2 && condition3)) { - return null; - } else { - - // explicitly enforce rule that items in H should not be lighter than the sketch's tau - final boolean antiCondition4 = thereExistUnmarkedHItemsLighterThanTarget(gadget_.getTau()); - if (antiCondition4) { - return null; - } else { - // conditions 1 through 4 hold - return markMovingGadgetCoercer(); - } - } - } - - // this is a condition checked in detectAndHandleSubcaseOfPseudoExact() - private boolean thereExistUnmarkedHItemsLighterThanTarget(final double threshold) { - for (int i = 0; i < gadget_.getHRegionCount(); ++i) { - if ((gadget_.getWeight(i) < threshold) && !gadget_.getMark(i)) { - return true; - } - } - - return false; - } - - // this is basically a continuation of getResult() - private VarOptItemsSketch migrateMarkedItemsByDecreasingK() { - final VarOptItemsSketch gcopy = gadget_.copyAndSetN(false, n_); - - final int rCount = gcopy.getRRegionCount(); - final int hCount = gcopy.getHRegionCount(); - final int k = gcopy.getK(); - - assert gcopy.getNumMarksInH() > 0; // ensured by caller - // either full (of samples), or in pseudo-exact mode, or both - assert (rCount == 0) || (k == (hCount + rCount)); - - // if non-full and pseudo-exact, change k so that gcopy is full - if ((rCount == 0) && (hCount < k)) { - gcopy.forceSetK(hCount); - } - - // Now k equals the number of samples, so reducing k will increase tau. - // Also, we know that there are at least 2 samples because 0 or 1 would have been handled - // by the earlier logic in getResult() - assert gcopy.getK() >= 2; - gcopy.decreaseKBy1(); - - // gcopy is now in estimation mode, just like the final result must be (due to marked items) - assert gcopy.getRRegionCount() > 0; - assert gcopy.getTau() > 0.0; - - // keep reducing k until all marked items have been absorbed into the reservoir - while (gcopy.getNumMarksInH() > 0) { - assert gcopy.getK() >= 2; // because h_ and r_ are both at least 1 - gcopy.decreaseKBy1(); - } - - gcopy.stripMarks(); - return gcopy; - } -} diff --git a/src/main/java/org/apache/datasketches/sampling/package-info.java b/src/main/java/org/apache/datasketches/sampling/package-info.java deleted file mode 100644 index bbe446914..000000000 --- a/src/main/java/org/apache/datasketches/sampling/package-info.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of - * weighted and unweighted items from a stream. - * - *

These sketches are mergeable and can be serialized and deserialized to/from a compact - * form.

- * @see org.apache.datasketches.sampling.ReservoirItemsSketch - * @see org.apache.datasketches.sampling.ReservoirLongsSketch - * @see org.apache.datasketches.sampling.VarOptItemsSketch - */ -package org.apache.datasketches.sampling; diff --git a/src/main/java/org/apache/datasketches/tdigest/BinarySearch.java b/src/main/java/org/apache/datasketches/tdigest/BinarySearch.java deleted file mode 100644 index cdd14b89b..000000000 --- a/src/main/java/org/apache/datasketches/tdigest/BinarySearch.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tdigest; - -/** - * Algorithms with logarithmic complexity for searching in an array. - */ -public final class BinarySearch { - - /** - * No argument constructor. - */ - public BinarySearch() { } - - /** - * Returns an index to the first element in the range [first, last) such that - * element < value is false (i.e. that is greater than or equal to value), - * or last if no such element is found. - * The range [first, last) must be partitioned with respect to the expression element < value, - * i.e., all elements for which the expression is true must precede all elements - * for which the expression is false. - * A fully-sorted range meets this criterion. - * The number of comparisons performed is logarithmic in the distance between first and last. - * - * @param values array of values - * @param first index to the first element in the range - * @param last index to the element past the end of the range - * @param value to look for - * @return index to the element found or last if not found - */ - static int lowerBound(final double[] values, int first, final int last, final double value) { - int current; - int step; - int count = last - first; - while (count > 0) { - step = count / 2; - current = first + step; - if (values[current] < value) { - first = ++current; - count -= step + 1; - } else { - count = step; - } - } - return first; - } - - /** - * Returns an index to the first element in the range [first, last) such that - * value < element is true (i.e. that is strictly greater than value), - * or last if no such element is found. - * The range [first, last) must be partitioned with respect to the expression !(value < element), - * i.e., all elements for which the expression is true must precede all elements - * for which the expression is false. - * A fully-sorted range meets this criterion. - * The number of comparisons performed is logarithmic in the distance between first and last. - * - * @param values array of values - * @param first index to the first element in the range - * @param last index to the element past the end of the range - * @param value to look for - * @return index to the element found or last if not found - */ - static int upperBound(final double[] values, int first, final int last, final double value) { - int current; - int step; - int count = last - first; - while (count > 0) { - step = count / 2; - current = first + step; - if (!(value < values[current])) { - first = ++current; - count -= step + 1; - } else { - count = step; - } - } - return first; - } - -} diff --git a/src/main/java/org/apache/datasketches/tdigest/Sort.java b/src/main/java/org/apache/datasketches/tdigest/Sort.java deleted file mode 100644 index 849f36a09..000000000 --- a/src/main/java/org/apache/datasketches/tdigest/Sort.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tdigest; - -import java.util.concurrent.ThreadLocalRandom; - -/** - * Specialized sorting algorithm that can sort one array and permute another array the same way. - */ -public final class Sort { - - /** - * No argument constructor. - */ - public Sort() { } - - /** - * Stable sort two arrays. - * The first array is sorted while the second array is permuted the same way. - * - * @param keys array to be sorted - * @param values array to be permuted the same way - * @param n number of elements to sort from the beginning of the arrays - */ - public static void stableSort(final double[] keys, final long[] values, final int n) { - stableLimitedQuickSort(keys, values, 0, n, 64); - stableLimitedInsertionSort(keys, values, 0, n, 64); - } - - private static void stableLimitedQuickSort(final double[] keys, final long[] values, - int start, int end, final int limit) { - // the while loop implements tail-recursion to avoid excessive stack calls on nasty cases - while (end - start > limit) { - - final int pivotIndex = start + ThreadLocalRandom.current().nextInt(end - start); - final double pivotValue = keys[pivotIndex]; - - // move pivot to beginning of array - swap(keys, start, pivotIndex); - swap(values, start, pivotIndex); - - // use a three way partition because many duplicate values is an important case - int low = start + 1; // low points to first value not known to be equal to pivotValue - int high = end; // high points to first value > pivotValue - int i = low; // i scans the array - while (i < high) { - // invariant: values[k] == pivotValue for k in [0..low) - // invariant: values[k] < pivotValue for k in [low..i) - // invariant: values[k] > pivotValue for k in [high..end) - // in-loop: i < high - // in-loop: low < high - // in-loop: i >= low - final double vi = keys[i]; - if (vi == pivotValue && i == pivotIndex) { - if (low != i) { - swap(keys, low, i); - swap(values, low, i); - } else { - i++; - } - low++; - } else if (vi > pivotValue || (vi == pivotValue && i > pivotIndex)) { - high--; - swap(keys, i, high); - swap(values, i, high); - } else { - i++; - } - } - // assert i == high || low == high therefore, we are done with partition - // at this point, i == high, [start, low) == pivot, - // [low, high) < pivot and [high, end) > pivot - // we have to move the values equal to the pivot into the middle. - // To do this, we swap pivot values into the top end of the [low, high) range - // stopping when we run out of destinations or when we run out of values to copy - int from = start; - int to = high - 1; - for (i = 0; from < low && to >= low; i++) { - swap(keys, from, to); - swap(values, from++, to--); - } - if (from == low) { - // ran out of things to copy. This means that the last destination is the boundary - low = to + 1; - } else { - // ran out of places to copy to. This means that there are uncopied pivots and the - // boundary is at the beginning of those - low = from; - } - - // now recurse, but arrange it to handle the longer limit by tail recursion - // we have to sort the pivot values because they may have different weights - // we can't do that, however until we know how much weight is in the left and right - if (low - start < end - high) { - // left side is smaller - stableLimitedQuickSort(keys, values, start, low, limit); - // this is really a way to do - // quickSort(keys, values, high, end, limit); - start = high; - } else { - stableLimitedQuickSort(keys, values, high, end, limit); - // this is really a way to do - // quickSort(keys, values, start, low, limit); - end = low; - } - } - } - - private static void stableLimitedInsertionSort(final double[] keys, final long[] values, - final int start, final int n, final int limit) { - for (int i = start + 1; i < n; i++) { - final double k = keys[i]; - final long v = values[i]; - final int m = Math.max(i - limit, start); - // values in [start, i) are ordered - // scan backwards to find where to stick the current key - for (int j = i; j >= m; j--) { - if (j == 0 || keys[j - 1] <= k) { - if (j < i) { - System.arraycopy(keys, j, keys, j + 1, i - j); - System.arraycopy(values, j, values, j + 1, i - j); - keys[j] = k; - values[j] = v; - } - break; - } - } - } - } - - private static void swap(final double[] values, final int i, final int j) { - final double tmpValue = values[i]; - values[i] = values[j]; - values[j] = tmpValue; - } - - private static void swap(final long[] values, final int i, final int j) { - final long tmpValue = values[i]; - values[i] = values[j]; - values[j] = tmpValue; - } - - /** - * Reverse the first n elements of the given array. - * - * @param values array to be reversed - * @param n number of elements to reverse - */ - public static void reverse(final double[] values, final int n) { - for (int i = 0; i < n / 2; i++) { - swap(values, i, n - i - 1); - } - } - - /** - * Reverse the first n elements of the given array. - * - * @param values array to be reversed - * @param n number of elements to reverse - */ - public static void reverse(final long[] values, final int n) { - for (int i = 0; i < n / 2; i++) { - swap(values, i, n - i - 1); - } - } -} diff --git a/src/main/java/org/apache/datasketches/tdigest/TDigestDouble.java b/src/main/java/org/apache/datasketches/tdigest/TDigestDouble.java deleted file mode 100644 index 0f059937d..000000000 --- a/src/main/java/org/apache/datasketches/tdigest/TDigestDouble.java +++ /dev/null @@ -1,647 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tdigest; - -import static org.apache.datasketches.common.SpecialValueLayouts.JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN; -import static org.apache.datasketches.common.SpecialValueLayouts.JAVA_FLOAT_UNALIGNED_BIG_ENDIAN; -import static org.apache.datasketches.common.SpecialValueLayouts.JAVA_INT_UNALIGNED_BIG_ENDIAN; -import static org.apache.datasketches.common.SpecialValueLayouts.JAVA_SHORT_UNALIGNED_BIG_ENDIAN; -import static org.apache.datasketches.common.Util.LS; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.positional.PositionalSegment; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.quantilescommon.QuantilesAPI; -import org.apache.datasketches.quantilescommon.QuantilesUtil; - -/** - * t-Digest for estimating quantiles and ranks. - * This implementation is based on the following paper: - * Ted Dunning, Otmar Ertl. Extremely Accurate Quantiles Using t-Digests - * and the following implementation: - * https://github.com/tdunning/t-digest - * This implementation is similar to MergingDigest in the above implementation - */ -public final class TDigestDouble { - - /** the default value of K if one is not specified */ - public static final short DEFAULT_K = 200; - - private boolean reverseMerge_; - private final short k_; - private double minValue_; - private double maxValue_; - private final int centroidsCapacity_; - private int numCentroids_; - private final double[] centroidMeans_; - private final long[] centroidWeights_; - private long centroidsWeight_; - private int numBuffered_; - private final double[] bufferValues_; - - private static final int BUFFER_MULTIPLIER = 4; - - private static final byte PREAMBLE_LONGS_EMPTY_OR_SINGLE = 1; - private static final byte PREAMBLE_LONGS_MULTIPLE = 2; - private static final byte SERIAL_VERSION = 1; - - private static final int COMPAT_DOUBLE = 1; - private static final int COMPAT_FLOAT = 2; - - private enum Flags { IS_EMPTY, IS_SINGLE_VALUE, REVERSE_MERGE } - - /** - * Constructor with the default K - */ - public TDigestDouble() { - this(DEFAULT_K); - } - - /** - * Constructor - * @param k affects the size of TDigest and its estimation error - */ - public TDigestDouble(final short k) { - this(false, k, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, null, null, 0, null); - } - - /** - * Returns parameter k (compression) that was used to configure this TDigest - * @return parameter k (compression) that was used to configure this TDigest - */ - public short getK() { - return k_; - } - - /** - * Update this TDigest with the given value - * @param value to update the TDigest with - */ - public void update(final double value) { - if (Double.isNaN(value)) { return; } - if (numBuffered_ == (centroidsCapacity_ * BUFFER_MULTIPLIER)) { compress(); } - bufferValues_[numBuffered_] = value; - numBuffered_++; - minValue_ = Math.min(minValue_, value); - maxValue_ = Math.max(maxValue_, value); - } - - /** - * Merge the given TDigest into this one - * @param other TDigest to merge - */ - public void merge(final TDigestDouble other) { - if (other.isEmpty()) { return; } - final int num = numCentroids_ + numBuffered_ + other.numCentroids_ + other.numBuffered_; - final double[] values = new double[num]; - final long[] weights = new long[num]; - System.arraycopy(bufferValues_, 0, values, 0, numBuffered_); - Arrays.fill(weights, 0, numBuffered_, 1); - System.arraycopy(other.bufferValues_, 0, values, numBuffered_, other.numBuffered_); - Arrays.fill(weights, numBuffered_, numBuffered_ + other.numBuffered_, 1); - System.arraycopy(other.centroidMeans_, 0, values, numBuffered_ + other.numBuffered_, other.numCentroids_); - System.arraycopy(other.centroidWeights_, 0, weights, numBuffered_ + other.numBuffered_, other.numCentroids_); - merge(values, weights, numBuffered_ + other.getTotalWeight(), numBuffered_ + other.numBuffered_ + other.numCentroids_); - } - - /** - * Process buffered values and merge centroids if needed - */ - private void compress() { - if (numBuffered_ == 0) { return; } - final int num = numBuffered_ + numCentroids_; - final double[] values = new double[num]; - final long[] weights = new long[num]; - System.arraycopy(bufferValues_, 0, values, 0, numBuffered_); - Arrays.fill(weights, 0, numBuffered_, 1); - merge(values, weights, numBuffered_, numBuffered_); - } - - /** - * Returns true if TDigest has not seen any data - * @return true if TDigest has not seen any data - */ - public boolean isEmpty() { - return (numCentroids_ == 0) && (numBuffered_ == 0); - } - - /** - * Returns minimum value seen by TDigest - * @return minimum value seen by TDigest - */ - public double getMinValue() { - if (isEmpty()) { throw new SketchesStateException(QuantilesAPI.EMPTY_MSG); } - return minValue_; - } - - /** - * Returns maximum value seen by TDigest - * @return maximum value seen by TDigest - */ - public double getMaxValue() { - if (isEmpty()) { throw new SketchesStateException(QuantilesAPI.EMPTY_MSG); } - return maxValue_; - } - - /** - * Returns total weight - * @return total weight - */ - public long getTotalWeight() { - return centroidsWeight_ + numBuffered_; - } - - /** - * Compute approximate normalized rank of the given value. - * @param value to be ranked - * @return normalized rank (from 0 to 1 inclusive) - */ - public double getRank(final double value) { - if (isEmpty()) { throw new SketchesStateException(QuantilesAPI.EMPTY_MSG); } - if (Double.isNaN(value)) { throw new SketchesArgumentException("Operation is undefined for Nan"); } - if (value < minValue_) { return 0; } - if (value > maxValue_) { return 1; } - if ((numCentroids_ + numBuffered_) == 1) { return 0.5; } - - compress(); // side effect - - // left tail - final double firstMean = centroidMeans_[0]; - if (value < firstMean) { - if ((firstMean - minValue_) > 0) { - if (value == minValue_) { return 0.5 / centroidsWeight_; } - return (1.0 + (((value - minValue_) / (firstMean - minValue_)) * ((centroidWeights_[0] / 2.0) - 1.0))); - } - return 0; // should never happen - } - - // right tail - final double lastMean = centroidMeans_[numCentroids_ - 1]; - if (value > lastMean) { - if ((maxValue_ - lastMean) > 0) { - if (value == maxValue_) { return 1.0 - (0.5 / centroidsWeight_); } - return 1.0 - ((1.0 + (((maxValue_ - value) / (maxValue_ - lastMean)) - * ((centroidWeights_[numCentroids_ - 1] / 2.0) - 1.0))) / centroidsWeight_); - } - return 1; // should never happen - } - - int lower = BinarySearch.lowerBound(centroidMeans_, 0, numCentroids_, value); - if (lower == numCentroids_) { throw new SketchesStateException("lower == end in getRank()"); } - int upper = BinarySearch.upperBound(centroidMeans_, lower, numCentroids_, value); - if (upper == 0) { throw new SketchesStateException("upper == begin in getRank()"); } - if (value < centroidMeans_[lower]) { lower--; } - if ((upper == numCentroids_) || (centroidMeans_[upper - 1] >= value)) { upper--; } - - double weightBelow = 0; - int i = 0; - while (i != lower) { weightBelow += centroidWeights_[i++]; } - weightBelow += centroidWeights_[lower] / 2.0; - - double weightDelta = 0; - while (i != upper) { weightDelta += centroidWeights_[i++]; } - weightDelta -= centroidWeights_[lower] / 2.0; - weightDelta += centroidWeights_[upper] / 2.0; - if ((centroidMeans_[upper] - centroidMeans_[lower]) > 0) { - return (weightBelow + ((weightDelta * (value - centroidMeans_[lower])) - / (centroidMeans_[upper] - centroidMeans_[lower]))) / centroidsWeight_; - } - return (weightBelow + (weightDelta / 2.0)) / centroidsWeight_; - } - - /** - * Compute approximate quantile value corresponding to the given normalized rank - * @param rank normalized rank (from 0 to 1 inclusive) - * @return quantile value corresponding to the given rank - */ - public double getQuantile(final double rank) { - if (isEmpty()) { throw new SketchesStateException(QuantilesAPI.EMPTY_MSG); } - if (Double.isNaN(rank)) { throw new SketchesArgumentException("Operation is undefined for Nan"); } - if ((rank < 0) || (rank > 1)) { throw new SketchesArgumentException("Normalized rank must be within [0, 1]"); } - - compress(); // side effect - - if (numCentroids_ == 1) { return centroidMeans_[0]; } - - // at least 2 centroids - final double weight = rank * centroidsWeight_; - if (weight < 1) { return minValue_; } - if (weight > (centroidsWeight_ - 1.0)) { return maxValue_; } - final double firstWeight = centroidWeights_[0]; - if ((firstWeight > 1) && (weight < (firstWeight / 2.0))) { - return minValue_ + (((weight - 1.0) / ((firstWeight / 2.0) - 1.0)) * (centroidMeans_[0] - minValue_)); - } - final double lastWeight = centroidWeights_[numCentroids_ - 1]; - if ((lastWeight > 1) && ((centroidsWeight_ - weight) <= (lastWeight / 2.0))) { - return maxValue_ + (((centroidsWeight_ - weight - 1.0) / ((lastWeight / 2.0) - 1.0)) - * (maxValue_ - centroidMeans_[numCentroids_ - 1])); - } - - // interpolate between extremes - double weightSoFar = firstWeight / 2.0; - for (int i = 0; i < (numCentroids_ - 1); i++) { - final double dw = (centroidWeights_[i] + centroidWeights_[i + 1]) / 2.0; - if ((weightSoFar + dw) > weight) { - // the target weight is between centroids i and i+1 - double leftWeight = 0; - if (centroidWeights_[i] == 1) { - if ((weight - weightSoFar) < 0.5) { return centroidMeans_[i]; } - leftWeight = 0.5; - } - double rightWeight = 0; - if (centroidWeights_[i + 1] == 1) { - if (((weightSoFar + dw) - weight) <= 0.5) { return centroidMeans_[i + 1]; } - rightWeight = 0.5; - } - final double w1 = weight - weightSoFar - leftWeight; - final double w2 = (weightSoFar + dw) - weight - rightWeight; - return weightedAverage(centroidMeans_[i], w1, centroidMeans_[i + 1], w2); - } - weightSoFar += dw; - } - final double w1 = weight - centroidsWeight_ - (centroidWeights_[numCentroids_ - 1] / 2.0); - final double w2 = (centroidWeights_[numCentroids_ - 1] / 2.0) - w1; - return weightedAverage(centroidMeans_[numCentroids_ - 1], w1, maxValue_, w2); - } - - /** - * Returns an approximation to the Probability Mass Function (PMF) of the input stream - * given a set of split points. - * - * @param splitPoints an array of m unique, monotonically increasing values - * that divide the input domain into m+1 consecutive disjoint intervals (bins). - * - * @return an array of m+1 doubles each of which is an approximation - * to the fraction of the input stream values (the mass) that fall into one of those intervals. - * @throws SketchesStateException if sketch is empty. - */ - public double[] getPMF(final double[] splitPoints) { - final double[] buckets = getCDF(splitPoints); - for (int i = buckets.length; i-- > 1; ) { - buckets[i] -= buckets[i - 1]; - } - return buckets; - } - - /** - * Returns an approximation to the Cumulative Distribution Function (CDF), which is the - * cumulative analog of the PMF, of the input stream given a set of split points. - * - * @param splitPoints an array of m unique, monotonically increasing values - * that divide the input domain into m+1 consecutive disjoint intervals. - * - * @return an array of m+1 doubles, which are a consecutive approximation to the CDF - * of the input stream given the splitPoints. The value at array position j of the returned - * CDF array is the sum of the returned values in positions 0 through j of the returned PMF - * array. This can be viewed as array of ranks of the given split points plus one more value - * that is always 1. - * @throws SketchesStateException if sketch is empty. - */ - public double[] getCDF(final double[] splitPoints) { - if (isEmpty()) { throw new SketchesStateException(QuantilesAPI.EMPTY_MSG); } - QuantilesUtil.checkDoublesSplitPointsOrder(splitPoints); - final int len = splitPoints.length + 1; - final double[] ranks = new double[len]; - for (int i = 0; i < (len - 1); i++) { - ranks[i] = getRank(splitPoints[i]); - } - ranks[len - 1] = 1.0; - return ranks; - } - - /** - * Computes size needed to serialize the current state. - * @return size in bytes needed to serialize this tdigest - */ - int getSerializedSizeBytes() { - compress(); // side effect - return (getPreambleLongs() * Long.BYTES) - + (isEmpty() ? 0 : (isSingleValue() ? Double.BYTES : (2 * Double.BYTES) + ((Double.BYTES + Long.BYTES) * numCentroids_))); - } - - /** - * Serialize this TDigest to a byte array form. - * @return byte array - */ - public byte[] toByteArray() { - compress(); // side effect - final byte[] bytes = new byte[getSerializedSizeBytes()]; - final PositionalSegment posSeg = PositionalSegment.wrap(MemorySegment.ofArray(bytes)); - posSeg.setByte((byte) getPreambleLongs()); - posSeg.setByte(SERIAL_VERSION); - posSeg.setByte((byte) Family.TDIGEST.getID()); - posSeg.setShort(k_); - posSeg.setByte((byte) ( - (isEmpty() ? 1 << Flags.IS_EMPTY.ordinal() : 0) - | (isSingleValue() ? 1 << Flags.IS_SINGLE_VALUE.ordinal() : 0) - | (reverseMerge_ ? 1 << Flags.REVERSE_MERGE.ordinal() : 0) - )); - posSeg.setShort((short) 0); // unused - if (isEmpty()) { return bytes; } - if (isSingleValue()) { - posSeg.setDouble(minValue_); - return bytes; - } - posSeg.setInt(numCentroids_); - posSeg.setInt(0); // unused - posSeg.setDouble(minValue_); - posSeg.setDouble(maxValue_); - for (int i = 0; i < numCentroids_; i++) { - posSeg.setDouble(centroidMeans_[i]); - posSeg.setLong(centroidWeights_[i]); - } - return bytes; - } - - /** - * Deserialize TDigest from a given MemorySegment. - * Supports reading format of the reference implementation (auto-detected). - * @param seg instance of MemorySegment - * @return an instance of TDigest - */ - public static TDigestDouble heapify(final MemorySegment seg) { - return heapify(seg, false); - } - - /** - * Deserialize TDigest from a given MemorySegment. Supports reading compact format - * with (float, int) centroids as opposed to (double, long) to represent (mean, weight). - * Supports reading format of the reference implementation (auto-detected). - * @param seg instance of MemorySegment - * @param isFloat if true the input represents (float, int) format - * @return an instance of TDigest - */ - public static TDigestDouble heapify(final MemorySegment seg, final boolean isFloat) { - final PositionalSegment posSeg = PositionalSegment.wrap(seg); - final byte preambleLongs = posSeg.getByte(); - final byte serialVersion = posSeg.getByte(); - final byte sketchType = posSeg.getByte(); - - if (sketchType != (byte) Family.TDIGEST.getID()) { - if ((preambleLongs == 0) && (serialVersion == 0) && (sketchType == 0)) { return heapifyCompat(seg); } - throw new SketchesArgumentException("Sketch type mismatch: expected " + Family.TDIGEST.getID() + ", actual " + sketchType); - } - if (serialVersion != SERIAL_VERSION) { - throw new SketchesArgumentException("Serial version mismatch: expected " + SERIAL_VERSION + ", actual " + serialVersion); - } - final short k = posSeg.getShort(); - final byte flagsByte = posSeg.getByte(); - final boolean isEmpty = (flagsByte & (1 << Flags.IS_EMPTY.ordinal())) > 0; - final boolean isSingleValue = (flagsByte & (1 << Flags.IS_SINGLE_VALUE.ordinal())) > 0; - final byte expectedPreambleLongs = isEmpty || isSingleValue ? PREAMBLE_LONGS_EMPTY_OR_SINGLE : PREAMBLE_LONGS_MULTIPLE; - if (preambleLongs != expectedPreambleLongs) { - throw new SketchesArgumentException("Preamble longs mismatch: expected " + expectedPreambleLongs + ", actual " + preambleLongs); - } - posSeg.getShort(); // unused - if (isEmpty) { return new TDigestDouble(k); } - final boolean reverseMerge = (flagsByte & (1 << Flags.REVERSE_MERGE.ordinal())) > 0; - if (isSingleValue) { - final double value; - if (isFloat) { - value = posSeg.getFloat(); - } else { - value = posSeg.getDouble(); - } - return new TDigestDouble(reverseMerge, k, value, value, new double[] {value}, new long[] {1}, 1, null); - } - final int numCentroids = posSeg.getInt(); - final int numBuffered = posSeg.getInt(); - final double min; - final double max; - if (isFloat) { - min = posSeg.getFloat(); - max = posSeg.getFloat(); - } else { - min = posSeg.getDouble(); - max = posSeg.getDouble(); - } - final double[] means = new double[numCentroids]; - final long[] weights = new long[numCentroids]; - long totalWeight = 0; - for (int i = 0; i < numCentroids; i++) { - means[i] = isFloat ? posSeg.getFloat() : posSeg.getDouble(); - weights[i] = isFloat ? posSeg.getInt() : posSeg.getLong(); - totalWeight += weights[i]; - } - final double[] buffered = new double[numBuffered]; - for (int i = 0; i < numBuffered; i++) { - buffered[i] = isFloat ? posSeg.getFloat() : posSeg.getDouble(); - } - return new TDigestDouble(reverseMerge, k, min, max, means, weights, totalWeight, buffered); - } - - // compatibility with the format of the reference implementation - // default byte order of ByteBuffer is used there, which is big endian - private static TDigestDouble heapifyCompat(final MemorySegment seg) { - int offset = 0; - final int type = seg.get(JAVA_INT_UNALIGNED_BIG_ENDIAN, offset); offset += Integer.BYTES; - if ((type != COMPAT_DOUBLE) && (type != COMPAT_FLOAT)) { - throw new SketchesArgumentException("unexpected compatibility type " + type); - } - if (type == COMPAT_DOUBLE) { // compatibility with asBytes() - final double min = seg.get(JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN, offset); offset += Double.BYTES; - final double max = seg.get(JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN, offset); offset += Double.BYTES; - final short k = (short) seg.get(JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN, offset); offset += Double.BYTES; - final int numCentroids = seg.get(JAVA_INT_UNALIGNED_BIG_ENDIAN, offset); offset += Integer.BYTES; - final double[] means = new double[numCentroids]; - final long[] weights = new long[numCentroids]; - long totalWeight = 0; - for (int i = 0; i < numCentroids; i++) { - weights[i] = (long) seg.get(JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN, offset); offset += Double.BYTES; - means[i] = seg.get(JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN, offset); offset += Double.BYTES; - totalWeight += weights[i]; - } - return new TDigestDouble(false, k, min, max, means, weights, totalWeight, null); - } - // COMPAT_FLOAT: compatibility with asSmallBytes(), reference implementation uses doubles for min and max - final double min = seg.get(JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN, offset); offset += Double.BYTES; - final double max = seg.get(JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN, offset);offset += Double.BYTES; - final short k = (short) seg.get(JAVA_FLOAT_UNALIGNED_BIG_ENDIAN, offset); offset += Float.BYTES; - // reference implementation stores capacities of the array of centroids and the buffer as shorts - // they can be derived from k in the constructor - seg.get(JAVA_INT_UNALIGNED_BIG_ENDIAN, offset); offset += Integer.BYTES; - final int numCentroids = seg.get(JAVA_SHORT_UNALIGNED_BIG_ENDIAN, offset); offset += Short.BYTES; - final double[] means = new double[numCentroids]; - final long[] weights = new long[numCentroids]; - long totalWeight = 0; - for (int i = 0; i < numCentroids; i++) { - weights[i] = (long) seg.get(JAVA_FLOAT_UNALIGNED_BIG_ENDIAN, offset); offset += Float.BYTES; - means[i] = seg.get(JAVA_FLOAT_UNALIGNED_BIG_ENDIAN, offset); offset += Float.BYTES; - totalWeight += weights[i]; - } - return new TDigestDouble(false, k, min, max, means, weights, totalWeight, null); - } - - /** - * Human-readable summary of this TDigest as a string - * @return summary of this TDigest - */ - @Override - public String toString() { - return toString(false); - } - - /** - * Human-readable summary of this TDigest as a string - * @param printCentroids if true append the list of centroids with weights - * @return summary of this TDigest - */ - public String toString(final boolean printCentroids) { - final StringBuilder sb = new StringBuilder(); - - sb.append("MergingDigest").append(LS) - .append(" Compression: ").append(k_).append(LS) - .append(" Centroids: ").append(numCentroids_).append(LS) - .append(" Buffered: ").append(numBuffered_).append(LS) - .append(" Centroids Capacity: ").append(centroidsCapacity_).append(LS) - .append(" Buffer Capacity: ").append(centroidsCapacity_ * BUFFER_MULTIPLIER).append(LS) - .append("Centroids Weight: ").append(centroidsWeight_).append(LS) - .append(" Total Weight: ").append(getTotalWeight()).append(LS) - .append(" Reverse Merge: ").append(reverseMerge_).append(LS); - if (!isEmpty()) { - sb.append(" Min: ").append(minValue_).append(LS) - .append(" Max: ").append(maxValue_).append(LS); - } - if (printCentroids) { - if (numCentroids_ > 0) { - sb.append("Centroids:").append(LS); - for (int i = 0; i < numCentroids_; i++) { - sb.append(i).append(": ").append(centroidMeans_[i]).append(", ").append(centroidWeights_[i]).append(LS); - } - } - if (numBuffered_ > 0) { - sb.append("Buffer:").append(LS); - for (int i = 0; i < numBuffered_; i++) { - sb.append(i).append(": ").append(bufferValues_[i]).append(LS); - } - } - } - return sb.toString(); - } - - private TDigestDouble(final boolean reverseMerge, final short k, final double min, final double max, - final double[] means, final long[] weights, final long weight, final double[] buffer) { - reverseMerge_ = reverseMerge; - k_ = k; - minValue_ = min; - maxValue_ = max; - if (k < 10) { throw new SketchesArgumentException("k must be at least 10"); } - final int fudge = k < 30 ? 30 : 10; - centroidsCapacity_ = (k_ * 2) + fudge; - centroidMeans_ = new double[centroidsCapacity_]; - centroidWeights_ = new long[centroidsCapacity_]; - bufferValues_ = new double[centroidsCapacity_ * BUFFER_MULTIPLIER]; - numCentroids_ = 0; - numBuffered_ = 0; - centroidsWeight_ = weight; - if ((means != null) && (weights != null)) { - System.arraycopy(means, 0, centroidMeans_, 0, means.length); - System.arraycopy(weights, 0, centroidWeights_, 0, weights.length); - numCentroids_ = means.length; - } - if (buffer != null) { - System.arraycopy(buffer, 0, bufferValues_, 0, buffer.length); - numBuffered_ = buffer.length; - } - } - - // assumes that there is enough room in the input arrays to add centroids from this TDigest - private void merge(final double[] values, final long[] weights, final long weight, int num) { - System.arraycopy(centroidMeans_, 0, values, num, numCentroids_); - System.arraycopy(centroidWeights_, 0, weights, num, numCentroids_); - num += numCentroids_; - centroidsWeight_ += weight; - numCentroids_ = 0; - Sort.stableSort(values, weights, num); - if (reverseMerge_) { // this might be avoidable if stableSort could be implemented with a boolean parameter to invert the logic - Sort.reverse(values, num); - Sort.reverse(weights, num); - } - centroidMeans_[0] = values[0]; - centroidWeights_[0] = weights[0]; - numCentroids_++; - int current = 1; - double weightSoFar = 0; - while (current != num) { - final double proposedWeight = centroidWeights_[numCentroids_ - 1] + weights[current]; - boolean addThis = false; - if ((current != 1) && (current != (num - 1))) { - final double q0 = weightSoFar / centroidsWeight_; - final double q2 = (weightSoFar + proposedWeight) / centroidsWeight_; - final double normalizer = ScaleFunction.normalizer(k_ * 2, centroidsWeight_); - addThis = proposedWeight <= (centroidsWeight_ * Math.min(ScaleFunction.max(q0, normalizer), ScaleFunction.max(q2, normalizer))); - } - if (addThis) { // merge into existing centroid - centroidWeights_[numCentroids_ - 1] += weights[current]; - centroidMeans_[numCentroids_ - 1] += ((values[current] - centroidMeans_[numCentroids_ - 1]) - * weights[current]) / centroidWeights_[numCentroids_ - 1]; - } else { // copy to a new centroid - weightSoFar += centroidWeights_[numCentroids_ - 1]; - centroidMeans_[numCentroids_] = values[current]; - centroidWeights_[numCentroids_] = weights[current]; - numCentroids_++; - } - current++; - } - if (reverseMerge_) { - Sort.reverse(centroidMeans_, numCentroids_); - Sort.reverse(centroidWeights_, numCentroids_); - } - numBuffered_ = 0; - reverseMerge_ = !reverseMerge_; - minValue_ = Math.min(minValue_, centroidMeans_[0]); - maxValue_ = Math.max(maxValue_, centroidMeans_[numCentroids_ - 1]); - } - - private boolean isSingleValue() { - return getTotalWeight() == 1; - } - - private int getPreambleLongs() { - return isEmpty() || isSingleValue() ? PREAMBLE_LONGS_EMPTY_OR_SINGLE : PREAMBLE_LONGS_MULTIPLE; - } - - /* - * Generates cluster sizes proportional to q*(1-q). - * The use of a normalizing function results in a strictly bounded number of clusters no matter how many samples. - * Corresponds to K_2 in the reference implementation - */ - private static final class ScaleFunction { - static double max(final double q, final double normalizer) { - return (q * (1 - q)) / normalizer; - } - - static double normalizer(final double compression, final double n) { - return compression / z(compression, n); - } - - static double z(final double compression, final double n) { - return (4 * Math.log(n / compression)) + 24; - } - } - - private static double weightedAverage(final double x1, final double w1, final double x2, final double w2) { - return ((x1 * w1) + (x2 * w2)) / (w1 + w2); - } -} diff --git a/src/main/java/org/apache/datasketches/tdigest/package-info.java b/src/main/java/org/apache/datasketches/tdigest/package-info.java deleted file mode 100644 index e0fa8e583..000000000 --- a/src/main/java/org/apache/datasketches/tdigest/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * t-Digest for estimating quantiles and ranks. - */ -package org.apache.datasketches.tdigest; diff --git a/src/main/java/org/apache/datasketches/theta/BitPacking.java b/src/main/java/org/apache/datasketches/theta/BitPacking.java deleted file mode 100644 index fb8aa0619..000000000 --- a/src/main/java/org/apache/datasketches/theta/BitPacking.java +++ /dev/null @@ -1,6294 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Used as part of Theta compression. - */ -final class BitPacking { - - private BitPacking() { } - - /** - * The bit packing operation - * @param value the value to pack - * @param bits number of bits to pack - * @param buffer the output byte array buffer - * @param bufOffset the byte offset in the buffer - * @param bitOffset the bit offset - */ - static void packBits(final long value, int bits, final byte[] buffer, int bufOffset, final int bitOffset) { - if (bitOffset > 0) { - final int chunkBits = 8 - bitOffset; - final int mask = (1 << chunkBits) - 1; - if (bits < chunkBits) { - buffer[bufOffset] |= (value << (chunkBits - bits)) & mask; - return; - } - buffer[bufOffset++] |= (value >>> (bits - chunkBits)) & mask; - bits -= chunkBits; - } - while (bits >= 8) { - buffer[bufOffset++] = (byte)(value >>> (bits - 8)); - bits -= 8; - } - if (bits > 0) { - buffer[bufOffset] = (byte)(value << (8 - bits)); - } - } - - /** - * The unpacking operation - * @param value the output array - * @param index index of the value array - * @param bits the number of bits to unpack - * @param buffer the input packed buffer - * @param bufOffset the buffer offset - * @param bitOffset the bit offset - */ - static void unpackBits(final long[] value, final int index, int bits, final byte[] buffer, - int bufOffset,final int bitOffset) { - final int availBits = 8 - bitOffset; - final int chunkBits = availBits <= bits ? availBits : bits; - final int mask = (1 << chunkBits) - 1; - value[index] = (buffer[bufOffset] >>> (availBits - chunkBits)) & mask; - bufOffset += availBits == chunkBits ? 1 : 0; - bits -= chunkBits; - while (bits >= 8) { - value[index] <<= 8; - value[index] |= (Byte.toUnsignedLong(buffer[bufOffset++])); - bits -= 8; - } - if (bits > 0) { - value[index] <<= bits; - value[index] |= Byte.toUnsignedLong(buffer[bufOffset]) >>> (8 - bits); - } - } - - // pack given number of bits from a block of 8 64-bit values into bytes - // we don't need 0 and 64 bits - // we assume that higher bits (which we are not packing) are zeros - // this assumption allows to avoid masking operations - - static void packBitsBlock8(final long[] values, final int i, final byte[] buf, final int off, final int bits) { - switch (bits) { - case 1: packBits1(values, i, buf, off); break; - case 2: packBits2(values, i, buf, off); break; - case 3: packBits3(values, i, buf, off); break; - case 4: packBits4(values, i, buf, off); break; - case 5: packBits5(values, i, buf, off); break; - case 6: packBits6(values, i, buf, off); break; - case 7: packBits7(values, i, buf, off); break; - case 8: packBits8(values, i, buf, off); break; - case 9: packBits9(values, i, buf, off); break; - case 10: packBits10(values, i, buf, off); break; - case 11: packBits11(values, i, buf, off); break; - case 12: packBits12(values, i, buf, off); break; - case 13: packBits13(values, i, buf, off); break; - case 14: packBits14(values, i, buf, off); break; - case 15: packBits15(values, i, buf, off); break; - case 16: packBits16(values, i, buf, off); break; - case 17: packBits17(values, i, buf, off); break; - case 18: packBits18(values, i, buf, off); break; - case 19: packBits19(values, i, buf, off); break; - case 20: packBits20(values, i, buf, off); break; - case 21: packBits21(values, i, buf, off); break; - case 22: packBits22(values, i, buf, off); break; - case 23: packBits23(values, i, buf, off); break; - case 24: packBits24(values, i, buf, off); break; - case 25: packBits25(values, i, buf, off); break; - case 26: packBits26(values, i, buf, off); break; - case 27: packBits27(values, i, buf, off); break; - case 28: packBits28(values, i, buf, off); break; - case 29: packBits29(values, i, buf, off); break; - case 30: packBits30(values, i, buf, off); break; - case 31: packBits31(values, i, buf, off); break; - case 32: packBits32(values, i, buf, off); break; - case 33: packBits33(values, i, buf, off); break; - case 34: packBits34(values, i, buf, off); break; - case 35: packBits35(values, i, buf, off); break; - case 36: packBits36(values, i, buf, off); break; - case 37: packBits37(values, i, buf, off); break; - case 38: packBits38(values, i, buf, off); break; - case 39: packBits39(values, i, buf, off); break; - case 40: packBits40(values, i, buf, off); break; - case 41: packBits41(values, i, buf, off); break; - case 42: packBits42(values, i, buf, off); break; - case 43: packBits43(values, i, buf, off); break; - case 44: packBits44(values, i, buf, off); break; - case 45: packBits45(values, i, buf, off); break; - case 46: packBits46(values, i, buf, off); break; - case 47: packBits47(values, i, buf, off); break; - case 48: packBits48(values, i, buf, off); break; - case 49: packBits49(values, i, buf, off); break; - case 50: packBits50(values, i, buf, off); break; - case 51: packBits51(values, i, buf, off); break; - case 52: packBits52(values, i, buf, off); break; - case 53: packBits53(values, i, buf, off); break; - case 54: packBits54(values, i, buf, off); break; - case 55: packBits55(values, i, buf, off); break; - case 56: packBits56(values, i, buf, off); break; - case 57: packBits57(values, i, buf, off); break; - case 58: packBits58(values, i, buf, off); break; - case 59: packBits59(values, i, buf, off); break; - case 60: packBits60(values, i, buf, off); break; - case 61: packBits61(values, i, buf, off); break; - case 62: packBits62(values, i, buf, off); break; - case 63: packBits63(values, i, buf, off); break; - default: throw new SketchesArgumentException("wrong number of bits in packBitsBlock8: " + bits); - } - } - - static void unpackBitsBlock8(final long[] values, final int i, final byte[] buf, final int off, final int bits) { - switch (bits) { - case 1: unpackBits1(values, i, buf, off); break; - case 2: unpackBits2(values, i, buf, off); break; - case 3: unpackBits3(values, i, buf, off); break; - case 4: unpackBits4(values, i, buf, off); break; - case 5: unpackBits5(values, i, buf, off); break; - case 6: unpackBits6(values, i, buf, off); break; - case 7: unpackBits7(values, i, buf, off); break; - case 8: unpackBits8(values, i, buf, off); break; - case 9: unpackBits9(values, i, buf, off); break; - case 10: unpackBits10(values, i, buf, off); break; - case 11: unpackBits11(values, i, buf, off); break; - case 12: unpackBits12(values, i, buf, off); break; - case 13: unpackBits13(values, i, buf, off); break; - case 14: unpackBits14(values, i, buf, off); break; - case 15: unpackBits15(values, i, buf, off); break; - case 16: unpackBits16(values, i, buf, off); break; - case 17: unpackBits17(values, i, buf, off); break; - case 18: unpackBits18(values, i, buf, off); break; - case 19: unpackBits19(values, i, buf, off); break; - case 20: unpackBits20(values, i, buf, off); break; - case 21: unpackBits21(values, i, buf, off); break; - case 22: unpackBits22(values, i, buf, off); break; - case 23: unpackBits23(values, i, buf, off); break; - case 24: unpackBits24(values, i, buf, off); break; - case 25: unpackBits25(values, i, buf, off); break; - case 26: unpackBits26(values, i, buf, off); break; - case 27: unpackBits27(values, i, buf, off); break; - case 28: unpackBits28(values, i, buf, off); break; - case 29: unpackBits29(values, i, buf, off); break; - case 30: unpackBits30(values, i, buf, off); break; - case 31: unpackBits31(values, i, buf, off); break; - case 32: unpackBits32(values, i, buf, off); break; - case 33: unpackBits33(values, i, buf, off); break; - case 34: unpackBits34(values, i, buf, off); break; - case 35: unpackBits35(values, i, buf, off); break; - case 36: unpackBits36(values, i, buf, off); break; - case 37: unpackBits37(values, i, buf, off); break; - case 38: unpackBits38(values, i, buf, off); break; - case 39: unpackBits39(values, i, buf, off); break; - case 40: unpackBits40(values, i, buf, off); break; - case 41: unpackBits41(values, i, buf, off); break; - case 42: unpackBits42(values, i, buf, off); break; - case 43: unpackBits43(values, i, buf, off); break; - case 44: unpackBits44(values, i, buf, off); break; - case 45: unpackBits45(values, i, buf, off); break; - case 46: unpackBits46(values, i, buf, off); break; - case 47: unpackBits47(values, i, buf, off); break; - case 48: unpackBits48(values, i, buf, off); break; - case 49: unpackBits49(values, i, buf, off); break; - case 50: unpackBits50(values, i, buf, off); break; - case 51: unpackBits51(values, i, buf, off); break; - case 52: unpackBits52(values, i, buf, off); break; - case 53: unpackBits53(values, i, buf, off); break; - case 54: unpackBits54(values, i, buf, off); break; - case 55: unpackBits55(values, i, buf, off); break; - case 56: unpackBits56(values, i, buf, off); break; - case 57: unpackBits57(values, i, buf, off); break; - case 58: unpackBits58(values, i, buf, off); break; - case 59: unpackBits59(values, i, buf, off); break; - case 60: unpackBits60(values, i, buf, off); break; - case 61: unpackBits61(values, i, buf, off); break; - case 62: unpackBits62(values, i, buf, off); break; - case 63: unpackBits63(values, i, buf, off); break; - default: throw new SketchesArgumentException("wrong number of bits unpackBitsBlock8: " + bits); - } - } - - static void packBits1(final long[] values, final int i, final byte[] buf, final int off) { - buf[off] = (byte) (values[i + 0] << 7); - buf[off] |= values[i + 1] << 6; - buf[off] |= values[i + 2] << 5; - buf[off] |= values[i + 3] << 4; - buf[off] |= values[i + 4] << 3; - buf[off] |= values[i + 5] << 2; - buf[off] |= values[i + 6] << 1; - buf[off] |= values[i + 7]; - } - - static void packBits2(final long[] values, final int i, final byte[] buf, int off) { - buf[off] = (byte) (values[i + 0] << 6); - buf[off] |= values[i + 1] << 4; - buf[off] |= values[i + 2] << 2; - buf[off++] |= values[i + 3]; - - buf[off] = (byte) (values[i + 4] << 6); - buf[off] |= values[i + 5] << 4; - buf[off] |= values[i + 6] << 2; - buf[off] |= values[i + 7]; - } - - static void packBits3(final long[] values, final int i, final byte[] buf, int off) { - buf[off] = (byte) (values[i + 0] << 5); - buf[off] |= values[i + 1] << 2; - buf[off++] |= values[i + 2] >>> 1; - - buf[off] = (byte) (values[i + 2] << 7); - buf[off] |= values[i + 3] << 4; - buf[off] |= values[i + 4] << 1; - buf[off++] |= values[i + 5] >>> 2; - - buf[off] = (byte) (values[i + 5] << 6); - buf[off] |= values[i + 6] << 3; - buf[off] |= values[i + 7]; - } - - static void packBits4(final long[] values, final int i, final byte[] buf, int off) { - buf[off] = (byte) (values[i + 0] << 4); - buf[off++] |= values[i + 1]; - - buf[off] = (byte) (values[i + 2] << 4); - buf[off++] |= values[i + 3]; - - buf[off] = (byte) (values[i + 4] << 4); - buf[off++] |= values[i + 5]; - - buf[off] = (byte) (values[i + 6] << 4); - buf[off] |= values[i + 7]; - } - - static void packBits5(final long[] values, final int i, final byte[] buf, int off) { - buf[off] = (byte) (values[i + 0] << 3); - buf[off++] |= values[i + 1] >>> 2; - - buf[off] = (byte) (values[i + 1] << 6); - buf[off] |= values[i + 2] << 1; - buf[off++] |= values[i + 3] >>> 4; - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 1; - - buf[off] = (byte) (values[i + 4] << 7); - buf[off] |= values[i + 5] << 2; - buf[off++] |= values[i + 6] >>> 3; - - buf[off] = (byte) (values[i + 6] << 5); - buf[off] |= values[i + 7]; - } - - static void packBits6(final long[] values, final int i, final byte[] buf, int off) { - buf[off] = (byte) (values[i + 0] << 2); - buf[off++] |= values[i + 1] >>> 4; - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 2; - - buf[off] = (byte) (values[i + 2] << 6); - buf[off++] |= values[i + 3]; - - buf[off] = (byte) (values[i + 4] << 2); - buf[off++] |= values[i + 5] >>> 4; - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 2; - - buf[off] = (byte) (values[i + 6] << 6); - buf[off] |= values[i + 7]; - } - - static void packBits7(final long[] values, final int i, final byte[] buf, int off) { - buf[off] = (byte) (values[i + 0] << 1); - buf[off++] |= values[i + 1] >>> 6; - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 5; - - buf[off] = (byte) (values[i + 2] << 3); - buf[off++] |= values[i + 3] >>> 4; - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 3; - - buf[off] = (byte) (values[i + 4] << 5); - buf[off++] |= values[i + 5] >>> 2; - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 1; - - buf[off] = (byte) (values[i + 6] << 7); - buf[off] |= values[i + 7]; - } - - static void packBits8(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0]); - buf[off++] = (byte) (values[i + 1]); - buf[off++] = (byte) (values[i + 2]); - buf[off++] = (byte) (values[i + 3]); - buf[off++] = (byte) (values[i + 4]); - buf[off++] = (byte) (values[i + 5]); - buf[off++] = (byte) (values[i + 6]); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits9(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 1); - - buf[off] = (byte) (values[i + 0] << 7); - buf[off++] |= values[i + 1] >>> 2; - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 3; - - buf[off] = (byte) (values[i + 2] << 5); - buf[off++] |= values[i + 3] >>> 4; - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 5; - - buf[off] = (byte) (values[i + 4] << 3); - buf[off++] |= values[i + 5] >>> 6; - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 7; - - buf[off] = (byte) (values[i + 6] << 1); - buf[off++] |= values[i + 7] >>> 8; - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits10(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 2); - - buf[off] = (byte) (values[i + 0] << 6); - buf[off++] |= values[i + 1] >>> 4; - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 6; - - buf[off] = (byte) (values[i + 2] << 2); - buf[off++] |= values[i + 3] >>> 8; - - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 2); - - buf[off] = (byte) (values[i + 4] << 6); - buf[off++] |= values[i + 5] >>> 4; - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 6; - - buf[off] = (byte) (values[i + 6] << 2); - buf[off++] |= values[i + 7] >>> 8; - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits11(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 3); - - buf[off] = (byte) (values[i + 0] << 5); - buf[off++] |= values[i + 1] >>> 6; - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 9; - - buf[off++] = (byte) (values[i + 2] >>> 1); - - buf[off] = (byte) (values[i + 2] << 7); - buf[off++] |= values[i + 3] >>> 4; - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 7; - - buf[off] = (byte) (values[i + 4] << 1); - buf[off++] |= values[i + 5] >>> 10; - - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 5; - - buf[off] = (byte) (values[i + 6] << 3); - buf[off++] |= values[i + 7] >>> 8; - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits12(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 4); - - buf[off] = (byte) (values[i + 0] << 4); - buf[off++] |= values[i + 1] >>> 8; - - buf[off++] = (byte) (values[i + 1]); - - buf[off++] = (byte) (values[i + 2] >>> 4); - - buf[off] = (byte) (values[i + 2] << 4); - buf[off++] |= values[i + 3] >>> 8; - - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 4); - - buf[off] = (byte) (values[i + 4] << 4); - buf[off++] |= values[i + 5] >>> 8; - - buf[off++] = (byte) (values[i + 5]); - - buf[off++] = (byte) (values[i + 6] >>> 4); - - buf[off] = (byte) (values[i + 6] << 4); - buf[off++] |= values[i + 7] >>> 8; - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits13(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 5); - - buf[off] = (byte) (values[i + 0] << 3); - buf[off++] |= values[i + 1] >>> 10; - - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 7; - - buf[off] = (byte) (values[i + 2] << 1); - buf[off++] |= values[i + 3] >>> 12; - - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 9; - - buf[off++] = (byte) (values[i + 4] >>> 1); - - buf[off] = (byte) (values[i + 4] << 7); - buf[off++] |= values[i + 5] >>> 6; - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 11; - - buf[off++] = (byte) (values[i + 6] >>> 3); - - buf[off] = (byte) (values[i + 6] << 5); - buf[off++] |= values[i + 7] >>> 8; - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits14(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 6); - - buf[off] = (byte) (values[i + 0] << 2); - buf[off++] |= values[i + 1] >>> 12; - - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 10; - - buf[off++] = (byte) (values[i + 2] >>> 2); - - buf[off] = (byte) (values[i + 2] << 6); - buf[off++] |= values[i + 3] >>> 8; - - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 6); - - buf[off] = (byte) (values[i + 4] << 2); - buf[off++] |= values[i + 5] >>> 12; - - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 10; - - buf[off++] = (byte) (values[i + 6] >>> 2); - - buf[off] = (byte) (values[i + 6] << 6); - buf[off++] |= values[i + 7] >>> 8; - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits15(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 7); - - buf[off] = (byte) (values[i + 0] << 1); - buf[off++] |= values[i + 1] >>> 14; - - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 13; - - buf[off++] = (byte) (values[i + 2] >>> 5); - - buf[off] = (byte) (values[i + 2] << 3); - buf[off++] |= values[i + 3] >>> 12; - - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 11; - - buf[off++] = (byte) (values[i + 4] >>> 3); - - buf[off] = (byte) (values[i + 4] << 5); - buf[off++] |= values[i + 5] >>> 10; - - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 9; - - buf[off++] = (byte) (values[i + 6] >>> 1); - - buf[off] = (byte) (values[i + 6] << 7); - buf[off++] |= values[i + 7] >>> 8; - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits16(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 8); - buf[off++] = (byte) (values[i + 0]); - - buf[off++] = (byte) (values[i + 1] >>> 8); - buf[off++] = (byte) (values[i + 1]); - - buf[off++] = (byte) (values[i + 2] >>> 8); - buf[off++] = (byte) (values[i + 2]); - - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 8); - buf[off++] = (byte) (values[i + 4]); - - buf[off++] = (byte) (values[i + 5] >>> 8); - buf[off++] = (byte) (values[i + 5]); - - buf[off++] = (byte) (values[i + 6] >>> 8); - buf[off++] = (byte) (values[i + 6]); - - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits17(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 9); - - buf[off++] = (byte) (values[i + 0] >>> 1); - - buf[off] = (byte) (values[i + 0] << 7); - buf[off++] |= values[i + 1] >>> 10; - - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 11; - - buf[off++] = (byte) (values[i + 2] >>> 3); - - buf[off] = (byte) (values[i + 2] << 5); - buf[off++] |= values[i + 3] >>> 12; - - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 13; - - buf[off++] = (byte) (values[i + 4] >>> 5); - - buf[off] = (byte) (values[i + 4] << 3); - buf[off++] |= values[i + 5] >>> 14; - - buf[off++] = (byte) (values[i + 5] >>> 6); - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 15; - - buf[off++] = (byte) (values[i + 6] >>> 7); - - buf[off] = (byte) (values[i + 6] << 1); - buf[off++] |= values[i + 7] >>> 16; - - buf[off++] = (byte) (values[i + 7] >>> 8); - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits18(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 10); - - buf[off++] = (byte) (values[i + 0] >>> 2); - - buf[off] = (byte) (values[i + 0] << 6); - buf[off++] |= values[i + 1] >>> 12; - - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 14; - - buf[off++] = (byte) (values[i + 2] >>> 6); - - buf[off] = (byte) (values[i + 2] << 2); - buf[off++] |= values[i + 3] >>> 16; - - buf[off++] = (byte) (values[i + 3] >>> 8); - - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 10); - - buf[off++] = (byte) (values[i + 4] >>> 2); - - buf[off] = (byte) (values[i + 4] << 6); - buf[off++] |= values[i + 5] >>> 12; - - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 14; - - buf[off++] = (byte) (values[i + 6] >>> 6); - - buf[off] = (byte) (values[i + 6] << 2); - buf[off++] |= values[i + 7] >>> 16; - - buf[off++] = (byte) (values[i + 7] >>> 8); - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits19(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 11); - - buf[off++] = (byte) (values[i + 0] >>> 3); - - buf[off] = (byte) (values[i + 0] << 5); - buf[off++] |= values[i + 1] >>> 14; - - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 17; - - buf[off++] = (byte) (values[i + 2] >>> 9); - - buf[off++] = (byte) (values[i + 2] >>> 1); - - buf[off] = (byte) (values[i + 2] << 7); - buf[off++] |= values[i + 3] >>> 12; - - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 15; - - buf[off++] |= values[i + 4] >>> 7; - - buf[off] = (byte) (values[i + 4] << 1); - buf[off++] |= values[i + 5] >>> 18; - - buf[off++] = (byte) (values[i + 5] >>> 10); - - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 13; - - buf[off++] = (byte) (values[i + 6] >>> 5); - - buf[off] = (byte) (values[i + 6] << 3); - buf[off++] |= values[i + 7] >>> 16; - - buf[off++] = (byte) (values[i + 7] >>> 8); - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits20(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 12); - - buf[off++] = (byte) (values[i + 0] >>> 4); - - buf[off] = (byte) (values[i + 0] << 4); - buf[off++] |= values[i + 1] >>> 16; - - buf[off++] = (byte) (values[i + 1] >>> 8); - - buf[off++] = (byte) (values[i + 1]); - - buf[off++] = (byte) (values[i + 2] >>> 12); - - buf[off++] = (byte) (values[i + 2] >>> 4); - - buf[off] = (byte) (values[i + 2] << 4); - buf[off++] |= values[i + 3] >>> 16; - - buf[off++] = (byte) (values[i + 3] >>> 8); - - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 12); - - buf[off++] = (byte) (values[i + 4] >>> 4); - - buf[off] = (byte) (values[i + 4] << 4); - buf[off++] |= values[i + 5] >>> 16; - - buf[off++] = (byte) (values[i + 5] >>> 8); - - buf[off++] = (byte) (values[i + 5]); - - buf[off++] = (byte) (values[i + 6] >>> 12); - - buf[off++] = (byte) (values[i + 6] >>> 4); - - buf[off] = (byte) (values[i + 6] << 4); - buf[off++] |= values[i + 7] >>> 16; - - buf[off++] = (byte) (values[i + 7] >>> 8); - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits21(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 13); - - buf[off++] = (byte) (values[i + 0] >>> 5); - - buf[off] = (byte) (values[i + 0] << 3); - buf[off++] |= values[i + 1] >>> 18; - - buf[off++] = (byte) (values[i + 1] >>> 10); - - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 15; - - buf[off++] = (byte) (values[i + 2] >>> 7); - - buf[off] = (byte) (values[i + 2] << 1); - buf[off++] |= values[i + 3] >>> 20; - - buf[off++] = (byte) (values[i + 3] >>> 12); - - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 17; - - buf[off++] = (byte) (values[i + 4] >>> 9); - - buf[off++] = (byte) (values[i + 4] >>> 1); - - buf[off] = (byte) (values[i + 4] << 7); - buf[off++] |= values[i + 5] >>> 14; - - buf[off++] = (byte) (values[i + 5] >>> 6); - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 19; - - buf[off++] = (byte) (values[i + 6] >>> 11); - - buf[off++] = (byte) (values[i + 6] >>> 3); - - buf[off] = (byte) (values[i + 6] << 5); - buf[off++] |= values[i + 7] >>> 16; - - buf[off++] = (byte) (values[i + 7] >>> 8); - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits22(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 14); - - buf[off++] = (byte) (values[i + 0] >>> 6); - - buf[off] = (byte) (values[i + 0] << 2); - buf[off++] |= values[i + 1] >>> 20; - - buf[off++] = (byte) (values[i + 1] >>> 12); - - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 18; - - buf[off++] = (byte) (values[i + 2] >>> 10); - - buf[off++] = (byte) (values[i + 2] >>> 2); - - buf[off] = (byte) (values[i + 2] << 6); - buf[off++] |= values[i + 3] >>> 16; - - buf[off++] = (byte) (values[i + 3] >>> 8); - - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 14); - - buf[off++] = (byte) (values[i + 4] >>> 6); - - buf[off] = (byte) (values[i + 4] << 2); - buf[off++] |= values[i + 5] >>> 20; - - buf[off++] = (byte) (values[i + 5] >>> 12); - - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 18; - - buf[off++] = (byte) (values[i + 6] >>> 10); - - buf[off++] = (byte) (values[i + 6] >>> 2); - - buf[off] = (byte) (values[i + 6] << 6); - buf[off++] |= values[i + 7] >>> 16; - - buf[off++] = (byte) (values[i + 7] >>> 8); - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits23(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 15); - - buf[off++] = (byte) (values[i + 0] >>> 7); - - buf[off] = (byte) (values[i + 0] << 1); - buf[off++] |= values[i + 1] >>> 22; - - buf[off++] = (byte) (values[i + 1] >>> 14); - - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 21; - - buf[off++] = (byte) (values[i + 2] >>> 13); - - buf[off++] = (byte) (values[i + 2] >>> 5); - - buf[off] = (byte) (values[i + 2] << 3); - buf[off++] |= values[i + 3] >>> 20; - - buf[off++] = (byte) (values[i + 3] >>> 12); - - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 19; - - buf[off++] = (byte) (values[i + 4] >>> 11); - - buf[off++] = (byte) (values[i + 4] >>> 3); - - buf[off] = (byte) (values[i + 4] << 5); - buf[off++] |= values[i + 5] >>> 18; - - buf[off++] = (byte) (values[i + 5] >>> 10); - - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 17; - - buf[off++] = (byte) (values[i + 6] >>> 9); - - buf[off++] = (byte) (values[i + 6] >>> 1); - - buf[off] = (byte) (values[i + 6] << 7); - buf[off++] |= values[i + 7] >>> 16; - - buf[off++] = (byte) (values[i + 7] >>> 8); - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits24(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 16); - buf[off++] = (byte) (values[i + 0] >>> 8); - buf[off++] = (byte) (values[i + 0]); - - buf[off++] = (byte) (values[i + 1] >>> 16); - buf[off++] = (byte) (values[i + 1] >>> 8); - buf[off++] = (byte) (values[i + 1]); - - buf[off++] = (byte) (values[i + 2] >>> 16); - buf[off++] = (byte) (values[i + 2] >>> 8); - buf[off++] = (byte) (values[i + 2]); - - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 16); - buf[off++] = (byte) (values[i + 4] >>> 8); - buf[off++] = (byte) (values[i + 4]); - - buf[off++] = (byte) (values[i + 5] >>> 16); - buf[off++] = (byte) (values[i + 5] >>> 8); - buf[off++] = (byte) (values[i + 5]); - - buf[off++] = (byte) (values[i + 6] >>> 16); - buf[off++] = (byte) (values[i + 6] >>> 8); - buf[off++] = (byte) (values[i + 6]); - - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits25(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 17); - - buf[off++] = (byte) (values[i + 0] >>> 9); - - buf[off++] = (byte) (values[i + 0] >>> 1); - - buf[off] = (byte) (values[i + 0] << 7); - buf[off++] |= values[i + 1] >>> 18; - - buf[off++] = (byte) (values[i + 1] >>> 10); - - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 19; - - buf[off++] = (byte) (values[i + 2] >>> 11); - - buf[off++] = (byte) (values[i + 2] >>> 3); - - buf[off] = (byte) (values[i + 2] << 5); - buf[off++] |= values[i + 3] >>> 20; - - buf[off++] = (byte) (values[i + 3] >>> 12); - - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 21; - - buf[off++] = (byte) (values[i + 4] >>> 13); - - buf[off++] = (byte) (values[i + 4] >>> 5); - - buf[off] = (byte) (values[i + 4] << 3); - buf[off++] |= values[i + 5] >>> 22; - - buf[off++] = (byte) (values[i + 5] >>> 14); - - buf[off++] = (byte) (values[i + 5] >>> 6); - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 23; - - buf[off++] = (byte) (values[i + 6] >>> 15); - - buf[off++] = (byte) (values[i + 6] >>> 7); - - buf[off] = (byte) (values[i + 6] << 1); - buf[off++] |= values[i + 7] >>> 24; - - buf[off++] = (byte) (values[i + 7] >>> 16); - - buf[off++] = (byte) (values[i + 7] >>> 8); - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits26(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 18); - - buf[off++] = (byte) (values[i + 0] >>> 10); - - buf[off++] = (byte) (values[i + 0] >>> 2); - - buf[off] = (byte) (values[i + 0] << 6); - buf[off++] |= values[i + 1] >>> 20; - - buf[off++] = (byte) (values[i + 1] >>> 12); - - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 22; - - buf[off++] = (byte) (values[i + 2] >>> 14); - - buf[off++] = (byte) (values[i + 2] >>> 6); - - buf[off] = (byte) (values[i + 2] << 2); - buf[off++] |= values[i + 3] >>> 24; - - buf[off++] = (byte) (values[i + 3] >>> 16); - - buf[off++] = (byte) (values[i + 3] >>> 8); - - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 18); - - buf[off++] = (byte) (values[i + 4] >>> 10); - - buf[off++] = (byte) (values[i + 4] >>> 2); - - buf[off] = (byte) (values[i + 4] << 6); - buf[off++] |= values[i + 5] >>> 20; - - buf[off++] = (byte) (values[i + 5] >>> 12); - - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 22; - - buf[off++] = (byte) (values[i + 6] >>> 14); - - buf[off++] = (byte) (values[i + 6] >>> 6); - - buf[off] = (byte) (values[i + 6] << 2); - buf[off++] |= values[i + 7] >>> 24; - - buf[off++] = (byte) (values[i + 7] >>> 16); - - buf[off++] = (byte) (values[i + 7] >>> 8); - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits27(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 19); - - buf[off++] = (byte) (values[i + 0] >>> 11); - - buf[off++] = (byte) (values[i + 0] >>> 3); - - buf[off] = (byte) (values[i + 0] << 5); - buf[off++] |= values[i + 1] >>> 22; - - buf[off++] = (byte) (values[i + 1] >>> 14); - - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 25; - - buf[off++] = (byte) (values[i + 2] >>> 17); - - buf[off++] = (byte) (values[i + 2] >>> 9); - - buf[off++] = (byte) (values[i + 2] >>> 1); - - buf[off] = (byte) (values[i + 2] << 7); - buf[off++] |= values[i + 3] >>> 20; - - buf[off++] = (byte) (values[i + 3] >>> 12); - - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 23; - - buf[off++] = (byte) (values[i + 4] >>> 15); - - buf[off++] = (byte) (values[i + 4] >>> 7); - - buf[off] = (byte) (values[i + 4] << 1); - buf[off++] |= values[i + 5] >>> 26; - - buf[off++] = (byte) (values[i + 5] >>> 18); - - buf[off++] = (byte) (values[i + 5] >>> 10); - - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 21; - - buf[off++] = (byte) (values[i + 6] >>> 13); - - buf[off++] = (byte) (values[i + 6] >>> 5); - - buf[off] = (byte) (values[i + 6] << 3); - buf[off++] |= values[i + 7] >>> 24; - - buf[off++] = (byte) (values[i + 7] >>> 16); - - buf[off++] = (byte) (values[i + 7] >>> 8); - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits28(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 20); - buf[off++] = (byte) (values[i + 0] >>> 12); - buf[off++] = (byte) (values[i + 0] >>> 4); - buf[off] = (byte) (values[i + 0] << 4); - buf[off++] |= values[i + 1] >>> 24; - buf[off++] = (byte) (values[i + 1] >>> 16); - buf[off++] = (byte) (values[i + 1] >>> 8); - buf[off++] = (byte) (values[i + 1]); - buf[off++] = (byte) (values[i + 2] >>> 20); - buf[off++] = (byte) (values[i + 2] >>> 12); - buf[off++] = (byte) (values[i + 2] >>> 4); - buf[off] = (byte) (values[i + 2] << 4); - buf[off++] |= values[i + 3] >>> 24; - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - buf[off++] = (byte) (values[i + 4] >>> 20); - buf[off++] = (byte) (values[i + 4] >>> 12); - buf[off++] = (byte) (values[i + 4] >>> 4); - buf[off] = (byte) (values[i + 4] << 4); - buf[off++] |= values[i + 5] >>> 24; - buf[off++] = (byte) (values[i + 5] >>> 16); - buf[off++] = (byte) (values[i + 5] >>> 8); - buf[off++] = (byte) (values[i + 5]); - buf[off++] = (byte) (values[i + 6] >>> 20); - buf[off++] = (byte) (values[i + 6] >>> 12); - buf[off++] = (byte) (values[i + 6] >>> 4); - buf[off] = (byte) (values[i + 6] << 4); - buf[off++] |= values[i + 7] >>> 24; - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits29(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 21); - - buf[off++] = (byte) (values[i + 0] >>> 13); - - buf[off++] = (byte) (values[i + 0] >>> 5); - - buf[off] = (byte) (values[i + 0] << 3); - buf[off++] |= values[i + 1] >>> 26; - - buf[off++] = (byte) (values[i + 1] >>> 18); - - buf[off++] = (byte) (values[i + 1] >>> 10); - - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 23; - - buf[off++] = (byte) (values[i + 2] >>> 15); - - buf[off++] = (byte) (values[i + 2] >>> 7); - - buf[off] = (byte) (values[i + 2] << 1); - buf[off++] |= values[i + 3] >>> 28; - - buf[off++] = (byte) (values[i + 3] >>> 20); - - buf[off++] = (byte) (values[i + 3] >>> 12); - - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 25; - - buf[off++] = (byte) (values[i + 4] >>> 17); - - buf[off++] = (byte) (values[i + 4] >>> 9); - - buf[off++] = (byte) (values[i + 4] >>> 1); - - buf[off] = (byte) (values[i + 4] << 7); - buf[off++] |= values[i + 5] >>> 22; - - buf[off++] = (byte) (values[i + 5] >>> 14); - - buf[off++] = (byte) (values[i + 5] >>> 6); - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 27; - - buf[off++] = (byte) (values[i + 6] >>> 19); - - buf[off++] = (byte) (values[i + 6] >>> 11); - - buf[off++] = (byte) (values[i + 6] >>> 3); - - buf[off] = (byte) (values[i + 6] << 5); - buf[off++] |= values[i + 7] >>> 24; - - buf[off++] = (byte) (values[i + 7] >>> 16); - - buf[off++] = (byte) (values[i + 7] >>> 8); - - buf[off] = (byte) (values[i + 7]); - } - - static void packBits30(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 22); - buf[off++] = (byte) (values[i + 0] >>> 14); - buf[off++] = (byte) (values[i + 0] >>> 6); - - buf[off] = (byte) (values[i + 0] << 2); - buf[off++] |= values[i + 1] >>> 28; - buf[off++] = (byte) (values[i + 1] >>> 20); - buf[off++] = (byte) (values[i + 1] >>> 12); - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 26; - buf[off++] = (byte) (values[i + 2] >>> 18); - buf[off++] = (byte) (values[i + 2] >>> 10); - buf[off++] = (byte) (values[i + 2] >>> 2); - - buf[off] = (byte) (values[i + 2] << 6); - buf[off++] |= values[i + 3] >>> 24; - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 22); - buf[off++] = (byte) (values[i + 4] >>> 14); - buf[off++] = (byte) (values[i + 4] >>> 6); - - buf[off] = (byte) (values[i + 4] << 2); - buf[off++] |= values[i + 5] >>> 28; - buf[off++] = (byte) (values[i + 5] >>> 20); - buf[off++] = (byte) (values[i + 5] >>> 12); - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 26; - buf[off++] = (byte) (values[i + 6] >>> 18); - buf[off++] = (byte) (values[i + 6] >>> 10); - buf[off++] = (byte) (values[i + 6] >>> 2); - - buf[off] = (byte) (values[i + 6] << 6); - buf[off++] |= values[i + 7] >>> 24; - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits31(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 23); - buf[off++] = (byte) (values[i + 0] >>> 15); - buf[off++] = (byte) (values[i + 0] >>> 7); - - buf[off] = (byte) (values[i + 0] << 1); - buf[off++] |= values[i + 1] >>> 30; - buf[off++] = (byte) (values[i + 1] >>> 22); - buf[off++] = (byte) (values[i + 1] >>> 14); - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 29; - buf[off++] = (byte) (values[i + 2] >>> 21); - buf[off++] = (byte) (values[i + 2] >>> 13); - buf[off++] = (byte) (values[i + 2] >>> 5); - - buf[off] = (byte) (values[i + 2] << 3); - buf[off++] |= values[i + 3] >>> 28; - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 27; - buf[off++] = (byte) (values[i + 4] >>> 19); - buf[off++] = (byte) (values[i + 4] >>> 11); - buf[off++] = (byte) (values[i + 4] >>> 3); - - buf[off] = (byte) (values[i + 4] << 5); - buf[off++] |= values[i + 5] >>> 26; - buf[off++] = (byte) (values[i + 5] >>> 18); - buf[off++] = (byte) (values[i + 5] >>> 10); - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 25; - buf[off++] = (byte) (values[i + 6] >>> 17); - buf[off++] = (byte) (values[i + 6] >>> 9); - buf[off++] = (byte) (values[i + 6] >>> 1); - - buf[off] = (byte) (values[i + 6] << 7); - buf[off++] |= values[i + 7] >>> 24; - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits32(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 24); - buf[off++] = (byte) (values[i + 0] >>> 16); - buf[off++] = (byte) (values[i + 0] >>> 8); - buf[off++] = (byte) (values[i + 0]); - - buf[off++] = (byte) (values[i + 1] >>> 24); - buf[off++] = (byte) (values[i + 1] >>> 16); - buf[off++] = (byte) (values[i + 1] >>> 8); - buf[off++] = (byte) (values[i + 1]); - - buf[off++] = (byte) (values[i + 2] >>> 24); - buf[off++] = (byte) (values[i + 2] >>> 16); - buf[off++] = (byte) (values[i + 2] >>> 8); - buf[off++] = (byte) (values[i + 2]); - - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 24); - buf[off++] = (byte) (values[i + 4] >>> 16); - buf[off++] = (byte) (values[i + 4] >>> 8); - buf[off++] = (byte) (values[i + 4]); - - buf[off++] = (byte) (values[i + 5] >>> 24); - buf[off++] = (byte) (values[i + 5] >>> 16); - buf[off++] = (byte) (values[i + 5] >>> 8); - buf[off++] = (byte) (values[i + 5]); - - buf[off++] = (byte) (values[i + 6] >>> 24); - buf[off++] = (byte) (values[i + 6] >>> 16); - buf[off++] = (byte) (values[i + 6] >>> 8); - buf[off++] = (byte) (values[i + 6]); - - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits33(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 25); - buf[off++] = (byte) (values[i + 0] >>> 17); - buf[off++] = (byte) (values[i + 0] >>> 9); - buf[off++] = (byte) (values[i + 0] >>> 1); - - buf[off] = (byte) (values[i + 0] << 7); - buf[off++] |= values[i + 1] >>> 26; - buf[off++] = (byte) (values[i + 1] >>> 18); - buf[off++] = (byte) (values[i + 1] >>> 10); - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 27; - buf[off++] = (byte) (values[i + 2] >>> 19); - buf[off++] = (byte) (values[i + 2] >>> 11); - buf[off++] = (byte) (values[i + 2] >>> 3); - - buf[off] = (byte) (values[i + 2] << 5); - buf[off++] |= values[i + 3] >>> 28; - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 29; - buf[off++] = (byte) (values[i + 4] >>> 21); - buf[off++] = (byte) (values[i + 4] >>> 13); - buf[off++] = (byte) (values[i + 4] >>> 5); - - buf[off] = (byte) (values[i + 4] << 3); - buf[off++] |= values[i + 5] >>> 30; - buf[off++] = (byte) (values[i + 5] >>> 22); - buf[off++] = (byte) (values[i + 5] >>> 14); - buf[off++] = (byte) (values[i + 5] >>> 6); - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 31; - buf[off++] = (byte) (values[i + 6] >>> 23); - buf[off++] = (byte) (values[i + 6] >>> 15); - buf[off++] = (byte) (values[i + 6] >>> 7); - - buf[off] = (byte) (values[i + 6] << 1); - buf[off++] |= values[i + 7] >>> 32; - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits34(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 26); - buf[off++] = (byte) (values[i + 0] >>> 18); - buf[off++] = (byte) (values[i + 0] >>> 10); - buf[off++] = (byte) (values[i + 0] >>> 2); - - buf[off] = (byte) (values[i + 0] << 6); - buf[off++] |= values[i + 1] >>> 28; - buf[off++] = (byte) (values[i + 1] >>> 20); - buf[off++] = (byte) (values[i + 1] >>> 12); - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 30; - buf[off++] = (byte) (values[i + 2] >>> 22); - buf[off++] = (byte) (values[i + 2] >>> 14); - buf[off++] = (byte) (values[i + 2] >>> 6); - - buf[off] = (byte) (values[i + 2] << 2); - buf[off++] |= values[i + 3] >>> 32; - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 26); - buf[off++] = (byte) (values[i + 4] >>> 18); - buf[off++] = (byte) (values[i + 4] >>> 10); - buf[off++] = (byte) (values[i + 4] >>> 2); - - buf[off] = (byte) (values[i + 4] << 6); - buf[off++] |= values[i + 5] >>> 28; - buf[off++] = (byte) (values[i + 5] >>> 20); - buf[off++] = (byte) (values[i + 5] >>> 12); - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 30; - buf[off++] = (byte) (values[i + 6] >>> 22); - buf[off++] = (byte) (values[i + 6] >>> 14); - buf[off++] = (byte) (values[i + 6] >>> 6); - - buf[off] = (byte) (values[i + 6] << 2); - buf[off++] |= values[i + 7] >>> 32; - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits35(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 27); - buf[off++] = (byte) (values[i + 0] >>> 19); - buf[off++] = (byte) (values[i + 0] >>> 11); - buf[off++] = (byte) (values[i + 0] >>> 3); - - buf[off] = (byte) (values[i + 0] << 5); - buf[off++] |= values[i + 1] >>> 30; - buf[off++] = (byte) (values[i + 1] >>> 22); - buf[off++] = (byte) (values[i + 1] >>> 14); - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 33; - buf[off++] = (byte) (values[i + 2] >>> 25); - buf[off++] = (byte) (values[i + 2] >>> 17); - buf[off++] = (byte) (values[i + 2] >>> 9); - buf[off++] = (byte) (values[i + 2] >>> 1); - - buf[off] = (byte) (values[i + 2] << 7); - buf[off++] |= values[i + 3] >>> 28; - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 31; - buf[off++] = (byte) (values[i + 4] >>> 23); - buf[off++] = (byte) (values[i + 4] >>> 15); - buf[off++] = (byte) (values[i + 4] >>> 7); - - buf[off] = (byte) (values[i + 4] << 1); - buf[off++] |= values[i + 5] >>> 34; - buf[off++] = (byte) (values[i + 5] >>> 26); - buf[off++] = (byte) (values[i + 5] >>> 18); - buf[off++] = (byte) (values[i + 5] >>> 10); - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 29; - buf[off++] = (byte) (values[i + 6] >>> 21); - buf[off++] = (byte) (values[i + 6] >>> 13); - buf[off++] = (byte) (values[i + 6] >>> 5); - - buf[off] = (byte) (values[i + 6] << 3); - buf[off++] |= values[i + 7] >>> 32; - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits36(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 28); - buf[off++] = (byte) (values[i + 0] >>> 20); - buf[off++] = (byte) (values[i + 0] >>> 12); - buf[off++] = (byte) (values[i + 0] >>> 4); - - buf[off] = (byte) (values[i + 0] << 4); - buf[off++] |= values[i + 1] >>> 32; - buf[off++] = (byte) (values[i + 1] >>> 24); - buf[off++] = (byte) (values[i + 1] >>> 16); - buf[off++] = (byte) (values[i + 1] >>> 8); - buf[off++] = (byte) (values[i + 1]); - - buf[off++] = (byte) (values[i + 2] >>> 28); - buf[off++] = (byte) (values[i + 2] >>> 20); - buf[off++] = (byte) (values[i + 2] >>> 12); - buf[off++] = (byte) (values[i + 2] >>> 4); - - buf[off] = (byte) (values[i + 2] << 4); - buf[off++] |= values[i + 3] >>> 32; - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 28); - buf[off++] = (byte) (values[i + 4] >>> 20); - buf[off++] = (byte) (values[i + 4] >>> 12); - buf[off++] = (byte) (values[i + 4] >>> 4); - - buf[off] = (byte) (values[i + 4] << 4); - buf[off++] |= values[i + 5] >>> 32; - buf[off++] = (byte) (values[i + 5] >>> 24); - buf[off++] = (byte) (values[i + 5] >>> 16); - buf[off++] = (byte) (values[i + 5] >>> 8); - buf[off++] = (byte) (values[i + 5]); - - buf[off++] = (byte) (values[i + 6] >>> 28); - buf[off++] = (byte) (values[i + 6] >>> 20); - buf[off++] = (byte) (values[i + 6] >>> 12); - buf[off++] = (byte) (values[i + 6] >>> 4); - - buf[off] = (byte) (values[i + 6] << 4); - buf[off++] |= values[i + 7] >>> 32; - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits37(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 29); - buf[off++] = (byte) (values[i + 0] >>> 21); - buf[off++] = (byte) (values[i + 0] >>> 13); - buf[off++] = (byte) (values[i + 0] >>> 5); - - buf[off] = (byte) (values[i + 0] << 3); - buf[off++] |= values[i + 1] >>> 34; - buf[off++] = (byte) (values[i + 1] >>> 26); - buf[off++] = (byte) (values[i + 1] >>> 18); - buf[off++] = (byte) (values[i + 1] >>> 10); - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 31; - buf[off++] = (byte) (values[i + 2] >>> 23); - buf[off++] = (byte) (values[i + 2] >>> 15); - buf[off++] = (byte) (values[i + 2] >>> 7); - - buf[off] = (byte) (values[i + 2] << 1); - buf[off++] |= values[i + 3] >>> 36; - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 33; - buf[off++] = (byte) (values[i + 4] >>> 25); - buf[off++] = (byte) (values[i + 4] >>> 17); - buf[off++] = (byte) (values[i + 4] >>> 9); - buf[off++] = (byte) (values[i + 4] >>> 1); - - buf[off] = (byte) (values[i + 4] << 7); - buf[off++] |= values[i + 5] >>> 30; - buf[off++] = (byte) (values[i + 5] >>> 22); - buf[off++] = (byte) (values[i + 5] >>> 14); - buf[off++] = (byte) (values[i + 5] >>> 6); - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 35; - buf[off++] = (byte) (values[i + 6] >>> 27); - buf[off++] = (byte) (values[i + 6] >>> 19); - buf[off++] = (byte) (values[i + 6] >>> 11); - buf[off++] = (byte) (values[i + 6] >>> 3); - - buf[off] = (byte) (values[i + 6] << 5); - buf[off++] |= values[i + 7] >>> 32; - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits38(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 30); - buf[off++] = (byte) (values[i + 0] >>> 22); - buf[off++] = (byte) (values[i + 0] >>> 14); - buf[off++] = (byte) (values[i + 0] >>> 6); - - buf[off] = (byte) (values[i + 0] << 2); - buf[off++] |= values[i + 1] >>> 36; - buf[off++] = (byte) (values[i + 1] >>> 28); - buf[off++] = (byte) (values[i + 1] >>> 20); - buf[off++] = (byte) (values[i + 1] >>> 12); - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 34; - buf[off++] = (byte) (values[i + 2] >>> 26); - buf[off++] = (byte) (values[i + 2] >>> 18); - buf[off++] = (byte) (values[i + 2] >>> 10); - buf[off++] = (byte) (values[i + 2] >>> 2); - - buf[off] = (byte) (values[i + 2] << 6); - buf[off++] |= values[i + 3] >>> 32; - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 30); - buf[off++] = (byte) (values[i + 4] >>> 22); - buf[off++] = (byte) (values[i + 4] >>> 14); - buf[off++] = (byte) (values[i + 4] >>> 6); - - buf[off] = (byte) (values[i + 4] << 2); - buf[off++] |= values[i + 5] >>> 36; - buf[off++] = (byte) (values[i + 5] >>> 28); - buf[off++] = (byte) (values[i + 5] >>> 20); - buf[off++] = (byte) (values[i + 5] >>> 12); - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 34; - buf[off++] = (byte) (values[i + 6] >>> 26); - buf[off++] = (byte) (values[i + 6] >>> 18); - buf[off++] = (byte) (values[i + 6] >>> 10); - buf[off++] = (byte) (values[i + 6] >>> 2); - - buf[off] = (byte) (values[i + 6] << 6); - buf[off++] |= values[i + 7] >>> 32; - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits39(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 31); - buf[off++] = (byte) (values[i + 0] >>> 23); - buf[off++] = (byte) (values[i + 0] >>> 15); - buf[off++] = (byte) (values[i + 0] >>> 7); - - buf[off] = (byte) (values[i + 0] << 1); - buf[off++] |= values[i + 1] >>> 38; - buf[off++] = (byte) (values[i + 1] >>> 30); - buf[off++] = (byte) (values[i + 1] >>> 22); - buf[off++] = (byte) (values[i + 1] >>> 14); - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 37; - buf[off++] = (byte) (values[i + 2] >>> 29); - buf[off++] = (byte) (values[i + 2] >>> 21); - buf[off++] = (byte) (values[i + 2] >>> 13); - buf[off++] = (byte) (values[i + 2] >>> 5); - - buf[off] = (byte) (values[i + 2] << 3); - buf[off++] |= values[i + 3] >>> 36; - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 35; - buf[off++] = (byte) (values[i + 4] >>> 27); - buf[off++] = (byte) (values[i + 4] >>> 19); - buf[off++] = (byte) (values[i + 4] >>> 11); - buf[off++] = (byte) (values[i + 4] >>> 3); - - buf[off] = (byte) (values[i + 4] << 5); - buf[off++] |= values[i + 5] >>> 34; - buf[off++] = (byte) (values[i + 5] >>> 26); - buf[off++] = (byte) (values[i + 5] >>> 18); - buf[off++] = (byte) (values[i + 5] >>> 10); - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 33; - buf[off++] = (byte) (values[i + 6] >>> 25); - buf[off++] = (byte) (values[i + 6] >>> 17); - buf[off++] = (byte) (values[i + 6] >>> 9); - buf[off++] = (byte) (values[i + 6] >>> 1); - - buf[off] = (byte) (values[i + 6] << 7); - buf[off++] |= values[i + 7] >>> 32; - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits40(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 32); - buf[off++] = (byte) (values[i + 0] >>> 24); - buf[off++] = (byte) (values[i + 0] >>> 16); - buf[off++] = (byte) (values[i + 0] >>> 8); - buf[off++] = (byte) (values[i + 0]); - - buf[off++] = (byte) (values[i + 1] >>> 32); - buf[off++] = (byte) (values[i + 1] >>> 24); - buf[off++] = (byte) (values[i + 1] >>> 16); - buf[off++] = (byte) (values[i + 1] >>> 8); - buf[off++] = (byte) (values[i + 1]); - - buf[off++] = (byte) (values[i + 2] >>> 32); - buf[off++] = (byte) (values[i + 2] >>> 24); - buf[off++] = (byte) (values[i + 2] >>> 16); - buf[off++] = (byte) (values[i + 2] >>> 8); - buf[off++] = (byte) (values[i + 2]); - - buf[off++] = (byte) (values[i + 3] >>> 32); - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 32); - buf[off++] = (byte) (values[i + 4] >>> 24); - buf[off++] = (byte) (values[i + 4] >>> 16); - buf[off++] = (byte) (values[i + 4] >>> 8); - buf[off++] = (byte) (values[i + 4]); - - buf[off++] = (byte) (values[i + 5] >>> 32); - buf[off++] = (byte) (values[i + 5] >>> 24); - buf[off++] = (byte) (values[i + 5] >>> 16); - buf[off++] = (byte) (values[i + 5] >>> 8); - buf[off++] = (byte) (values[i + 5]); - - buf[off++] = (byte) (values[i + 6] >>> 32); - buf[off++] = (byte) (values[i + 6] >>> 24); - buf[off++] = (byte) (values[i + 6] >>> 16); - buf[off++] = (byte) (values[i + 6] >>> 8); - buf[off++] = (byte) (values[i + 6]); - - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits41(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 33); - buf[off++] = (byte) (values[i + 0] >>> 25); - buf[off++] = (byte) (values[i + 0] >>> 17); - buf[off++] = (byte) (values[i + 0] >>> 9); - buf[off++] = (byte) (values[i + 0] >>> 1); - - buf[off] = (byte) (values[i + 0] << 7); - buf[off++] |= values[i + 1] >>> 34; - buf[off++] = (byte) (values[i + 1] >>> 26); - buf[off++] = (byte) (values[i + 1] >>> 18); - buf[off++] = (byte) (values[i + 1] >>> 10); - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 35; - buf[off++] = (byte) (values[i + 2] >>> 27); - buf[off++] = (byte) (values[i + 2] >>> 19); - buf[off++] = (byte) (values[i + 2] >>> 11); - buf[off++] = (byte) (values[i + 2] >>> 3); - - buf[off] = (byte) (values[i + 2] << 5); - buf[off++] |= values[i + 3] >>> 36; - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 37; - buf[off++] = (byte) (values[i + 4] >>> 29); - buf[off++] = (byte) (values[i + 4] >>> 21); - buf[off++] = (byte) (values[i + 4] >>> 13); - buf[off++] = (byte) (values[i + 4] >>> 5); - - buf[off] = (byte) (values[i + 4] << 3); - buf[off++] |= values[i + 5] >>> 38; - buf[off++] = (byte) (values[i + 5] >>> 30); - buf[off++] = (byte) (values[i + 5] >>> 22); - buf[off++] = (byte) (values[i + 5] >>> 14); - buf[off++] = (byte) (values[i + 5] >>> 6); - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 39; - buf[off++] = (byte) (values[i + 6] >>> 31); - buf[off++] = (byte) (values[i + 6] >>> 23); - buf[off++] = (byte) (values[i + 6] >>> 15); - buf[off++] = (byte) (values[i + 6] >>> 7); - - buf[off] = (byte) (values[i + 6] << 1); - buf[off++] |= values[i + 7] >>> 40; - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits42(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 34); - buf[off++] = (byte) (values[i + 0] >>> 26); - buf[off++] = (byte) (values[i + 0] >>> 18); - buf[off++] = (byte) (values[i + 0] >>> 10); - buf[off++] = (byte) (values[i + 0] >>> 2); - - buf[off] = (byte) (values[i + 0] << 6); - buf[off++] |= values[i + 1] >>> 36; - buf[off++] = (byte) (values[i + 1] >>> 28); - buf[off++] = (byte) (values[i + 1] >>> 20); - buf[off++] = (byte) (values[i + 1] >>> 12); - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 38; - buf[off++] = (byte) (values[i + 2] >>> 30); - buf[off++] = (byte) (values[i + 2] >>> 22); - buf[off++] = (byte) (values[i + 2] >>> 14); - buf[off++] = (byte) (values[i + 2] >>> 6); - - buf[off] = (byte) (values[i + 2] << 2); - buf[off++] |= values[i + 3] >>> 40; - buf[off++] = (byte) (values[i + 3] >>> 32); - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 34); - buf[off++] = (byte) (values[i + 4] >>> 26); - buf[off++] = (byte) (values[i + 4] >>> 18); - buf[off++] = (byte) (values[i + 4] >>> 10); - buf[off++] = (byte) (values[i + 4] >>> 2); - - buf[off] = (byte) (values[i + 4] << 6); - buf[off++] |= values[i + 5] >>> 36; - buf[off++] = (byte) (values[i + 5] >>> 28); - buf[off++] = (byte) (values[i + 5] >>> 20); - buf[off++] = (byte) (values[i + 5] >>> 12); - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 38; - buf[off++] = (byte) (values[i + 6] >>> 30); - buf[off++] = (byte) (values[i + 6] >>> 22); - buf[off++] = (byte) (values[i + 6] >>> 14); - buf[off++] = (byte) (values[i + 6] >>> 6); - - buf[off] = (byte) (values[i + 6] << 2); - buf[off++] |= values[i + 7] >>> 40; - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits43(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 35); - buf[off++] = (byte) (values[i + 0] >>> 27); - buf[off++] = (byte) (values[i + 0] >>> 19); - buf[off++] = (byte) (values[i + 0] >>> 11); - buf[off++] = (byte) (values[i + 0] >>> 3); - - buf[off] = (byte) (values[i + 0] << 5); - buf[off++] |= values[i + 1] >>> 38; - buf[off++] = (byte) (values[i + 1] >>> 30); - buf[off++] = (byte) (values[i + 1] >>> 22); - buf[off++] = (byte) (values[i + 1] >>> 14); - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 41; - buf[off++] = (byte) (values[i + 2] >>> 33); - buf[off++] = (byte) (values[i + 2] >>> 25); - buf[off++] = (byte) (values[i + 2] >>> 17); - buf[off++] = (byte) (values[i + 2] >>> 9); - buf[off++] = (byte) (values[i + 2] >>> 1); - - buf[off] = (byte) (values[i + 2] << 7); - buf[off++] |= values[i + 3] >>> 36; - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 39; - buf[off++] = (byte) (values[i + 4] >>> 31); - buf[off++] = (byte) (values[i + 4] >>> 23); - buf[off++] = (byte) (values[i + 4] >>> 15); - buf[off++] = (byte) (values[i + 4] >>> 7); - - buf[off] = (byte) (values[i + 4] << 1); - buf[off++] |= values[i + 5] >>> 42; - buf[off++] = (byte) (values[i + 5] >>> 34); - buf[off++] = (byte) (values[i + 5] >>> 26); - buf[off++] = (byte) (values[i + 5] >>> 18); - buf[off++] = (byte) (values[i + 5] >>> 10); - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 37; - buf[off++] = (byte) (values[i + 6] >>> 29); - buf[off++] = (byte) (values[i + 6] >>> 21); - buf[off++] = (byte) (values[i + 6] >>> 13); - buf[off++] = (byte) (values[i + 6] >>> 5); - - buf[off] = (byte) (values[i + 6] << 3); - buf[off++] |= values[i + 7] >>> 40; - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits44(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 36); - buf[off++] = (byte) (values[i + 0] >>> 28); - buf[off++] = (byte) (values[i + 0] >>> 20); - buf[off++] = (byte) (values[i + 0] >>> 12); - buf[off++] = (byte) (values[i + 0] >>> 4); - - buf[off] = (byte) (values[i + 0] << 4); - buf[off++] |= values[i + 1] >>> 40; - buf[off++] = (byte) (values[i + 1] >>> 32); - buf[off++] = (byte) (values[i + 1] >>> 24); - buf[off++] = (byte) (values[i + 1] >>> 16); - buf[off++] = (byte) (values[i + 1] >>> 8); - buf[off++] = (byte) (values[i + 1]); - - buf[off++] = (byte) (values[i + 2] >>> 36); - buf[off++] = (byte) (values[i + 2] >>> 28); - buf[off++] = (byte) (values[i + 2] >>> 20); - buf[off++] = (byte) (values[i + 2] >>> 12); - buf[off++] = (byte) (values[i + 2] >>> 4); - - buf[off] = (byte) (values[i + 2] << 4); - buf[off++] |= values[i + 3] >>> 40; - buf[off++] = (byte) (values[i + 3] >>> 32); - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 36); - buf[off++] = (byte) (values[i + 4] >>> 28); - buf[off++] = (byte) (values[i + 4] >>> 20); - buf[off++] = (byte) (values[i + 4] >>> 12); - buf[off++] = (byte) (values[i + 4] >>> 4); - - buf[off] = (byte) (values[i + 4] << 4); - buf[off++] |= values[i + 5] >>> 40; - buf[off++] = (byte) (values[i + 5] >>> 32); - buf[off++] = (byte) (values[i + 5] >>> 24); - buf[off++] = (byte) (values[i + 5] >>> 16); - buf[off++] = (byte) (values[i + 5] >>> 8); - buf[off++] = (byte) (values[i + 5]); - - buf[off++] = (byte) (values[i + 6] >>> 36); - buf[off++] = (byte) (values[i + 6] >>> 28); - buf[off++] = (byte) (values[i + 6] >>> 20); - buf[off++] = (byte) (values[i + 6] >>> 12); - buf[off++] = (byte) (values[i + 6] >>> 4); - - buf[off] = (byte) (values[i + 6] << 4); - buf[off++] |= values[i + 7] >>> 40; - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits45(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 37); - buf[off++] = (byte) (values[i + 0] >>> 29); - buf[off++] = (byte) (values[i + 0] >>> 21); - buf[off++] = (byte) (values[i + 0] >>> 13); - buf[off++] = (byte) (values[i + 0] >>> 5); - - buf[off] = (byte) (values[i + 0] << 3); - buf[off++] |= values[i + 1] >>> 42; - buf[off++] = (byte) (values[i + 1] >>> 34); - buf[off++] = (byte) (values[i + 1] >>> 26); - buf[off++] = (byte) (values[i + 1] >>> 18); - buf[off++] = (byte) (values[i + 1] >>> 10); - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 39; - buf[off++] = (byte) (values[i + 2] >>> 31); - buf[off++] = (byte) (values[i + 2] >>> 23); - buf[off++] = (byte) (values[i + 2] >>> 15); - buf[off++] = (byte) (values[i + 2] >>> 7); - - buf[off] = (byte) (values[i + 2] << 1); - buf[off++] |= values[i + 3] >>> 44; - buf[off++] = (byte) (values[i + 3] >>> 36); - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 41; - buf[off++] = (byte) (values[i + 4] >>> 33); - buf[off++] = (byte) (values[i + 4] >>> 25); - buf[off++] = (byte) (values[i + 4] >>> 17); - buf[off++] = (byte) (values[i + 4] >>> 9); - buf[off++] = (byte) (values[i + 4] >>> 1); - - buf[off] = (byte) (values[i + 4] << 7); - buf[off++] |= values[i + 5] >>> 38; - buf[off++] = (byte) (values[i + 5] >>> 30); - buf[off++] = (byte) (values[i + 5] >>> 22); - buf[off++] = (byte) (values[i + 5] >>> 14); - buf[off++] = (byte) (values[i + 5] >>> 6); - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 43; - buf[off++] = (byte) (values[i + 6] >>> 35); - buf[off++] = (byte) (values[i + 6] >>> 27); - buf[off++] = (byte) (values[i + 6] >>> 19); - buf[off++] = (byte) (values[i + 6] >>> 11); - buf[off++] = (byte) (values[i + 6] >>> 3); - - buf[off] = (byte) (values[i + 6] << 5); - buf[off++] |= values[i + 7] >>> 40; - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits46(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 38); - buf[off++] = (byte) (values[i + 0] >>> 30); - buf[off++] = (byte) (values[i + 0] >>> 22); - buf[off++] = (byte) (values[i + 0] >>> 14); - buf[off++] = (byte) (values[i + 0] >>> 6); - - buf[off] = (byte) (values[i + 0] << 2); - buf[off++] |= values[i + 1] >>> 44; - buf[off++] = (byte) (values[i + 1] >>> 36); - buf[off++] = (byte) (values[i + 1] >>> 28); - buf[off++] = (byte) (values[i + 1] >>> 20); - buf[off++] = (byte) (values[i + 1] >>> 12); - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 42; - buf[off++] = (byte) (values[i + 2] >>> 34); - buf[off++] = (byte) (values[i + 2] >>> 26); - buf[off++] = (byte) (values[i + 2] >>> 18); - buf[off++] = (byte) (values[i + 2] >>> 10); - buf[off++] = (byte) (values[i + 2] >>> 2); - - buf[off] = (byte) (values[i + 2] << 6); - buf[off++] |= values[i + 3] >>> 40; - buf[off++] = (byte) (values[i + 3] >>> 32); - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 38); - buf[off++] = (byte) (values[i + 4] >>> 30); - buf[off++] = (byte) (values[i + 4] >>> 22); - buf[off++] = (byte) (values[i + 4] >>> 14); - buf[off++] = (byte) (values[i + 4] >>> 6); - - buf[off] = (byte) (values[i + 4] << 2); - buf[off++] |= values[i + 5] >>> 44; - buf[off++] = (byte) (values[i + 5] >>> 36); - buf[off++] = (byte) (values[i + 5] >>> 28); - buf[off++] = (byte) (values[i + 5] >>> 20); - buf[off++] = (byte) (values[i + 5] >>> 12); - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 42; - buf[off++] = (byte) (values[i + 6] >>> 34); - buf[off++] = (byte) (values[i + 6] >>> 26); - buf[off++] = (byte) (values[i + 6] >>> 18); - buf[off++] = (byte) (values[i + 6] >>> 10); - buf[off++] = (byte) (values[i + 6] >>> 2); - - buf[off] = (byte) (values[i + 6] << 6); - buf[off++] |= values[i + 7] >>> 40; - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits47(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 39); - buf[off++] = (byte) (values[i + 0] >>> 31); - buf[off++] = (byte) (values[i + 0] >>> 23); - buf[off++] = (byte) (values[i + 0] >>> 15); - buf[off++] = (byte) (values[i + 0] >>> 7); - - buf[off] = (byte) (values[i + 0] << 1); - buf[off++] |= values[i + 1] >>> 46; - buf[off++] = (byte) (values[i + 1] >>> 38); - buf[off++] = (byte) (values[i + 1] >>> 30); - buf[off++] = (byte) (values[i + 1] >>> 22); - buf[off++] = (byte) (values[i + 1] >>> 14); - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 45; - buf[off++] = (byte) (values[i + 2] >>> 37); - buf[off++] = (byte) (values[i + 2] >>> 29); - buf[off++] = (byte) (values[i + 2] >>> 21); - buf[off++] = (byte) (values[i + 2] >>> 13); - buf[off++] = (byte) (values[i + 2] >>> 5); - - buf[off] = (byte) (values[i + 2] << 3); - buf[off++] |= values[i + 3] >>> 44; - buf[off++] = (byte) (values[i + 3] >>> 36); - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 43; - buf[off++] = (byte) (values[i + 4] >>> 35); - buf[off++] = (byte) (values[i + 4] >>> 27); - buf[off++] = (byte) (values[i + 4] >>> 19); - buf[off++] = (byte) (values[i + 4] >>> 11); - buf[off++] = (byte) (values[i + 4] >>> 3); - - buf[off] = (byte) (values[i + 4] << 5); - buf[off++] |= values[i + 5] >>> 42; - buf[off++] = (byte) (values[i + 5] >>> 34); - buf[off++] = (byte) (values[i + 5] >>> 26); - buf[off++] = (byte) (values[i + 5] >>> 18); - buf[off++] = (byte) (values[i + 5] >>> 10); - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 41; - buf[off++] = (byte) (values[i + 6] >>> 33); - buf[off++] = (byte) (values[i + 6] >>> 25); - buf[off++] = (byte) (values[i + 6] >>> 17); - buf[off++] = (byte) (values[i + 6] >>> 9); - buf[off++] = (byte) (values[i + 6] >>> 1); - - buf[off] = (byte) (values[i + 6] << 7); - buf[off++] |= values[i + 7] >>> 40; - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits48(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 40); - buf[off++] = (byte) (values[i + 0] >>> 32); - buf[off++] = (byte) (values[i + 0] >>> 24); - buf[off++] = (byte) (values[i + 0] >>> 16); - buf[off++] = (byte) (values[i + 0] >>> 8); - buf[off++] = (byte) (values[i + 0]); - - buf[off++] = (byte) (values[i + 1] >>> 40); - buf[off++] = (byte) (values[i + 1] >>> 32); - buf[off++] = (byte) (values[i + 1] >>> 24); - buf[off++] = (byte) (values[i + 1] >>> 16); - buf[off++] = (byte) (values[i + 1] >>> 8); - buf[off++] = (byte) (values[i + 1]); - - buf[off++] = (byte) (values[i + 2] >>> 40); - buf[off++] = (byte) (values[i + 2] >>> 32); - buf[off++] = (byte) (values[i + 2] >>> 24); - buf[off++] = (byte) (values[i + 2] >>> 16); - buf[off++] = (byte) (values[i + 2] >>> 8); - buf[off++] = (byte) (values[i + 2]); - - buf[off++] = (byte) (values[i + 3] >>> 40); - buf[off++] = (byte) (values[i + 3] >>> 32); - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 40); - buf[off++] = (byte) (values[i + 4] >>> 32); - buf[off++] = (byte) (values[i + 4] >>> 24); - buf[off++] = (byte) (values[i + 4] >>> 16); - buf[off++] = (byte) (values[i + 4] >>> 8); - buf[off++] = (byte) (values[i + 4]); - - buf[off++] = (byte) (values[i + 5] >>> 40); - buf[off++] = (byte) (values[i + 5] >>> 32); - buf[off++] = (byte) (values[i + 5] >>> 24); - buf[off++] = (byte) (values[i + 5] >>> 16); - buf[off++] = (byte) (values[i + 5] >>> 8); - buf[off++] = (byte) (values[i + 5]); - - buf[off++] = (byte) (values[i + 6] >>> 40); - buf[off++] = (byte) (values[i + 6] >>> 32); - buf[off++] = (byte) (values[i + 6] >>> 24); - buf[off++] = (byte) (values[i + 6] >>> 16); - buf[off++] = (byte) (values[i + 6] >>> 8); - buf[off++] = (byte) (values[i + 6]); - - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits49(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 41); - buf[off++] = (byte) (values[i + 0] >>> 33); - buf[off++] = (byte) (values[i + 0] >>> 25); - buf[off++] = (byte) (values[i + 0] >>> 17); - buf[off++] = (byte) (values[i + 0] >>> 9); - buf[off++] = (byte) (values[i + 0] >>> 1); - - buf[off] = (byte) (values[i + 0] << 7); - buf[off++] |= values[i + 1] >>> 42; - buf[off++] = (byte) (values[i + 1] >>> 34); - buf[off++] = (byte) (values[i + 1] >>> 26); - buf[off++] = (byte) (values[i + 1] >>> 18); - buf[off++] = (byte) (values[i + 1] >>> 10); - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 43; - buf[off++] = (byte) (values[i + 2] >>> 35); - buf[off++] = (byte) (values[i + 2] >>> 27); - buf[off++] = (byte) (values[i + 2] >>> 19); - buf[off++] = (byte) (values[i + 2] >>> 11); - buf[off++] = (byte) (values[i + 2] >>> 3); - - buf[off] = (byte) (values[i + 2] << 5); - buf[off++] |= values[i + 3] >>> 44; - buf[off++] = (byte) (values[i + 3] >>> 36); - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 45; - buf[off++] = (byte) (values[i + 4] >>> 37); - buf[off++] = (byte) (values[i + 4] >>> 29); - buf[off++] = (byte) (values[i + 4] >>> 21); - buf[off++] = (byte) (values[i + 4] >>> 13); - buf[off++] = (byte) (values[i + 4] >>> 5); - - buf[off] = (byte) (values[i + 4] << 3); - buf[off++] |= values[i + 5] >>> 46; - buf[off++] = (byte) (values[i + 5] >>> 38); - buf[off++] = (byte) (values[i + 5] >>> 30); - buf[off++] = (byte) (values[i + 5] >>> 22); - buf[off++] = (byte) (values[i + 5] >>> 14); - buf[off++] = (byte) (values[i + 5] >>> 6); - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 47; - buf[off++] = (byte) (values[i + 6] >>> 39); - buf[off++] = (byte) (values[i + 6] >>> 31); - buf[off++] = (byte) (values[i + 6] >>> 23); - buf[off++] = (byte) (values[i + 6] >>> 15); - buf[off++] = (byte) (values[i + 6] >>> 7); - - buf[off] = (byte) (values[i + 6] << 1); - buf[off++] |= values[i + 7] >>> 48; - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits50(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 42); - buf[off++] = (byte) (values[i + 0] >>> 34); - buf[off++] = (byte) (values[i + 0] >>> 26); - buf[off++] = (byte) (values[i + 0] >>> 18); - buf[off++] = (byte) (values[i + 0] >>> 10); - buf[off++] = (byte) (values[i + 0] >>> 2); - - buf[off] = (byte) (values[i + 0] << 6); - buf[off++] |= values[i + 1] >>> 44; - buf[off++] = (byte) (values[i + 1] >>> 36); - buf[off++] = (byte) (values[i + 1] >>> 28); - buf[off++] = (byte) (values[i + 1] >>> 20); - buf[off++] = (byte) (values[i + 1] >>> 12); - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 46; - buf[off++] = (byte) (values[i + 2] >>> 38); - buf[off++] = (byte) (values[i + 2] >>> 30); - buf[off++] = (byte) (values[i + 2] >>> 22); - buf[off++] = (byte) (values[i + 2] >>> 14); - buf[off++] = (byte) (values[i + 2] >>> 6); - - buf[off] = (byte) (values[i + 2] << 2); - buf[off++] |= values[i + 3] >>> 48; - buf[off++] = (byte) (values[i + 3] >>> 40); - buf[off++] = (byte) (values[i + 3] >>> 32); - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 42); - buf[off++] = (byte) (values[i + 4] >>> 34); - buf[off++] = (byte) (values[i + 4] >>> 26); - buf[off++] = (byte) (values[i + 4] >>> 18); - buf[off++] = (byte) (values[i + 4] >>> 10); - buf[off++] = (byte) (values[i + 4] >>> 2); - - buf[off] = (byte) (values[i + 4] << 6); - buf[off++] |= values[i + 5] >>> 44; - buf[off++] = (byte) (values[i + 5] >>> 36); - buf[off++] = (byte) (values[i + 5] >>> 28); - buf[off++] = (byte) (values[i + 5] >>> 20); - buf[off++] = (byte) (values[i + 5] >>> 12); - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 46; - buf[off++] = (byte) (values[i + 6] >>> 38); - buf[off++] = (byte) (values[i + 6] >>> 30); - buf[off++] = (byte) (values[i + 6] >>> 22); - buf[off++] = (byte) (values[i + 6] >>> 14); - buf[off++] = (byte) (values[i + 6] >>> 6); - - buf[off] = (byte) (values[i + 6] << 2); - buf[off++] |= values[i + 7] >>> 48; - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits51(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 43); - buf[off++] = (byte) (values[i + 0] >>> 35); - buf[off++] = (byte) (values[i + 0] >>> 27); - buf[off++] = (byte) (values[i + 0] >>> 19); - buf[off++] = (byte) (values[i + 0] >>> 11); - buf[off++] = (byte) (values[i + 0] >>> 3); - - buf[off] = (byte) (values[i + 0] << 5); - buf[off++] |= values[i + 1] >>> 46; - buf[off++] = (byte) (values[i + 1] >>> 38); - buf[off++] = (byte) (values[i + 1] >>> 30); - buf[off++] = (byte) (values[i + 1] >>> 22); - buf[off++] = (byte) (values[i + 1] >>> 14); - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 49; - buf[off++] = (byte) (values[i + 2] >>> 41); - buf[off++] = (byte) (values[i + 2] >>> 33); - buf[off++] = (byte) (values[i + 2] >>> 25); - buf[off++] = (byte) (values[i + 2] >>> 17); - buf[off++] = (byte) (values[i + 2] >>> 9); - buf[off++] = (byte) (values[i + 2] >>> 1); - - buf[off] = (byte) (values[i + 2] << 7); - buf[off++] |= values[i + 3] >>> 44; - buf[off++] = (byte) (values[i + 3] >>> 36); - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 47; - buf[off++] = (byte) (values[i + 4] >>> 39); - buf[off++] = (byte) (values[i + 4] >>> 31); - buf[off++] = (byte) (values[i + 4] >>> 23); - buf[off++] = (byte) (values[i + 4] >>> 15); - buf[off++] = (byte) (values[i + 4] >>> 7); - - buf[off] = (byte) (values[i + 4] << 1); - buf[off++] |= values[i + 5] >>> 50; - buf[off++] = (byte) (values[i + 5] >>> 42); - buf[off++] = (byte) (values[i + 5] >>> 34); - buf[off++] = (byte) (values[i + 5] >>> 26); - buf[off++] = (byte) (values[i + 5] >>> 18); - buf[off++] = (byte) (values[i + 5] >>> 10); - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 45; - buf[off++] = (byte) (values[i + 6] >>> 37); - buf[off++] = (byte) (values[i + 6] >>> 29); - buf[off++] = (byte) (values[i + 6] >>> 21); - buf[off++] = (byte) (values[i + 6] >>> 13); - buf[off++] = (byte) (values[i + 6] >>> 5); - - buf[off] = (byte) (values[i + 6] << 3); - buf[off++] |= values[i + 7] >>> 48; - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits52(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 44); - buf[off++] = (byte) (values[i + 0] >>> 36); - buf[off++] = (byte) (values[i + 0] >>> 28); - buf[off++] = (byte) (values[i + 0] >>> 20); - buf[off++] = (byte) (values[i + 0] >>> 12); - buf[off++] = (byte) (values[i + 0] >>> 4); - - buf[off] = (byte) (values[i + 0] << 4); - buf[off++] |= values[i + 1] >>> 48; - buf[off++] = (byte) (values[i + 1] >>> 40); - buf[off++] = (byte) (values[i + 1] >>> 32); - buf[off++] = (byte) (values[i + 1] >>> 24); - buf[off++] = (byte) (values[i + 1] >>> 16); - buf[off++] = (byte) (values[i + 1] >>> 8); - buf[off++] = (byte) (values[i + 1]); - - buf[off++] = (byte) (values[i + 2] >>> 44); - buf[off++] = (byte) (values[i + 2] >>> 36); - buf[off++] = (byte) (values[i + 2] >>> 28); - buf[off++] = (byte) (values[i + 2] >>> 20); - buf[off++] = (byte) (values[i + 2] >>> 12); - buf[off++] = (byte) (values[i + 2] >>> 4); - - buf[off] = (byte) (values[i + 2] << 4); - buf[off++] |= values[i + 3] >>> 48; - buf[off++] = (byte) (values[i + 3] >>> 40); - buf[off++] = (byte) (values[i + 3] >>> 32); - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 44); - buf[off++] = (byte) (values[i + 4] >>> 36); - buf[off++] = (byte) (values[i + 4] >>> 28); - buf[off++] = (byte) (values[i + 4] >>> 20); - buf[off++] = (byte) (values[i + 4] >>> 12); - buf[off++] = (byte) (values[i + 4] >>> 4); - - buf[off] = (byte) (values[i + 4] << 4); - buf[off++] |= values[i + 5] >>> 48; - buf[off++] = (byte) (values[i + 5] >>> 40); - buf[off++] = (byte) (values[i + 5] >>> 32); - buf[off++] = (byte) (values[i + 5] >>> 24); - buf[off++] = (byte) (values[i + 5] >>> 16); - buf[off++] = (byte) (values[i + 5] >>> 8); - buf[off++] = (byte) (values[i + 5]); - - buf[off++] = (byte) (values[i + 6] >>> 44); - buf[off++] = (byte) (values[i + 6] >>> 36); - buf[off++] = (byte) (values[i + 6] >>> 28); - buf[off++] = (byte) (values[i + 6] >>> 20); - buf[off++] = (byte) (values[i + 6] >>> 12); - buf[off++] = (byte) (values[i + 6] >>> 4); - - buf[off] = (byte) (values[i + 6] << 4); - buf[off++] |= values[i + 7] >>> 48; - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits53(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 45); - buf[off++] = (byte) (values[i + 0] >>> 37); - buf[off++] = (byte) (values[i + 0] >>> 29); - buf[off++] = (byte) (values[i + 0] >>> 21); - buf[off++] = (byte) (values[i + 0] >>> 13); - buf[off++] = (byte) (values[i + 0] >>> 5); - - buf[off] = (byte) (values[i + 0] << 3); - buf[off++] |= values[i + 1] >>> 50; - buf[off++] = (byte) (values[i + 1] >>> 42); - buf[off++] = (byte) (values[i + 1] >>> 34); - buf[off++] = (byte) (values[i + 1] >>> 26); - buf[off++] = (byte) (values[i + 1] >>> 18); - buf[off++] = (byte) (values[i + 1] >>> 10); - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 47; - buf[off++] = (byte) (values[i + 2] >>> 39); - buf[off++] = (byte) (values[i + 2] >>> 31); - buf[off++] = (byte) (values[i + 2] >>> 23); - buf[off++] = (byte) (values[i + 2] >>> 15); - buf[off++] = (byte) (values[i + 2] >>> 7); - - buf[off] = (byte) (values[i + 2] << 1); - buf[off++] |= values[i + 3] >>> 52; - buf[off++] = (byte) (values[i + 3] >>> 44); - buf[off++] = (byte) (values[i + 3] >>> 36); - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 49; - buf[off++] = (byte) (values[i + 4] >>> 41); - buf[off++] = (byte) (values[i + 4] >>> 33); - buf[off++] = (byte) (values[i + 4] >>> 25); - buf[off++] = (byte) (values[i + 4] >>> 17); - buf[off++] = (byte) (values[i + 4] >>> 9); - buf[off++] = (byte) (values[i + 4] >>> 1); - - buf[off] = (byte) (values[i + 4] << 7); - buf[off++] |= values[i + 5] >>> 46; - buf[off++] = (byte) (values[i + 5] >>> 38); - buf[off++] = (byte) (values[i + 5] >>> 30); - buf[off++] = (byte) (values[i + 5] >>> 22); - buf[off++] = (byte) (values[i + 5] >>> 14); - buf[off++] = (byte) (values[i + 5] >>> 6); - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 51; - buf[off++] = (byte) (values[i + 6] >>> 43); - buf[off++] = (byte) (values[i + 6] >>> 35); - buf[off++] = (byte) (values[i + 6] >>> 27); - buf[off++] = (byte) (values[i + 6] >>> 19); - buf[off++] = (byte) (values[i + 6] >>> 11); - buf[off++] = (byte) (values[i + 6] >>> 3); - - buf[off] = (byte) (values[i + 6] << 5); - buf[off++] |= values[i + 7] >>> 48; - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits54(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 46); - buf[off++] = (byte) (values[i + 0] >>> 38); - buf[off++] = (byte) (values[i + 0] >>> 30); - buf[off++] = (byte) (values[i + 0] >>> 22); - buf[off++] = (byte) (values[i + 0] >>> 14); - buf[off++] = (byte) (values[i + 0] >>> 6); - - buf[off] = (byte) (values[i + 0] << 2); - buf[off++] |= values[i + 1] >>> 52; - buf[off++] = (byte) (values[i + 1] >>> 44); - buf[off++] = (byte) (values[i + 1] >>> 36); - buf[off++] = (byte) (values[i + 1] >>> 28); - buf[off++] = (byte) (values[i + 1] >>> 20); - buf[off++] = (byte) (values[i + 1] >>> 12); - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 50; - buf[off++] = (byte) (values[i + 2] >>> 42); - buf[off++] = (byte) (values[i + 2] >>> 34); - buf[off++] = (byte) (values[i + 2] >>> 26); - buf[off++] = (byte) (values[i + 2] >>> 18); - buf[off++] = (byte) (values[i + 2] >>> 10); - buf[off++] = (byte) (values[i + 2] >>> 2); - - buf[off] = (byte) (values[i + 2] << 6); - buf[off++] |= values[i + 3] >>> 48; - buf[off++] = (byte) (values[i + 3] >>> 40); - buf[off++] = (byte) (values[i + 3] >>> 32); - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 46); - buf[off++] = (byte) (values[i + 4] >>> 38); - buf[off++] = (byte) (values[i + 4] >>> 30); - buf[off++] = (byte) (values[i + 4] >>> 22); - buf[off++] = (byte) (values[i + 4] >>> 14); - buf[off++] = (byte) (values[i + 4] >>> 6); - - buf[off] = (byte) (values[i + 4] << 2); - buf[off++] |= values[i + 5] >>> 52; - buf[off++] = (byte) (values[i + 5] >>> 44); - buf[off++] = (byte) (values[i + 5] >>> 36); - buf[off++] = (byte) (values[i + 5] >>> 28); - buf[off++] = (byte) (values[i + 5] >>> 20); - buf[off++] = (byte) (values[i + 5] >>> 12); - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 50; - buf[off++] = (byte) (values[i + 6] >>> 42); - buf[off++] = (byte) (values[i + 6] >>> 34); - buf[off++] = (byte) (values[i + 6] >>> 26); - buf[off++] = (byte) (values[i + 6] >>> 18); - buf[off++] = (byte) (values[i + 6] >>> 10); - buf[off++] = (byte) (values[i + 6] >>> 2); - - buf[off] = (byte) (values[i + 6] << 6); - buf[off++] |= values[i + 7] >>> 48; - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits55(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 47); - buf[off++] = (byte) (values[i + 0] >>> 39); - buf[off++] = (byte) (values[i + 0] >>> 31); - buf[off++] = (byte) (values[i + 0] >>> 23); - buf[off++] = (byte) (values[i + 0] >>> 15); - buf[off++] = (byte) (values[i + 0] >>> 7); - - buf[off] = (byte) (values[i + 0] << 1); - buf[off++] |= values[i + 1] >>> 54; - buf[off++] = (byte) (values[i + 1] >>> 46); - buf[off++] = (byte) (values[i + 1] >>> 38); - buf[off++] = (byte) (values[i + 1] >>> 30); - buf[off++] = (byte) (values[i + 1] >>> 22); - buf[off++] = (byte) (values[i + 1] >>> 14); - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 53; - buf[off++] = (byte) (values[i + 2] >>> 45); - buf[off++] = (byte) (values[i + 2] >>> 37); - buf[off++] = (byte) (values[i + 2] >>> 29); - buf[off++] = (byte) (values[i + 2] >>> 21); - buf[off++] = (byte) (values[i + 2] >>> 13); - buf[off++] = (byte) (values[i + 2] >>> 5); - - buf[off] = (byte) (values[i + 2] << 3); - buf[off++] |= values[i + 3] >>> 52; - buf[off++] = (byte) (values[i + 3] >>> 44); - buf[off++] = (byte) (values[i + 3] >>> 36); - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 51; - buf[off++] = (byte) (values[i + 4] >>> 43); - buf[off++] = (byte) (values[i + 4] >>> 35); - buf[off++] = (byte) (values[i + 4] >>> 27); - buf[off++] = (byte) (values[i + 4] >>> 19); - buf[off++] = (byte) (values[i + 4] >>> 11); - buf[off++] = (byte) (values[i + 4] >>> 3); - - buf[off] = (byte) (values[i + 4] << 5); - buf[off++] |= values[i + 5] >>> 50; - buf[off++] = (byte) (values[i + 5] >>> 42); - buf[off++] = (byte) (values[i + 5] >>> 34); - buf[off++] = (byte) (values[i + 5] >>> 26); - buf[off++] = (byte) (values[i + 5] >>> 18); - buf[off++] = (byte) (values[i + 5] >>> 10); - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 49; - buf[off++] = (byte) (values[i + 6] >>> 41); - buf[off++] = (byte) (values[i + 6] >>> 33); - buf[off++] = (byte) (values[i + 6] >>> 25); - buf[off++] = (byte) (values[i + 6] >>> 17); - buf[off++] = (byte) (values[i + 6] >>> 9); - buf[off++] = (byte) (values[i + 6] >>> 1); - - buf[off] = (byte) (values[i + 6] << 7); - buf[off++] |= values[i + 7] >>> 48; - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits56(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 48); - buf[off++] = (byte) (values[i + 0] >>> 40); - buf[off++] = (byte) (values[i + 0] >>> 32); - buf[off++] = (byte) (values[i + 0] >>> 24); - buf[off++] = (byte) (values[i + 0] >>> 16); - buf[off++] = (byte) (values[i + 0] >>> 8); - buf[off++] = (byte) (values[i + 0]); - - buf[off++] = (byte) (values[i + 1] >>> 48); - buf[off++] = (byte) (values[i + 1] >>> 40); - buf[off++] = (byte) (values[i + 1] >>> 32); - buf[off++] = (byte) (values[i + 1] >>> 24); - buf[off++] = (byte) (values[i + 1] >>> 16); - buf[off++] = (byte) (values[i + 1] >>> 8); - buf[off++] = (byte) (values[i + 1]); - - buf[off++] = (byte) (values[i + 2] >>> 48); - buf[off++] = (byte) (values[i + 2] >>> 40); - buf[off++] = (byte) (values[i + 2] >>> 32); - buf[off++] = (byte) (values[i + 2] >>> 24); - buf[off++] = (byte) (values[i + 2] >>> 16); - buf[off++] = (byte) (values[i + 2] >>> 8); - buf[off++] = (byte) (values[i + 2]); - - buf[off++] = (byte) (values[i + 3] >>> 48); - buf[off++] = (byte) (values[i + 3] >>> 40); - buf[off++] = (byte) (values[i + 3] >>> 32); - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 48); - buf[off++] = (byte) (values[i + 4] >>> 40); - buf[off++] = (byte) (values[i + 4] >>> 32); - buf[off++] = (byte) (values[i + 4] >>> 24); - buf[off++] = (byte) (values[i + 4] >>> 16); - buf[off++] = (byte) (values[i + 4] >>> 8); - buf[off++] = (byte) (values[i + 4]); - - buf[off++] = (byte) (values[i + 5] >>> 48); - buf[off++] = (byte) (values[i + 5] >>> 40); - buf[off++] = (byte) (values[i + 5] >>> 32); - buf[off++] = (byte) (values[i + 5] >>> 24); - buf[off++] = (byte) (values[i + 5] >>> 16); - buf[off++] = (byte) (values[i + 5] >>> 8); - buf[off++] = (byte) (values[i + 5]); - - buf[off++] = (byte) (values[i + 6] >>> 48); - buf[off++] = (byte) (values[i + 6] >>> 40); - buf[off++] = (byte) (values[i + 6] >>> 32); - buf[off++] = (byte) (values[i + 6] >>> 24); - buf[off++] = (byte) (values[i + 6] >>> 16); - buf[off++] = (byte) (values[i + 6] >>> 8); - buf[off++] = (byte) (values[i + 6]); - - buf[off++] = (byte) (values[i + 7] >>> 48); - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits57(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 49); - buf[off++] = (byte) (values[i + 0] >>> 41); - buf[off++] = (byte) (values[i + 0] >>> 33); - buf[off++] = (byte) (values[i + 0] >>> 25); - buf[off++] = (byte) (values[i + 0] >>> 17); - buf[off++] = (byte) (values[i + 0] >>> 9); - buf[off++] = (byte) (values[i + 0] >>> 1); - - buf[off] = (byte) (values[i + 0] << 7); - buf[off++] |= values[i + 1] >>> 50; - buf[off++] = (byte) (values[i + 1] >>> 42); - buf[off++] = (byte) (values[i + 1] >>> 34); - buf[off++] = (byte) (values[i + 1] >>> 26); - buf[off++] = (byte) (values[i + 1] >>> 18); - buf[off++] = (byte) (values[i + 1] >>> 10); - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 51; - buf[off++] = (byte) (values[i + 2] >>> 43); - buf[off++] = (byte) (values[i + 2] >>> 35); - buf[off++] = (byte) (values[i + 2] >>> 27); - buf[off++] = (byte) (values[i + 2] >>> 19); - buf[off++] = (byte) (values[i + 2] >>> 11); - buf[off++] = (byte) (values[i + 2] >>> 3); - - buf[off] = (byte) (values[i + 2] << 5); - buf[off++] |= values[i + 3] >>> 52; - buf[off++] = (byte) (values[i + 3] >>> 44); - buf[off++] = (byte) (values[i + 3] >>> 36); - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 53; - buf[off++] = (byte) (values[i + 4] >>> 45); - buf[off++] = (byte) (values[i + 4] >>> 37); - buf[off++] = (byte) (values[i + 4] >>> 29); - buf[off++] = (byte) (values[i + 4] >>> 21); - buf[off++] = (byte) (values[i + 4] >>> 13); - buf[off++] = (byte) (values[i + 4] >>> 5); - - buf[off] = (byte) (values[i + 4] << 3); - buf[off++] |= values[i + 5] >>> 54; - buf[off++] = (byte) (values[i + 5] >>> 46); - buf[off++] = (byte) (values[i + 5] >>> 38); - buf[off++] = (byte) (values[i + 5] >>> 30); - buf[off++] = (byte) (values[i + 5] >>> 22); - buf[off++] = (byte) (values[i + 5] >>> 14); - buf[off++] = (byte) (values[i + 5] >>> 6); - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 55; - buf[off++] = (byte) (values[i + 6] >>> 47); - buf[off++] = (byte) (values[i + 6] >>> 39); - buf[off++] = (byte) (values[i + 6] >>> 31); - buf[off++] = (byte) (values[i + 6] >>> 23); - buf[off++] = (byte) (values[i + 6] >>> 15); - buf[off++] = (byte) (values[i + 6] >>> 7); - - buf[off] = (byte) (values[i + 6] << 1); - buf[off++] |= values[i + 7] >>> 56; - buf[off++] = (byte) (values[i + 7] >>> 48); - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits58(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 50); - buf[off++] = (byte) (values[i + 0] >>> 42); - buf[off++] = (byte) (values[i + 0] >>> 34); - buf[off++] = (byte) (values[i + 0] >>> 26); - buf[off++] = (byte) (values[i + 0] >>> 18); - buf[off++] = (byte) (values[i + 0] >>> 10); - buf[off++] = (byte) (values[i + 0] >>> 2); - - buf[off] = (byte) (values[i + 0] << 6); - buf[off++] |= values[i + 1] >>> 52; - buf[off++] = (byte) (values[i + 1] >>> 44); - buf[off++] = (byte) (values[i + 1] >>> 36); - buf[off++] = (byte) (values[i + 1] >>> 28); - buf[off++] = (byte) (values[i + 1] >>> 20); - buf[off++] = (byte) (values[i + 1] >>> 12); - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 54; - buf[off++] = (byte) (values[i + 2] >>> 46); - buf[off++] = (byte) (values[i + 2] >>> 38); - buf[off++] = (byte) (values[i + 2] >>> 30); - buf[off++] = (byte) (values[i + 2] >>> 22); - buf[off++] = (byte) (values[i + 2] >>> 14); - buf[off++] = (byte) (values[i + 2] >>> 6); - - buf[off] = (byte) (values[i + 2] << 2); - buf[off++] |= values[i + 3] >>> 56; - buf[off++] = (byte) (values[i + 3] >>> 48); - buf[off++] = (byte) (values[i + 3] >>> 40); - buf[off++] = (byte) (values[i + 3] >>> 32); - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 50); - buf[off++] = (byte) (values[i + 4] >>> 42); - buf[off++] = (byte) (values[i + 4] >>> 34); - buf[off++] = (byte) (values[i + 4] >>> 26); - buf[off++] = (byte) (values[i + 4] >>> 18); - buf[off++] = (byte) (values[i + 4] >>> 10); - buf[off++] = (byte) (values[i + 4] >>> 2); - - buf[off] = (byte) (values[i + 4] << 6); - buf[off++] |= values[i + 5] >>> 52; - buf[off++] = (byte) (values[i + 5] >>> 44); - buf[off++] = (byte) (values[i + 5] >>> 36); - buf[off++] = (byte) (values[i + 5] >>> 28); - buf[off++] = (byte) (values[i + 5] >>> 20); - buf[off++] = (byte) (values[i + 5] >>> 12); - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 54; - buf[off++] = (byte) (values[i + 6] >>> 46); - buf[off++] = (byte) (values[i + 6] >>> 38); - buf[off++] = (byte) (values[i + 6] >>> 30); - buf[off++] = (byte) (values[i + 6] >>> 22); - buf[off++] = (byte) (values[i + 6] >>> 14); - buf[off++] = (byte) (values[i + 6] >>> 6); - - buf[off] = (byte) (values[i + 6] << 2); - buf[off++] |= values[i + 7] >>> 56; - buf[off++] = (byte) (values[i + 7] >>> 48); - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits59(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 51); - buf[off++] = (byte) (values[i + 0] >>> 43); - buf[off++] = (byte) (values[i + 0] >>> 35); - buf[off++] = (byte) (values[i + 0] >>> 27); - buf[off++] = (byte) (values[i + 0] >>> 19); - buf[off++] = (byte) (values[i + 0] >>> 11); - buf[off++] = (byte) (values[i + 0] >>> 3); - - buf[off] = (byte) (values[i + 0] << 5); - buf[off++] |= values[i + 1] >>> 54; - buf[off++] = (byte) (values[i + 1] >>> 46); - buf[off++] = (byte) (values[i + 1] >>> 38); - buf[off++] = (byte) (values[i + 1] >>> 30); - buf[off++] = (byte) (values[i + 1] >>> 22); - buf[off++] = (byte) (values[i + 1] >>> 14); - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 57; - buf[off++] = (byte) (values[i + 2] >>> 49); - buf[off++] = (byte) (values[i + 2] >>> 41); - buf[off++] = (byte) (values[i + 2] >>> 33); - buf[off++] = (byte) (values[i + 2] >>> 25); - buf[off++] = (byte) (values[i + 2] >>> 17); - buf[off++] = (byte) (values[i + 2] >>> 9); - buf[off++] = (byte) (values[i + 2] >>> 1); - - buf[off] = (byte) (values[i + 2] << 7); - buf[off++] |= values[i + 3] >>> 52; - buf[off++] = (byte) (values[i + 3] >>> 44); - buf[off++] = (byte) (values[i + 3] >>> 36); - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 55; - buf[off++] = (byte) (values[i + 4] >>> 47); - buf[off++] = (byte) (values[i + 4] >>> 39); - buf[off++] = (byte) (values[i + 4] >>> 31); - buf[off++] = (byte) (values[i + 4] >>> 23); - buf[off++] = (byte) (values[i + 4] >>> 15); - buf[off++] = (byte) (values[i + 4] >>> 7); - - buf[off] = (byte) (values[i + 4] << 1); - buf[off++] |= values[i + 5] >>> 58; - buf[off++] = (byte) (values[i + 5] >>> 50); - buf[off++] = (byte) (values[i + 5] >>> 42); - buf[off++] = (byte) (values[i + 5] >>> 34); - buf[off++] = (byte) (values[i + 5] >>> 26); - buf[off++] = (byte) (values[i + 5] >>> 18); - buf[off++] = (byte) (values[i + 5] >>> 10); - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 53; - buf[off++] = (byte) (values[i + 6] >>> 45); - buf[off++] = (byte) (values[i + 6] >>> 37); - buf[off++] = (byte) (values[i + 6] >>> 29); - buf[off++] = (byte) (values[i + 6] >>> 21); - buf[off++] = (byte) (values[i + 6] >>> 13); - buf[off++] = (byte) (values[i + 6] >>> 5); - - buf[off] = (byte) (values[i + 6] << 3); - buf[off++] |= values[i + 7] >>> 56; - buf[off++] = (byte) (values[i + 7] >>> 48); - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits60(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 52); - buf[off++] = (byte) (values[i + 0] >>> 44); - buf[off++] = (byte) (values[i + 0] >>> 36); - buf[off++] = (byte) (values[i + 0] >>> 28); - buf[off++] = (byte) (values[i + 0] >>> 20); - buf[off++] = (byte) (values[i + 0] >>> 12); - buf[off++] = (byte) (values[i + 0] >>> 4); - - buf[off] = (byte) (values[i + 0] << 4); - buf[off++] |= values[i + 1] >>> 56; - buf[off++] = (byte) (values[i + 1] >>> 48); - buf[off++] = (byte) (values[i + 1] >>> 40); - buf[off++] = (byte) (values[i + 1] >>> 32); - buf[off++] = (byte) (values[i + 1] >>> 24); - buf[off++] = (byte) (values[i + 1] >>> 16); - buf[off++] = (byte) (values[i + 1] >>> 8); - buf[off++] = (byte) (values[i + 1]); - - buf[off++] = (byte) (values[i + 2] >>> 52); - buf[off++] = (byte) (values[i + 2] >>> 44); - buf[off++] = (byte) (values[i + 2] >>> 36); - buf[off++] = (byte) (values[i + 2] >>> 28); - buf[off++] = (byte) (values[i + 2] >>> 20); - buf[off++] = (byte) (values[i + 2] >>> 12); - buf[off++] = (byte) (values[i + 2] >>> 4); - - buf[off] = (byte) (values[i + 2] << 4); - buf[off++] |= values[i + 3] >>> 56; - buf[off++] = (byte) (values[i + 3] >>> 48); - buf[off++] = (byte) (values[i + 3] >>> 40); - buf[off++] = (byte) (values[i + 3] >>> 32); - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 52); - buf[off++] = (byte) (values[i + 4] >>> 44); - buf[off++] = (byte) (values[i + 4] >>> 36); - buf[off++] = (byte) (values[i + 4] >>> 28); - buf[off++] = (byte) (values[i + 4] >>> 20); - buf[off++] = (byte) (values[i + 4] >>> 12); - buf[off++] = (byte) (values[i + 4] >>> 4); - - buf[off] = (byte) (values[i + 4] << 4); - buf[off++] |= values[i + 5] >>> 56; - buf[off++] = (byte) (values[i + 5] >>> 48); - buf[off++] = (byte) (values[i + 5] >>> 40); - buf[off++] = (byte) (values[i + 5] >>> 32); - buf[off++] = (byte) (values[i + 5] >>> 24); - buf[off++] = (byte) (values[i + 5] >>> 16); - buf[off++] = (byte) (values[i + 5] >>> 8); - buf[off++] = (byte) (values[i + 5]); - - buf[off++] = (byte) (values[i + 6] >>> 52); - buf[off++] = (byte) (values[i + 6] >>> 44); - buf[off++] = (byte) (values[i + 6] >>> 36); - buf[off++] = (byte) (values[i + 6] >>> 28); - buf[off++] = (byte) (values[i + 6] >>> 20); - buf[off++] = (byte) (values[i + 6] >>> 12); - buf[off++] = (byte) (values[i + 6] >>> 4); - - buf[off] = (byte) (values[i + 6] << 4); - buf[off++] |= values[i + 7] >>> 56; - buf[off++] = (byte) (values[i + 7] >>> 48); - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits61(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 53); - buf[off++] = (byte) (values[i + 0] >>> 45); - buf[off++] = (byte) (values[i + 0] >>> 37); - buf[off++] = (byte) (values[i + 0] >>> 29); - buf[off++] = (byte) (values[i + 0] >>> 21); - buf[off++] = (byte) (values[i + 0] >>> 13); - buf[off++] = (byte) (values[i + 0] >>> 5); - - buf[off] = (byte) (values[i + 0] << 3); - buf[off++] |= values[i + 1] >>> 58; - buf[off++] = (byte) (values[i + 1] >>> 50); - buf[off++] = (byte) (values[i + 1] >>> 42); - buf[off++] = (byte) (values[i + 1] >>> 34); - buf[off++] = (byte) (values[i + 1] >>> 26); - buf[off++] = (byte) (values[i + 1] >>> 18); - buf[off++] = (byte) (values[i + 1] >>> 10); - buf[off++] = (byte) (values[i + 1] >>> 2); - - buf[off] = (byte) (values[i + 1] << 6); - buf[off++] |= values[i + 2] >>> 55; - buf[off++] = (byte) (values[i + 2] >>> 47); - buf[off++] = (byte) (values[i + 2] >>> 39); - buf[off++] = (byte) (values[i + 2] >>> 31); - buf[off++] = (byte) (values[i + 2] >>> 23); - buf[off++] = (byte) (values[i + 2] >>> 15); - buf[off++] = (byte) (values[i + 2] >>> 7); - - buf[off] = (byte) (values[i + 2] << 1); - buf[off++] |= values[i + 3] >>> 60; - buf[off++] = (byte) (values[i + 3] >>> 52); - buf[off++] = (byte) (values[i + 3] >>> 44); - buf[off++] = (byte) (values[i + 3] >>> 36); - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 57; - buf[off++] = (byte) (values[i + 4] >>> 49); - buf[off++] = (byte) (values[i + 4] >>> 41); - buf[off++] = (byte) (values[i + 4] >>> 33); - buf[off++] = (byte) (values[i + 4] >>> 25); - buf[off++] = (byte) (values[i + 4] >>> 17); - buf[off++] = (byte) (values[i + 4] >>> 9); - buf[off++] = (byte) (values[i + 4] >>> 1); - - buf[off] = (byte) (values[i + 4] << 7); - buf[off++] |= values[i + 5] >>> 54; - buf[off++] = (byte) (values[i + 5] >>> 46); - buf[off++] = (byte) (values[i + 5] >>> 38); - buf[off++] = (byte) (values[i + 5] >>> 30); - buf[off++] = (byte) (values[i + 5] >>> 22); - buf[off++] = (byte) (values[i + 5] >>> 14); - buf[off++] = (byte) (values[i + 5] >>> 6); - - buf[off] = (byte) (values[i + 5] << 2); - buf[off++] |= values[i + 6] >>> 59; - buf[off++] = (byte) (values[i + 6] >>> 51); - buf[off++] = (byte) (values[i + 6] >>> 43); - buf[off++] = (byte) (values[i + 6] >>> 35); - buf[off++] = (byte) (values[i + 6] >>> 27); - buf[off++] = (byte) (values[i + 6] >>> 19); - buf[off++] = (byte) (values[i + 6] >>> 11); - buf[off++] = (byte) (values[i + 6] >>> 3); - - buf[off] = (byte) (values[i + 6] << 5); - buf[off++] |= values[i + 7] >>> 56; - buf[off++] = (byte) (values[i + 7] >>> 48); - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits62(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 54); - buf[off++] = (byte) (values[i + 0] >>> 46); - buf[off++] = (byte) (values[i + 0] >>> 38); - buf[off++] = (byte) (values[i + 0] >>> 30); - buf[off++] = (byte) (values[i + 0] >>> 22); - buf[off++] = (byte) (values[i + 0] >>> 14); - buf[off++] = (byte) (values[i + 0] >>> 6); - - buf[off] = (byte) (values[i + 0] << 2); - buf[off++] |= values[i + 1] >>> 60; - buf[off++] = (byte) (values[i + 1] >>> 52); - buf[off++] = (byte) (values[i + 1] >>> 44); - buf[off++] = (byte) (values[i + 1] >>> 36); - buf[off++] = (byte) (values[i + 1] >>> 28); - buf[off++] = (byte) (values[i + 1] >>> 20); - buf[off++] = (byte) (values[i + 1] >>> 12); - buf[off++] = (byte) (values[i + 1] >>> 4); - - buf[off] = (byte) (values[i + 1] << 4); - buf[off++] |= values[i + 2] >>> 58; - buf[off++] = (byte) (values[i + 2] >>> 50); - buf[off++] = (byte) (values[i + 2] >>> 42); - buf[off++] = (byte) (values[i + 2] >>> 34); - buf[off++] = (byte) (values[i + 2] >>> 26); - buf[off++] = (byte) (values[i + 2] >>> 18); - buf[off++] = (byte) (values[i + 2] >>> 10); - buf[off++] = (byte) (values[i + 2] >>> 2); - - buf[off] = (byte) (values[i + 2] << 6); - buf[off++] |= values[i + 3] >>> 56; - buf[off++] = (byte) (values[i + 3] >>> 48); - buf[off++] = (byte) (values[i + 3] >>> 40); - buf[off++] = (byte) (values[i + 3] >>> 32); - buf[off++] = (byte) (values[i + 3] >>> 24); - buf[off++] = (byte) (values[i + 3] >>> 16); - buf[off++] = (byte) (values[i + 3] >>> 8); - buf[off++] = (byte) (values[i + 3]); - - buf[off++] = (byte) (values[i + 4] >>> 54); - buf[off++] = (byte) (values[i + 4] >>> 46); - buf[off++] = (byte) (values[i + 4] >>> 38); - buf[off++] = (byte) (values[i + 4] >>> 30); - buf[off++] = (byte) (values[i + 4] >>> 22); - buf[off++] = (byte) (values[i + 4] >>> 14); - buf[off++] = (byte) (values[i + 4] >>> 6); - - buf[off] = (byte) (values[i + 4] << 2); - buf[off++] |= values[i + 5] >>> 60; - buf[off++] = (byte) (values[i + 5] >>> 52); - buf[off++] = (byte) (values[i + 5] >>> 44); - buf[off++] = (byte) (values[i + 5] >>> 36); - buf[off++] = (byte) (values[i + 5] >>> 28); - buf[off++] = (byte) (values[i + 5] >>> 20); - buf[off++] = (byte) (values[i + 5] >>> 12); - buf[off++] = (byte) (values[i + 5] >>> 4); - - buf[off] = (byte) (values[i + 5] << 4); - buf[off++] |= values[i + 6] >>> 58; - buf[off++] = (byte) (values[i + 6] >>> 50); - buf[off++] = (byte) (values[i + 6] >>> 42); - buf[off++] = (byte) (values[i + 6] >>> 34); - buf[off++] = (byte) (values[i + 6] >>> 26); - buf[off++] = (byte) (values[i + 6] >>> 18); - buf[off++] = (byte) (values[i + 6] >>> 10); - buf[off++] = (byte) (values[i + 6] >>> 2); - - buf[off] = (byte) (values[i + 6] << 6); - buf[off++] |= values[i + 7] >>> 56; - buf[off++] = (byte) (values[i + 7] >>> 48); - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) (values[i + 7]); - } - - static void packBits63(final long[] values, final int i, final byte[] buf, int off) { - buf[off++] = (byte) (values[i + 0] >>> 55); - buf[off++] = (byte) (values[i + 0] >>> 47); - buf[off++] = (byte) (values[i + 0] >>> 39); - buf[off++] = (byte) (values[i + 0] >>> 31); - buf[off++] = (byte) (values[i + 0] >>> 23); - buf[off++] = (byte) (values[i + 0] >>> 15); - buf[off++] = (byte) (values[i + 0] >>> 7); - - buf[off] = (byte) (values[i + 0] << 1); - buf[off++] |= values[i + 1] >>> 62; - buf[off++] = (byte) (values[i + 1] >>> 54); - buf[off++] = (byte) (values[i + 1] >>> 46); - buf[off++] = (byte) (values[i + 1] >>> 38); - buf[off++] = (byte) (values[i + 1] >>> 30); - buf[off++] = (byte) (values[i + 1] >>> 22); - buf[off++] = (byte) (values[i + 1] >>> 14); - buf[off++] = (byte) (values[i + 1] >>> 6); - - buf[off] = (byte) (values[i + 1] << 2); - buf[off++] |= values[i + 2] >>> 61; - buf[off++] = (byte) (values[i + 2] >>> 53); - buf[off++] = (byte) (values[i + 2] >>> 45); - buf[off++] = (byte) (values[i + 2] >>> 37); - buf[off++] = (byte) (values[i + 2] >>> 29); - buf[off++] = (byte) (values[i + 2] >>> 21); - buf[off++] = (byte) (values[i + 2] >>> 13); - buf[off++] = (byte) (values[i + 2] >>> 5); - - buf[off] = (byte) (values[i + 2] << 3); - buf[off++] |= values[i + 3] >>> 60; - buf[off++] = (byte) (values[i + 3] >>> 52); - buf[off++] = (byte) (values[i + 3] >>> 44); - buf[off++] = (byte) (values[i + 3] >>> 36); - buf[off++] = (byte) (values[i + 3] >>> 28); - buf[off++] = (byte) (values[i + 3] >>> 20); - buf[off++] = (byte) (values[i + 3] >>> 12); - buf[off++] = (byte) (values[i + 3] >>> 4); - - buf[off] = (byte) (values[i + 3] << 4); - buf[off++] |= values[i + 4] >>> 59; - buf[off++] = (byte) (values[i + 4] >>> 51); - buf[off++] = (byte) (values[i + 4] >>> 43); - buf[off++] = (byte) (values[i + 4] >>> 35); - buf[off++] = (byte) (values[i + 4] >>> 27); - buf[off++] = (byte) (values[i + 4] >>> 19); - buf[off++] = (byte) (values[i + 4] >>> 11); - buf[off++] = (byte) (values[i + 4] >>> 3); - - buf[off] = (byte) (values[i + 4] << 5); - buf[off++] |= values[i + 5] >>> 58; - buf[off++] = (byte) (values[i + 5] >>> 50); - buf[off++] = (byte) (values[i + 5] >>> 42); - buf[off++] = (byte) (values[i + 5] >>> 34); - buf[off++] = (byte) (values[i + 5] >>> 26); - buf[off++] = (byte) (values[i + 5] >>> 18); - buf[off++] = (byte) (values[i + 5] >>> 10); - buf[off++] = (byte) (values[i + 5] >>> 2); - - buf[off] = (byte) (values[i + 5] << 6); - buf[off++] |= values[i + 6] >>> 57; - buf[off++] = (byte) (values[i + 6] >>> 49); - buf[off++] = (byte) (values[i + 6] >>> 41); - buf[off++] = (byte) (values[i + 6] >>> 33); - buf[off++] = (byte) (values[i + 6] >>> 25); - buf[off++] = (byte) (values[i + 6] >>> 17); - buf[off++] = (byte) (values[i + 6] >>> 9); - buf[off++] = (byte) (values[i + 6] >>> 1); - - buf[off] = (byte) (values[i + 6] << 7); - buf[off++] |= values[i + 7] >>> 56; - buf[off++] = (byte) (values[i + 7] >>> 48); - buf[off++] = (byte) (values[i + 7] >>> 40); - buf[off++] = (byte) (values[i + 7] >>> 32); - buf[off++] = (byte) (values[i + 7] >>> 24); - buf[off++] = (byte) (values[i + 7] >>> 16); - buf[off++] = (byte) (values[i + 7] >>> 8); - buf[off] = (byte) values[i + 7]; - } - - static void unpackBits1(final long[] values, final int i, final byte[] buf, final int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off]) >>> 7) & 1; - values[i + 1] = (Byte.toUnsignedLong(buf[off]) >>> 6) & 1; - values[i + 2] = (Byte.toUnsignedLong(buf[off]) >>> 5) & 1; - values[i + 3] = (Byte.toUnsignedLong(buf[off]) >>> 4) & 1; - values[i + 4] = (Byte.toUnsignedLong(buf[off]) >>> 3) & 1; - values[i + 5] = (Byte.toUnsignedLong(buf[off]) >>> 2) & 1; - values[i + 6] = (Byte.toUnsignedLong(buf[off]) >>> 1) & 1; - values[i + 7] = Byte.toUnsignedLong(buf[off]) & 1; - } - - static void unpackBits2(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off]) >>> 6) & 3; - values[i + 1] = (Byte.toUnsignedLong(buf[off]) >>> 4) & 3; - values[i + 2] = (Byte.toUnsignedLong(buf[off]) >>> 2) & 3; - values[i + 3] = Byte.toUnsignedLong(buf[off++]) & 3; - values[i + 4] = (Byte.toUnsignedLong(buf[off]) >>> 6) & 3; - values[i + 5] = (Byte.toUnsignedLong(buf[off]) >>> 4) & 3; - values[i + 6] = (Byte.toUnsignedLong(buf[off]) >>> 2) & 3; - values[i + 7] = Byte.toUnsignedLong(buf[off]) & 3; - } - - static void unpackBits3(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off]) >>> 5; - values[i + 1] = (Byte.toUnsignedLong(buf[off]) >>> 2) & 7; - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 1; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 7; - values[i + 3] = (Byte.toUnsignedLong(buf[off]) >>> 4) & 7; - values[i + 4] = (Byte.toUnsignedLong(buf[off]) >>> 1) & 7; - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 1) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - values[i + 6] = (Byte.toUnsignedLong(buf[off]) >>> 3) & 7; - values[i + 7] = Byte.toUnsignedLong(buf[off]) & 7; - } - - static void unpackBits4(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off]) >>> 4; - values[i + 1] = Byte.toUnsignedLong(buf[off++]) & 0xf; - values[i + 2] = Byte.toUnsignedLong(buf[off]) >>> 4; - values[i + 3] = Byte.toUnsignedLong(buf[off++]) & 0xf; - values[i + 4] = Byte.toUnsignedLong(buf[off]) >>> 4; - values[i + 5] = Byte.toUnsignedLong(buf[off++]) & 0xf; - values[i + 6] = Byte.toUnsignedLong(buf[off]) >>> 4; - values[i + 7] = Byte.toUnsignedLong(buf[off]) & 0xf; - } - - static void unpackBits5(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 7) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off]) >>> 1) & 0x1f; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 1) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 1; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 5] = (Byte.toUnsignedLong(buf[off]) >>> 2) & 0x1f; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 3; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 7] = Byte.toUnsignedLong(buf[off]) & 0x1f; - } - - static void unpackBits6(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 3) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 2; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 3] = Byte.toUnsignedLong(buf[off++]) & 0x3f; - - values[i + 4] = Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 3) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 2; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 7] = Byte.toUnsignedLong(buf[off]) & 0x3f; - } - - static void unpackBits7(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 1) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 5; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 7) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 3; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 1; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 7] = Byte.toUnsignedLong(buf[off]) & 0x7f; - } - - static void unpackBits8(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]); - values[i + 1] = Byte.toUnsignedLong(buf[off++]); - values[i + 2] = Byte.toUnsignedLong(buf[off++]); - values[i + 3] = Byte.toUnsignedLong(buf[off++]); - values[i + 4] = Byte.toUnsignedLong(buf[off++]); - values[i + 5] = Byte.toUnsignedLong(buf[off++]); - values[i + 6] = Byte.toUnsignedLong(buf[off++]); - values[i + 7] = Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits9(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 3; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 5; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 7) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 7; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 1) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits10(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 6; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 3) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 6; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 3) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits11(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 9; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 7; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 1) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 5; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 7) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits12(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 2] = Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 6] = Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits13(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 7) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 7; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 1) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 9; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 11; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits14(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 3) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 10; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 3) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 10; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits15(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 1) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 13; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 7) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 11; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 9; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits16(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]); - values[i + 1] = Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - values[i + 2] = Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]); - values[i + 3] = Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - values[i + 4] = Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]); - values[i + 5] = Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - values[i + 6] = Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]); - values[i + 7] = Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits17(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 11; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 13; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 7) << 14; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 15; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 1) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits18(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 14; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 3) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 14; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 3) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits19(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 17; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 15; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 1) << 18; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 13; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 7) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits20(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 16; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 2] = Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 16; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 6] = Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits21(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 7) << 18; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 15; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 1) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 17; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 14; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 19; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits22(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 3) << 20; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 18; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 3) << 20; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 18; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits23(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 1) << 22; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 21; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 7) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 19; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 18; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 17; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits24(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]); - values[i + 1] = Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - values[i + 2] = Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]); - values[i + 3] = Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - values[i + 4] = Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]); - values[i + 5] = Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - values[i + 6] = Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]); - values[i + 7] = Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits25(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 18; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 19; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 21; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 7) << 22; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 23; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 1) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits26(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 20; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 22; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 3) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 20; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 22; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 3) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits27(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 22; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 25; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 23; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 1) << 26; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 21; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 7) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits28(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 24; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 2] = Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 24; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 6] = Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits29(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 7) << 26; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 23; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 1) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 25; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 22; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 27; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits30(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 3) << 28; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 26; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 3) << 28; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 26; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits31(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 1) << 30; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 29; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 7) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 27; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 26; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 25; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits32(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]); - values[i + 1] = (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - values[i + 2] = (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]); - values[i + 3] = (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]); - values[i + 5] = (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - values[i + 6] = (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]); - values[i + 7] = (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits33(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 26; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 27; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 29; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 7) << 30; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 31; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 1) << 32; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits34(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 28; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 30; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 3) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 28; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 30; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 3) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]); - } - - static void unpackBits35(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 30; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 33; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 31; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 1) << 34; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 29; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 7) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits36(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 32; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 2] = (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 32; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 6] = (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits37(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 7) << 34; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 31; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 23; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 1) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 33; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 30; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 22; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 35; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits38(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 3) << 36; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 34; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 3) << 36; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 34; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits39(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 1) << 38; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 37; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 7) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 35; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 34; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 33; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits40(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]); - values[i + 1] = (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - values[i + 2] = (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]); - values[i + 3] = (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]); - values[i + 5] = (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - values[i + 6] = (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]); - values[i + 7] = (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits41(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 33; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 34; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 35; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 37; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 7) << 38; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 39; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 1) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits42(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 36; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 38; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 3) << 40; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 36; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 38; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 3) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits43(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 35; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 38; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 41; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 33; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 39; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 1) << 42; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 37; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 7) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits44(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 40; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 2] = (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 40; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 40; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 6] = (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits45(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 37; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 7) << 42; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 39; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 23; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 1) << 44; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 41; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 33; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 38; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 22; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 43; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 35; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits46(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 3) << 44; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 42; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 40; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 3) << 44; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 42; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits47(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 39; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 1) << 46; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 45; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 37; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 7) << 44; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 43; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 35; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 42; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 41; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 33; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits48(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]); - values[i + 1] = (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - values[i + 2] = (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]); - values[i + 3] = (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]); - values[i + 5] = (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - values[i + 6] = (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]); - values[i + 7] = (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits49(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 41; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 33; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 42; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 43; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 35; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 44; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 45; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 37; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 7) << 46; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 47; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 39; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 1) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits50(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 44; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 46; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 3) << 48; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 44; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 46; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 3) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits51(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 43; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 35; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 46; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 49; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 41; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 33; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 44; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 47; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 39; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 1) << 50; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 45; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 37; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 7) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits52(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 48; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 2] = (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 48; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 48; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 6] = (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits53(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 45; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 37; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 7) << 50; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 47; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 39; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 23; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 1) << 52; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 49; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 41; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 33; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 46; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 51; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 43; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 35; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits54(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 46; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 3) << 52; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 50; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 48; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 46; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 3) << 52; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 50; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]); - } - - static void unpackBits55(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 47; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 39; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 1) << 54; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 46; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 53; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 45; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 37; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 7) << 52; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 51; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 43; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 35; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 50; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 49; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 41; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 33; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits56(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]); - values[i + 1] = (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - values[i + 2] = (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]); - values[i + 3] = (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]); - values[i + 5] = (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - values[i + 6] = (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]); - values[i + 7] = (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits57(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 49; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 41; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 33; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 50; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 51; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 43; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 35; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 52; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 53; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 45; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 37; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 7) << 54; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 46; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 55; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 47; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 39; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 1) << 56; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits58(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 50; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 52; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 54; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 46; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 3) << 56; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 50; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 52; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 54; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 46; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 3) << 56; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]); - } - - static void unpackBits59(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 51; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 43; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 35; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 54; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 46; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 57; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 49; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 41; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 33; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 52; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 55; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 47; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 39; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 1) << 58; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 50; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 53; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 45; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 37; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 7) << 56; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits60(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 52; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 56; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 2] = (Byte.toUnsignedLong(buf[off++])) << 52; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 56; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 52; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 56; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 6] = (Byte.toUnsignedLong(buf[off++])) << 52; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 56; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits61(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 53; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 45; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 37; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 7) << 58; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 50; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 55; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 47; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 39; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 1) << 60; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 52; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 57; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 49; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 41; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 33; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 54; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 46; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 3) << 59; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 51; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 43; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 35; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 56; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits62(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 54; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 46; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 3) << 60; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 52; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 58; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 50; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 56; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]); - - values[i + 4] = (Byte.toUnsignedLong(buf[off++])) << 54; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 46; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 3) << 60; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 52; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 58; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 50; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 56; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - - static void unpackBits63(final long[] values, final int i, final byte[] buf, int off) { - values[i + 0] = (Byte.toUnsignedLong(buf[off++])) << 55; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 47; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 39; - values[i + 0] |= (Byte.toUnsignedLong(buf[off++])) << 31; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 23; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 15; - values[i + 0] |= Byte.toUnsignedLong(buf[off++]) << 7; - values[i + 0] |= Byte.toUnsignedLong(buf[off]) >>> 1; - - values[i + 1] = (Byte.toUnsignedLong(buf[off++]) & 1) << 62; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 54; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 46; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 38; - values[i + 1] |= (Byte.toUnsignedLong(buf[off++])) << 30; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 22; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 14; - values[i + 1] |= Byte.toUnsignedLong(buf[off++]) << 6; - values[i + 1] |= Byte.toUnsignedLong(buf[off]) >>> 2; - - values[i + 2] = (Byte.toUnsignedLong(buf[off++]) & 3) << 61; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 53; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 45; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 37; - values[i + 2] |= (Byte.toUnsignedLong(buf[off++])) << 29; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 21; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 13; - values[i + 2] |= Byte.toUnsignedLong(buf[off++]) << 5; - values[i + 2] |= Byte.toUnsignedLong(buf[off]) >>> 3; - - values[i + 3] = (Byte.toUnsignedLong(buf[off++]) & 7) << 60; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 52; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 44; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 36; - values[i + 3] |= (Byte.toUnsignedLong(buf[off++])) << 28; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 20; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 12; - values[i + 3] |= Byte.toUnsignedLong(buf[off++]) << 4; - values[i + 3] |= Byte.toUnsignedLong(buf[off]) >>> 4; - - values[i + 4] = (Byte.toUnsignedLong(buf[off++]) & 0xf) << 59; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 51; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 43; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 35; - values[i + 4] |= (Byte.toUnsignedLong(buf[off++])) << 27; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 19; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 11; - values[i + 4] |= Byte.toUnsignedLong(buf[off++]) << 3; - values[i + 4] |= Byte.toUnsignedLong(buf[off]) >>> 5; - - values[i + 5] = (Byte.toUnsignedLong(buf[off++]) & 0x1f) << 58; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 50; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 42; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 34; - values[i + 5] |= (Byte.toUnsignedLong(buf[off++])) << 26; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 18; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 10; - values[i + 5] |= Byte.toUnsignedLong(buf[off++]) << 2; - values[i + 5] |= Byte.toUnsignedLong(buf[off]) >>> 6; - - values[i + 6] = (Byte.toUnsignedLong(buf[off++]) & 0x3f) << 57; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 49; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 41; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 33; - values[i + 6] |= (Byte.toUnsignedLong(buf[off++])) << 25; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 17; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 9; - values[i + 6] |= Byte.toUnsignedLong(buf[off++]) << 1; - values[i + 6] |= Byte.toUnsignedLong(buf[off]) >>> 7; - - values[i + 7] = (Byte.toUnsignedLong(buf[off++]) & 0x7f) << 56; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 48; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 40; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 32; - values[i + 7] |= (Byte.toUnsignedLong(buf[off++])) << 24; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 16; - values[i + 7] |= Byte.toUnsignedLong(buf[off++]) << 8; - values[i + 7] |= Byte.toUnsignedLong(buf[off]); - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/BytesCompactCompressedHashIterator.java b/src/main/java/org/apache/datasketches/theta/BytesCompactCompressedHashIterator.java deleted file mode 100644 index 5b8e97be7..000000000 --- a/src/main/java/org/apache/datasketches/theta/BytesCompactCompressedHashIterator.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -/* - * This is to uncompress serial version 4 sketch incrementally - */ -final class BytesCompactCompressedHashIterator implements HashIterator { - private byte[] bytes; - private int offset; - private int entryBits; - private int numEntries; - private int index; - private long previous; - private int offsetBits; - private long[] buffer; - private boolean isBlockMode; - - BytesCompactCompressedHashIterator( - final byte[] bytes, - final int offset, - final int entryBits, - final int numEntries - ) { - this.bytes = bytes; - this.offset = offset; - this.entryBits = entryBits; - this.numEntries = numEntries; - index = -1; - previous = 0; - offsetBits = 0; - buffer = new long[8]; - isBlockMode = numEntries >= 8; - } - - @Override - public long get() { - return buffer[index & 7]; - } - - @Override - public boolean next() { - if (++index == numEntries) { return false; } - if (isBlockMode) { - if ((index & 7) == 0) { - if (numEntries - index >= 8) { - unpack8(); - } else { - isBlockMode = false; - unpack1(); - } - } - } else { - unpack1(); - } - return true; - } - - private void unpack1() { - final int i = index & 7; - BitPacking.unpackBits(buffer, i, entryBits, bytes, offset, offsetBits); - offset += (offsetBits + entryBits) >>> 3; - offsetBits = (offsetBits + entryBits) & 7; - buffer[i] += previous; - previous = buffer[i]; - } - - private void unpack8() { - BitPacking.unpackBitsBlock8(buffer, 0, bytes, offset, entryBits); - offset += entryBits; - for (int i = 0; i < 8; i++) { - buffer[i] += previous; - previous = buffer[i]; - } - } -} diff --git a/src/main/java/org/apache/datasketches/theta/BytesCompactHashIterator.java b/src/main/java/org/apache/datasketches/theta/BytesCompactHashIterator.java deleted file mode 100644 index cd880de17..000000000 --- a/src/main/java/org/apache/datasketches/theta/BytesCompactHashIterator.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import org.apache.datasketches.common.ByteArrayUtil; - -/* - * This is to iterate over serial version 3 sketch representation - */ -final class BytesCompactHashIterator implements HashIterator { - final private byte[] bytes; - final private int offset; - final private int numEntries; - private int index; - - BytesCompactHashIterator( - final byte[] bytes, - final int offset, - final int numEntries - ) { - this.bytes = bytes; - this.offset = offset; - this.numEntries = numEntries; - index = -1; - } - - @Override - public long get() { - return ByteArrayUtil.getLongLE(bytes, offset + index * Long.BYTES); - } - - @Override - public boolean next() { - return ++index < numEntries; - } -} diff --git a/src/main/java/org/apache/datasketches/theta/CompactOperations.java b/src/main/java/org/apache/datasketches/theta/CompactOperations.java deleted file mode 100644 index 46d2d7e7e..000000000 --- a/src/main/java/org/apache/datasketches/theta/CompactOperations.java +++ /dev/null @@ -1,382 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.theta.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.LG_NOM_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.ORDERED_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.READ_ONLY_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.SER_VER; -import static org.apache.datasketches.theta.PreambleUtil.SINGLEITEM_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.checkSegPreambleCap; -import static org.apache.datasketches.theta.PreambleUtil.extractCurCount; -import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.extractFlags; -import static org.apache.datasketches.theta.PreambleUtil.extractLgArrLongs; -import static org.apache.datasketches.theta.PreambleUtil.extractSeedHash; -import static org.apache.datasketches.theta.PreambleUtil.extractSerVer; -import static org.apache.datasketches.theta.PreambleUtil.extractThetaLong; -import static org.apache.datasketches.theta.PreambleUtil.insertCurCount; -import static org.apache.datasketches.theta.PreambleUtil.insertFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.insertFlags; -import static org.apache.datasketches.theta.PreambleUtil.insertP; -import static org.apache.datasketches.theta.PreambleUtil.insertPreLongs; -import static org.apache.datasketches.theta.PreambleUtil.insertSeedHash; -import static org.apache.datasketches.theta.PreambleUtil.insertSerVer; -import static org.apache.datasketches.theta.PreambleUtil.insertThetaLong; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; - -/** - * @author Lee Rhodes - */ -final class CompactOperations { - - private CompactOperations() {} - - static CompactThetaSketch componentsToCompact( //No error checking - final long thetaLong, - final int curCount, - final short seedHash, - final boolean srcEmpty, - final boolean srcCompact, - final boolean srcOrdered, - final boolean dstOrdered, - final MemorySegment dstWSeg, - final long[] hashArr) //may not be compacted, ordered or unordered, may be null - { - final boolean direct = dstWSeg != null; - final boolean empty = srcEmpty || ((curCount == 0) && (thetaLong == Long.MAX_VALUE)); - final boolean single = (curCount == 1) && (thetaLong == Long.MAX_VALUE); - final long[] hashArrOut; - if (!srcCompact) { - hashArrOut = CompactOperations.compactCache(hashArr, curCount, thetaLong, dstOrdered); - } else { - hashArrOut = hashArr; - } - if (!srcOrdered && dstOrdered && !empty && !single) { - Arrays.sort(hashArrOut); - } - //Note: for empty or single we always output the ordered form. - final boolean dstOrderedOut = (empty || single) ? true : dstOrdered; - if (direct) { - final int preLongs = computeCompactPreLongs(empty, curCount, thetaLong); - int flags = READ_ONLY_FLAG_MASK | COMPACT_FLAG_MASK; //always LE - flags |= empty ? EMPTY_FLAG_MASK : 0; - flags |= dstOrderedOut ? ORDERED_FLAG_MASK : 0; - flags |= single ? SINGLEITEM_FLAG_MASK : 0; - - final MemorySegment seg = - loadCompactMemorySegment(hashArrOut, seedHash, curCount, thetaLong, dstWSeg, (byte)flags, preLongs); - return new DirectCompactSketch(seg); - - } else { //Heap - if (empty) { - return EmptyCompactSketch.getInstance(); - } - if (single) { - return new SingleItemSketch(hashArrOut[0], seedHash); - } - return new HeapCompactSketch(hashArrOut, empty, seedHash, curCount, thetaLong, dstOrderedOut); - } - } - - /** - * Heapify or convert a source ThetaSketch MemorySegment image into a heap or target MemorySegment CompactThetaSketch. - * This assumes hashSeed is OK; serVer = 3. - * @param srcSeg the given input source MemorySegment image. Can be Read Only. - * @param dstOrdered the desired ordering of the resulting CompactThetaSketch - * @param dstWSeg Used for the target CompactThetaSketch if it is MemorySegment-based. Must be Writable. - * If null, return on-heap. - * @return a CompactThetaSketch of the correct form. - */ - @SuppressWarnings("unused") - static CompactThetaSketch segmentToCompact( - final MemorySegment srcSeg, - final boolean dstOrdered, - final MemorySegment dstWSeg) - { - //extract Pre0 fields and Flags from srcMem - final int srcPreLongs = checkSegPreambleCap(srcSeg); - final int srcSerVer = extractSerVer(srcSeg); //not used - final int srcFamId = extractFamilyID(srcSeg); - final int srcLgArrLongs = extractLgArrLongs(srcSeg); - final int srcFlags = extractFlags(srcSeg); - final short srcSeedHash = (short) extractSeedHash(srcSeg); - - //srcFlags - final boolean srcReadOnlyFlag = (srcFlags & READ_ONLY_FLAG_MASK) > 0; - final boolean srcEmptyFlag = (srcFlags & EMPTY_FLAG_MASK) > 0; - final boolean srcCompactFlag = (srcFlags & COMPACT_FLAG_MASK) > 0; - final boolean srcOrderedFlag = (srcFlags & ORDERED_FLAG_MASK) > 0; - final boolean srcSingleFlag = (srcFlags & SINGLEITEM_FLAG_MASK) > 0; - - final boolean single = srcSingleFlag - || SingleItemSketch.checkForSingleItem(srcPreLongs, srcSerVer, srcFamId, srcFlags); - - //extract pre1 and pre2 fields - final int curCount = single ? 1 : (srcPreLongs > 1) ? extractCurCount(srcSeg) : 0; - final long thetaLong = (srcPreLongs > 2) ? extractThetaLong(srcSeg) : Long.MAX_VALUE; - - //do some basic checks ... - if (srcEmptyFlag) { assert (curCount == 0) && (thetaLong == Long.MAX_VALUE); } - if (single) { assert (curCount == 1) && (thetaLong == Long.MAX_VALUE); } - checkFamilyAndFlags(srcFamId, srcCompactFlag, srcReadOnlyFlag); - - //dispatch empty and single cases - //Note: for empty and single we always output the ordered form. - final boolean dstOrderedOut = (srcEmptyFlag || single) ? true : dstOrdered; - if (srcEmptyFlag) { - if (dstWSeg != null) { - MemorySegment.copy(EmptyCompactSketch.EMPTY_COMPACT_SKETCH_ARR, 0, dstWSeg, JAVA_BYTE, 0, 8); - return new DirectCompactSketch(dstWSeg); - } else { - return EmptyCompactSketch.getInstance(); - } - } - if (single) { - final long hash = srcSeg.get(JAVA_LONG_UNALIGNED, srcPreLongs << 3); - final SingleItemSketch sis = new SingleItemSketch(hash, srcSeedHash); - if (dstWSeg != null) { - MemorySegment.copy(sis.toByteArray(), 0, dstWSeg, JAVA_BYTE, 0, 16); - return new DirectCompactSketch(dstWSeg); - } else { //heap - return sis; - } - } - - //extract hashArr > 1 - final long[] hashArr; - if (srcCompactFlag) { - hashArr = new long[curCount]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, srcPreLongs << 3, hashArr, 0, curCount); - } else { //update sketch, thus hashTable form - final int srcCacheLen = 1 << srcLgArrLongs; - final long[] tempHashArr = new long[srcCacheLen]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, srcPreLongs << 3, tempHashArr, 0, srcCacheLen); - hashArr = compactCache(tempHashArr, curCount, thetaLong, dstOrderedOut); - } - - final int flagsOut = READ_ONLY_FLAG_MASK | COMPACT_FLAG_MASK - | ((dstOrderedOut) ? ORDERED_FLAG_MASK : 0); - - //load the destination. - if (dstWSeg != null) { - final MemorySegment tgtSeg = loadCompactMemorySegment(hashArr, srcSeedHash, curCount, thetaLong, dstWSeg, - (byte)flagsOut, srcPreLongs); - return new DirectCompactSketch(tgtSeg); - } else { //heap - return new HeapCompactSketch(hashArr, srcEmptyFlag, srcSeedHash, curCount, thetaLong, - dstOrderedOut); - } - } - - private static void checkFamilyAndFlags( - final int srcFamId, - final boolean srcCompactFlag, - final boolean srcReadOnlyFlag) { - final Family srcFamily = Family.idToFamily(srcFamId); - if (srcCompactFlag) { - if ((srcFamily == Family.COMPACT) && srcReadOnlyFlag) { return; } - } else if ((srcFamily == Family.ALPHA) || (srcFamily == Family.QUICKSELECT)) { return; } - throw new SketchesArgumentException( - "Possible Corruption: Family does not match flags: Family: " - + srcFamily.toString() - + ", Compact Flag: " + srcCompactFlag - + ", ReadOnly Flag: " + srcReadOnlyFlag); - } - - //All arguments must be valid and correct including flags. - // Used as helper to create byte arrays as well as loading MemorySegment for direct compact sketches - //Input must be writable, return can be Read Only - static MemorySegment loadCompactMemorySegment( - final long[] compactHashArr, - final short seedHash, - final int curCount, - final long thetaLong, - final MemorySegment dstWSeg, - final byte flags, - final int preLongs) - { - assert (dstWSeg != null) && (compactHashArr != null); - final int outLongs = preLongs + curCount; - final int outBytes = outLongs << 3; - final int dstBytes = (int) dstWSeg.byteSize(); - if (outBytes > dstBytes) { - throw new SketchesArgumentException("Insufficient Space in MemorySegment: " + dstBytes - + ", Need: " + outBytes); - } - final byte famID = (byte) Family.COMPACT.getID(); - - //It is important to make sure that all byte fields are initialized, even those that are not used by the CompactThetaSketch. - // Otherwise, uninitialized fields could could cause other problems downstream. - // As written below, all fields are initialized. - - //The first 8 bytes (pre0) - insertPreLongs(dstWSeg, preLongs); //RF not used = 0 - insertSerVer(dstWSeg, SER_VER); - insertFamilyID(dstWSeg, famID); - //The following initializes the lgNomLongs and lgArrLongs to 0. - //They are not used in CompactThetaSketches. - dstWSeg.set(JAVA_SHORT_UNALIGNED, LG_NOM_LONGS_BYTE, (short)0); - insertFlags(dstWSeg, flags); - insertSeedHash(dstWSeg, seedHash); - - if ((preLongs == 1) && (curCount == 1)) { //singleItem, theta = 1.0 - dstWSeg.set(JAVA_LONG_UNALIGNED, 8, compactHashArr[0]); - return dstWSeg; - } - if (preLongs > 1) { - insertCurCount(dstWSeg, curCount); - insertP(dstWSeg, (float) 0.0); //0.0 to be consistent with C++ - } - if (preLongs > 2) { - insertThetaLong(dstWSeg, thetaLong); - } - if (curCount > 0) { //theta could be < 1.0. - MemorySegment.copy(compactHashArr, 0, dstWSeg, JAVA_LONG_UNALIGNED, preLongs << 3, curCount); - } - return dstWSeg; //if prelongs == 3 & curCount == 0, theta could be < 1.0. This can be read-only - } - - /** - * Copies then compacts, cleans, and may sort the resulting array. - * The source cache can be a hash table with interstitial zeros or - * "dirty" values, which are hash values greater than theta. - * These can be generated by the Alpha sketch. - * @param srcCache anything - * @param curCount must be correct - * @param thetaLong The correct - * thetaLong. - * @param dstOrdered true if output array must be sorted - * @return the compacted array. - */ - static long[] compactCache(final long[] srcCache, final int curCount, - final long thetaLong, final boolean dstOrdered) { - if (curCount == 0) { - return new long[0]; - } - final long[] cacheOut = new long[curCount]; - final int len = srcCache.length; - int j = 0; - for (int i = 0; i < len; i++) { //scan the full srcCache - final long v = srcCache[i]; - if ((v <= 0L) || (v >= thetaLong) ) { continue; } //ignoring zeros or dirty values - cacheOut[j++] = v; - } - if (j < curCount) { - throw new SketchesStateException( - "Possible Corruption: curCount parameter is incorrect."); - } - if (dstOrdered && (curCount > 1)) { - Arrays.sort(cacheOut); - } - return cacheOut; - } - - /* - * The truth table for empty, curCount and theta when compacting is as follows: - *
-   * Num Theta CurCount Empty State    Name, Comments
-   *  0    1.0     0      T     OK     EMPTY: The Normal Empty State
-   *  1    1.0     0      F   Internal This can occur internally as the result of an intersection of two exact,
-   *                                   disjoint sets, or ThetaAnotB of two exact, identical sets. There is no probability
-   *                                   distribution, so this is converted internally to EMPTY {1.0, 0, T}.
-   *                                   This is handled in ThetaSetOperation.createCompactThetaSketch().
-   *  2    1.0    !0      T   Error    Empty=T and curCount !0 should never coexist.
-   *                                   This is checked in all compacting operations.
-   *  3    1.0    !0      F     OK     EXACT: This corresponds to a sketch in exact mode
-   *  4   <1.0     0      T   Internal This can be an initial UpdatableThetaSketch state if p < 1.0,
-   *                                   so change theta to 1.0. Return {Th = 1.0, 0, T}.
-   *                                   This is handled in UpdatableThetaSketch.compact() and toByteArray().
-   *  5   <1.0     0      F     OK     This can result from set operations
-   *  6   <1.0    !0      T   Error    Empty=T and curCount !0 should never coexist.
-   *                                   This is checked in all compacting operations.
-   *  7   <1.0    !0      F     OK     This corresponds to a sketch in estimation mode
-   * 
- * #4 is handled by correctThetaOnCompact(boolean, int) (below). - * #2 & #6 handled by checkIllegalCurCountAndEmpty(boolean, int) - */ - - /** - * This corrects a temporary anomalous condition where compact() or toByteArray() is called on an UpdatableThetaSketch - * that was initialized with p < 1.0 and update() was never called. In this case Theta < 1.0, - * curCount = 0, and empty = true. The correction is to change Theta to 1.0, which makes the - * returning sketch empty. This should only be used in the compaction or serialization of an - * UpdatableThetaSketch. - * @param empty the given empty state - * @param curCount the given curCount - * @param thetaLong the given thetaLong - * @return thetaLong - */ - static long correctThetaOnCompact(final boolean empty, final int curCount, - final long thetaLong) { //handles #4 above - return (empty && (curCount == 0)) ? Long.MAX_VALUE : thetaLong; - } - - /** - * This checks for the illegal condition where curCount > 0 and the state of - * empty = true. This check can be used anywhere a sketch is returned or a sketch is created - * from complete arguments. - * @param empty the given empty state - * @param curCount the given current count - */ //This handles #2 and #6 above - static void checkIllegalCurCountAndEmpty(final boolean empty, final int curCount) { - if (empty && curCount != 0) { //this handles #2 and #6 above - throw new SketchesStateException("Possible corruption. Illegal State: Empty=true and Current Count != 0."); - } - } - - /** - * This compute number of preamble longs for a compact sketch based on empty, - * curCount and thetaLong. - * This also accommodates for EmptyCompactThetaSketch and SingleItemThetaSketch. - * @param empty The given empty state - * @param curCount The given current count (retained entries) - * @param thetaLong the current thetaLong - * @return the number of preamble longs - */ - static int computeCompactPreLongs(final boolean empty, final int curCount, - final long thetaLong) { - return (thetaLong < Long.MAX_VALUE) ? 3 : empty ? 1 : (curCount > 1) ? 2 : 1; - } - - /** - * This checks for the singleItem CompactThetaSketch. - * @param empty the given empty state - * @param curCount the given curCount - * @param thetaLong the given thetaLong - * @return true if notEmpty, curCount = 1 and theta = 1.0; - */ - static boolean isSingleItem(final boolean empty, final int curCount, - final long thetaLong) { - return !empty && (curCount == 1) && (thetaLong == Long.MAX_VALUE); - } -} - diff --git a/src/main/java/org/apache/datasketches/theta/CompactThetaSketch.java b/src/main/java/org/apache/datasketches/theta/CompactThetaSketch.java deleted file mode 100644 index 5b784469c..000000000 --- a/src/main/java/org/apache/datasketches/theta/CompactThetaSketch.java +++ /dev/null @@ -1,436 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.common.Family.idToFamily; -import static org.apache.datasketches.theta.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.FLAGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.ORDERED_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.READ_ONLY_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.extractEntryBitsV4; -import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.extractFlags; -import static org.apache.datasketches.theta.PreambleUtil.extractNumEntriesBytesV4; -import static org.apache.datasketches.theta.PreambleUtil.extractSeedHash; -import static org.apache.datasketches.theta.PreambleUtil.extractSerVer; -import static org.apache.datasketches.theta.PreambleUtil.extractThetaLongV4; -import static org.apache.datasketches.theta.PreambleUtil.wholeBytesToHoldBits; -import static org.apache.datasketches.theta.SingleItemSketch.checkForSingleItem; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; - -/** - * The parent class of all the CompactThetaSketches. CompactThetaSketches are never created directly. - * They are created as a result of the compact() method of an UpdatableThetaSketch, a result of a - * getResult() of a ThetaSetOperation, or from a heapify method. - * - *

A CompactThetaSketch is the simplest form of a ThetaSketches. It consists of a compact list - * (i.e., no intervening spaces) of hash values, which may be ordered or not, a value for theta - * and a seed hash. A CompactThetaSketch is immutable (read-only), - * and the space required when stored is only the space required for the hash values and 8 to 24 - * bytes of preamble. An empty CompactThetaSketch consumes only 8 bytes.

- * - * @author Lee Rhodes - */ -public abstract class CompactThetaSketch extends ThetaSketch { - - /** - * No argument constructor. - */ - public CompactThetaSketch() { } - - /** - * Heapify takes a CompactThetaSketch image in a MemorySegment and instantiates an on-heap CompactThetaSketch. - * - *

The resulting sketch will not retain any link to the source MemorySegment and all of its data will be - * copied to the heap CompactThetaSketch.

- * - *

The {@link Util#DEFAULT_UPDATE_SEED DEFAULT_UPDATE_SEED} is assumed.

- * - * @param srcSeg an image of a CompactThetaSketch. - * @return a CompactThetaSketch on the heap. - */ - public static CompactThetaSketch heapify(final MemorySegment srcSeg) { - return heapify(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Heapify takes a CompactThetaSketch image in a MemorySegment and instantiates an on-heap CompactThetaSketch. - * - *

The resulting sketch will not retain any link to the source MemorySegment and all of its data will be - * copied to the heap CompactThetaSketch.

- * - *

This method checks if the given expectedSeed was used to create the source MemorySegment image.

- * - * @param srcSeg an image of a CompactThetaSketch that was created using the given expectedSeed. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See Update Hash Seed. - * @return a CompactThetaSketch on the heap. - */ - public static CompactThetaSketch heapify(final MemorySegment srcSeg, final long expectedSeed) { - final int serVer = extractSerVer(srcSeg); - final int familyID = extractFamilyID(srcSeg); - final Family family = idToFamily(familyID); - if (family != Family.COMPACT) { - throw new SketchesArgumentException("Corrupted: " + family + " is not Compact!"); - } - if (serVer == 4) { - return heapifyV4(srcSeg, expectedSeed); - } - if (serVer == 3) { - final int flags = extractFlags(srcSeg); - final boolean srcOrdered = (flags & ORDERED_FLAG_MASK) != 0; - final boolean empty = (flags & EMPTY_FLAG_MASK) != 0; - if (!empty) { PreambleUtil.checkSegmentSeedHash(srcSeg, expectedSeed); } - return CompactOperations.segmentToCompact(srcSeg, srcOrdered, null); - } - //not SerVer 3 or 4 - throw new SketchesArgumentException( - "Corrupted: Serialization Version " + serVer + " not recognized."); - } - - /** - * Wrap takes the CompactThetaSketch image in given MemorySegment and refers to it directly. - * There is no data copying onto the java heap. - * The wrap operation enables fast read-only merging and access to all the public read-only API. - * - *

Wrapping any subclass of this class that is empty or contains only a single item will - * result in heapified forms of empty and single item sketch respectively. - * This is actually faster and consumes less overall space.

- * - *

The {@link Util#DEFAULT_UPDATE_SEED DEFAULT_UPDATE_SEED} is assumed.

- * - * @param srcSeg an image of a CompactThetaSketch. - * @return a CompactThetaSketch backed by the given MemorySegment. - */ - public static CompactThetaSketch wrap(final MemorySegment srcSeg) { - return wrap(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Wrap takes the sketch image in the given MemorySegment and refers to it directly. - * There is no data copying onto the java heap. - * The wrap operation enables fast read-only merging and access to all the public read-only API. - * - *

Wrapping any subclass of this class that is empty or contains only a single item will - * result in heapified forms of empty and single item sketch respectively. - * This is actually faster and consumes less overall space.

- * - *

This method checks if the given expectedSeed was used to create the source MemorySegment image.

- * - * @param srcSeg an image of a CompactThetaSketch that was created using the given expectedSeed. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See Update Hash Seed. - * @return a CompactThetaketch backed by the given MemorySegment. - */ - public static CompactThetaSketch wrap(final MemorySegment srcSeg, final long expectedSeed) { - final int serVer = extractSerVer(srcSeg); - final int familyID = extractFamilyID(srcSeg); - final Family family = Family.idToFamily(familyID); - if (family != Family.COMPACT) { - throw new SketchesArgumentException("Corrupted: " + family + " is not Compact!"); - } - final short seedHash = Util.computeSeedHash(expectedSeed); - - - if (serVer == 3) { - if (PreambleUtil.isEmptyFlag(srcSeg)) { - return EmptyCompactSketch.getHeapInstance(srcSeg); - } - if (checkForSingleItem(srcSeg)) { - return SingleItemSketch.heapify(srcSeg, seedHash); - } - //not empty & not singleItem - final int flags = extractFlags(srcSeg); - final boolean compactFlag = (flags & COMPACT_FLAG_MASK) > 0; - if (!compactFlag) { - throw new SketchesArgumentException( - "Corrupted: COMPACT family sketch image must have compact flag set"); - } - final boolean readOnly = (flags & READ_ONLY_FLAG_MASK) > 0; - if (!readOnly) { - throw new SketchesArgumentException( - "Corrupted: COMPACT family sketch image must have Read-Only flag set"); - } - return DirectCompactSketch.wrapInstance(srcSeg, seedHash); - } - if (serVer == 4) { - return DirectCompactCompressedSketch.wrapInstance(srcSeg, seedHash); - } - //not SerVer 3 or 4 - throw new SketchesArgumentException( - "Corrupted: Serialization Version " + serVer + " not recognized."); - } - - /** - * Wrap takes the sketch image in the given byte array and refers to it directly. - * There is no data copying onto the java heap. - * The wrap operation enables fast read-only merging and access to all the public read-only API. - * - *

Only sketches that have been explicitly stored as direct sketches can be wrapped.

- * - *

Wrapping any subclass of this class that is empty or contains only a single item will - * result in heapified forms of empty and single item sketch respectively. - * This is actually faster and consumes less overall space.

- * - *

This method checks if the DEFAULT_UPDATE_SEED was used to create the source byte array image.

- * - * @param bytes a byte array image of a CompactThetaSketch that was created using the DEFAULT_UPDATE_SEED. - * - * @return a CompactThetaSketch backed by the given byte array except as above. - */ - public static CompactThetaSketch wrap(final byte[] bytes) { - return wrap(bytes, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Wrap takes the sketch image in the given byte array and refers to it directly. - * There is no data copying onto the java heap. - * The wrap operation enables fast read-only merging and access to all the public read-only API. - * - *

Only sketches that have been explicitly stored as direct sketches can be wrapped.

- * - *

Wrapping any subclass of this class that is empty or contains only a single item will - * result in heapified forms of empty and single item sketch respectively. - * This is actually faster and consumes less overall space.

- * - *

This method checks if the given expectedSeed was used to create the source byte array image.

- * - * @param bytes a byte array image of a CompactThetaSketch that was created using the given expectedSeed. - * @param expectedSeed the seed used to validate the given byte array image. - * See Update Hash Seed. - * @return a CompactThetaSketch backed by the given byte array except as above. - */ - public static CompactThetaSketch wrap(final byte[] bytes, final long expectedSeed) { - final int serVer = bytes[PreambleUtil.SER_VER_BYTE]; - final int familyId = bytes[PreambleUtil.FAMILY_BYTE]; - final Family family = Family.idToFamily(familyId); - if (family != Family.COMPACT) { - throw new SketchesArgumentException("Corrupted: " + family + " is not Compact!"); - } - final short seedHash = Util.computeSeedHash(expectedSeed); - - if (serVer == 3) { - final int flags = bytes[FLAGS_BYTE]; - if ((flags & EMPTY_FLAG_MASK) > 0) { - return EmptyCompactSketch.getHeapInstance(MemorySegment.ofArray(bytes)); - } - final int preLongs = bytes[PREAMBLE_LONGS_BYTE]; - if (checkForSingleItem(preLongs, serVer, familyId, flags)) { - return SingleItemSketch.heapify(MemorySegment.ofArray(bytes), seedHash); - } - //not empty & not singleItem - final boolean compactFlag = (flags & COMPACT_FLAG_MASK) > 0; - if (!compactFlag) { - throw new SketchesArgumentException( - "Corrupted: COMPACT family sketch image must have compact flag set"); - } - final boolean readOnly = (flags & READ_ONLY_FLAG_MASK) > 0; - if (!readOnly) { - throw new SketchesArgumentException( - "Corrupted: COMPACT family sketch image must have Read-Only flag set"); - } - return WrappedCompactSketch.wrapInstance(bytes, seedHash); - } - if (serVer ==4) { - return WrappedCompactCompressedSketch.wrapInstance(bytes, seedHash); - } - //not SerVer 3 or 4 - throw new SketchesArgumentException( - "Corrupted: Serialization Version " + serVer + " not recognized."); - } - - //ThetaSketch Overrides - - @Override - public abstract CompactThetaSketch compact(final boolean dstOrdered, final MemorySegment dstSeg); - - @Override - public int getCompactBytes() { - return getCurrentBytes(); - } - - @Override - int getCurrentDataLongs() { - return getRetainedEntries(true); - } - - @Override - public Family getFamily() { - return Family.COMPACT; - } - - @Override - public boolean hasMemorySegment() { - return ((this instanceof DirectCompactSketch) && ((DirectCompactSketch)this).hasMemorySegment()); - } - - @Override - public boolean isCompact() { - return true; - } - - @Override - public boolean isOffHeap() { - return ((this instanceof DirectCompactSketch) && ((DirectCompactSketch)this).isOffHeap()); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return ((this instanceof DirectCompactSketch) && ((DirectCompactSketch)this).isSameResource(that)); - } - - @Override - public double getEstimate() { - return ThetaSketch.estimate(getThetaLong(), getRetainedEntries()); - } - - /** - * gets the sketch as a compressed byte array - * @return the sketch as a compressed byte array - */ - public byte[] toByteArrayCompressed() { - if (!isOrdered() || (getRetainedEntries() == 0) || ((getRetainedEntries() == 1) && !isEstimationMode())) { - return toByteArray(); - } - return toByteArrayV4(); - } - - private int computeMinLeadingZeros() { - // compression is based on leading zeros in deltas between ordered hash values - // assumes ordered sketch - long previous = 0; - long ored = 0; - final HashIterator it = iterator(); - while (it.next()) { - final long delta = it.get() - previous; - ored |= delta; - previous = it.get(); - } - return Long.numberOfLeadingZeros(ored); - } - - private byte[] toByteArrayV4() { - final int preambleLongs = isEstimationMode() ? 2 : 1; - final int entryBits = 64 - computeMinLeadingZeros(); - final int compressedBits = entryBits * getRetainedEntries(); - - // store num_entries as whole bytes since whole-byte blocks will follow (most probably) - final int numEntriesBytes = wholeBytesToHoldBits(32 - Integer.numberOfLeadingZeros(getRetainedEntries())); - - final int sizeBytes = (preambleLongs * Long.BYTES) + numEntriesBytes + wholeBytesToHoldBits(compressedBits); - final byte[] bytes = new byte[sizeBytes]; - final MemorySegment wseg = MemorySegment.ofArray(bytes); - int offsetBytes = 0; - wseg.set(JAVA_BYTE, offsetBytes++, (byte) preambleLongs); - wseg.set(JAVA_BYTE, offsetBytes++, (byte) 4); // to do: add constant - wseg.set(JAVA_BYTE, offsetBytes++, (byte) Family.COMPACT.getID()); - wseg.set(JAVA_BYTE, offsetBytes++, (byte) entryBits); - wseg.set(JAVA_BYTE, offsetBytes++, (byte) numEntriesBytes); - wseg.set(JAVA_BYTE, offsetBytes++, (byte) (COMPACT_FLAG_MASK | READ_ONLY_FLAG_MASK | ORDERED_FLAG_MASK)); - wseg.set(JAVA_SHORT_UNALIGNED, offsetBytes, getSeedHash()); - offsetBytes += Short.BYTES; - if (isEstimationMode()) { - wseg.set(JAVA_LONG_UNALIGNED, offsetBytes, getThetaLong()); - offsetBytes += Long.BYTES; - } - int numEntries = getRetainedEntries(); - for (int i = 0; i < numEntriesBytes; i++) { - wseg.set(JAVA_BYTE, offsetBytes++, (byte) (numEntries & 0xff)); - numEntries >>>= 8; - } - long previous = 0; - final long[] deltas = new long[8]; - final HashIterator it = iterator(); - int i; - for (i = 0; (i + 7) < getRetainedEntries(); i += 8) { - for (int j = 0; j < 8; j++) { - it.next(); - deltas[j] = it.get() - previous; - previous = it.get(); - } - BitPacking.packBitsBlock8(deltas, 0, bytes, offsetBytes, entryBits); - offsetBytes += entryBits; - } - int offsetBits = 0; - for (; i < getRetainedEntries(); i++) { - it.next(); - final long delta = it.get() - previous; - previous = it.get(); - BitPacking.packBits(delta, entryBits, bytes, offsetBytes, offsetBits); - offsetBytes += (offsetBits + entryBits) >>> 3; - offsetBits = (offsetBits + entryBits) & 7; - } - return bytes; - } - - private static CompactThetaSketch heapifyV4(final MemorySegment srcSeg, final long seed) { - final int preLongs = ThetaSketch.getPreambleLongs(srcSeg); - final int entryBits = extractEntryBitsV4(srcSeg); - final int numEntriesBytes = extractNumEntriesBytesV4(srcSeg); - final short seedHash = (short) extractSeedHash(srcSeg); - PreambleUtil.checkSegmentSeedHash(srcSeg, seed); - int offsetBytes = 8; - long theta = Long.MAX_VALUE; - if (preLongs > 1) { - theta = extractThetaLongV4(srcSeg); - offsetBytes += Long.BYTES; - } - int numEntries = 0; - for (int i = 0; i < numEntriesBytes; i++) { - numEntries |= Byte.toUnsignedInt(srcSeg.get(JAVA_BYTE, offsetBytes++)) << (i << 3); - } - final long[] entries = new long[numEntries]; - final byte[] bytes = new byte[entryBits]; // temporary buffer for unpacking - int i; - for (i = 0; (i + 7) < numEntries; i += 8) { - MemorySegment.copy(srcSeg, JAVA_BYTE, offsetBytes, bytes, 0, entryBits); - BitPacking.unpackBitsBlock8(entries, i, bytes, 0, entryBits); - offsetBytes += entryBits; - } - if (i < numEntries) { - MemorySegment.copy(srcSeg, JAVA_BYTE, offsetBytes, bytes, 0, wholeBytesToHoldBits((numEntries - i) * entryBits)); - int offsetBits = 0; - offsetBytes = 0; - for (; i < numEntries; i++) { - BitPacking.unpackBits(entries, i, entryBits, bytes, offsetBytes, offsetBits); - offsetBytes += (offsetBits + entryBits) >>> 3; - offsetBits = (offsetBits + entryBits) & 7; - } - } - // undo deltas - long previous = 0; - for (i = 0; i < numEntries; i++) { - entries[i] += previous; - previous = entries[i]; - } - return new HeapCompactSketch(entries, false, seedHash, numEntries, theta, true); - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/ConcurrentBackgroundThetaPropagation.java b/src/main/java/org/apache/datasketches/theta/ConcurrentBackgroundThetaPropagation.java deleted file mode 100644 index c12f8aa4e..000000000 --- a/src/main/java/org/apache/datasketches/theta/ConcurrentBackgroundThetaPropagation.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Background propagation thread. Propagates a given sketch or a hash value from local threads - * buffers into the shared sketch which stores the most up-to-date estimation of number of unique - * items. This propagation is done at the background by dedicated threads, which allows - * application threads to continue updating their local buffer. - * - * @author eshcar - */ -final class ConcurrentBackgroundThetaPropagation implements Runnable { - - // Shared sketch to absorb the data - private final ConcurrentSharedThetaSketch sharedThetaSketch; - - // Propagation flag of local buffer that is being processed. - // It is the synchronization primitive to coordinate the work of the propagation with the - // local buffer. Updated when the propagation completes. - private final AtomicBoolean localPropagationInProgress; - - // ThetaSketch to be propagated to shared sketch. Can be null if only a single hash is propagated - private final ThetaSketch sketchIn; - - // Hash of the datum to be propagated to shared sketch. Can be ConcurrentSharedThetaSketch.NOT_SINGLE_HASH - // if the data is propagated through a sketch. - private final long singleHash; - - // The propagation epoch. The data can be propagated only within the context of this epoch. - // The data should not be propagated if this epoch is not equal to the - // shared sketch epoch. - private final long epoch; - - ConcurrentBackgroundThetaPropagation(final ConcurrentSharedThetaSketch sharedThetaSketch, - final AtomicBoolean localPropagationInProgress, final ThetaSketch sketchIn, final long singleHash, - final long epoch) { - this.sharedThetaSketch = sharedThetaSketch; - this.localPropagationInProgress = localPropagationInProgress; - this.sketchIn = sketchIn; - this.singleHash = singleHash; - this.epoch = epoch; - } - - /** - * Propagation protocol: - * 1) validate propagation is executed at the context of the right epoch, otherwise abort - * 2) handle propagation: either of a single hash or of a sketch - * 3) complete propagation: ping local buffer - */ - @Override - public void run() { - // 1) validate propagation is executed at the context of the right epoch, otherwise abort - if (!sharedThetaSketch.validateEpoch(epoch)) { - // invalid epoch - should not propagate - sharedThetaSketch.endPropagation(null, false); - return; - } - - // 2) handle propagation: either of a single hash or of a sketch - if (singleHash != ConcurrentSharedThetaSketch.NOT_SINGLE_HASH) { - sharedThetaSketch.propagate(singleHash); - } else if (sketchIn != null) { - final long volTheta = sharedThetaSketch.getVolatileTheta(); - assert volTheta <= sketchIn.getThetaLong() : - "volTheta = " + volTheta + ", bufTheta = " + sketchIn.getThetaLong(); - - // propagate values from input sketch one by one - final long[] cacheIn = sketchIn.getCache(); - - if (sketchIn.isOrdered()) { //Ordered compact, Use early stop - for (final long hashIn : cacheIn) { - if (hashIn >= volTheta) { - break; //early stop - } - sharedThetaSketch.propagate(hashIn); - } - } else { //not ordered, also may have zeros (gaps) in the array. - for (final long hashIn : cacheIn) { - if (hashIn > 0) { - sharedThetaSketch.propagate(hashIn); - } - } - } - } - - // 3) complete propagation: ping local buffer - sharedThetaSketch.endPropagation(localPropagationInProgress, false); - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/ConcurrentDirectQuickSelectSketch.java b/src/main/java/org/apache/datasketches/theta/ConcurrentDirectQuickSelectSketch.java deleted file mode 100644 index 5a0bbf22f..000000000 --- a/src/main/java/org/apache/datasketches/theta/ConcurrentDirectQuickSelectSketch.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.theta.PreambleUtil.THETA_LONG; - -import java.lang.foreign.MemorySegment; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SuppressFBWarnings; - -/** - * A concurrent shared sketch that is based on DirectQuickSelectSketch. - * It reflects all data processed by a single or multiple update threads, and can serve queries at - * any time. - * Background propagation threads are used to propagate data from thread local buffers into this - * sketch which stores the most up-to-date estimation of number of unique items. - * - * @author eshcar - * @author Lee Rhodes - */ -final class ConcurrentDirectQuickSelectSketch extends DirectQuickSelectSketch - implements ConcurrentSharedThetaSketch { - - // The propagation thread - private ExecutorService executorService_; - - // A flag to coordinate between several eager propagation threads - private final AtomicBoolean sharedPropagationInProgress_; - - // Theta value of concurrent sketch - private volatile long volatileThetaLong_; - - // A snapshot of the estimated number of unique entries - private volatile double volatileEstimate_; - - // Num of retained entries in which the sketch toggles from sync (exact) mode to async - // propagation mode - private final long exactLimit_; - - // An epoch defines an interval between two resets. A propagation invoked at epoch i cannot - // affect the sketch at epoch j > i. - private volatile long epoch_; - - /** - * Construct a new sketch instance and initialize the given MemorySegment as its backing store. - * - * @param lgNomLongs See lgNomLongs. - * @param seed See Update Hash Seed. - * @param maxConcurrencyError the max error value including error induced by concurrency. - * @param dstSeg the given MemorySegment object destination. It cannot be null. - */ - ConcurrentDirectQuickSelectSketch(final int lgNomLongs, final long seed, - final double maxConcurrencyError, final MemorySegment dstSeg) { - super(lgNomLongs, seed, 1.0F, //p - ResizeFactor.X1, //rf, - dstSeg, - null, - false); //unionGadget - - volatileThetaLong_ = Long.MAX_VALUE; - volatileEstimate_ = 0; - exactLimit_ = ConcurrentSharedThetaSketch.computeExactLimit(1L << getLgNomLongs(), - maxConcurrencyError); - sharedPropagationInProgress_ = new AtomicBoolean(false); - epoch_ = 0; - initBgPropagationService(); - } - - ConcurrentDirectQuickSelectSketch(final UpdatableThetaSketch sketch, final long seed, - final double maxConcurrencyError, final MemorySegment dstSeg) { - super(sketch.getLgNomLongs(), seed, 1.0F, //p - ResizeFactor.X1, //rf, - dstSeg, - null, - false); //unionGadget - - exactLimit_ = ConcurrentSharedThetaSketch.computeExactLimit(1L << getLgNomLongs(), - maxConcurrencyError); - sharedPropagationInProgress_ = new AtomicBoolean(false); - epoch_ = 0; - initBgPropagationService(); - for (final long hashIn : sketch.getCache()) { - propagate(hashIn); - } - wseg_.set(JAVA_LONG_UNALIGNED, THETA_LONG, sketch.getThetaLong()); - updateVolatileTheta(); - updateEstimationSnapshot(); - } - - //ThetaSketch overrides - - @Override - public double getEstimate() { - return volatileEstimate_; - } - - @Override - public boolean isEstimationMode() { - return getRetainedEntries(false) > exactLimit_ || super.isEstimationMode(); - } - - @Override - public byte[] toByteArray() { - while (!sharedPropagationInProgress_.compareAndSet(false, true)) { /* busy wait till free */ } - final byte[] res = super.toByteArray(); - sharedPropagationInProgress_.set(false); - return res; - } - - //UpdatableThetaSketch overrides - - @Override - public UpdatableThetaSketch rebuild() { - super.rebuild(); - updateEstimationSnapshot(); - return this; - } - - /** - * {@inheritDoc} - * Takes care of mutual exclusion with propagation thread. - */ - @Override - public void reset() { - advanceEpoch(); - super.reset(); - volatileThetaLong_ = Long.MAX_VALUE; - volatileEstimate_ = 0; - } - - @Override - UpdateReturnState hashUpdate(final long hash) { - final String msg = "No update method should be called directly to a shared theta sketch." - + " Updating the shared sketch is only permitted through propagation from local sketches."; - throw new UnsupportedOperationException(msg); - } - - //ConcurrentSharedThetaSketch declarations - - @Override - public long getExactLimit() { - return exactLimit_; - } - - @Override - public boolean startEagerPropagation() { - while (!sharedPropagationInProgress_.compareAndSet(false, true)) { /* busy wait till free */ } - return !isEstimationMode();// no eager propagation is allowed in estimation mode - } - - @Override - public void endPropagation(final AtomicBoolean localPropagationInProgress, final boolean isEager) { - //update volatile theta, uniques estimate and propagation flag - updateVolatileTheta(); - updateEstimationSnapshot(); - if (isEager) { - sharedPropagationInProgress_.set(false); - } - if (localPropagationInProgress != null) { - localPropagationInProgress.set(false); //clear local propagation flag - } - } - - @Override - public long getVolatileTheta() { - return volatileThetaLong_; - } - - @Override - public void awaitBgPropagationTermination() { - try { - executorService_.shutdown(); - while (!executorService_.awaitTermination(1, TimeUnit.MILLISECONDS)) { - Thread.sleep(1); - } - } catch (final InterruptedException e) { - e.printStackTrace(); - } - } - - @Override - public void initBgPropagationService() { - executorService_ = ConcurrentPropagationService.getExecutorService(Thread.currentThread().threadId()); - } - - @Override - public boolean propagate(final AtomicBoolean localPropagationInProgress, - final ThetaSketch sketchIn, final long singleHash) { - final long epoch = epoch_; - if (singleHash != NOT_SINGLE_HASH // namely, is a single hash and - && getRetainedEntries(false) < exactLimit_) { // a small sketch then propagate myself (blocking) - if (!startEagerPropagation()) { - endPropagation(localPropagationInProgress, true); - return false; - } - if (!validateEpoch(epoch)) { - endPropagation(null, true); // do not change local flag - return true; - } - propagate(singleHash); - endPropagation(localPropagationInProgress, true); - return true; - } - // otherwise, be nonblocking, let background thread do the work - final ConcurrentBackgroundThetaPropagation job = new ConcurrentBackgroundThetaPropagation( - this, localPropagationInProgress, sketchIn, singleHash, epoch); - executorService_.execute(job); - return true; - } - - @Override - public void propagate(final long singleHash) { - super.hashUpdate(singleHash); - } - - @Override - public void updateEstimationSnapshot() { - volatileEstimate_ = super.getEstimate(); - } - - @Override - public void updateVolatileTheta() { - volatileThetaLong_ = getThetaLong(); - } - - @Override - public boolean validateEpoch(final long epoch) { - return epoch_ == epoch; - } - - //Restricted - - /** - * Advances the epoch while there is no background propagation - * This ensures a propagation invoked before the reset cannot affect the sketch after the reset - * is completed. Ignore AT_NONATOMIC_OPERATIONS_ON_SHARED_VARIABLE and AT_NONATOMIC_OPERATIONS_ON_SHARED_VARIABLE - * SpotBugs warnings, they are False Positive. - */ - - @SuppressFBWarnings(value = {"AT_NONATOMIC_OPERATIONS_ON_SHARED_VARIABLE", "VO_VOLATILE_INCREMENT"}, - justification = "Likely False Positive, Fix Later") - private void advanceEpoch() { - awaitBgPropagationTermination(); - startEagerPropagation(); - ConcurrentPropagationService.resetExecutorService(Thread.currentThread().threadId()); - // this increment of a volatile field is done within the scope of the propagation - // synchronization and hence is done by a single thread. - epoch_++; - endPropagation(null, true); - initBgPropagationService(); - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/ConcurrentHeapQuickSelectSketch.java b/src/main/java/org/apache/datasketches/theta/ConcurrentHeapQuickSelectSketch.java deleted file mode 100644 index bc7876f10..000000000 --- a/src/main/java/org/apache/datasketches/theta/ConcurrentHeapQuickSelectSketch.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SuppressFBWarnings; - -/** - * A concurrent shared sketch that is based on HeapQuickSelectThetaSketch. - * It reflects all data processed by a single or multiple update threads, and can serve queries at - * any time. - * Background propagation threads are used to propagate data from thread local buffers into this - * sketch which stores the most up-to-date estimation of number of unique items. - * - * @author eshcar - * @author Lee Rhodes - */ -final class ConcurrentHeapQuickSelectSketch extends HeapQuickSelectSketch - implements ConcurrentSharedThetaSketch { - - // The propagation thread - private volatile ExecutorService executorService_; - - //A flag to coordinate between several eager propagation threads - private final AtomicBoolean sharedPropagationInProgress_; - - // Theta value of concurrent sketch - private volatile long volatileThetaLong_; - - // A snapshot of the estimated number of unique entries - private volatile double volatileEstimate_; - - // Num of retained entries in which the sketch toggles from sync (exact) mode to async - // propagation mode - private final long exactLimit_; - - // An epoch defines an interval between two resets. A propagation invoked at epoch i cannot - // affect the sketch at epoch j > i. - private volatile long epoch_; - - /** - * Construct a new sketch instance on the java heap. - * - * @param lgNomLongs See lgNomLongs. - * @param seed See seed - * @param maxConcurrencyError the max error value including error induced by concurrency - * - */ - ConcurrentHeapQuickSelectSketch(final int lgNomLongs, final long seed, - final double maxConcurrencyError) { - super(lgNomLongs, seed, 1.0F, //p - ResizeFactor.X1, //rf, - false); //unionGadget - - volatileThetaLong_ = Long.MAX_VALUE; - volatileEstimate_ = 0; - exactLimit_ = ConcurrentSharedThetaSketch.computeExactLimit(1L << getLgNomLongs(), - maxConcurrencyError); - sharedPropagationInProgress_ = new AtomicBoolean(false); - epoch_ = 0; - initBgPropagationService(); - } - - ConcurrentHeapQuickSelectSketch(final UpdatableThetaSketch sketch, final long seed, - final double maxConcurrencyError) { - super(sketch.getLgNomLongs(), seed, 1.0F, //p - ResizeFactor.X1, //rf, - false); //unionGadget - - exactLimit_ = ConcurrentSharedThetaSketch.computeExactLimit(1L << getLgNomLongs(), - maxConcurrencyError); - sharedPropagationInProgress_ = new AtomicBoolean(false); - epoch_ = 0; - initBgPropagationService(); - for (final long hashIn : sketch.getCache()) { - propagate(hashIn); - } - thetaLong_ = sketch.getThetaLong(); - updateVolatileTheta(); - updateEstimationSnapshot(); - } - - //ThetaSketch overrides - - @Override - public double getEstimate() { - return volatileEstimate_; - } - - @Override - public boolean isEstimationMode() { - return (getRetainedEntries(false) > exactLimit_) || super.isEstimationMode(); - } - - @Override - public byte[] toByteArray() { - while (!sharedPropagationInProgress_.compareAndSet(false, true)) { /* busy wait till free */ } - final byte[] res = super.toByteArray(); - sharedPropagationInProgress_.set(false); - return res; - } - - //UpdatableThetaSketch overrides - - @Override - public UpdatableThetaSketch rebuild() { - super.rebuild(); - updateEstimationSnapshot(); - return this; - } - - /** - * {@inheritDoc} - * Takes care of mutual exclusion with propagation thread. - */ - @Override - public void reset() { - advanceEpoch(); - super.reset(); - volatileThetaLong_ = Long.MAX_VALUE; - volatileEstimate_ = 0; - } - - @Override - UpdateReturnState hashUpdate(final long hash) { - final String msg = "No update method should be called directly to a shared theta sketch." - + " Updating the shared sketch is only permitted through propagation from local sketches."; - throw new UnsupportedOperationException(msg); - } - - //ConcurrentSharedThetaSketch declarations - - @Override - public long getExactLimit() { - return exactLimit_; - } - - @Override - public boolean startEagerPropagation() { - while (!sharedPropagationInProgress_.compareAndSet(false, true)) { /* busy wait till free */ } - return (!isEstimationMode());// no eager propagation is allowed in estimation mode - } - - @Override - public void endPropagation(final AtomicBoolean localPropagationInProgress, final boolean isEager) { - //update volatile theta, uniques estimate and propagation flag - updateVolatileTheta(); - updateEstimationSnapshot(); - if (isEager) { - sharedPropagationInProgress_.set(false); - } - if (localPropagationInProgress != null) { - localPropagationInProgress.set(false); //clear local propagation flag - } - } - - @Override - public long getVolatileTheta() { - return volatileThetaLong_; - } - - @Override - public void awaitBgPropagationTermination() { - try { - executorService_.shutdown(); - while (!executorService_.awaitTermination(1, TimeUnit.MILLISECONDS)) { - Thread.sleep(1); - } - } catch (final InterruptedException e) { - e.printStackTrace(); - } - } - - @Override - public void initBgPropagationService() { - executorService_ = ConcurrentPropagationService.getExecutorService(Thread.currentThread().threadId()); - } - - @Override - public boolean propagate(final AtomicBoolean localPropagationInProgress, - final ThetaSketch sketchIn, final long singleHash) { - final long epoch = epoch_; - if ((singleHash != NOT_SINGLE_HASH) //namely, is a single hash and - && (getRetainedEntries(false) < exactLimit_)) { //a small sketch then propagate myself (blocking) - if (!startEagerPropagation()) { - endPropagation(localPropagationInProgress, true); - return false; - } - if (!validateEpoch(epoch)) { - endPropagation(null, true); // do not change local flag - return true; - } - propagate(singleHash); - endPropagation(localPropagationInProgress, true); - return true; - } - // otherwise, be nonblocking, let background thread do the work - final ConcurrentBackgroundThetaPropagation job = new ConcurrentBackgroundThetaPropagation( - this, localPropagationInProgress, sketchIn, singleHash, epoch); - executorService_.execute(job); - return true; - } - - @Override - public void propagate(final long singleHash) { - super.hashUpdate(singleHash); - } - - @Override - public void updateEstimationSnapshot() { - volatileEstimate_ = super.getEstimate(); - } - - @Override - public void updateVolatileTheta() { - volatileThetaLong_ = getThetaLong(); - } - - @Override - public boolean validateEpoch(final long epoch) { - return epoch_ == epoch; - } - - //Restricted - - /** - * Advances the epoch while there is no background propagation - * This ensures a propagation invoked before the reset cannot affect the sketch after the reset - * is completed. - */ - @SuppressFBWarnings(value = {"VO_VOLATILE_INCREMENT", "AT_NONATOMIC_OPERATIONS_ON_SHARED_VARIABLE"}, - justification = "Likely False Positive, Fix Later") - private void advanceEpoch() { - awaitBgPropagationTermination(); - startEagerPropagation(); - ConcurrentPropagationService.resetExecutorService(Thread.currentThread().threadId()); - // this increment of a volatile field is done within the scope of the propagation - // synchronization and hence is done by a single thread - // Ignore the SpotBugs warnings - epoch_++; - endPropagation(null, true); - initBgPropagationService(); - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/ConcurrentHeapThetaBuffer.java b/src/main/java/org/apache/datasketches/theta/ConcurrentHeapThetaBuffer.java deleted file mode 100644 index ffe831020..000000000 --- a/src/main/java/org/apache/datasketches/theta/ConcurrentHeapThetaBuffer.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.apache.datasketches.theta.UpdateReturnState.ConcurrentBufferInserted; -import static org.apache.datasketches.theta.UpdateReturnState.ConcurrentPropagated; -import static org.apache.datasketches.theta.UpdateReturnState.RejectedOverTheta; - -import java.lang.foreign.MemorySegment; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.thetacommon.HashOperations; - -/** - * This is a theta filtering, bounded size buffer that operates in the context of a single writing - * thread. When the buffer becomes full its content is propagated into the shared sketch, which - * may be on a different thread. The limit on the buffer size is configurable. A bound of size 1 - * allows the combination of buffers and shared sketch to maintain an error bound in real-time - * that is close to the error bound of a sequential theta sketch. Allowing larger buffer sizes - * enables amortization of the cost propagations and substantially improves overall system throughput. - * The error caused by the buffering is essentially a perspective of time and synchronization - * and not really a true error. At the end of a stream, after all the buffers have synchronized with - * the shared sketch, there is no additional error. - * Propagation is done either synchronously by the updating thread, or asynchronously by a - * background propagation thread. - * - *

This is a buffer, not a sketch, and it extends the HeapQuickSelectThetaSketch - * in order to leverage some of the sketch machinery to make its work simple. However, if this - * buffer receives a query, like getEstimate(), the correct answer does not come from the super - * HeapQuickSelectThetaSketch, which knows nothing about the concurrency relationship to the - * shared concurrent sketch, it must come from the shared concurrent sketch. As a result nearly all - * of the inherited sketch methods are redirected to the shared concurrent sketch. - * - * @author eshcar - * @author Lee Rhodes - */ -final class ConcurrentHeapThetaBuffer extends HeapQuickSelectSketch { - - // Shared sketch consisting of the global sample set and theta value. - private final ConcurrentSharedThetaSketch shared; - - // A flag indicating whether the shared sketch is in shared mode and requires eager propagation - // Initially this is true. Once it is set to false (estimation mode) it never flips back. - private volatile boolean isExactMode; - - // A flag to indicate if we expect the propagated data to be ordered - private final boolean propagateOrderedCompact; - - // Propagation flag is set to true while propagation is in progress (or pending). - // It is the synchronization primitive to coordinate the work with the propagation thread. - private final AtomicBoolean localPropagationInProgress; - - ConcurrentHeapThetaBuffer(final int lgNomLongs, final long seed, - final ConcurrentSharedThetaSketch shared, final boolean propagateOrderedCompact, - final int maxNumLocalThreads) { - super(computeLogBufferSize(lgNomLongs, shared.getExactLimit(), maxNumLocalThreads), - seed, 1.0F, //p - ResizeFactor.X1, //rf - false); //not a union gadget - - this.shared = shared; - isExactMode = true; - this.propagateOrderedCompact = propagateOrderedCompact; - localPropagationInProgress = new AtomicBoolean(false); - } - - private static int computeLogBufferSize(final int lgNomLongs, final long exactSize, - final int maxNumLocalBuffers) { - return Math.min(lgNomLongs, (int)Math.log(Math.sqrt(exactSize) / (2 * maxNumLocalBuffers))); - } - - //concurrent restricted methods - - /** - * Propagates a single hash value to the shared sketch - * - * @param hash to be propagated - */ - private boolean propagateToSharedSketch(final long hash) { - //no inspection StatementWithEmptyBody - while (localPropagationInProgress.get()) { /* busy wait until previous propagation completed */ } - localPropagationInProgress.set(true); - final boolean res = shared.propagate(localPropagationInProgress, null, hash); - //in this case the parent empty_ and curCount_ were not touched - thetaLong_ = shared.getVolatileTheta(); - return res; - } - - /** - * Propagates the content of the buffer as a sketch to the shared sketch - */ - private void propagateToSharedSketch() { - //no inspection StatementWithEmptyBody - while (localPropagationInProgress.get()) { /* busy wait until previous propagation completed */ } - - final CompactThetaSketch compactSketch = compact(propagateOrderedCompact, null); - localPropagationInProgress.set(true); - shared.propagate(localPropagationInProgress, compactSketch, - ConcurrentSharedThetaSketch.NOT_SINGLE_HASH); - super.reset(); - thetaLong_ = shared.getVolatileTheta(); - } - - //Public ThetaSketch overrides proxies to shared ConcurrentThetaSketch - - @Override - public int getCompactBytes() { - return shared.getCompactBytes(); - } - - @Override - public int getCurrentBytes() { - return shared.getCurrentBytes(); - } - - @Override - public double getEstimate() { - return shared.getEstimate(); - } - - @Override - public double getLowerBound(final int numStdDev) { - return shared.getLowerBound(numStdDev); - } - - @Override - public double getUpperBound(final int numStdDev) { - return shared.getUpperBound(numStdDev); - } - - @Override - public boolean hasMemorySegment() { - return shared.hasMemorySegment(); - } - - @Override - public boolean isOffHeap() { - return shared.isOffHeap(); - } - - @Override - public boolean isEmpty() { - return shared.isEmpty(); - } - - @Override - public boolean isEstimationMode() { - return shared.isEstimationMode(); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return shared.isSameResource(that); - } - - //End of proxies - - @Override - public byte[] toByteArray() { - throw new UnsupportedOperationException("Local theta buffer need not be serialized"); - } - - //Public UpdatableThetaSketch overrides - - @Override - public void reset() { - super.reset(); - isExactMode = true; - localPropagationInProgress.set(false); - } - - //Restricted UpdatableThetaSketch overrides - - /** - * Updates buffer with given hash value. - * Triggers propagation to shared sketch if buffer is full. - * - * @param hash the given input hash value. A hash of zero or Long.MAX_VALUE is ignored. - * A negative hash value will throw an exception. - * @return - * See Update Return State - */ - @Override - UpdateReturnState hashUpdate(final long hash) { - if (isExactMode) { - isExactMode = !shared.isEstimationMode(); - } - HashOperations.checkHashCorruption(hash); - if ((getHashTableThreshold() == 0) || isExactMode ) { - //The over-theta and zero test - if (HashOperations.continueCondition(getThetaLong(), hash)) { - return RejectedOverTheta; //signal that hash was rejected due to theta or zero. - } - if (propagateToSharedSketch(hash)) { - return ConcurrentPropagated; - } - } - final UpdateReturnState state = super.hashUpdate(hash); - if (isOutOfSpace(getRetainedEntries(true) + 1)) { - propagateToSharedSketch(); - return ConcurrentPropagated; - } - if (state == UpdateReturnState.InsertedCountIncremented) { - return ConcurrentBufferInserted; - } - return state; - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/ConcurrentPropagationService.java b/src/main/java/org/apache/datasketches/theta/ConcurrentPropagationService.java deleted file mode 100644 index aa422d2c5..000000000 --- a/src/main/java/org/apache/datasketches/theta/ConcurrentPropagationService.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.apache.datasketches.common.SuppressFBWarnings; - -/** - * Pool of threads to serve all propagation tasks in the system. - * - * @author Eshcar Hillel - */ -final class ConcurrentPropagationService { - - static int NUM_POOL_THREADS = 3; // Default: 3 threads - private static volatile ConcurrentPropagationService instance = null; // Singleton - private static ExecutorService[] propagationExecutorService = null; - - @SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Fix later") - private ConcurrentPropagationService() { - propagationExecutorService = new ExecutorService[NUM_POOL_THREADS]; - } - - //Factory: Get the singleton - private static ConcurrentPropagationService getInstance() { - if (instance == null) { - synchronized (ConcurrentPropagationService.class) { - if (instance == null) { - instance = new ConcurrentPropagationService(); //SpotBugs: SSD_DO_NOT_USE_INSTANCE_LOCK_ON_SHARED_STATIC_DATA - } - } - } - return instance; - } - - public static ExecutorService getExecutorService(final long id) { - return getInstance().initExecutorService((int) id % NUM_POOL_THREADS); - } - - @SuppressWarnings("static-access") - public static ExecutorService resetExecutorService(final long id) { - return getInstance().propagationExecutorService[(int) id % NUM_POOL_THREADS] = null; - } - - @SuppressWarnings("static-method") - private ExecutorService initExecutorService(final int i) { - if (propagationExecutorService[i] == null) { - propagationExecutorService[i] = Executors.newSingleThreadExecutor(); - } - return propagationExecutorService[i]; - } -} diff --git a/src/main/java/org/apache/datasketches/theta/ConcurrentSharedThetaSketch.java b/src/main/java/org/apache/datasketches/theta/ConcurrentSharedThetaSketch.java deleted file mode 100644 index eeb207d3c..000000000 --- a/src/main/java/org/apache/datasketches/theta/ConcurrentSharedThetaSketch.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import java.lang.foreign.MemorySegment; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.datasketches.common.MemorySegmentStatus; - -/** - * An internal interface to define the API of a concurrent shared theta sketch. - * It reflects all data processed by a single or multiple update threads, and can serve queries at - * any time. - * - * @author eshcar - */ -interface ConcurrentSharedThetaSketch extends MemorySegmentStatus { - - long NOT_SINGLE_HASH = -1L; - double MIN_ERROR = 0.0000001; - - static long computeExactLimit(final long k, final double error) { - return 2 * Math.min(k, (long) Math.ceil(1.0 / Math.pow(Math.max(error,MIN_ERROR), 2.0))); - } - - /** - * Returns flip point (number of updates) from exact to estimate mode. - * @return flip point from exact to estimate mode - */ - long getExactLimit(); - - /** - * Ensures mutual exclusion. No other thread can update the shared sketch while propagation is - * in progress - * @return true if eager propagation was started - */ - boolean startEagerPropagation(); - - /** - * Completes the propagation: end mutual exclusion block. - * Notifies the local thread the propagation is completed - * - * @param localPropagationInProgress the synchronization primitive through which propagator - * notifies local thread the propagation is completed - * @param isEager true if the propagation is in eager mode - */ - void endPropagation(AtomicBoolean localPropagationInProgress, boolean isEager); - - /** - * Returns the value of the volatile theta managed by the shared sketch - * @return the value of the volatile theta managed by the shared sketch - */ - long getVolatileTheta(); - - /** - * Awaits termination of background (lazy) propagation tasks - */ - void awaitBgPropagationTermination(); - - /** - * Init background (lazy) propagation service - */ - void initBgPropagationService(); - - /** - * (Eager) Propagates the given sketch or hash value into this sketch - * @param localPropagationInProgress the flag to be updated when propagation is done - * @param sketchIn any Theta sketch with the data - * @param singleHash a single hash value - * @return true if propagation successfully started - */ - boolean propagate(final AtomicBoolean localPropagationInProgress, final ThetaSketch sketchIn, - final long singleHash); - - /** - * (Lazy/Eager) Propagates the given hash value into this sketch - * @param singleHash a single hash value - */ - void propagate(final long singleHash); - - /** - * Updates the estimation of the number of unique entries by capturing a snapshot of the sketch - * data, namely, volatile theta and the num of valid entries in the sketch - */ - void updateEstimationSnapshot(); - - /** - * Updates the value of the volatile theta by extracting it from the underlying sketch managed - * by the shared sketch - */ - void updateVolatileTheta(); - - /** - * Validates the shared sketch is in the context of the given epoch - * - * @param epoch the epoch number to be validates - * @return true iff the shared sketch is in the context of the given epoch - */ - boolean validateEpoch(long epoch); - - //The following mirrors are public methods that already exist on the "extends" side of the dual - // inheritance. They are provided here to allow casts to this interface access - // to these methods without having to cast back to the extended parent class. - // - //This allows an internal class to cast either the Concurrent Direct or Concurrent Heap - //shared class to this interface and have access to the above special concurrent methods as - //well as the methods below. - // - //For the external user all of the below methods can be obtained by casting the shared - //sketch to UpdatableThetaSketch. However, these methods here also act as an alias so that an - //attempt to access these methods from the local buffer will be diverted to the shared - //sketch. - - //From ThetaSketch and MemoryStatus - - int getCompactBytes(); - - int getCurrentBytes(); - - double getEstimate(); - - double getLowerBound(int numStdDev); - - double getUpperBound(int numStdDev); - - boolean isEmpty(); - - boolean isEstimationMode(); - - byte[] toByteArray(); - - int getRetainedEntries(boolean valid); - - CompactThetaSketch compact(); - - CompactThetaSketch compact(boolean ordered, MemorySegment wseg); - - UpdatableThetaSketch rebuild(); - - void reset(); -} - diff --git a/src/main/java/org/apache/datasketches/theta/DirectCompactCompressedSketch.java b/src/main/java/org/apache/datasketches/theta/DirectCompactCompressedSketch.java deleted file mode 100644 index 9f37241d2..000000000 --- a/src/main/java/org/apache/datasketches/theta/DirectCompactCompressedSketch.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.extractEntryBitsV4; -import static org.apache.datasketches.theta.PreambleUtil.extractNumEntriesBytesV4; -import static org.apache.datasketches.theta.PreambleUtil.extractSeedHash; -import static org.apache.datasketches.theta.PreambleUtil.extractThetaLongV4; -import static org.apache.datasketches.theta.PreambleUtil.wholeBytesToHoldBits; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Util; - -/** - * An off-heap (Direct), compact, compressed, read-only sketch. It is not empty, not a single item and ordered. - * - *

This sketch can only be associated with a Serialization Version 4 format binary image.

- * - *

This implementation uses data in a given MemorySegment that is owned and managed by the caller. - * This MemorySegment can be off-heap, which if managed properly will greatly reduce the need for - * the JVM to perform garbage collection.

- */ -final class DirectCompactCompressedSketch extends DirectCompactSketch { - /** - * Construct this sketch with the given MemorySegment. - * @param seg Read-only MemorySegment object. - */ - DirectCompactCompressedSketch(final MemorySegment seg) { - super(seg); - } - - /** - * Wraps the given MemorySegment, which must be a SerVer 4 compressed CompactThetaSketch image. - * Must check the validity of the MemorySegment before calling. - * @param srcSeg The source MemorySegment - * @param seedHash The update seedHash. - * See Seed Hash. - * @return this sketch - */ - static DirectCompactCompressedSketch wrapInstance(final MemorySegment srcSeg, final short seedHash) { - Util.checkSeedHashes((short) extractSeedHash(srcSeg), seedHash); - return new DirectCompactCompressedSketch(srcSeg); - } - - //ThetaSketch Overrides - - @Override - public CompactThetaSketch compact(final boolean dstOrdered, final MemorySegment dstSeg) { - if (dstSeg != null) { - MemorySegment.copy(seg_, 0, dstSeg, 0, getCurrentBytes()); - return new DirectCompactSketch(dstSeg); - } - return CompactThetaSketch.heapify(seg_, Util.DEFAULT_UPDATE_SEED); - } - - @Override - public int getCurrentBytes() { - final int preLongs = ThetaSketch.getPreambleLongs(seg_); - final int entryBits = extractEntryBitsV4(seg_); - final int numEntriesBytes = extractNumEntriesBytesV4(seg_); - return preLongs * Long.BYTES + numEntriesBytes + wholeBytesToHoldBits(getRetainedEntries() * entryBits); - } - - private static final int START_PACKED_DATA_EXACT_MODE = 8; - private static final int START_PACKED_DATA_ESTIMATION_MODE = 16; - - @Override - public int getRetainedEntries(final boolean valid) { //valid is only relevant for the AlphaSketch - // number of entries is stored using variable length encoding - // most significant bytes with all zeros are not stored - // one byte in the preamble has the number of non-zero bytes used - final int preLongs = ThetaSketch.getPreambleLongs(seg_); // if > 1 then the second long has theta - final int numEntriesBytes = extractNumEntriesBytesV4(seg_); - int offsetBytes = preLongs > 1 ? START_PACKED_DATA_ESTIMATION_MODE : START_PACKED_DATA_EXACT_MODE; - int numEntries = 0; - for (int i = 0; i < numEntriesBytes; i++) { - numEntries |= Byte.toUnsignedInt(seg_.get(JAVA_BYTE, offsetBytes++)) << (i << 3); - } - return numEntries; - } - - @Override - public long getThetaLong() { - final int preLongs = ThetaSketch.getPreambleLongs(seg_); - return (preLongs > 1) ? extractThetaLongV4(seg_) : Long.MAX_VALUE; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public boolean isOrdered() { - return true; - } - - @Override - public HashIterator iterator() { - return new MemorySegmentCompactCompressedHashIterator( - seg_, - (ThetaSketch.getPreambleLongs(seg_) > 1 ? START_PACKED_DATA_ESTIMATION_MODE : START_PACKED_DATA_EXACT_MODE) - + extractNumEntriesBytesV4(seg_), - extractEntryBitsV4(seg_), - getRetainedEntries() - ); - } - - //restricted methods - - @Override - long[] getCache() { - final int numEntries = getRetainedEntries(); - final long[] cache = new long[numEntries]; - int i = 0; - final HashIterator it = iterator(); - while (it.next()) { - cache[i++] = it.get(); - } - return cache; - } -} diff --git a/src/main/java/org/apache/datasketches/theta/DirectCompactSketch.java b/src/main/java/org/apache/datasketches/theta/DirectCompactSketch.java deleted file mode 100644 index 749d8dfed..000000000 --- a/src/main/java/org/apache/datasketches/theta/DirectCompactSketch.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.theta.CompactOperations.checkIllegalCurCountAndEmpty; -import static org.apache.datasketches.theta.CompactOperations.segmentToCompact; -import static org.apache.datasketches.theta.PreambleUtil.ORDERED_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.extractCurCount; -import static org.apache.datasketches.theta.PreambleUtil.extractFlags; -import static org.apache.datasketches.theta.PreambleUtil.extractSeedHash; -import static org.apache.datasketches.theta.PreambleUtil.extractThetaLong; -import static org.apache.datasketches.theta.SingleItemSketch.checkForSingleItem; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.Util; - -/** - * An off-heap (Direct), compact, read-only sketch. The internal hash array can be either ordered - * or unordered. It is not empty, not a single item. - * - *

This sketch can only be associated with a Serialization Version 3 format binary image.

- * - *

This implementation uses data in a given MemorySegment that is owned and managed by the caller. - * This MemorySegment can be off-heap, which if managed properly will greatly reduce the need for - * the JVM to perform garbage collection.

- * - * @author Lee Rhodes - */ -class DirectCompactSketch extends CompactThetaSketch { - final MemorySegment seg_; - - /** - * Construct this sketch with the given MemorySegment. - * @param seg (optional) Read-only MemorySegment object. - */ - DirectCompactSketch(final MemorySegment seg) { - seg_ = seg; - } - - /** - * Wraps the given MemorySegment, which must be a SerVer 3, CompactThetaSketch image. - * Must check the validity of the MemorySegment before calling. The order bit must be set properly. - * @param srcSeg the given MemorySegment - * @param seedHash The update seedHash. - * See Seed Hash. - * @return this sketch - */ - static DirectCompactSketch wrapInstance(final MemorySegment srcSeg, final short seedHash) { - Util.checkSeedHashes((short) extractSeedHash(srcSeg), seedHash); - return new DirectCompactSketch(srcSeg); - } - - //ThetaSketch Overrides - - @Override - public CompactThetaSketch compact(final boolean dstOrdered, final MemorySegment dstSeg) { - return segmentToCompact(seg_, dstOrdered, dstSeg); - } - - @Override - public int getCurrentBytes() { - if (checkForSingleItem(seg_)) { return 16; } - final int preLongs = ThetaSketch.getPreambleLongs(seg_); - final int curCount = (preLongs == 1) ? 0 : extractCurCount(seg_); - return (preLongs + curCount) << 3; - } - - @Override - public int getRetainedEntries(final boolean valid) { //valid is only relevant for the AlphaSketch - if (checkForSingleItem(seg_)) { return 1; } - final int preLongs = ThetaSketch.getPreambleLongs(seg_); - return (preLongs == 1) ? 0 : extractCurCount(seg_); - } - - @Override - public long getThetaLong() { - final int preLongs = ThetaSketch.getPreambleLongs(seg_); - return (preLongs > 2) ? extractThetaLong(seg_) : Long.MAX_VALUE; - } - - @Override - public boolean hasMemorySegment() { - return (seg_ != null) && seg_.scope().isAlive(); - } - - @Override - public boolean isOffHeap() { - return hasMemorySegment() && seg_.isNative(); - } - - @Override - public boolean isEmpty() { - final boolean emptyFlag = PreambleUtil.isEmptyFlag(seg_); - final long thetaLong = getThetaLong(); - final int curCount = getRetainedEntries(true); - return emptyFlag || ((curCount == 0) && (thetaLong == Long.MAX_VALUE)); - } - - @Override - public boolean isOrdered() { - return (extractFlags(seg_) & ORDERED_FLAG_MASK) > 0; - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return hasMemorySegment() && MemorySegmentStatus.isSameResource(seg_, that); - - } - - @Override - public HashIterator iterator() { - return new MemorySegmentHashIterator(seg_, getRetainedEntries(true), getThetaLong()); - } - - @Override - public byte[] toByteArray() { - checkIllegalCurCountAndEmpty(isEmpty(), getRetainedEntries()); - final int outBytes = getCurrentBytes(); - final byte[] byteArrOut = new byte[outBytes]; - MemorySegment.copy(seg_, JAVA_BYTE, 0, byteArrOut, 0, outBytes); - return byteArrOut; - } - - //restricted methods - - @Override - long[] getCache() { - if (checkForSingleItem(seg_)) { return new long[] { seg_.get(JAVA_LONG_UNALIGNED, 8) }; } - final int preLongs = ThetaSketch.getPreambleLongs(seg_); - final int curCount = (preLongs == 1) ? 0 : extractCurCount(seg_); - if (curCount > 0) { - final long[] cache = new long[curCount]; - MemorySegment.copy(seg_, JAVA_LONG_UNALIGNED, preLongs << 3, cache, 0, curCount); - return cache; - } - return new long[0]; - } - - @Override - int getCompactPreambleLongs() { - return ThetaSketch.getPreambleLongs(seg_); - } - - @Override - int getCurrentPreambleLongs() { - return ThetaSketch.getPreambleLongs(seg_); - } - - @Override - MemorySegment getMemorySegment() { - return seg_; - } - - @Override - short getSeedHash() { - return (short) extractSeedHash(seg_); - } -} diff --git a/src/main/java/org/apache/datasketches/theta/DirectQuickSelectSketch.java b/src/main/java/org/apache/datasketches/theta/DirectQuickSelectSketch.java deleted file mode 100644 index 2172a1f65..000000000 --- a/src/main/java/org/apache/datasketches/theta/DirectQuickSelectSketch.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.Util.LONG_MAX_VALUE_AS_DOUBLE; -import static org.apache.datasketches.theta.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.FLAGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.P_FLOAT; -import static org.apache.datasketches.theta.PreambleUtil.RETAINED_ENTRIES_INT; -import static org.apache.datasketches.theta.PreambleUtil.SER_VER; -import static org.apache.datasketches.theta.PreambleUtil.THETA_LONG; -import static org.apache.datasketches.theta.PreambleUtil.extractLgArrLongs; -import static org.apache.datasketches.theta.PreambleUtil.extractLgNomLongs; -import static org.apache.datasketches.theta.PreambleUtil.getUpdatableSegBytes; -import static org.apache.datasketches.theta.PreambleUtil.insertCurCount; -import static org.apache.datasketches.theta.PreambleUtil.insertFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.insertFlags; -import static org.apache.datasketches.theta.PreambleUtil.insertLgArrLongs; -import static org.apache.datasketches.theta.PreambleUtil.insertLgNomLongs; -import static org.apache.datasketches.theta.PreambleUtil.insertLgResizeFactor; -import static org.apache.datasketches.theta.PreambleUtil.insertP; -import static org.apache.datasketches.theta.PreambleUtil.insertPreLongs; -import static org.apache.datasketches.theta.PreambleUtil.insertSeedHash; -import static org.apache.datasketches.theta.PreambleUtil.insertSerVer; -import static org.apache.datasketches.theta.PreambleUtil.insertThetaLong; -import static org.apache.datasketches.theta.PreambleUtil.insertUnionThetaLong; -import static org.apache.datasketches.theta.Rebuilder.actLgResizeFactor; -import static org.apache.datasketches.theta.Rebuilder.moveAndResize; -import static org.apache.datasketches.theta.Rebuilder.quickSelectAndRebuild; -import static org.apache.datasketches.theta.Rebuilder.resize; -import static org.apache.datasketches.theta.UpdateReturnState.InsertedCountIncremented; -import static org.apache.datasketches.theta.UpdateReturnState.InsertedCountIncrementedRebuilt; -import static org.apache.datasketches.theta.UpdateReturnState.InsertedCountIncrementedResized; -import static org.apache.datasketches.theta.UpdateReturnState.RejectedDuplicate; -import static org.apache.datasketches.theta.UpdateReturnState.RejectedOverTheta; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SuppressFBWarnings; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.HashOperations; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * The UpdatableThetaSketch using the QuickSelect algorithm in a MemorySegment. - * This subclass implements methods, which affect the state (update, rebuild, reset) - * - *

This implementation uses data in a given MemorySegment that is owned and managed by the caller. - * This MemorySegment can be off-heap, which if managed properly will greatly reduce the need for - * the JVM to perform garbage collection.

- * - * @author Lee Rhodes - * @author Kevin Lang - */ -class DirectQuickSelectSketch extends DirectQuickSelectSketchR { - private static final double DQS_RESIZE_THRESHOLD = 15.0 / 16.0; //tuned for space - int hashTableThreshold_; //computed and mutable, kept only on heap, never serialized. - private final MemorySegmentRequest mSegReq; - - /** - * Construct this sketch as a result of a wrap operation where the given MemorySegment already has an updatable sketch image. - * @param wseg the given MemorySegment that has an updatable sketch image. - * @param mSegReq an implementation of the MemorySegmentRequest interface or null. - * @param seed See Update Hash Seed. - */ - private DirectQuickSelectSketch( - final MemorySegment wseg, - final MemorySegmentRequest mSegReq, - final long seed) { - this.mSegReq = mSegReq == null ? MemorySegmentRequest.DEFAULT : mSegReq; - super(wseg, seed); - } - - /** - * Construct a new sketch instance and initialize the given MemorySegment as its backing store. - * This is only called internally by other theta sketch classes. - * - * @param lgNomLongs See lgNomLongs. - * @param seed See Update Hash Seed. - * @param p - * See Sampling Probability, p - * @param rf Resize Factor - * See Resize Factor - * @param dstSeg the given MemorySegment object destination. It cannot be null. - * It will be cleared prior to use. - * @param mSegReq an implementation of the MemorySegmentRequest interface or null. - * @param unionGadget true if this sketch is implementing the ThetaUnion gadget function. - * Otherwise, it is behaving as a normal QuickSelectThetaSketch. - */ - DirectQuickSelectSketch( - final int lgNomLongs, - final long seed, - final float p, - final ResizeFactor rf, - final MemorySegment dstSeg, - final MemorySegmentRequest mSegReq, - final boolean unionGadget) { - - //Choose family, preambleLongs - final Family family = unionGadget ? Family.UNION : Family.QUICKSELECT; - final int preambleLongs = unionGadget ? Family.UNION.getMinPreLongs() : Family.QUICKSELECT.getMinPreLongs(); - - //Set RF, lgArrLongs. - final int lgRF = rf.lg(); - final int lgArrLongs = lgRF == 0 ? lgNomLongs + 1 : ThetaUtil.MIN_LG_ARR_LONGS; - - //check Segment capacity - final int minReqBytes = getUpdatableSegBytes(lgArrLongs, preambleLongs); - final long curSegCapBytes = dstSeg.byteSize(); - if (curSegCapBytes < minReqBytes) { - throw new SketchesArgumentException( - "MemorySegment capacity is less than minimum required: " + curSegCapBytes + " < " + minReqBytes); - } - - //@formatter:off - //Build preamble - insertPreLongs(dstSeg, preambleLongs); //byte 0 - insertLgResizeFactor(dstSeg, lgRF); //byte 0 - insertSerVer(dstSeg, SER_VER); //byte 1 - insertFamilyID(dstSeg, family.getID()); //byte 2 - insertLgNomLongs(dstSeg, lgNomLongs); //byte 3 - insertLgArrLongs(dstSeg, lgArrLongs); //byte 4 - insertFlags(dstSeg, EMPTY_FLAG_MASK); //byte 5 - insertSeedHash(dstSeg, Util.computeSeedHash(seed)); //bytes 6,7 - insertCurCount(dstSeg, 0); //bytes 8-11 - insertP(dstSeg, p); //bytes 12-15 - final long thetaLong = (long)(p * LONG_MAX_VALUE_AS_DOUBLE); - insertThetaLong(dstSeg, thetaLong); //bytes 16-23 - //@formatter:on - - if (unionGadget) { insertUnionThetaLong(dstSeg, thetaLong); } - - //clear hash table area - dstSeg.asSlice(preambleLongs << 3, Long.BYTES << lgArrLongs).fill((byte)0); - hashTableThreshold_ = getOffHeapHashTableThreshold(lgNomLongs, lgArrLongs); - this.mSegReq = mSegReq == null ? MemorySegmentRequest.DEFAULT : mSegReq; - super(dstSeg, seed); - } - - /** - * Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch. - * @param srcSeg The given MemorySegment object must be in hash table form and not read only. - * @param mSegReq an implementation of the MemorySegmentRequest interface or null. - * @param seed See Update Hash Seed - * @return instance of this sketch - */ - //called from ThetaUnionImpl and UpdatableThetaSketch - static DirectQuickSelectSketch writableWrap( - final MemorySegment srcSeg, - final MemorySegmentRequest mSegReq, - final long seed) { - final int preambleLongs = ThetaSketch.getPreambleLongs(srcSeg); //byte 0 - final int lgNomLongs = extractLgNomLongs(srcSeg); //byte 3 - final int lgArrLongs = extractLgArrLongs(srcSeg); //byte 4 - - UpdatableThetaSketch.checkUnionAndQuickSelectFamily(srcSeg, preambleLongs, lgNomLongs); - checkSegIntegrity(srcSeg, seed, preambleLongs, lgNomLongs, lgArrLongs); - - if (isResizeFactorIncorrect(srcSeg, lgNomLongs, lgArrLongs)) { - //If incorrect it sets it to X2 which always works. - insertLgResizeFactor(srcSeg, ResizeFactor.X2.lg()); - } - - final DirectQuickSelectSketch dqss = new DirectQuickSelectSketch(srcSeg, mSegReq, seed); - dqss.hashTableThreshold_ = getOffHeapHashTableThreshold(lgNomLongs, lgArrLongs); - return dqss; - } - - /** - * Fast-wrap a sketch around the given source MemorySegment containing sketch data that originated from - * this sketch. This does NO validity checking of the given MemorySegment. - * @param srcSeg The given MemorySegment must be in hash table form and not read only. - * @param mSegReq an implementation of the MemorySegmentRequest interface or null. - * @param seed See Update Hash Seed - * @return instance of this sketch - */ - //called from ThetaUnionImpl <- ThetaUnion - static DirectQuickSelectSketch fastWritableWrap( - final MemorySegment srcSeg, - final MemorySegmentRequest mSegReq, - final long seed) { - final int lgNomLongs = extractLgNomLongs(srcSeg); //byte 3 - final int lgArrLongs = extractLgArrLongs(srcSeg); //byte 4 - - final DirectQuickSelectSketch dqss = new DirectQuickSelectSketch(srcSeg, mSegReq, seed); - dqss.hashTableThreshold_ = getOffHeapHashTableThreshold(lgNomLongs, lgArrLongs); - return dqss; - } - - //ThetaSketch - - //UpdatableThetaSketch - - @Override - public UpdatableThetaSketch rebuild() { - final int lgNomLongs = getLgNomLongs(); - final int preambleLongs = wseg_.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE) & 0X3F; - if (getRetainedEntries(true) > 1 << lgNomLongs) { - quickSelectAndRebuild(wseg_, preambleLongs, lgNomLongs); - } - return this; - } - - @Override - public void reset() { - //clear hash table - //hash table size and hashTableThreshold stays the same - //lgArrLongs stays the same - //thetaLongs resets to p - final int arrLongs = 1 << getLgArrLongs(); - final int preambleLongs = wseg_.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE) & 0X3F; - final int preBytes = preambleLongs << 3; - wseg_.asSlice(preBytes, arrLongs * 8L).fill((byte)0); - wseg_.set(JAVA_BYTE, FLAGS_BYTE, (byte) EMPTY_FLAG_MASK); - wseg_.set(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT, 0); - final float p = wseg_.get(JAVA_FLOAT_UNALIGNED, P_FLOAT); - final long thetaLong = (long) (p * LONG_MAX_VALUE_AS_DOUBLE); - wseg_.set(JAVA_LONG_UNALIGNED, THETA_LONG, thetaLong); - } - - //restricted methods - - @Override - UpdateReturnState hashUpdate(final long hash) { - HashOperations.checkHashCorruption(hash); - - wseg_.set(JAVA_BYTE, FLAGS_BYTE, (byte) (wseg_.get(JAVA_BYTE, FLAGS_BYTE) & ~EMPTY_FLAG_MASK)); - final long thetaLong = getThetaLong(); - final int lgNomLongs = getLgNomLongs(); - //The over-theta test - if (HashOperations.continueCondition(thetaLong, hash)) { - return RejectedOverTheta; //signal that hash was rejected due to theta or zero. - } - - final int lgArrLongs = getLgArrLongs(); - final int preambleLongs = wseg_.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE) & 0X3F; - - //The duplicate test - final int index = HashOperations.hashSearchOrInsertMemorySegment(wseg_, lgArrLongs, hash, preambleLongs << 3); - if (index >= 0) { return RejectedDuplicate; } //Duplicate, not inserted - - //insertion occurred, increment curCount - final int curCount = getRetainedEntries(true) + 1; - wseg_.set(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT, curCount); //update curCount - - if (isOutOfSpace(curCount)) { //we need to do something, we are out of space - - if (lgArrLongs > lgNomLongs) { //at full size, rebuild, assumes no dirty values, changes thetaLong, curCount_ - assert lgArrLongs == lgNomLongs + 1 : "lgArr: " + lgArrLongs + ", lgNom: " + lgNomLongs; - //rebuild, refresh curCount based on # values in the hashtable. - quickSelectAndRebuild(wseg_, preambleLongs, lgNomLongs); - return InsertedCountIncrementedRebuilt; - } //end of rebuild, exit - - else { //Not at full size, resize. Should not get here if lgRF = 0 and segCap is too small. - final int lgRF = getLgRF(); - final int actLgRF = actLgResizeFactor(wseg_.byteSize(), lgArrLongs, preambleLongs, lgRF); - int tgtLgArrLongs = Math.min(lgArrLongs + actLgRF, lgNomLongs + 1); - - if (actLgRF > 0) { //Expand in current MemorySegment - //lgArrLongs will change; thetaLong, curCount will not - resize(wseg_, preambleLongs, lgArrLongs, tgtLgArrLongs); - hashTableThreshold_ = getOffHeapHashTableThreshold(lgNomLongs, tgtLgArrLongs); - return InsertedCountIncrementedResized; - } //end of Expand in current MemorySegment, exit. - - else { //Request larger segment, then resize. lgArrLongs will change; thetaLong, curCount will not - final int preBytes = preambleLongs << 3; - tgtLgArrLongs = Math.min(lgArrLongs + lgRF, lgNomLongs + 1); - final int tgtArrBytes = 8 << tgtLgArrLongs; - final int reqBytes = tgtArrBytes + preBytes; - - final MemorySegment newDstSeg = mSegReq.request(reqBytes); - - moveAndResize(wseg_, preambleLongs, lgArrLongs, newDstSeg, tgtLgArrLongs, thetaLong); - final MemorySegment oldSeg = wseg_; - wseg_ = newDstSeg; - mSegReq.requestClose(oldSeg); - - hashTableThreshold_ = getOffHeapHashTableThreshold(lgNomLongs, tgtLgArrLongs); - return InsertedCountIncrementedResized; - } //end of request new segment & resize - } //end of resize - } //end of isOutOfSpace - return InsertedCountIncremented; - } - - @Override - boolean isOutOfSpace(final int numEntries) { - return numEntries > hashTableThreshold_; - } - - /** - * Returns the cardinality limit given the current size of the hash table array. - * - * @param lgNomLongs See lgNomLongs. - * @param lgArrLongs See lgArrLongs. - * @return the hash table threshold - */ - @SuppressFBWarnings(value = "DB_DUPLICATE_BRANCHES", justification = "False Positive, see the code comments") - protected static final int getOffHeapHashTableThreshold(final int lgNomLongs, final int lgArrLongs) { - //SpotBugs may complain (DB_DUPLICATE_BRANCHES) if DQS_RESIZE_THRESHOLD == REBUILD_THRESHOLD, - //but this allows us to tune these constants for different sketches. - final double fraction = lgArrLongs <= lgNomLongs ? DQS_RESIZE_THRESHOLD : ThetaUtil.REBUILD_THRESHOLD; - return (int) (fraction * (1 << lgArrLongs)); - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/DirectQuickSelectSketchR.java b/src/main/java/org/apache/datasketches/theta/DirectQuickSelectSketchR.java deleted file mode 100644 index 37fabf844..000000000 --- a/src/main/java/org/apache/datasketches/theta/DirectQuickSelectSketchR.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.theta.CompactOperations.checkIllegalCurCountAndEmpty; -import static org.apache.datasketches.theta.CompactOperations.computeCompactPreLongs; -import static org.apache.datasketches.theta.CompactOperations.correctThetaOnCompact; -import static org.apache.datasketches.theta.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.LG_ARR_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.LG_RESIZE_FACTOR_BIT; -import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.P_FLOAT; -import static org.apache.datasketches.theta.PreambleUtil.RETAINED_ENTRIES_INT; -import static org.apache.datasketches.theta.PreambleUtil.THETA_LONG; -import static org.apache.datasketches.theta.PreambleUtil.checkSegPreambleCap; -import static org.apache.datasketches.theta.PreambleUtil.extractCurCount; -import static org.apache.datasketches.theta.PreambleUtil.extractLgArrLongs; -import static org.apache.datasketches.theta.PreambleUtil.extractLgNomLongs; -import static org.apache.datasketches.theta.PreambleUtil.extractThetaLong; -import static org.apache.datasketches.theta.PreambleUtil.insertThetaLong; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesReadOnlyException; - -/** - * The read-only ThetaSketch in a MemorySegment. - * - *

This implementation uses data in a given MemorySegment that is owned and managed by the caller. - * This MemorySegment can be off-heap, which if managed properly will greatly reduce the need for - * the JVM to perform garbage collection.

- * - * @author Lee Rhodes - * @author Kevin Lang - */ -class DirectQuickSelectSketchR extends UpdatableThetaSketch { - - /** - * This MemorySegment reference is also used by the writable child DirectQuickSelectThetaSketch. - * - *

When this class is constructed with the writable constructor, called by the writable child DirectQuickSelectThetaSketch, - * this reference can be changed, its contents can be modified.

- * - *

When this class is constructed with the read-only constructor, called from local factories, this MemorySegment will - * be placed in read-only mode.

- */ - MemorySegment wseg_; // - - /** - * This writable constructor is only called by the writable child DirectQuickSelectThetaSketch and then this class provides the - * read-only methods for the DirectQuickSelectThetaSketch class. - * @param wseg the writable MemorySegment used by the writable child DirectQuickSelectThetaSketch. - * @param seed the seed for the update function for the writable child DirectQuickSelectThetaSketch. - */ - DirectQuickSelectSketchR(final MemorySegment wseg, final long seed) { - Objects.requireNonNull(wseg, "MemorySegment wseg must not be null"); - super(seed); - wseg_ = wseg; - } - - /** - * This read-only constructor is only called by local factory methods which use this class as a read-only direct sketch. - * @param seed the seed used to validate the internal hashes of the given source MemorySegment. - * @param srcSeg the read-only MemorySegment used by this class in read-only mode. - */ - private DirectQuickSelectSketchR(final long seed, final MemorySegment srcSeg) { - Objects.requireNonNull(srcSeg, "MemorySegment srcSeg must not be null"); - super(seed); - wseg_ = srcSeg.asReadOnly(); - } - - /** - * Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch. - * @param srcSeg the source MemorySegment. - * The given MemorySegment object must be in hash table form and not read only. - * @param seed See Update Hash Seed - * @return instance of this sketch - */ - static DirectQuickSelectSketchR readOnlyWrap(final MemorySegment srcSeg, final long seed) { - final int preambleLongs = checkSegPreambleCap(srcSeg); //byte 0 - final int lgNomLongs = extractLgNomLongs(srcSeg); //byte 3 - final int lgArrLongs = extractLgArrLongs(srcSeg); //byte 4 - checkSegIntegrity(srcSeg, seed, preambleLongs, lgNomLongs, lgArrLongs); - UpdatableThetaSketch.checkUnionAndQuickSelectFamily(srcSeg, preambleLongs, lgNomLongs); - return new DirectQuickSelectSketchR(seed, srcSeg); - } - - /** - * Fast-wrap a sketch around the given source MemorySegment containing sketch data that originated from - * this sketch. This does NO validity checking of the given MemorySegment. - * Caller must ensure segment contents are a valid sketch image. - * @param srcSeg The given MemorySegment object must be in hash table form and not read only. - * @param seed See Update Hash Seed - * @return instance of this sketch - */ - static DirectQuickSelectSketchR fastReadOnlyWrap(final MemorySegment srcSeg, final long seed) { - return new DirectQuickSelectSketchR(seed, srcSeg); - } - - //ThetaSketch - - @Override - public int getCurrentBytes() { - //not compact - final int lgArrLongs = wseg_.get(JAVA_BYTE, LG_ARR_LONGS_BYTE) & 0XFF; //mask to byte - final int preLongs = wseg_.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE) & 0X3F; //mask to 6 bits - return preLongs + (1 << lgArrLongs) << 3; - } - - @Override - public double getEstimate() { - final int curCount = extractCurCount(wseg_); - final long thetaLong = extractThetaLong(wseg_); - return ThetaSketch.estimate(thetaLong, curCount); - } - - @Override - public Family getFamily() { - final int familyID = wseg_.get(JAVA_BYTE, FAMILY_BYTE) & 0XFF; //mask to byte - return Family.idToFamily(familyID); - } - - @Override - public int getRetainedEntries(final boolean valid) { //valid is only relevant for the AlphaSketch - return wseg_.get(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT); - } - - @Override - public long getThetaLong() { - return isEmpty() ? Long.MAX_VALUE : wseg_.get(JAVA_LONG_UNALIGNED, THETA_LONG); - } - - @Override - public boolean hasMemorySegment() { - return wseg_ != null && wseg_.scope().isAlive(); - } - - @Override - public boolean isOffHeap() { - return hasMemorySegment() && wseg_.isNative(); - } - - @Override - public boolean isEmpty() { - return PreambleUtil.isEmptyFlag(wseg_); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return hasMemorySegment() && MemorySegmentStatus.isSameResource(wseg_, that); //null checks done here - } - - @Override - public HashIterator iterator() { - return new MemorySegmentHashIterator(wseg_, 1 << getLgArrLongs(), getThetaLong()); - } - - @Override - public byte[] toByteArray() { //MY_FAMILY is stored in wseg_ - final int curCount = extractCurCount(wseg_); - checkIllegalCurCountAndEmpty(isEmpty(), curCount); - final int lengthBytes = getCurrentBytes(); - final byte[] byteArray = new byte[lengthBytes]; - final MemorySegment seg = MemorySegment.ofArray(byteArray); - MemorySegment.copy(wseg_, 0, seg, 0, lengthBytes); - final long thetaLong = correctThetaOnCompact(isEmpty(), curCount, extractThetaLong(wseg_)); - insertThetaLong(seg, thetaLong); - return byteArray; - } - - //UpdatableThetaSketch - - @Override - public final int getLgNomLongs() { - return PreambleUtil.extractLgNomLongs(wseg_); - } - - @Override - float getP() { - return wseg_.get(JAVA_FLOAT_UNALIGNED, P_FLOAT); - } - - @Override - public ResizeFactor getResizeFactor() { - return ResizeFactor.getRF(getLgRF()); - } - - @Override - public UpdatableThetaSketch rebuild() { - throw new SketchesReadOnlyException(); - } - - @Override - public void reset() { - throw new SketchesReadOnlyException(); - } - - //restricted methods - - @Override - long[] getCache() { - final long lgArrLongs = wseg_.get(JAVA_BYTE, LG_ARR_LONGS_BYTE) & 0XFF; //mask to byte - final int preambleLongs = wseg_.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE) & 0X3F; //mask to 6 bits - final long[] cacheArr = new long[1 << lgArrLongs]; - MemorySegment.copy(wseg_, JAVA_LONG_UNALIGNED, preambleLongs << 3, cacheArr, 0, 1 << lgArrLongs); - return cacheArr; - } - - @Override - int getCompactPreambleLongs() { - return computeCompactPreLongs(isEmpty(), getRetainedEntries(true), getThetaLong()); - } - - @Override - int getCurrentPreambleLongs() { - return ThetaSketch.getPreambleLongs(wseg_); - } - - @Override - MemorySegment getMemorySegment() { - return wseg_; - } - - @Override - short getSeedHash() { - return (short) PreambleUtil.extractSeedHash(wseg_); - } - - @Override - boolean isDirty() { - return false; //Always false for QuickSelectThetaSketch - } - - @Override - boolean isOutOfSpace(final int numEntries) { //overridden by writable DirectQuickSelectSketch - return false; - } - - @Override - int getLgArrLongs() { - return wseg_.get(JAVA_BYTE, LG_ARR_LONGS_BYTE) & 0XFF; //mask to byte - } - - int getLgRF() { //only Direct needs this - return wseg_.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE) >>> LG_RESIZE_FACTOR_BIT & 0X3; //mask to 2 bits - } - - @Override - UpdateReturnState hashUpdate(final long hash) { - throw new SketchesReadOnlyException(); - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/EmptyCompactSketch.java b/src/main/java/org/apache/datasketches/theta/EmptyCompactSketch.java deleted file mode 100644 index a5ffed2f7..000000000 --- a/src/main/java/org/apache/datasketches/theta/EmptyCompactSketch.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Singleton empty CompactThetaSketch. - * - * @author Lee Rhodes - */ -final class EmptyCompactSketch extends CompactThetaSketch { - - //For backward compatibility, a candidate long must have Flags= compact, read-only, - // COMPACT-Family=3, SerVer=3, PreLongs=1, and be exactly 8 bytes long. The seedHash is ignored. - // NOTE: The empty and ordered flags may or may not be set - private static final long EMPTY_SKETCH_MASK = 0X00_00_EB_00_00_FF_FF_FFL; - private static final long EMPTY_SKETCH_TEST = 0X00_00_0A_00_00_03_03_01L; - //When returning a byte array the empty and ordered bits are also set - static final byte[] EMPTY_COMPACT_SKETCH_ARR = { 1, 3, 3, 0, 0, 0x1E, 0, 0 }; - private static final EmptyCompactSketch EMPTY_COMPACT_SKETCH = new EmptyCompactSketch(); - - private EmptyCompactSketch() {} - - static synchronized EmptyCompactSketch getInstance() { - return EMPTY_COMPACT_SKETCH; - } - - //This should be a heapify - static synchronized EmptyCompactSketch getHeapInstance(final MemorySegment srcSeg) { - final long pre0 = srcSeg.get(JAVA_LONG_UNALIGNED, 0); - if (testCandidatePre0(pre0)) { - return EMPTY_COMPACT_SKETCH; - } - final long maskedPre0 = pre0 & EMPTY_SKETCH_MASK; - throw new SketchesArgumentException("Input MemorySegment does not match required Preamble. " - + "MemorySegment Pre0: " + Long.toHexString(maskedPre0) - + ", required Pre0: " + Long.toHexString(EMPTY_SKETCH_TEST)); - } - - @Override - // This returns with ordered flag = true independent of dstOrdered. - // This is required for fast detection. - // The hashSeed is ignored and set == 0. - public CompactThetaSketch compact(final boolean dstOrdered, final MemorySegment dstWSeg) { - if (dstWSeg == null) { return EmptyCompactSketch.getInstance(); } - //dstWSeg.putByteArray(0, EMPTY_COMPACT_SKETCH_ARR, 0, 8); - MemorySegment.copy(EMPTY_COMPACT_SKETCH_ARR, 0, dstWSeg, JAVA_BYTE, 0, 8); - return new DirectCompactSketch(dstWSeg); - } - - //static - - static boolean testCandidatePre0(final long candidate) { - return (candidate & EMPTY_SKETCH_MASK) == EMPTY_SKETCH_TEST; - } - - @Override - public int getCurrentBytes() { - return 8; - } - - @Override - public double getEstimate() { return 0; } - - @Override - public int getRetainedEntries(final boolean valid) { //valid is only relevant for the AlphaSketch - return 0; - } - - @Override - public long getThetaLong() { - return Long.MAX_VALUE; - } - - @Override - public boolean isEmpty() { - return true; - } - - @Override - public boolean isOrdered() { - return true; - } - - @Override - public HashIterator iterator() { - return new HeapCompactHashIterator(new long[0]); - } - - /** - * Returns 8 bytes representing a CompactThetaSketch that the following flags set: - * ordered, compact, empty, readOnly. The SerVer is 3, the Family is COMPACT(3), - * and the PreLongs = 1. The seedHash is zero. - */ - @Override - public byte[] toByteArray() { - return EMPTY_COMPACT_SKETCH_ARR; - } - - @Override - long[] getCache() { - return new long[0]; - } - - @Override - int getCompactPreambleLongs() { - return 1; - } - - @Override - int getCurrentPreambleLongs() { - return 1; - } - - @Override - short getSeedHash() { - return 0; - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/HashIterator.java b/src/main/java/org/apache/datasketches/theta/HashIterator.java deleted file mode 100644 index d7dce4183..000000000 --- a/src/main/java/org/apache/datasketches/theta/HashIterator.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -/** - * This is used to iterate over the retained hash values of the Theta sketch. - * @author Lee Rhodes - */ -public interface HashIterator { - - /** - * Gets the hash value - * @return the hash value - */ - long get(); - - /** - * Returns true at the next hash value in sequence. - * If false, the iteration is done. - * @return true at the next hash value in sequence. - */ - boolean next(); -} diff --git a/src/main/java/org/apache/datasketches/theta/HeapAlphaSketch.java b/src/main/java/org/apache/datasketches/theta/HeapAlphaSketch.java deleted file mode 100644 index 8b64b177f..000000000 --- a/src/main/java/org/apache/datasketches/theta/HeapAlphaSketch.java +++ /dev/null @@ -1,603 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static java.lang.Math.sqrt; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.Util.DEFAULT_UPDATE_SEED; -import static org.apache.datasketches.common.Util.LONG_MAX_VALUE_AS_DOUBLE; -import static org.apache.datasketches.common.Util.checkBounds; -import static org.apache.datasketches.theta.PreambleUtil.extractCurCount; -import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.extractLgArrLongs; -import static org.apache.datasketches.theta.PreambleUtil.extractLgNomLongs; -import static org.apache.datasketches.theta.PreambleUtil.extractLgResizeFactor; -import static org.apache.datasketches.theta.PreambleUtil.extractP; -import static org.apache.datasketches.theta.PreambleUtil.extractThetaLong; -import static org.apache.datasketches.theta.UpdateReturnState.InsertedCountIncremented; -import static org.apache.datasketches.theta.UpdateReturnState.InsertedCountNotIncremented; -import static org.apache.datasketches.theta.UpdateReturnState.RejectedDuplicate; -import static org.apache.datasketches.theta.UpdateReturnState.RejectedOverTheta; -import static org.apache.datasketches.thetacommon.HashOperations.STRIDE_MASK; - -import java.lang.foreign.MemorySegment; -import java.util.Objects; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.thetacommon.HashOperations; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * This sketch uses the - * ThetaSketch Framework - * and the - * Alpha TCF algorithm - * with a single cache. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -final class HeapAlphaSketch extends HeapUpdateSketch { - private static final int ALPHA_MIN_LG_NOM_LONGS = 9; //The smallest Log2 k allowed => 512. - private final double alpha_; // computed from lgNomLongs - private final long split1_; // computed from alpha and p - - private int lgArrLongs_; - private int hashTableThreshold_; //never serialized - private int curCount_ = 0; - private long thetaLong_; - private boolean empty_ = true; - - private long[] cache_; - private boolean dirty_ = false; - - private HeapAlphaSketch(final int lgNomLongs, final long seed, final float p, - final ResizeFactor rf, final double alpha, final long split1) { - super(lgNomLongs, seed, p, rf); - alpha_ = alpha; - split1_ = split1; - } - - /** - * Get a new sketch instance on the java heap. - * - * @param lgNomLongs See lgNomLongs - * @param seed See Update Hash Seed - * @param p See Sampling Probability, p - * @param rf See Resize Factor - * @return instance of this sketch - */ - static HeapAlphaSketch newHeapInstance(final int lgNomLongs, final long seed, final float p, - final ResizeFactor rf) { - - if (lgNomLongs < ALPHA_MIN_LG_NOM_LONGS) { - throw new SketchesArgumentException( - "This sketch requires a minimum nominal entries of " + (1 << ALPHA_MIN_LG_NOM_LONGS)); - } - - final double nomLongs = (1L << lgNomLongs); - final double alpha = nomLongs / (nomLongs + 1.0); - final long split1 = (long) (((p * (alpha + 1.0)) / 2.0) * LONG_MAX_VALUE_AS_DOUBLE); - - final HeapAlphaSketch has = new HeapAlphaSketch(lgNomLongs, seed, p, rf, alpha, split1); - - final int lgArrLongs = ThetaUtil.startingSubMultiple(lgNomLongs + 1, rf.lg(), ThetaUtil.MIN_LG_ARR_LONGS); - has.lgArrLongs_ = lgArrLongs; - has.hashTableThreshold_ = setHashTableThreshold(lgNomLongs, lgArrLongs); - has.curCount_ = 0; - has.thetaLong_ = (long)(p * LONG_MAX_VALUE_AS_DOUBLE); - has.empty_ = true; //other flags: reserved = readOnly = compact = ordered = false; - has.cache_ = new long[1 << lgArrLongs]; - return has; - } - - /** - * Heapify a sketch from a MemorySegment object containing sketch data. - * @param srcSeg The source MemorySegment object. - * It must have a size of at least 24 bytes. - * The assumed seed is {@link org.apache.datasketches.common.Util#DEFAULT_UPDATE_SEED DEFAULT_UPDATE_SEED} - * @return instance of this sketch - */ - static HeapAlphaSketch heapifyInstance(final MemorySegment srcSeg) { - return heapifyInstance(srcSeg, DEFAULT_UPDATE_SEED); - } - - /** - * Heapify a sketch from a MemorySegment object containing sketch data. - * @param srcSeg The source MemorySegment object. - * It must have a size of at least 24 bytes. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See seed - * @return instance of this sketch - */ - static HeapAlphaSketch heapifyInstance(final MemorySegment srcSeg, final long expectedSeed) { - Objects.requireNonNull(srcSeg, "Source MemorySegment must not be null"); - checkBounds(0, 24, srcSeg.byteSize()); - final int preambleLongs = ThetaSketch.getPreambleLongs(srcSeg); //byte 0 - final int lgNomLongs = extractLgNomLongs(srcSeg); //byte 3 - final int lgArrLongs = extractLgArrLongs(srcSeg); //byte 4 - - checkAlphaFamily(srcSeg, preambleLongs, lgNomLongs); - checkSegIntegrity(srcSeg, expectedSeed, preambleLongs, lgNomLongs, lgArrLongs); - - final float p = extractP(srcSeg); //bytes 12-15 - final int seglgRF = extractLgResizeFactor(srcSeg); //byte 0 - ResizeFactor segRF = ResizeFactor.getRF(seglgRF); - - final double nomLongs = (1L << lgNomLongs); - final double alpha = nomLongs / (nomLongs + 1.0); - final long split1 = (long) (((p * (alpha + 1.0)) / 2.0) * LONG_MAX_VALUE_AS_DOUBLE); - - if (isResizeFactorIncorrect(srcSeg, lgNomLongs, lgArrLongs)) { - segRF = ResizeFactor.X2; //X2 always works. - } - - final HeapAlphaSketch has = new HeapAlphaSketch(lgNomLongs, expectedSeed, p, segRF, alpha, split1); - has.lgArrLongs_ = lgArrLongs; - has.hashTableThreshold_ = setHashTableThreshold(lgNomLongs, lgArrLongs); - has.curCount_ = extractCurCount(srcSeg); - has.thetaLong_ = extractThetaLong(srcSeg); - has.empty_ = PreambleUtil.isEmptyFlag(srcSeg); - has.cache_ = new long[1 << lgArrLongs]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, preambleLongs << 3, has.cache_, 0, 1 << lgArrLongs); //read in as hash table - return has; - } - - //ThetaSketch - - @Override - public Family getFamily() { - return Family.ALPHA; - } - - @Override - public HashIterator iterator() { - return new HeapHashIterator(cache_, thetaLong_); - } - - @Override - public double getEstimate() { - return (thetaLong_ > split1_) - ? ThetaSketch.estimate(thetaLong_, curCount_) - : (1 << lgNomLongs_) * (LONG_MAX_VALUE_AS_DOUBLE / thetaLong_); - } - - @Override - public double getLowerBound(final int numStdDev) { - if ((numStdDev < 1) || (numStdDev > 3)) { - throw new SketchesArgumentException("numStdDev can only be the values 1, 2 or 3."); - } - double lb; - if (isEstimationMode()) { - final int validCount = getRetainedEntries(true); - if (validCount > 0) { - final double est = getEstimate(); - final double var = getVariance(1 << lgNomLongs_, getP(), alpha_, getTheta(), validCount); - lb = est - (numStdDev * sqrt(var)); - lb = max(lb, 0.0); - } - else { - lb = 0.0; - } - } - else { - lb = curCount_; - } - return lb; - } - - @Override - public int getRetainedEntries(final boolean valid) { //valid is only relevant for the AlphaSketch - if (curCount_ > 0) { - if (valid && isDirty()) { - return HashOperations.countPart(getCache(), getLgArrLongs(), getThetaLong()); - } - } - return curCount_; - } - - @Override - public long getThetaLong() { - return thetaLong_; - } - - @Override - public double getUpperBound(final int numStdDev) { - if ((numStdDev < 1) || (numStdDev > 3)) { - throw new SketchesArgumentException("numStdDev can only be the values 1, 2 or 3."); - } - if (isEstimationMode()) { - final double var = - getVariance(1 << lgNomLongs_, getP(), alpha_, getTheta(), getRetainedEntries(true)); - return getEstimate() + (numStdDev * sqrt(var)); - } - return curCount_; - } - - @Override - public boolean isEmpty() { - return empty_; - } - - /* - * AlphaSketch Preamble Layout ( same as UpdatableThetaSketch ) - *
-   * Long || Start Byte Adr:
-   * Adr:
-   *      ||    7   |    6   |    5   |    4   |    3   |    2     |    1     |        0           |
-   *  0   ||    Seed Hash    | Flags  |  LgArr | LgNom  | FamID=1  | SerVer=3 | lgRF | PreLongs=3  |
-   *
-   *      ||   15   |   14   |   13   |   12   |   11   |   10     |    9     |     8              |
-   *  1   ||-----------------p-----------------|----------Retained Entries Count-------------------|
-   *
-   *      ||   23   |   22   |   21    |  20   |   19   |   18     |   17     |    16              |
-   *  2   ||---------------------------------Theta-------------------------------------------------|
-   * 
- */ - - @Override - public byte[] toByteArray() { - return toByteArray(Family.ALPHA.getMinPreLongs(), (byte) Family.ALPHA.getID()); - } - - //UpdatableThetaSketch - - @Override - public UpdatableThetaSketch rebuild() { - if (isDirty()) { - rebuildDirty(); - } - return this; - } - - @Override - public void reset() { - final int lgArrLongs = - ThetaUtil.startingSubMultiple(lgNomLongs_ + 1, getResizeFactor().lg(), ThetaUtil.MIN_LG_ARR_LONGS); - if (lgArrLongs == lgArrLongs_) { - final int arrLongs = cache_.length; - assert (1 << lgArrLongs_) == arrLongs; - java.util.Arrays.fill(cache_, 0L); - } - else { - cache_ = new long[1 << lgArrLongs]; - lgArrLongs_ = lgArrLongs; - } - hashTableThreshold_ = setHashTableThreshold(lgNomLongs_, lgArrLongs_); - empty_ = true; - curCount_ = 0; - thetaLong_ = (long)(getP() * LONG_MAX_VALUE_AS_DOUBLE); - dirty_ = false; - } - - //restricted methods - - @Override - int getCompactPreambleLongs() { - return CompactOperations.computeCompactPreLongs(empty_, curCount_, thetaLong_); - } - - @Override - int getCurrentPreambleLongs() { - return Family.ALPHA.getMinPreLongs(); - } - - @Override - long[] getCache() { - return cache_; - } - - @Override - boolean isDirty() { - return dirty_; - } - - @Override - boolean isOutOfSpace(final int numEntries) { - return numEntries > hashTableThreshold_; - } - - @Override - int getLgArrLongs() { - return lgArrLongs_; - } - - @Override - UpdateReturnState hashUpdate(final long hash) { - HashOperations.checkHashCorruption(hash); - empty_ = false; - - //The over-theta test - if (HashOperations.continueCondition(thetaLong_, hash)) { - return RejectedOverTheta; //signal that hash was rejected due to theta. - } - - //The duplicate/inserted tests - if (dirty_) { //may have dirty values, must be at tgt size - return enhancedHashInsert(cache_, hash); - } - - //NOT dirty, the other duplicate or inserted test - if (HashOperations.hashSearchOrInsert(cache_, lgArrLongs_, hash) >= 0) { - return UpdateReturnState.RejectedDuplicate; - } - //insertion occurred, must increment - curCount_++; - final int r = (thetaLong_ > split1_) ? 0 : 1; //are we in sketch mode? (i.e., seen k+1 inserts?) - if (r == 0) { //not yet sketch mode (has not seen k+1 inserts), but could be sampling - if (curCount_ > (1 << lgNomLongs_)) { // > k - //Reached the k+1 insert. Must be at tgt size or larger. - //Transition to ThetaSketch Mode. Happens only once. - //Decrement theta, make dirty, don't bother check size, already not-empty. - thetaLong_ = (long) (thetaLong_ * alpha_); - dirty_ = true; //now may have dirty values - } else //inserts (not entries!) <= k. It may not be at tgt size. - //Check size, don't decrement theta. count already ++, empty_ already false; - if (isOutOfSpace(curCount_)) { - resizeClean(); //not dirty, not at tgt size. - } - } - else { //r > 0: sketch mode and not dirty (e.g., after a rebuild). - //dec theta, make dirty, cnt already ++, must be at tgt size or larger. check for rebuild - assert (lgArrLongs_ > lgNomLongs_) : "lgArr: " + lgArrLongs_ + ", lgNom: " + lgNomLongs_; - thetaLong_ = (long) (thetaLong_ * alpha_); //decrement theta - dirty_ = true; //now may have dirty values - if (isOutOfSpace(curCount_)) { - rebuildDirty(); // at tgt size and maybe dirty - } - } - return UpdateReturnState.InsertedCountIncremented; - } - - /** - * Enhanced Knuth-style Open Addressing, Double Hash insert. - * The insertion process will overwrite an already existing, dirty (over-theta) value if one is - * found in the search. - * If an empty cell is found first, it will be inserted normally. - * - * @param hashTable the hash table to insert into - * @param hash must not be 0. If not a duplicate, it will be inserted into the hash array - * @return See Update Return State - */ - UpdateReturnState enhancedHashInsert(final long[] hashTable, final long hash) { - final int arrayMask = (1 << lgArrLongs_) - 1; // arrayLongs -1 - // make odd and independent of curProbe: - final int stride = (2 * (int) ((hash >>> lgArrLongs_) & STRIDE_MASK)) + 1; - int curProbe = (int) (hash & arrayMask); - long curTableHash = hashTable[curProbe]; - final int loopIndex = curProbe; - - // This is the enhanced part - // Search for duplicate or zero, or opportunity to replace garbage. - while ((curTableHash != hash) && (curTableHash != 0)) { - // curHash is not a duplicate and not zero - - if (curTableHash >= thetaLong_) { // curTableHash is garbage, do enhanced insert - final int rememberPos = curProbe; // remember its position. - // Now we must make sure there are no duplicates in this search path, - // so we keep searching - curProbe = (curProbe + stride) & arrayMask; // move forward - curTableHash = hashTable[curProbe]; - while ((curTableHash != hash) && (curTableHash != 0)) { - curProbe = (curProbe + stride) & arrayMask; - curTableHash = hashTable[curProbe]; - } - // curTableHash is a duplicate or zero - if (curTableHash == hash) { - return RejectedDuplicate; // duplicate, just return - } - assert (curTableHash == 0); // must be zero - // Now that we know there are no duplicates we can - // go back and insert at first garbage value position - hashTable[rememberPos] = hash; - thetaLong_ = (long) (thetaLong_ * alpha_); //decrement theta - dirty_ = true; //the decremented theta could have produced a new dirty value - return InsertedCountNotIncremented; - } - - // curTableHash was not a duplicate, not zero, and NOT garbage, - // so we keep searching - assert (curTableHash < thetaLong_); - curProbe = (curProbe + stride) & arrayMask; - curTableHash = hashTable[curProbe]; - - // ensure no infinite loop - if (curProbe == loopIndex) { - throw new SketchesArgumentException("No empty slot in table!"); - } - // end of Enhanced insert - } // end while and search - - // curTableHash is a duplicate or zero and NOT garbage - if (curTableHash == hash) { - return RejectedDuplicate; // duplicate, just return - } - // must be zero, so insert and increment - assert (curTableHash == 0); - hashTable[curProbe] = hash; - thetaLong_ = (long) (thetaLong_ * alpha_); //decrement theta - dirty_ = true; //the decremented theta could have produced a new dirty value - if (++curCount_ > hashTableThreshold_) { - rebuildDirty(); //at tgt size and maybe dirty - } - return InsertedCountIncremented; - } - - //At tgt size or greater - //Checks for rare lockup condition - // Used by hashUpdate(), rebuild() - private void rebuildDirty() { - final int curCountBefore = curCount_; - forceRebuildDirtyCache(); //changes curCount_ only - if (curCountBefore == curCount_) { - //clean but unsuccessful at reducing count, must take drastic measures, very rare. - forceResizeCleanCache(1); - } - } - - //curCount > hashTableThreshold - //Checks for rare lockup condition - // Used by hashUpdate() - private void resizeClean() { - //must resize, but are we at tgt size? - final int lgTgtLongs = lgNomLongs_ + 1; - if (lgTgtLongs > lgArrLongs_) { - //not yet at tgt size - final ResizeFactor rf = getResizeFactor(); - final int lgDeltaLongs = lgTgtLongs - lgArrLongs_; //must be > 0 - final int lgResizeFactor = max(min(rf.lg(), lgDeltaLongs), 1); //rf_.lg() could be 0 - forceResizeCleanCache(lgResizeFactor); - } - else { - //at tgt size or larger, no dirty values, must take drastic measures, very rare. - forceResizeCleanCache(1); - } - } - - //Force resize. Changes lgArrLongs_ only. Theta doesn't change, count doesn't change. - // Used by rebuildDirty(), resizeClean() - private void forceResizeCleanCache(final int lgResizeFactor) { - assert (!dirty_); // Should never be dirty before a resize. - lgArrLongs_ += lgResizeFactor; // new tgt size - final long[] tgtArr = new long[1 << lgArrLongs_]; - final int newCount = HashOperations.hashArrayInsert(cache_, tgtArr, lgArrLongs_, thetaLong_); - assert (curCount_ == newCount); - curCount_ = newCount; - cache_ = tgtArr; - hashTableThreshold_ = setHashTableThreshold(lgNomLongs_, lgArrLongs_); - } - - //Cache stays the same size. Must be dirty. Theta doesn't change, count will change. - // Used by rebuildDirtyAtTgtSize() - private void forceRebuildDirtyCache() { - final long[] tgtArr = new long[1 << lgArrLongs_]; - curCount_ = HashOperations.hashArrayInsert(cache_, tgtArr, lgArrLongs_, thetaLong_); - cache_ = tgtArr; - dirty_ = false; - //hashTableThreshold stays the same - } - - // @formatter:off - /** - * Computes an estimate of the error variance based on Historic Inverse Probability (HIP) - * estimators. See Cohen: All-Distances Sketches, Revisited: HIP Estimators for Massive Graph - * Analysis, Nov 2014. - *
-   * Table of sketch states and how Upper and Lower Bounds are computed
-   *
-   * Theta P    Count  Empty  EstMode Est   UB  LB   Comments
-   * 1.0   1.0  0      T      F       0     0   0    Empty sketch-mode only ThetaSketch
-   * 1.0   1.0  N      F      F       N     N   N    Degenerate sketch-mode only ThetaSketch
-   * <1.0  1.0  -      F      T       est   HIP HIP  Normal sketch-mode only ThetaSketch
-   *  P    <1.0 0      T      F       0     0   0    Virgin sampling ThetaSketch
-   *  P    <1.0 N      F      T       est   HIP HIP  Degenerate sampling ThetaSketch
-   *  <P   <1.0 N      F      T       est   HIP HIP  Sampling ThetaSketch also in sketch-mode
-   * 
- * @param k alias for nominal entries. - * @param p See Sampling Probability, p. - * @param alpha the value of alpha for this sketch - * @param theta See theta. - * @param count the current valid count. - * @return the variance. - */ - // @formatter:on - private static double getVariance(final double k, final double p, final double alpha, - final double theta, final int count) { - final double kPlus1 = k + 1.0; - final double y = 1.0 / p; - final double ySq = y * y; - final double ySqMinusY = ySq - y; - final int r = getR(theta, alpha, p); - final double result; - if (r == 0) { - result = count * ySqMinusY; - } - else if (r == 1) { - result = kPlus1 * ySqMinusY; //term1 - } - else { //r > 1 - final double b = 1.0 / alpha; - final double bSq = b * b; - final double x = p / theta; - final double xSq = x * x; - final double term1 = kPlus1 * ySqMinusY; - final double term2 = y / (1.0 - bSq); - final double term3 = (((y * bSq) - (y * xSq) - b - bSq) + x + (x * b)); - result = term1 + (term2 * term3); - } - final double term4 = (1 - theta) / (theta * theta); - return result + term4; - } - - /** - * Computes whether there have been 0, 1, or 2 or more actual insertions into the cache in a - * numerically safe way. - * @param theta See Theta. - * @param alpha internal computed value alpha. - * @param p See Sampling Probability, p. - * @return R. - */ - private static int getR(final double theta, final double alpha, final double p) { - final double split1 = (p * (alpha + 1.0)) / 2.0; - if (theta > split1) { return 0; } - if (theta > (alpha * split1)) { return 1; } - return 2; - } - - /** - * Returns the cardinality limit given the current size of the hash table array. - * - * @param lgNomLongs See lgNomLongs. - * @param lgArrLongs See lgArrLongs. - * @return the hash table threshold - */ - private static int setHashTableThreshold(final int lgNomLongs, final int lgArrLongs) { - final double fraction = (lgArrLongs <= lgNomLongs) ? ThetaUtil.RESIZE_THRESHOLD : ThetaUtil.REBUILD_THRESHOLD; - return (int) Math.floor(fraction * (1 << lgArrLongs)); - } - - static void checkAlphaFamily(final MemorySegment seg, final int preambleLongs, final int lgNomLongs) { - //Check Family - final int familyID = extractFamilyID(seg); //byte 2 - final Family family = Family.idToFamily(familyID); - if (family.equals(Family.ALPHA)) { - if (preambleLongs != Family.ALPHA.getMinPreLongs()) { - throw new SketchesArgumentException( - "Possible corruption: Invalid PreambleLongs value for ALPHA: " + preambleLongs); - } - } - else { - throw new SketchesArgumentException( - "Possible corruption: Invalid Family: " + family.toString()); - } - - //Check lgNomLongs - if (lgNomLongs < ALPHA_MIN_LG_NOM_LONGS) { - throw new SketchesArgumentException( - "Possible corruption: This sketch requires a minimum nominal entries of " - + (1 << ALPHA_MIN_LG_NOM_LONGS)); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/HeapCompactHashIterator.java b/src/main/java/org/apache/datasketches/theta/HeapCompactHashIterator.java deleted file mode 100644 index e8e5d8305..000000000 --- a/src/main/java/org/apache/datasketches/theta/HeapCompactHashIterator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -final class HeapCompactHashIterator implements HashIterator { - private long[] cache; - private int index; - - HeapCompactHashIterator(final long[] cache) { - this.cache = cache; - index = -1; - } - - @Override - public long get() { - return cache[index]; - } - - @Override - public boolean next() { - return ++index < cache.length; - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/HeapCompactSketch.java b/src/main/java/org/apache/datasketches/theta/HeapCompactSketch.java deleted file mode 100644 index 2e0fed42f..000000000 --- a/src/main/java/org/apache/datasketches/theta/HeapCompactSketch.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.apache.datasketches.theta.CompactOperations.checkIllegalCurCountAndEmpty; -import static org.apache.datasketches.theta.CompactOperations.componentsToCompact; -import static org.apache.datasketches.theta.CompactOperations.computeCompactPreLongs; -import static org.apache.datasketches.theta.CompactOperations.correctThetaOnCompact; -import static org.apache.datasketches.theta.CompactOperations.isSingleItem; -import static org.apache.datasketches.theta.CompactOperations.loadCompactMemorySegment; -import static org.apache.datasketches.theta.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.ORDERED_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.READ_ONLY_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.SINGLEITEM_FLAG_MASK; - -import java.lang.foreign.MemorySegment; - -/** - * Parent class of the HeapCompactThetaSketches. - * - * @author Lee Rhodes - */ -final class HeapCompactSketch extends CompactThetaSketch { - private final long thetaLong_; //computed - private final int curCount_; - private final int preLongs_; //computed - private final short seedHash_; - private final boolean empty_; - private final boolean ordered_; - private final boolean singleItem_; - private final long[] cache_; - - /** - * Constructs this sketch from correct, valid components. - * @param cache in compact form - * @param empty The correct Empty. - * @param seedHash The correct - * Seed Hash. - * @param curCount correct value - * @param thetaLong The correct - * thetaLong. - * @param ordered true if cache is ordered. - */ - HeapCompactSketch(final long[] cache, final boolean empty, final short seedHash, - final int curCount, final long thetaLong, final boolean ordered) { - seedHash_ = seedHash; - curCount_ = curCount; - empty_ = empty; - ordered_ = ordered; - cache_ = cache; - //computed - thetaLong_ = correctThetaOnCompact(empty, curCount, thetaLong); - preLongs_ = computeCompactPreLongs(empty, curCount, thetaLong); //considers singleItem - singleItem_ = isSingleItem(empty, curCount, thetaLong); - checkIllegalCurCountAndEmpty(empty, curCount); - } - - //ThetaSketch - - @Override - public CompactThetaSketch compact(final boolean dstOrdered, final MemorySegment dstSeg) { - if ((dstSeg == null) && (!dstOrdered || (ordered_ == dstOrdered))) { return this; } - return componentsToCompact(getThetaLong(), getRetainedEntries(true), getSeedHash(), isEmpty(), - true, ordered_, dstOrdered, dstSeg, getCache().clone()); - } - - @Override - public int getCurrentBytes() { - return (preLongs_ + curCount_) << 3; - } - - @Override - public int getRetainedEntries(final boolean valid) { //valid is only relevant for the AlphaSketch - return curCount_; - } - - @Override - public long getThetaLong() { - return thetaLong_; - } - - @Override - public boolean isEmpty() { - return empty_; - } - - @Override - public boolean isOrdered() { - return ordered_; - } - - @Override - public HashIterator iterator() { - return new HeapCompactHashIterator(cache_); - } - - //restricted methods - - @Override - long[] getCache() { - return cache_; - } - - @Override - int getCompactPreambleLongs() { - return preLongs_; - } - - @Override - int getCurrentPreambleLongs() { //already compact; ignored - return preLongs_; - } - - @Override - short getSeedHash() { - return seedHash_; - } - - //use of a MemorySegment is convenient. The byteArray and MemorySegment are loaded simultaneously. - @Override - public byte[] toByteArray() { - final int bytes = getCurrentBytes(); - final byte[] byteArray = new byte[bytes]; - final MemorySegment dstSeg = MemorySegment.ofArray(byteArray); - final int emptyBit = isEmpty() ? EMPTY_FLAG_MASK : 0; - final int orderedBit = ordered_ ? ORDERED_FLAG_MASK : 0; - final int singleItemBit = singleItem_ ? SINGLEITEM_FLAG_MASK : 0; - final byte flags = (byte) (emptyBit | READ_ONLY_FLAG_MASK | COMPACT_FLAG_MASK | orderedBit | singleItemBit); - final int preLongs = getCompactPreambleLongs(); - loadCompactMemorySegment(getCache(), getSeedHash(), getRetainedEntries(true), getThetaLong(), dstSeg, flags, preLongs); - return byteArray; - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/HeapHashIterator.java b/src/main/java/org/apache/datasketches/theta/HeapHashIterator.java deleted file mode 100644 index d689b912e..000000000 --- a/src/main/java/org/apache/datasketches/theta/HeapHashIterator.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -/** - * @author Lee Rhodes - */ -final class HeapHashIterator implements HashIterator { - private long[] cache; - private long thetaLong; - private int index; - private long hash; - - HeapHashIterator(final long[] cache, final long thetaLong) { - this.cache = cache; - this.thetaLong = thetaLong; - index = -1; - hash = 0; - } - - @Override - public long get() { - return hash; - } - - @Override - public boolean next() { - while (++index < cache.length) { - hash = cache[index]; - if ((hash != 0) && (hash < thetaLong)) { - return true; - } - } - return false; - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/HeapQuickSelectSketch.java b/src/main/java/org/apache/datasketches/theta/HeapQuickSelectSketch.java deleted file mode 100644 index a44ac9764..000000000 --- a/src/main/java/org/apache/datasketches/theta/HeapQuickSelectSketch.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.QuickSelect.selectExcludingZeros; -import static org.apache.datasketches.common.Util.LONG_MAX_VALUE_AS_DOUBLE; -import static org.apache.datasketches.theta.PreambleUtil.extractCurCount; -import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.extractLgArrLongs; -import static org.apache.datasketches.theta.PreambleUtil.extractLgNomLongs; -import static org.apache.datasketches.theta.PreambleUtil.extractLgResizeFactor; -import static org.apache.datasketches.theta.PreambleUtil.extractP; -import static org.apache.datasketches.theta.PreambleUtil.extractThetaLong; -import static org.apache.datasketches.theta.UpdateReturnState.InsertedCountIncremented; -import static org.apache.datasketches.theta.UpdateReturnState.InsertedCountIncrementedRebuilt; -import static org.apache.datasketches.theta.UpdateReturnState.InsertedCountIncrementedResized; -import static org.apache.datasketches.theta.UpdateReturnState.RejectedDuplicate; -import static org.apache.datasketches.theta.UpdateReturnState.RejectedOverTheta; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.thetacommon.HashOperations; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * @author Lee Rhodes - * @author Kevin Lang - */ -class HeapQuickSelectSketch extends HeapUpdateSketch { - private final Family MY_FAMILY; - - private final int preambleLongs_; - private int lgArrLongs_; - private int hashTableThreshold_; //never serialized - int curCount_; - long thetaLong_; - boolean empty_; - - private long[] cache_; - - private HeapQuickSelectSketch(final int lgNomLongs, final long seed, final float p, - final ResizeFactor rf, final int preambleLongs, final Family family) { - super(lgNomLongs, seed, p, rf); - preambleLongs_ = preambleLongs; - MY_FAMILY = family; - } - - /** - * Construct a new sketch instance on the java heap. - * - * @param lgNomLongs See lgNomLongs. - * @param seed See seed - * @param p See Sampling Probability, p - * @param rf See Resize Factor - * @param unionGadget true if this sketch is implementing the ThetaUnion gadget function. - * Otherwise, it is behaving as a normal QuickSelectThetaSketch. - */ - HeapQuickSelectSketch(final int lgNomLongs, final long seed, final float p, - final ResizeFactor rf, final boolean unionGadget) { - super(lgNomLongs, seed, p, rf); - - //Choose family, preambleLongs - if (unionGadget) { - preambleLongs_ = Family.UNION.getMinPreLongs(); - MY_FAMILY = Family.UNION; - } - else { - preambleLongs_ = Family.QUICKSELECT.getMinPreLongs(); - MY_FAMILY = Family.QUICKSELECT; - } - - lgArrLongs_ = ThetaUtil.startingSubMultiple(lgNomLongs + 1, rf.lg(), ThetaUtil.MIN_LG_ARR_LONGS); - hashTableThreshold_ = getHashTableThreshold(lgNomLongs, lgArrLongs_); - curCount_ = 0; - thetaLong_ = (long)(p * LONG_MAX_VALUE_AS_DOUBLE); - empty_ = true; //other flags: reserved = readOnly = compact = ordered = false; - cache_ = new long[1 << lgArrLongs_]; - } - - /** - * Heapify a sketch from a MemorySegment UpdatableThetaSketch or ThetaUnion object - * containing sketch data. - * @param srcSeg The source MemorySegment object. - * @param seed See seed - * @return instance of this sketch - */ - static HeapQuickSelectSketch heapifyInstance(final MemorySegment srcSeg, final long seed) { - final int preambleLongs = ThetaSketch.getPreambleLongs(srcSeg); //byte 0 - final int lgNomLongs = extractLgNomLongs(srcSeg); //byte 3 - final int lgArrLongs = extractLgArrLongs(srcSeg); //byte 4 - - checkUnionAndQuickSelectFamily(srcSeg, preambleLongs, lgNomLongs); - checkSegIntegrity(srcSeg, seed, preambleLongs, lgNomLongs, lgArrLongs); - - final float p = extractP(srcSeg); //bytes 12-15 - final int seglgRF = extractLgResizeFactor(srcSeg); //byte 0 - ResizeFactor segRF = ResizeFactor.getRF(seglgRF); - final int familyID = extractFamilyID(srcSeg); - final Family family = Family.idToFamily(familyID); - - if (isResizeFactorIncorrect(srcSeg, lgNomLongs, lgArrLongs)) { - segRF = ResizeFactor.X2; //X2 always works. - } - - final HeapQuickSelectSketch hqss = new HeapQuickSelectSketch(lgNomLongs, seed, p, segRF, - preambleLongs, family); - hqss.lgArrLongs_ = lgArrLongs; - hqss.hashTableThreshold_ = getHashTableThreshold(lgNomLongs, lgArrLongs); - hqss.curCount_ = extractCurCount(srcSeg); - hqss.thetaLong_ = extractThetaLong(srcSeg); - hqss.empty_ = PreambleUtil.isEmptyFlag(srcSeg); - hqss.cache_ = new long[1 << lgArrLongs]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, preambleLongs << 3, hqss.cache_, 0, 1 << lgArrLongs); //read in as hash table - return hqss; - } - - //ThetaSketch - - @Override - public double getEstimate() { - return ThetaSketch.estimate(thetaLong_, curCount_); - } - - @Override - public Family getFamily() { - return MY_FAMILY; - } - - @Override - public int getRetainedEntries(final boolean valid) { //valid is only relevant for the AlphaSketch - return curCount_; - } - - @Override - public long getThetaLong() { - return empty_ ? Long.MAX_VALUE : thetaLong_; - } - - @Override - public boolean isEmpty() { - return empty_; - } - - @Override - public HashIterator iterator() { - return new HeapHashIterator(cache_, thetaLong_); - } - - @Override - public byte[] toByteArray() { - return toByteArray(preambleLongs_, (byte) MY_FAMILY.getID()); - } - - //UpdatableThetaSketch - - @Override - public UpdatableThetaSketch rebuild() { - if (getRetainedEntries(true) > (1 << getLgNomLongs())) { - quickSelectAndRebuild(); - } - return this; - } - - @Override - public void reset() { - final ResizeFactor rf = getResizeFactor(); - final int lgArrLongsSM = ThetaUtil.startingSubMultiple(lgNomLongs_ + 1, rf.lg(), ThetaUtil.MIN_LG_ARR_LONGS); - if (lgArrLongsSM == lgArrLongs_) { - final int arrLongs = cache_.length; - assert (1 << lgArrLongs_) == arrLongs; - java.util.Arrays.fill(cache_, 0L); - } - else { - cache_ = new long[1 << lgArrLongsSM]; - lgArrLongs_ = lgArrLongsSM; - } - hashTableThreshold_ = getHashTableThreshold(lgNomLongs_, lgArrLongs_); - empty_ = true; - curCount_ = 0; - thetaLong_ = (long)(getP() * LONG_MAX_VALUE_AS_DOUBLE); - } - - //restricted methods - - @Override - long[] getCache() { - return cache_; - } - - @Override - int getCompactPreambleLongs() { - return CompactOperations.computeCompactPreLongs(empty_, curCount_, thetaLong_); - } - - @Override - int getCurrentPreambleLongs() { - return preambleLongs_; - } - - //only used by ConcurrentHeapThetaBuffer & Test - int getHashTableThreshold() { - return hashTableThreshold_; - } - - @Override - int getLgArrLongs() { - return lgArrLongs_; - } - - @Override - UpdateReturnState hashUpdate(final long hash) { - HashOperations.checkHashCorruption(hash); - empty_ = false; - - //The over-theta test - if (HashOperations.continueCondition(thetaLong_, hash)) { - return RejectedOverTheta; //signal that hash was rejected due to theta. - } - - //The duplicate test - if (HashOperations.hashSearchOrInsert(cache_, lgArrLongs_, hash) >= 0) { - return RejectedDuplicate; //Duplicate, not inserted - } - //insertion occurred, must increment curCount - curCount_++; - - if (isOutOfSpace(curCount_)) { //we need to do something, we are out of space - //must rebuild or resize - if (lgArrLongs_ <= lgNomLongs_) { //resize - resizeCache(); - return InsertedCountIncrementedResized; - } - //Already at tgt size, must rebuild - assert (lgArrLongs_ == (lgNomLongs_ + 1)) : "lgArr: " + lgArrLongs_ + ", lgNom: " + lgNomLongs_; - quickSelectAndRebuild(); //Changes thetaLong_, curCount_, reassigns cache - return InsertedCountIncrementedRebuilt; - } - return InsertedCountIncremented; - } - - @Override - boolean isDirty() { - return false; - } - - @Override - boolean isOutOfSpace(final int numEntries) { - return numEntries > hashTableThreshold_; - } - - //Must resize. Changes lgArrLongs_, cache_, hashTableThreshold; - // theta and count don't change. - // Used by hashUpdate() - private final void resizeCache() { - final ResizeFactor rf = getResizeFactor(); - final int lgMaxArrLongs = lgNomLongs_ + 1; - final int lgDeltaLongs = lgMaxArrLongs - lgArrLongs_; - final int lgResizeFactor = max(min(rf.lg(), lgDeltaLongs), 1); //rf_.lg() could be 0 - lgArrLongs_ += lgResizeFactor; // new arr size - - final long[] tgtArr = new long[1 << lgArrLongs_]; - final int newCount = HashOperations.hashArrayInsert(cache_, tgtArr, lgArrLongs_, thetaLong_); - - assert newCount == curCount_; //Assumes no dirty values. - curCount_ = newCount; - - cache_ = tgtArr; - hashTableThreshold_ = getHashTableThreshold(lgNomLongs_, lgArrLongs_); - } - - //array stays the same size. Changes theta and thus count - private final void quickSelectAndRebuild() { - final int arrLongs = 1 << lgArrLongs_; // generally 2 * k, - - final int pivot = (1 << lgNomLongs_) + 1; // pivot for QS = k + 1 - - thetaLong_ = selectExcludingZeros(cache_, curCount_, pivot); //messes up the cache_ - - // now we rebuild to clean up dirty data, update count, reconfigure as a hash table - final long[] tgtArr = new long[arrLongs]; - curCount_ = HashOperations.hashArrayInsert(cache_, tgtArr, lgArrLongs_, thetaLong_); - cache_ = tgtArr; - //hashTableThreshold stays the same - } - - /** - * Returns the cardinality limit given the current size of the hash table array. - * - * @param lgNomLongs See lgNomLongs. - * @param lgArrLongs See lgArrLongs. - * @return the hash table threshold - */ - private static final int getHashTableThreshold(final int lgNomLongs, final int lgArrLongs) { - final double fraction = (lgArrLongs <= lgNomLongs) ? ThetaUtil.RESIZE_THRESHOLD : ThetaUtil.REBUILD_THRESHOLD; - return (int) (fraction * (1 << lgArrLongs)); - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/HeapUpdateSketch.java b/src/main/java/org/apache/datasketches/theta/HeapUpdateSketch.java deleted file mode 100644 index e676a6652..000000000 --- a/src/main/java/org/apache/datasketches/theta/HeapUpdateSketch.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.theta.CompactOperations.checkIllegalCurCountAndEmpty; -import static org.apache.datasketches.theta.CompactOperations.correctThetaOnCompact; -import static org.apache.datasketches.theta.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.SER_VER; -import static org.apache.datasketches.theta.PreambleUtil.insertCurCount; -import static org.apache.datasketches.theta.PreambleUtil.insertFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.insertFlags; -import static org.apache.datasketches.theta.PreambleUtil.insertLgArrLongs; -import static org.apache.datasketches.theta.PreambleUtil.insertLgNomLongs; -import static org.apache.datasketches.theta.PreambleUtil.insertLgResizeFactor; -import static org.apache.datasketches.theta.PreambleUtil.insertP; -import static org.apache.datasketches.theta.PreambleUtil.insertPreLongs; -import static org.apache.datasketches.theta.PreambleUtil.insertSeedHash; -import static org.apache.datasketches.theta.PreambleUtil.insertSerVer; -import static org.apache.datasketches.theta.PreambleUtil.insertThetaLong; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * The parent class for HeapUpdatableThetaSketches. - * - * @author Lee Rhodes - */ -abstract class HeapUpdateSketch extends UpdatableThetaSketch { - final int lgNomLongs_; - private final float p_; - private final ResizeFactor rf_; - - HeapUpdateSketch(final int lgNomLongs, final long seed, final float p, final ResizeFactor rf) { - super(seed); - lgNomLongs_ = Math.max(lgNomLongs, ThetaUtil.MIN_LG_NOM_LONGS); - p_ = p; - rf_ = rf; - } - - //ThetaSketch - - @Override - public int getCurrentBytes() { - final int preLongs = getCurrentPreambleLongs(); - final int dataLongs = getCurrentDataLongs(); - return preLongs + dataLongs << 3; - } - - //UpdatableThetaSketch - - @Override - public final int getLgNomLongs() { - return lgNomLongs_; - } - - @Override - float getP() { - return p_; - } - - @Override - public ResizeFactor getResizeFactor() { - return rf_; - } - - //restricted methods - - @Override - short getSeedHash() { - return Util.computeSeedHash(getSeed()); - } - - //Used by HeapAlphaSketch and HeapQuickSelectThetaSketch / UpdatableThetaSketch - byte[] toByteArray(final int preLongs, final byte familyID) { - if (isDirty()) { rebuild(); } - checkIllegalCurCountAndEmpty(isEmpty(), getRetainedEntries(true)); - final int preBytes = (preLongs << 3) & 0X3F; //24 bytes; mask to 6 bits - final int dataBytes = getCurrentDataLongs() << 3; - final byte[] byteArrOut = new byte[preBytes + dataBytes]; - - final MemorySegment segOut = MemorySegment.ofArray(byteArrOut); - - //preamble first 8 bytes. Note: only compact can be reduced to 8 bytes. - final int lgRf = getResizeFactor().lg() & 0x3; //mask to 2 bits - insertPreLongs(segOut, preLongs); //byte 0 low 6 bits - insertLgResizeFactor(segOut, lgRf); //byte 0 high 2 bits - insertSerVer(segOut, SER_VER); //byte 1 - insertFamilyID(segOut, familyID); //byte 2 - insertLgNomLongs(segOut, getLgNomLongs()); //byte 3 - insertLgArrLongs(segOut, getLgArrLongs()); //byte 4 - insertSeedHash(segOut, getSeedHash()); //bytes 6 & 7 - - insertCurCount(segOut, this.getRetainedEntries(true)); - insertP(segOut, getP()); - final long thetaLong = - correctThetaOnCompact(isEmpty(), getRetainedEntries(true), getThetaLong()); - insertThetaLong(segOut, thetaLong); - - //Flags: BigEnd=0, ReadOnly=0, Empty=X, compact=0, ordered=0 - final byte flags = isEmpty() ? (byte) EMPTY_FLAG_MASK : 0; - insertFlags(segOut, flags); - - //Data - final int arrLongs = 1 << getLgArrLongs(); - final long[] cache = getCache(); - //segOut.putLongArray(preBytes, cache, 0, arrLongs); //load byteArrOut - - MemorySegment.copy(cache, 0, segOut, JAVA_LONG_UNALIGNED, preBytes, arrLongs); - return byteArrOut; - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/JaccardSimilarity.java b/src/main/java/org/apache/datasketches/theta/JaccardSimilarity.java deleted file mode 100644 index 2fc9d4fe5..000000000 --- a/src/main/java/org/apache/datasketches/theta/JaccardSimilarity.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.thetacommon.BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA; -import static org.apache.datasketches.thetacommon.BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA; -import static org.apache.datasketches.thetacommon.BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA; - -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * Jaccard similarity of two ThetaSketches. - * - * @author Lee Rhodes - */ -public final class JaccardSimilarity { - private static final double[] ZEROS = {0.0, 0.0, 0.0}; // LB, Estimate, UB - private static final double[] ONES = {1.0, 1.0, 1.0}; - - private JaccardSimilarity() { } - - /** - * Computes the Jaccard similarity index with upper and lower bounds. The Jaccard similarity index - * J(A,B) = (A ^ B)/(A U B) is used to measure how similar the two sketches are to each - * other. If J = 1.0, the sketches are considered equal. If J = 0, the two sketches are - * distinct from each other. A Jaccard of .95 means the overlap between the two - * populations is 95% of the union of the two populations. - * - *

Note: For very large pairs of sketches, where the configured nominal entries of the sketches - * are 2^25 or 2^26, this method may produce unpredictable results. - * - * @param sketchA given sketch A - * @param sketchB given sketch B - * @return a double array {LowerBound, Estimate, UpperBound} of the Jaccard index. - * The Upper and Lower bounds are for a confidence interval of 95.4% or +/- 2 standard deviations. - */ - public static double[] jaccard(final ThetaSketch sketchA, final ThetaSketch sketchB) { - //Corner case checks - if (sketchA == null || sketchB == null) { return ZEROS.clone(); } - if (sketchA == sketchB) { return ONES.clone(); } - if (sketchA.isEmpty() && sketchB.isEmpty()) { return ONES.clone(); } - if (sketchA.isEmpty() || sketchB.isEmpty()) { return ZEROS.clone(); } - - final int countA = sketchA.getRetainedEntries(true); - final int countB = sketchB.getRetainedEntries(true); - - //Create the ThetaUnion - final int minK = 1 << ThetaUtil.MIN_LG_NOM_LONGS; - final int maxK = 1 << ThetaUtil.MAX_LG_NOM_LONGS; - final int newK = max(min(ceilingPowerOf2(countA + countB), maxK), minK); - final ThetaUnion union = - ThetaSetOperation.builder().setNominalEntries(newK).buildUnion(); - union.union(sketchA); - union.union(sketchB); - final ThetaSketch unionAB = union.getResult(false, null); - final long thetaLongUAB = unionAB.getThetaLong(); - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - final int countUAB = unionAB.getRetainedEntries(true); - - //Check for identical data - if (countUAB == countA && countUAB == countB - && thetaLongUAB == thetaLongA && thetaLongUAB == thetaLongB) { - return ONES.clone(); - } - - //Create the ThetaIntersection - final ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(); - inter.intersect(sketchA); - inter.intersect(sketchB); - inter.intersect(unionAB); //ensures that intersection is a subset of the union - final ThetaSketch interABU = inter.getResult(false, null); - - final double lb = getLowerBoundForBoverA(unionAB, interABU); - final double est = getEstimateOfBoverA(unionAB, interABU); - final double ub = getUpperBoundForBoverA(unionAB, interABU); - return new double[] {lb, est, ub}; - } - - /** - * Returns true if the two given sketches have exactly the same hash values and the same - * theta values. Thus, they are equivalent. - * @param sketchA the given sketch A - * @param sketchB the given sketch B - * @return true if the two given sketches have exactly the same hash values and the same - * theta values. - */ - public static boolean exactlyEqual(final ThetaSketch sketchA, final ThetaSketch sketchB) { - //Corner case checks - if (sketchA == null || sketchB == null) { return false; } - if (sketchA == sketchB) { return true; } - if (sketchA.isEmpty() && sketchB.isEmpty()) { return true; } - if (sketchA.isEmpty() || sketchB.isEmpty()) { return false; } - - final int countA = sketchA.getRetainedEntries(true); - final int countB = sketchB.getRetainedEntries(true); - - //Create the ThetaUnion - final ThetaUnion union = - ThetaSetOperation.builder().setNominalEntries(ceilingPowerOf2(countA + countB)).buildUnion(); - union.union(sketchA); - union.union(sketchB); - final ThetaSketch unionAB = union.getResult(); - final long thetaLongUAB = unionAB.getThetaLong(); - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - final int countUAB = unionAB.getRetainedEntries(true); - - //Check for identical counts and thetas - if (countUAB == countA && countUAB == countB - && thetaLongUAB == thetaLongA && thetaLongUAB == thetaLongB) { - return true; - } - return false; - } - - /** - * Tests similarity of a measured ThetaSketch against an expected ThetaSketch. - * Computes the lower bound of the Jaccard index JLB of the measured and - * expected sketches. - * if JLB ≥ threshold, then the sketches are considered to be - * similar with a confidence of 97.7%. - * - * @param measured the sketch to be tested - * @param expected the reference sketch that is considered to be correct. - * @param threshold a real value between zero and one. - * @return if true, the similarity of the two sketches is greater than the given threshold - * with at least 97.7% confidence. - */ - public static boolean similarityTest(final ThetaSketch measured, final ThetaSketch expected, - final double threshold) { - //index 0: the lower bound - //index 1: the mean estimate - //index 2: the upper bound - final double jRatioLB = jaccard(measured, expected)[0]; //choosing the lower bound - return jRatioLB >= threshold; - } - - /** - * Tests dissimilarity of a measured ThetaSketch against an expected ThetaSketch. - * Computes the upper bound of the Jaccard index JUB of the measured and - * expected sketches. - * if JUB ≤ threshold, then the sketches are considered to be - * dissimilar with a confidence of 97.7%. - * - * @param measured the sketch to be tested - * @param expected the reference sketch that is considered to be correct. - * @param threshold a real value between zero and one. - * @return if true, the dissimilarity of the two sketches is greater than the given threshold - * with at least 97.7% confidence. - */ - public static boolean dissimilarityTest(final ThetaSketch measured, final ThetaSketch expected, - final double threshold) { - //index 0: the lower bound - //index 1: the mean estimate - //index 2: the upper bound - final double jRatioUB = jaccard(measured, expected)[2]; //choosing the upper bound - return jRatioUB <= threshold; - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/MemorySegmentCompactCompressedHashIterator.java b/src/main/java/org/apache/datasketches/theta/MemorySegmentCompactCompressedHashIterator.java deleted file mode 100644 index 5a474e49e..000000000 --- a/src/main/java/org/apache/datasketches/theta/MemorySegmentCompactCompressedHashIterator.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.wholeBytesToHoldBits; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentStatus; - -/* - * This is to uncompress serial version 4 sketch incrementally - */ -final class MemorySegmentCompactCompressedHashIterator implements HashIterator, MemorySegmentStatus { - private final MemorySegment seg; - private int offset; - private final int entryBits; - private final int numEntries; - private int index; - private long previous; - private int offsetBits; - private final long[] buffer; - private final byte[] bytes; - private boolean isBlockMode; - private boolean isFirstUnpack1; - - MemorySegmentCompactCompressedHashIterator( - final MemorySegment srcSeg, - final int offset, - final int entryBits, - final int numEntries) { - seg = srcSeg; - this.offset = offset; - this.entryBits = entryBits; - this.numEntries = numEntries; - index = -1; - previous = 0; - offsetBits = 0; - buffer = new long[8]; - bytes = new byte[entryBits]; - isBlockMode = numEntries >= 8; - isFirstUnpack1 = true; - } - - @Override - public long get() { - return buffer[index & 7]; - } - - @Override - public boolean hasMemorySegment() { - return (seg != null) && seg.scope().isAlive(); - } - - @Override - public boolean isOffHeap() { - return hasMemorySegment() && seg.isNative(); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return hasMemorySegment() && MemorySegmentStatus.isSameResource(seg, that); - } - - @Override - public boolean next() { - if (++index == numEntries) { return false; } - if (isBlockMode) { - if ((index & 7) == 0) { - if ((numEntries - index) >= 8) { - unpack8(); - } else { - isBlockMode = false; - unpack1(); - } - } - } else { - unpack1(); - } - return true; - } - - private void unpack1() { - if (isFirstUnpack1) { - MemorySegment.copy(seg, JAVA_BYTE, offset, bytes, 0, wholeBytesToHoldBits((numEntries - index) * entryBits)); - offset = 0; - isFirstUnpack1 = false; - } - final int i = index & 7; - BitPacking.unpackBits(buffer, i, entryBits, bytes, offset, offsetBits); - offset += (offsetBits + entryBits) >>> 3; - offsetBits = (offsetBits + entryBits) & 7; - buffer[i] += previous; - previous = buffer[i]; - } - - private void unpack8() { - MemorySegment.copy(seg, JAVA_BYTE, offset, bytes, 0, entryBits); - BitPacking.unpackBitsBlock8(buffer, 0, bytes, 0, entryBits); - offset += entryBits; - for (int i = 0; i < 8; i++) { - buffer[i] += previous; - previous = buffer[i]; - } - } -} diff --git a/src/main/java/org/apache/datasketches/theta/MemorySegmentHashIterator.java b/src/main/java/org/apache/datasketches/theta/MemorySegmentHashIterator.java deleted file mode 100644 index 89d6b19f2..000000000 --- a/src/main/java/org/apache/datasketches/theta/MemorySegmentHashIterator.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -/** - * @author Lee Rhodes - */ -final class MemorySegmentHashIterator implements HashIterator { - private MemorySegment seg; - private int arrLongs; - private long thetaLong; - private long offsetBytes; - private int index; - private long hash; - - MemorySegmentHashIterator(final MemorySegment srcSeg, final int arrLongs, final long thetaLong) { - this.seg = srcSeg; - this.arrLongs = arrLongs; - this.thetaLong = thetaLong; - offsetBytes = ThetaSketch.getPreambleLongs(srcSeg) << 3; - index = -1; - hash = 0; - } - - @Override - public long get() { - return hash; - } - - @Override - public boolean next() { - while (++index < arrLongs) { - hash = seg.get(JAVA_LONG_UNALIGNED, offsetBytes + (index << 3)); - if ((hash != 0) && (hash < thetaLong)) { - return true; - } - } - return false; - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/PreambleUtil.java b/src/main/java/org/apache/datasketches/theta/PreambleUtil.java deleted file mode 100644 index fcb7f24a4..000000000 --- a/src/main/java/org/apache/datasketches/theta/PreambleUtil.java +++ /dev/null @@ -1,545 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.zeroPad; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; - -//@formatter:off - -/** - * This class defines the preamble data structure and provides basic utilities for some of the key - * fields. - * - *

The intent of the design of this class was to isolate the detailed knowledge of the bit and - * byte layout of the serialized form of the sketches derived from the ThetaSketch class into one place. - * This allows the possibility of the introduction of different serialization - * schemes with minimal impact on the rest of the library.

- * - *

- * MAP: Low significance bytes of this long data structure are on the right. However, the - * multi-byte integers (int and long) are stored in native byte order. The - * byte values are treated as unsigned.

- * - *

An empty CompactThetaSketch only requires 8 bytes. - * Flags: notSI, Ordered*, Compact, Empty*, ReadOnly, LE. - * (*) Earlier versions did not set these.

- * - *
- * Long || Start Byte Adr:
- * Adr:
- *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |     0              |
- *  0   ||    Seed Hash    | Flags  |        |        | FamID  | SerVer |     PreLongs = 1   |
- * 
- * - *

A SingleItemThetaSketch (extends CompactThetaSketch) requires an 8 byte preamble plus a single - * hash item of 8 bytes. Flags: SingleItem*, Ordered, Compact, notEmpty, ReadOnly, LE. - * (*) Earlier versions did not set these.

- * - *
- * Long || Start Byte Adr:
- * Adr:
- *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |     0              |
- *  0   ||    Seed Hash    | Flags  |        |        | FamID  | SerVer |     PreLongs = 1   |
- *
- *      ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |     8              |
- *  1   ||---------------------------Single long hash----------------------------------------|
- * 
- * - *

An exact (non-estimating) CompactThetaSketch requires 16 bytes of preamble plus a compact array of - * longs.

- * - *
- * Long || Start Byte Adr:
- * Adr:
- *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |     0              |
- *  0   ||    Seed Hash    | Flags  |        |        | FamID  | SerVer |     PreLongs = 2   |
- *
- *      ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |     8              |
- *  1   ||-----------------p-----------------|----------Retained Entries Count---------------|
- *
- *      ||   23   |   22   |   21    |  20   |   19   |   18   |   17   |    16              |
- *  2   ||----------------------Start of Compact Long Array----------------------------------|
- * 
- * - *

An estimating CompactThetaSketch requires 24 bytes of preamble plus a compact array of longs.

- * - *
- * Long || Start Byte Adr:
- * Adr:
- *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |     0              |
- *  0   ||    Seed Hash    | Flags  |        |        | FamID  | SerVer |     PreLongs = 3   |
- *
- *      ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |     8              |
- *  1   ||-----------------p-----------------|----------Retained Entries Count---------------|
- *
- *      ||   23   |   22   |   21    |  20   |   19   |   18   |   17   |    16              |
- *  2   ||------------------------------THETA_LONG-------------------------------------------|
- *
- *      ||   31   |   30   |   29   |   28   |   27   |   26   |   25   |    24              |
- *  3   ||----------------------Start of Compact Long Array----------------------------------|
- *  
- * - *

The compressed CompactThetaSketch has 8 bytes of preamble in exact mode because theta can - * be assumed to be 1.0. In estimating mode, the 2nd 8 bytes is Theta as a Long. The following - * table assumes estimating mode. In any case the number of retained entries starts immediately - * after, followed immediately by the delta encoded compressed byte array.

- * Unique to this table: - *
  • Byte 3: entryBits (entBits): max number of bits for any one 64 bit hash not - * including leading zeros. A value in the range [1,63].
  • - *
  • Byte 4: numEntriesBytes (numEB): number of bytes required to hold the integer of number - * of retained entries not including leading zero bytes. A value in the range [1,4].
  • - *
  • The number of retained entries is stored starting at byte 16 (assuming estimating mode) - * and may extend through bytes 17, 18 and 19. In any case, the delta encoded compressed array - * starts immediately after and could start at byte 17, 18, 19 or 20.
  • - *
- * - *
- * Long || Start Byte Adr:
- * Adr:
- *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1     |   0              |
- *  0   ||    Seed Hash    | Flags  | numEB  | entBits| FamID  | SerVer=4 |   PreLongs = 3   |
- *
- *      ||   15   |   14   |   13   |   12   |   11   |   10   |    9     |   8              |
- *  1   ||------------------------------THETA_LONG-------------------------------------------| (only if estimating)
- *
- *      ||        |        |        |   20   |  (19)  |  (18)  |  (17)    |  16              |
- *  2   ||--------Retained Entries stored as 1 to 4 bytes in bytes 16-19---------------------|
- *
- *      ||        |        |        |        |        |        |          |                  |
- *  3   ||--------Delta encoded compressed byte array starts at bytes 17-20------------------|
- *  
- * - *

The UpdatableThetaSketch and AlphaSketch require 24 bytes of preamble followed by a non-compact - * array of longs representing a hash table.

- * - *

The following table applies to both the Theta UpdatableThetaSketch and the AlphaSketch

- *
- * Long || Start Byte Adr:
- * Adr:
- *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |     0              |
- *  0   ||    Seed Hash    | Flags  |  LgArr |  lgNom | FamID  | SerVer | RF, PreLongs = 3   |
- *
- *      ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |     8              |
- *  1   ||-----------------p-----------------|----------Retained Entries Count---------------|
- *
- *      ||   23   |   22   |   21    |  20   |   19   |   18   |   17   |    16              |
- *  2   ||------------------------------THETA_LONG-------------------------------------------|
- *
- *      ||   31   |   30   |   29   |   28   |   27   |   26   |   25   |    24              |
- *  3   ||----------------------Start of Hash Table of longs---------------------------------|
- *  
- * - *

ThetaUnion objects require 32 bytes of preamble plus a non-compact array of longs representing a - * hash table.

- * - *
- * Long || Start Byte Adr:
- * Adr:
- *      ||    7   |    6   |    5   |    4   |    3   |    2   |    1   |     0              |
- *  0   ||    Seed Hash    | Flags  |  LgArr |  lgNom | FamID  | SerVer | RF, PreLongs = 4   |
- *
- *      ||   15   |   14   |   13   |   12   |   11   |   10   |    9   |     8              |
- *  1   ||-----------------p-----------------|----------Retained Entries Count---------------|
- *
- *      ||   23   |   22   |   21    |  20   |   19   |   18   |   17   |    16              |
- *  2   ||------------------------------THETA_LONG-------------------------------------------|
- *
- *      ||   31   |   30   |   29   |   28   |   27   |   26   |   25   |    24              |
- *  3   ||---------------------------UNION THETA LONG----------------------------------------|
- *
- *      ||   39   |   38   |   37   |   36   |   35   |   34   |   33   |    32              |
- *  4   ||----------------------Start of Hash Table of longs---------------------------------|
- *
- *  
- * - * @author Lee Rhodes - */ -final class PreambleUtil { - - private PreambleUtil() {} - - // ###### DO NOT MESS WITH THIS FROM HERE ... - // Preamble byte Addresses - static final int PREAMBLE_LONGS_BYTE = 0; //lower 6 bits in byte 0. - static final int LG_RESIZE_FACTOR_BIT = 6; //upper 2 bits in byte 0. Used by Update, Alpha, not used by compact, direct - static final int SER_VER_BYTE = 1; - static final int FAMILY_BYTE = 2; - static final int LG_NOM_LONGS_BYTE = 3; //not used by compact - static final int LG_ARR_LONGS_BYTE = 4; //not used by compact - static final int FLAGS_BYTE = 5; - static final int SEED_HASH_SHORT = 6; //byte 6,7 - static final int RETAINED_ENTRIES_INT = 8; //8 byte aligned - static final int P_FLOAT = 12; //4 byte aligned, not used by compact - static final int THETA_LONG = 16; //8-byte aligned - static final int UNION_THETA_LONG = 24; //8-byte aligned, only used by ThetaUnion - - // flag byte bit masks - static final int RESERVED_FLAG_MASK = 1; //Bit 0: Reserved, no longer used. Was BigEndian - static final int READ_ONLY_FLAG_MASK = 2; //Bit 1: Reserved, Set but not read. - static final int EMPTY_FLAG_MASK = 4; //Bit 2: - static final int COMPACT_FLAG_MASK = 8; //Bit 3: - static final int ORDERED_FLAG_MASK = 16;//Bit 4: - static final int SINGLEITEM_FLAG_MASK = 32;//Bit 5: - //The last 2 bits (Bit 6,7) of the flags byte are reserved and assumed to be zero. - - //Other constants - static final int SER_VER = 3; - static final int SER_VER_COMPRESSED = 4; - - // serial version 4 compressed ordered sketch, not empty, not single item - static final int ENTRY_BITS_BYTE_V4 = 3; // number of bits packed in deltas between hashes - static final int NUM_ENTRIES_BYTES_BYTE_V4 = 4; // number of bytes used for the number of entries - static final int THETA_LONG_V4 = 8; //8-byte aligned - - /** - * Computes the number of bytes required for an updatable sketch using a hash-table cache. - * This does not apply for compact sketches. - * @param lgArrLongs log2(current hash-table size) - * @param preambleLongs current preamble size - * @return the size in bytes - */ - static int getUpdatableSegBytes(final int lgArrLongs, final int preambleLongs) { - return (8 << lgArrLongs) + (preambleLongs << 3); - } - - // STRINGS - - /** - * Returns a human readable string summary of the preamble state of the given byte array. - * Used primarily in testing. - * - * @param byteArr the given byte array. - * @return the summary preamble string. - */ - static String preambleToString(final byte[] byteArr) { - final MemorySegment seg = MemorySegment.ofArray(byteArr); - return preambleToString(seg); - } - - /** - * Returns a human readable string summary of the preamble state of the given MemorySegment. - * Note: other than making sure that the given MemorySegment size is large - * enough for just the preamble, this does not do much value checking of the contents of the - * preamble as this is primarily a tool for debugging the preamble visually. - * - * @param seg the given MemorySegment. - * @return the summary preamble string. - */ - static String preambleToString(final MemorySegment seg) { - final int preLongs = checkSegPreambleCap(seg); - final int rfId = extractLgResizeFactor(seg); - final ResizeFactor rf = ResizeFactor.getRF(rfId); - final int serVer = extractSerVer(seg); - final int familyId = extractFamilyID(seg); - final Family family = Family.idToFamily(familyId); - final int lgNomLongs = extractLgNomLongs(seg); - final int lgArrLongs = extractLgArrLongs(seg); - - //Flags - final int flags = extractFlags(seg); - final String flagsStr = flags + ", 0x" + Integer.toHexString(flags) + ", " - + zeroPad(Integer.toBinaryString(flags), 8); - final boolean readOnly = (flags & READ_ONLY_FLAG_MASK) > 0; - final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; - final boolean compact = (flags & COMPACT_FLAG_MASK) > 0; - final boolean ordered = (flags & ORDERED_FLAG_MASK) > 0; - final boolean singleItem = (flags & SINGLEITEM_FLAG_MASK) > 0; //!empty && (preLongs == 1); - - final int seedHash = extractSeedHash(seg); - - //assumes preLongs == 1; empty or singleItem - int curCount = singleItem ? 1 : 0; - float p = (float) 1.0; //preLongs 1 or 2 - long thetaLong = Long.MAX_VALUE; //preLongs 1 or 2 - long thetaULong = thetaLong; //preLongs 1, 2 or 3 - - if (preLongs == 2) { //exact (non-estimating) CompactThetaSketch - curCount = extractCurCount(seg); - p = extractP(seg); - } - else if (preLongs == 3) { //UpdatableThetaSketch - curCount = extractCurCount(seg); - p = extractP(seg); - thetaLong = extractThetaLong(seg); - thetaULong = thetaLong; - } - else if (preLongs == 4) { //ThetaUnion - curCount = extractCurCount(seg); - p = extractP(seg); - thetaLong = extractThetaLong(seg); - thetaULong = extractUnionThetaLong(seg); - } - //else the same as an empty sketch or singleItem - - final double thetaDbl = thetaLong / Util.LONG_MAX_VALUE_AS_DOUBLE; - final String thetaHex = zeroPad(Long.toHexString(thetaLong), 16); - final double thetaUDbl = thetaULong / Util.LONG_MAX_VALUE_AS_DOUBLE; - final String thetaUHex = zeroPad(Long.toHexString(thetaULong), 16); - - final StringBuilder sb = new StringBuilder(); - sb.append(LS); - sb.append("### SKETCH PREAMBLE SUMMARY:").append(LS); - sb.append("Byte 0: Preamble Longs : ").append(preLongs).append(LS); - sb.append("Byte 0: ResizeFactor : ").append(rfId + ", " + rf.toString()).append(LS); - sb.append("Byte 1: Serialization Version: ").append(serVer).append(LS); - sb.append("Byte 2: Family : ").append(familyId + ", " + family.toString()).append(LS); - sb.append("Byte 3: LgNomLongs, LgK : ").append(lgNomLongs).append(LS); - sb.append("Byte 4: LgArrLongs : ").append(lgArrLongs).append(LS); - sb.append("Byte 5: Flags Field : ").append(flagsStr).append(LS); - sb.append(" Bit Flag Name : State:").append(LS); - sb.append(" 0 RESERVED : ").append(LS); - sb.append(" 1 READ_ONLY : ").append(readOnly).append(LS); - sb.append(" 2 EMPTY : ").append(empty).append(LS); - sb.append(" 3 COMPACT : ").append(compact).append(LS); - sb.append(" 4 ORDERED : ").append(ordered).append(LS); - sb.append(" 5 SINGLE_ITEM : ").append(singleItem).append(LS); - sb.append("Bytes 6-7 : Seed Hash Hex : ").append(Integer.toHexString(seedHash)).append(LS); - if (preLongs == 1) { - sb.append(" --ABSENT FIELDS, ASSUMED:").append(LS); - sb.append("Bytes 8-11 : CurrentCount : ").append(curCount).append(LS); - sb.append("Bytes 12-15: P : ").append(p).append(LS); - sb.append("Bytes 16-23: Theta (double) : ").append(thetaDbl).append(LS); - sb.append(" Theta (long) : ").append(thetaLong).append(LS); - sb.append(" Theta (long,hex) : ").append(thetaHex).append(LS); - } - else if (preLongs == 2) { - sb.append("Bytes 8-11 : CurrentCount : ").append(curCount).append(LS); - sb.append("Bytes 12-15: P : ").append(p).append(LS); - sb.append(" --ABSENT, ASSUMED:").append(LS); - sb.append("Bytes 16-23: Theta (double) : ").append(thetaDbl).append(LS); - sb.append(" Theta (long) : ").append(thetaLong).append(LS); - sb.append(" Theta (long,hex) : ").append(thetaHex).append(LS); - } - else if (preLongs == 3) { - sb.append("Bytes 8-11 : CurrentCount : ").append(curCount).append(LS); - sb.append("Bytes 12-15: P : ").append(p).append(LS); - sb.append("Bytes 16-23: Theta (double) : ").append(thetaDbl).append(LS); - sb.append(" Theta (long) : ").append(thetaLong).append(LS); - sb.append(" Theta (long,hex) : ").append(thetaHex).append(LS); - if (serVer == 4) { - sb.append( "TOTAL Storage Bytes : ").append(seg.byteSize()).append(LS); - sb.append("### END SKETCH PREAMBLE SUMMARY").append(LS); - return sb.toString(); - } - } - else { //preLongs == 4 (ThetaUnion) - sb.append("Bytes 8-11 : CurrentCount : ").append(curCount).append(LS); - sb.append("Bytes 12-15: P : ").append(p).append(LS); - sb.append("Bytes 16-23: Theta (double) : ").append(thetaDbl).append(LS); - sb.append(" Theta (long) : ").append(thetaLong).append(LS); - sb.append(" Theta (long,hex) : ").append(thetaHex).append(LS); - sb.append("Bytes 25-31: ThetaU (double) : ").append(thetaUDbl).append(LS); - sb.append(" ThetaU (long) : ").append(thetaULong).append(LS); - sb.append(" ThetaU (long,hex): ").append(thetaUHex).append(LS); - } - sb.append( "Preamble Bytes : ").append(preLongs * 8).append(LS); - sb.append( "Retained Data Bytes : ").append(curCount * 8).append(LS); - sb.append( "TOTAL Storage Bytes : ").append(seg.byteSize()).append(LS); - sb.append("### END SKETCH PREAMBLE SUMMARY").append(LS); - return sb.toString(); - } - - //@formatter:on - - static int extractPreLongs(final MemorySegment seg) { - return seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE) & 0X3F; - } - - static int extractLgResizeFactor(final MemorySegment seg) { - return seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE) >>> LG_RESIZE_FACTOR_BIT & 0X3; - } - - static int extractSerVer(final MemorySegment seg) { - return seg.get(JAVA_BYTE, SER_VER_BYTE) & 0XFF; - } - - static int extractFamilyID(final MemorySegment seg) { - return seg.get(JAVA_BYTE, FAMILY_BYTE) & 0XFF; - } - - static int extractLgNomLongs(final MemorySegment seg) { - return seg.get(JAVA_BYTE, LG_NOM_LONGS_BYTE) & 0XFF; - } - - static int extractLgArrLongs(final MemorySegment seg) { - return seg.get(JAVA_BYTE, LG_ARR_LONGS_BYTE) & 0XFF; - } - - static int extractFlags(final MemorySegment seg) { - return seg.get(JAVA_BYTE, FLAGS_BYTE) & 0XFF; - } - - static int extractSeedHash(final MemorySegment seg) { - return seg.get(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT) & 0XFFFF; - } - - static int extractCurCount(final MemorySegment seg) { - return seg.get(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT); - } - - static float extractP(final MemorySegment seg) { - return seg.get(JAVA_FLOAT_UNALIGNED, P_FLOAT); - } - - static long extractThetaLong(final MemorySegment seg) { - return seg.get(JAVA_LONG_UNALIGNED, THETA_LONG); - } - - static long extractUnionThetaLong(final MemorySegment seg) { - return seg.get(JAVA_LONG_UNALIGNED, UNION_THETA_LONG); - } - - static int extractEntryBitsV4(final MemorySegment seg) { - return seg.get(JAVA_BYTE, ENTRY_BITS_BYTE_V4) & 0XFF; - } - - static int extractNumEntriesBytesV4(final MemorySegment seg) { - return seg.get(JAVA_BYTE, NUM_ENTRIES_BYTES_BYTE_V4) & 0XFF; - } - - static long extractThetaLongV4(final MemorySegment seg) { - return seg.get(JAVA_LONG_UNALIGNED, THETA_LONG_V4); - } - - /** - * Sets PreLongs in the low 6 bits and sets LgRF in the upper 2 bits = 0. - * @param seg the target MemorySegment - * @param preLongs the given number of preamble longs - */ - static void insertPreLongs(final MemorySegment seg, final int preLongs) { - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) (preLongs & 0X3F)); - } - - /** - * Sets the top 2 lgRF bits and does not affect the lower 6 bits (PreLongs). - * To work properly, this should be called after insertPreLongs(). - * @param seg the target MemorySegment - * @param rf the given lgRF bits - */ - static void insertLgResizeFactor(final MemorySegment seg, final int rf) { - final int curByte = seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE) & 0xFF; - final int shift = LG_RESIZE_FACTOR_BIT; // shift in bits - final int mask = 3; - final byte newByte = (byte) (((rf & mask) << shift) | (~(mask << shift) & curByte)); - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, newByte); - } - - static void insertSerVer(final MemorySegment seg, final int serVer) { - seg.set(JAVA_BYTE, SER_VER_BYTE, (byte) serVer); - } - - static void insertFamilyID(final MemorySegment seg, final int famId) { - seg.set(JAVA_BYTE, FAMILY_BYTE, (byte) famId); - } - - static void insertLgNomLongs(final MemorySegment seg, final int lgNomLongs) { - seg.set(JAVA_BYTE, LG_NOM_LONGS_BYTE, (byte) lgNomLongs); - } - - static void insertLgArrLongs(final MemorySegment seg, final int lgArrLongs) { - seg.set(JAVA_BYTE, LG_ARR_LONGS_BYTE, (byte) lgArrLongs); - } - - static void insertFlags(final MemorySegment seg, final int flags) { - seg.set(JAVA_BYTE, FLAGS_BYTE, (byte) flags); - } - - static void insertSeedHash(final MemorySegment seg, final int seedHash) { - seg.set(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT, (short) seedHash); - } - - static void insertCurCount(final MemorySegment seg, final int curCount) { - seg.set(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT, curCount); - } - - static void insertP(final MemorySegment seg, final float p) { - seg.set(JAVA_FLOAT_UNALIGNED, P_FLOAT, p); - } - - static void insertThetaLong(final MemorySegment seg, final long thetaLong) { - seg.set(JAVA_LONG_UNALIGNED, THETA_LONG, thetaLong); - } - - static void insertUnionThetaLong(final MemorySegment seg, final long unionThetaLong) { - seg.set(JAVA_LONG_UNALIGNED, UNION_THETA_LONG, unionThetaLong); - } - - static void setEmpty(final MemorySegment seg) { - int flags = seg.get(JAVA_BYTE, FLAGS_BYTE) & 0XFF; - flags |= EMPTY_FLAG_MASK; - seg.set(JAVA_BYTE, FLAGS_BYTE, (byte) flags); - } - - static void clearEmpty(final MemorySegment seg) { - int flags = seg.get(JAVA_BYTE, FLAGS_BYTE) & 0XFF; - flags &= ~EMPTY_FLAG_MASK; - seg.set(JAVA_BYTE, FLAGS_BYTE, (byte) flags); - } - - static boolean isEmptyFlag(final MemorySegment seg) { - return (extractFlags(seg) & EMPTY_FLAG_MASK) > 0; - } - - /** - * Checks MemorySegment for capacity to hold the preamble and returns the extracted preLongs. - * @param seg the given MemorySegment - * @return the extracted prelongs value. - */ - static int checkSegPreambleCap(final MemorySegment seg) { - try { - final int preLongs = extractPreLongs(seg); - final int required = Math.max(preLongs << 3, 8); - final long cap = seg.byteSize(); - if (cap < required) { throwNotBigEnough(cap, required); } - return preLongs; - } catch (IndexOutOfBoundsException e) { //thrown by MemorySegment - throw new SketchesArgumentException("Possible Corruption: Given MemorySegment is empty."); - } - } - - static short checkSegmentSeedHash(final MemorySegment seg, final long seed) { - final short seedHashSeg = (short) extractSeedHash(seg); - Util.checkSeedHashes(seedHashSeg, Util.computeSeedHash(seed)); //throws if bad seedHash - return seedHashSeg; - } - - private static void throwNotBigEnough(final long cap, final long required) { - throw new SketchesArgumentException( - "Possible Corruption: Size of MemorySegment not large enough: Size: " + cap - + " < Required: " + required); - } - - static int wholeBytesToHoldBits(final int bits) { - return (bits >>> 3) + ((bits & 7) > 0 ? 1 : 0); - } -} diff --git a/src/main/java/org/apache/datasketches/theta/Rebuilder.java b/src/main/java/org/apache/datasketches/theta/Rebuilder.java deleted file mode 100644 index 54b1e190b..000000000 --- a/src/main/java/org/apache/datasketches/theta/Rebuilder.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.QuickSelect.selectExcludingZeros; -import static org.apache.datasketches.theta.PreambleUtil.LG_ARR_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.extractCurCount; -import static org.apache.datasketches.theta.PreambleUtil.extractLgArrLongs; -import static org.apache.datasketches.theta.PreambleUtil.extractThetaLong; -import static org.apache.datasketches.theta.PreambleUtil.insertCurCount; -import static org.apache.datasketches.theta.PreambleUtil.insertLgArrLongs; -import static org.apache.datasketches.theta.PreambleUtil.insertThetaLong; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.HashOperations; - -/** - * This class performs resize, rebuild and move operations where the input and output are Theta sketch images in MemorySegments. - * - *

NOTE: These operations copy data from the input MemorySegment into local arrays, perform the required operations on the - * arrays, and then copies the result to the destination MemorySegment. Attempting to perform these operations directly on the - * MemorySegments would be slower due to MemorySegment internal checks. Meanwhile, he bulk copies performed by the MemorySegments are - * vectorized at the machine level and are quite fast. Measurements reveal that this is a good tradeoff.

- * - * @author Lee Rhodes - */ -final class Rebuilder { - - private Rebuilder() {} - - /** - * Rebuild the hashTable in the given MemorySegment at its current size. Changes theta and thus count. - * This assumes a MemorySegment preamble of standard form with correct values of curCount and thetaLong. - * ThetaLong and curCount will change. - * Afterwards, caller must update local class members curCount and thetaLong from MemorySegment. - * - * @param seg the given MemorySegment - * @param preambleLongs size of preamble in longs - * @param lgNomLongs the log_base2 of k, the configuration parameter of the sketch - */ - static final void quickSelectAndRebuild(final MemorySegment seg, final int preambleLongs, final int lgNomLongs) { - - //Copy data from input segment into local buffer array for QS algorithm - final int lgArrLongs = extractLgArrLongs(seg); - final int arrLongs = 1 << lgArrLongs; - final long[] tmpArr = new long[arrLongs]; - final int preBytes = preambleLongs << 3; - MemorySegment.copy(seg, JAVA_LONG_UNALIGNED, preBytes, tmpArr, 0, arrLongs); - - //Do the QuickSelect on a tmp arr to create new thetaLong - final int pivot = (1 << lgNomLongs) + 1; // (K+1) pivot for QS - final long newThetaLong = selectExcludingZeros(tmpArr, extractCurCount(seg), pivot); - insertThetaLong(seg, newThetaLong); //UPDATE thetaLong - - //Rebuild to clean up dirty data, update count - final long[] tgtArr = new long[arrLongs]; - final int newCurCount = - HashOperations.hashArrayInsert(tmpArr, tgtArr, lgArrLongs, newThetaLong); - insertCurCount(seg, newCurCount); //UPDATE curCount - - //put the rebuilt array back into MemorySegment - MemorySegment.copy(tgtArr, 0, seg, JAVA_LONG_UNALIGNED, preBytes, arrLongs); - } - - /** - * Moves me (the entire updatable sketch) to a new larger MemorySegment location and rebuilds the hash table. - * This assumes a MemorySegment preamble of standard form with the correct value of thetaLong. - * Afterwards, the caller must update the local MemorySegment reference, lgArrLongs - * and hashTableThreshold from the destination MemorySegment and free the source MemorySegment. - * - * @param srcSeg the source MemorySegment - * @param preambleLongs size of preamble in longs - * @param srcLgArrLongs size (log_base2) of source hash table - * @param dstSeg the destination MemorySegment, which may be garbage - * @param dstLgArrLongs the destination hash table target size - * @param thetaLong theta as a long - */ - static final void moveAndResize(final MemorySegment srcSeg, final int preambleLongs, - final int srcLgArrLongs, final MemorySegment dstSeg, final int dstLgArrLongs, final long thetaLong) { - - //Move Preamble to destination MemorySegment - final int preBytes = preambleLongs << 3; - MemorySegment.copy(srcSeg, 0, dstSeg, 0, preBytes); - - //Bulk copy source Hash Table to local buffer array - final int srcHTLen = 1 << srcLgArrLongs; - final long[] srcHTArr = new long[srcHTLen]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, preBytes, srcHTArr, 0, srcHTLen); - - //Create destination buffer - final int dstHTLen = 1 << dstLgArrLongs; - final long[] dstHTArr = new long[dstHTLen]; - - //Rebuild hash table in destination buffer - HashOperations.hashArrayInsert(srcHTArr, dstHTArr, dstLgArrLongs, thetaLong); - - //Bulk copy to destination MemorySegment - MemorySegment.copy(dstHTArr, 0, dstSeg, JAVA_LONG_UNALIGNED, preBytes, dstHTLen); - dstSeg.set(JAVA_BYTE, LG_ARR_LONGS_BYTE, (byte)dstLgArrLongs); //update lgArrLongs in dstSeg - } - - /** - * Resizes existing hash array into a larger one within a single MemorySegment, assuming enough space. - * This assumes a preamble of standard form with the correct value of thetaLong. - * The lgArrLongs will change. - * Afterwards, the caller must update the caller's local copies of lgArrLongs and hashTableThreshold - * from the returned MemorySegment. - * - * @param seg the source and destination MemorySegment - * @param preambleLongs the size of the preamble in longs - * @param srcLgArrLongs the size of the source hash table - * @param tgtLgArrLongs the LgArrLongs value for the new hash table - */ - static final void resize(final MemorySegment seg, final int preambleLongs, - final int srcLgArrLongs, final int tgtLgArrLongs) { - - //Preamble stays in place - final int preBytes = preambleLongs << 3; - - //Bulk copy source to on-heap buffer - final int srcHTLen = 1 << srcLgArrLongs; //current value - final long[] srcHTArr = new long[srcHTLen]; //on-heap src buffer - //seg.getLongArray(preBytes, srcHTArr, 0, srcHTLen); - MemorySegment.copy(seg, JAVA_LONG_UNALIGNED, preBytes, srcHTArr, 0, srcHTLen); - - //Create destination on-heap buffer - final int dstHTLen = 1 << tgtLgArrLongs; - final long[] dstHTArr = new long[dstHTLen]; //on-heap dst buffer - - //Rebuild hash table in destination buffer - HashOperations.hashArrayInsert(srcHTArr, dstHTArr, tgtLgArrLongs, extractThetaLong(seg)); - - //Bulk copy to destination segment - MemorySegment.copy(dstHTArr, 0, seg, JAVA_LONG_UNALIGNED, preBytes, dstHTLen); - insertLgArrLongs(seg, tgtLgArrLongs); //update in mem - } - - /** - * Returns the actual log2 Resize Factor that can be used to grow the hash table. This will be - * an integer value between zero and the given lgRF, inclusive; - * @param capBytes the current MemorySegment capacity in bytes - * @param lgArrLongs the current lg hash table size in longs - * @param preLongs the current preamble size in longs - * @param lgRF the configured lg Resize Factor - * @return the actual log2 Resize Factor that can be used to grow the hash table - */ - static final int actLgResizeFactor(final long capBytes, final int lgArrLongs, final int preLongs, - final int lgRF) { - final int maxHTLongs = Util.floorPowerOf2(((int)(capBytes >>> 3) - preLongs)); - final int lgFactor = Math.max(Integer.numberOfTrailingZeros(maxHTLongs) - lgArrLongs, 0); - return (lgFactor >= lgRF) ? lgRF : lgFactor; - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/SingleItemSketch.java b/src/main/java/org/apache/datasketches/theta/SingleItemSketch.java deleted file mode 100644 index 57112fedd..000000000 --- a/src/main/java/org/apache/datasketches/theta/SingleItemSketch.java +++ /dev/null @@ -1,411 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.datasketches.common.ByteArrayUtil.putLongLE; -import static org.apache.datasketches.hash.MurmurHash3.hash; -import static org.apache.datasketches.theta.PreambleUtil.SINGLEITEM_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.checkSegPreambleCap; -import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.extractFlags; -import static org.apache.datasketches.theta.PreambleUtil.extractSeedHash; -import static org.apache.datasketches.theta.PreambleUtil.extractSerVer; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; - -/** - * A CompactThetaSketch that holds only one item hash. - * - * @author Lee Rhodes - */ -final class SingleItemSketch extends CompactThetaSketch { - private static final long DEFAULT_SEED_HASH = Util.computeSeedHash(Util.DEFAULT_UPDATE_SEED) & 0xFFFFL; - - // For backward compatibility, a candidate pre0_ long must have: - // Flags (byte 5): Ordered, Compact, NOT Empty, Read Only, NOT BigEndian = 11010 = 0x1A. (without SI flag) - // Flags mask will be 0x1F. - // SingleItem flag may not be set due to a historical bug, so we can't depend on it for now. - // However, if the above flags are correct, preLongs == 1, SerVer >= 3, FamilyID == 3, - // and the hash seed matches, it is virtually guaranteed that we have a SingleItemThetaSketch. - - private static final long PRE0_LO6_SI = 0X00_00_3A_00_00_03_03_01L; //low 6 bytes, with SI flag - private long pre0_ = 0; - private long hash_ = 0; - - //Internal Constructor. All checking & hashing has been done, assumes default seed - private SingleItemSketch(final long hash) { - pre0_ = (DEFAULT_SEED_HASH << 48) | PRE0_LO6_SI; - hash_ = hash; - } - - //All checking & hashing has been done, given the relevant seed - SingleItemSketch(final long hash, final long seed) { - final long seedHash = Util.computeSeedHash(seed) & 0xFFFFL; - pre0_ = (seedHash << 48) | PRE0_LO6_SI; - hash_ = hash; - } - - //All checking & hashing has been done, given the relevant seedHash - SingleItemSketch(final long hash, final short seedHash) { - final long seedH = seedHash & 0xFFFFL; - pre0_ = (seedH << 48) | PRE0_LO6_SI; - hash_ = hash; - } - - /** - * Creates a SingleItemSketch on the heap given a SingleItemThetaSketch MemorySegment image and a seedHash. - * Checks the seed hash of the given MemorySegment against the given seedHash. - * @param srcSeg the MemorySegment to be heapified. - * @param expectedSeedHash the given seedHash to be checked against the srcSeg seedHash - * @return a SingleItemThetaSketch - */ //does not override ThetaSketch - static SingleItemSketch heapify(final MemorySegment srcSeg, final short expectedSeedHash) { - Util.checkSeedHashes((short) extractSeedHash(srcSeg), expectedSeedHash); - final boolean singleItem = checkForSingleItem(srcSeg); - if (singleItem) { return new SingleItemSketch(srcSeg.get(JAVA_LONG_UNALIGNED, 8), expectedSeedHash); } - throw new SketchesArgumentException("Input MemorySegment is not a SingleItemSketch."); - } - - @Override - public CompactThetaSketch compact(final boolean dstOrdered, final MemorySegment dstSeg) { - if (dstSeg == null) { return this; } - else { - dstSeg.set(JAVA_LONG_UNALIGNED, 0, pre0_); - dstSeg.set(JAVA_LONG_UNALIGNED, 8, hash_); - return new DirectCompactSketch(dstSeg); - } - } - - //Create methods using the default seed - - /** - * Create this sketch with a long. - * - * @param datum The given long datum. - * @return a SingleItemThetaSketch - */ - static SingleItemSketch create(final long datum) { - final long[] data = { datum }; - return new SingleItemSketch(hash(data, Util.DEFAULT_UPDATE_SEED)[0] >>> 1); - } - - /** - * Create this sketch with the given double (or float) datum. - * The double will be converted to a long using Double.doubleToLongBits(datum), - * which normalizes all NaN values to a single NaN representation. - * Plus and minus zero will be normalized to plus zero. - * The special floating-point values NaN and +/- Infinity are treated as distinct. - * - * @param datum The given double datum. - * @return a SingleItemThetaSketch - */ - static SingleItemSketch create(final double datum) { - final double d = (datum == 0.0) ? 0.0 : datum; // canonicalize -0.0, 0.0 - final long[] data = { Double.doubleToLongBits(d) };// canonicalize all NaN forms - return new SingleItemSketch(hash(data, Util.DEFAULT_UPDATE_SEED)[0] >>> 1); - } - - /** - * Create this sketch with the given String. - * The string is converted to a byte array using UTF8 encoding. - * If the string is null or empty no create attempt is made and the method returns null. - * - *

Note: this will not produce the same hash values as the {@link #create(char[])} - * method and will generally be a little slower depending on the complexity of the UTF8 encoding. - *

- * - * @param datum The given String. - * @return a SingleItemThetaSketch or null - */ - static SingleItemSketch create(final String datum) { - if ((datum == null) || datum.isEmpty()) { return null; } - final byte[] data = datum.getBytes(UTF_8); - return new SingleItemSketch(hash(data, Util.DEFAULT_UPDATE_SEED)[0] >>> 1); - } - - /** - * Create this sketch with the given byte array. - * If the byte array is null or empty no create attempt is made and the method returns null. - * - * @param data The given byte array. - * @return a SingleItemThetaSketch or null - */ - static SingleItemSketch create(final byte[] data) { - if ((data == null) || (data.length == 0)) { return null; } - return new SingleItemSketch(hash(data, Util.DEFAULT_UPDATE_SEED)[0] >>> 1); - } - - /** - * Create this sketch with the given char array. - * If the char array is null or empty no create attempt is made and the method returns null. - * - *

Note: this will not produce the same output hash values as the {@link #create(String)} - * method but will be a little faster as it avoids the complexity of the UTF8 encoding.

- * - * @param data The given char array. - * @return a SingleItemThetaSketch or null - */ - static SingleItemSketch create(final char[] data) { - if ((data == null) || (data.length == 0)) { return null; } - return new SingleItemSketch(hash(data, Util.DEFAULT_UPDATE_SEED)[0] >>> 1); - } - - /** - * Create this sketch with the given integer array. - * If the integer array is null or empty no create attempt is made and the method returns null. - * - * @param data The given int array. - * @return a SingleItemThetaSketch or null - */ - static SingleItemSketch create(final int[] data) { - if ((data == null) || (data.length == 0)) { return null; } - return new SingleItemSketch(hash(data, Util.DEFAULT_UPDATE_SEED)[0] >>> 1); - } - - /** - * Create this sketch with the given long array. - * If the long array is null or empty no create attempt is made and the method returns null. - * - * @param data The given long array. - * @return a SingleItemThetaSketch or null - */ - static SingleItemSketch create(final long[] data) { - if ((data == null) || (data.length == 0)) { return null; } - return new SingleItemSketch(hash(data, Util.DEFAULT_UPDATE_SEED)[0] >>> 1); - } - - //Updates with a user specified seed - - /** - * Create this sketch with a long and a seed. - * - * @param datum The given long datum. - * @param seed used to hash the given value. - * @return a SingleItemThetaSketch - */ - static SingleItemSketch create(final long datum, final long seed) { - final long[] data = { datum }; - return new SingleItemSketch(hash(data, seed)[0] >>> 1); - } - - /** - * Create this sketch with the given double (or float) datum and a seed. - * The double will be converted to a long using Double.doubleToLongBits(datum), - * which normalizes all NaN values to a single NaN representation. - * Plus and minus zero will be normalized to plus zero. - * The special floating-point values NaN and +/- Infinity are treated as distinct. - * - * @param datum The given double datum. - * @param seed used to hash the given value. - * @return a SingleItemThetaSketch - */ - static SingleItemSketch create(final double datum, final long seed) { - final double d = (datum == 0.0) ? 0.0 : datum; // canonicalize -0.0, 0.0 - final long[] data = { Double.doubleToLongBits(d) };// canonicalize all NaN forms - return new SingleItemSketch(hash(data, seed)[0] >>> 1, seed); - } - - /** - * Create this sketch with the given String and a seed. - * The string is converted to a byte array using UTF8 encoding. - * If the string is null or empty no create attempt is made and the method returns null. - * - *

Note: this will not produce the same output hash values as the {@link #create(char[])} - * method and will generally be a little slower depending on the complexity of the UTF8 encoding. - *

- * - * @param datum The given String. - * @param seed used to hash the given value. - * @return a SingleItemThetaSketch or null - */ - static SingleItemSketch create(final String datum, final long seed) { - if ((datum == null) || datum.isEmpty()) { return null; } - final byte[] data = datum.getBytes(UTF_8); - return new SingleItemSketch(hash(data, seed)[0] >>> 1, seed); - } - - /** - * Create this sketch with the given byte array and a seed. - * If the byte array is null or empty no create attempt is made and the method returns null. - * - * @param data The given byte array. - * @param seed used to hash the given value. - * @return a SingleItemThetaSketch or null - */ - static SingleItemSketch create(final byte[] data, final long seed) { - if ((data == null) || (data.length == 0)) { return null; } - return new SingleItemSketch(hash(data, seed)[0] >>> 1, seed); - } - - /** - * Create this sketch with the given char array and a seed. - * If the char array is null or empty no create attempt is made and the method returns null. - * - *

Note: this will not produce the same output hash values as the {@link #create(String)} - * method but will be a little faster as it avoids the complexity of the UTF8 encoding.

- * - * @param data The given char array. - * @param seed used to hash the given value. - * @return a SingleItemThetaSketch or null - */ - static SingleItemSketch create(final char[] data, final long seed) { - if ((data == null) || (data.length == 0)) { return null; } - return new SingleItemSketch(hash(data, seed)[0] >>> 1, seed); - } - - /** - * Create this sketch with the given integer array and a seed. - * If the integer array is null or empty no create attempt is made and the method returns null. - * - * @param data The given int array. - * @param seed used to hash the given value. - * @return a SingleItemThetaSketch or null - */ - static SingleItemSketch create(final int[] data, final long seed) { - if ((data == null) || (data.length == 0)) { return null; } - return new SingleItemSketch(hash(data, seed)[0] >>> 1, seed); - } - - /** - * Create this sketch with the given long array (as an item) and a seed. - * If the long array is null or empty no create attempt is made and the method returns null. - * - * @param data The given long array. - * @param seed used to hash the given value. - * @return a SingleItemThetaSketch or null - */ - static SingleItemSketch create(final long[] data, final long seed) { - if ((data == null) || (data.length == 0)) { return null; } - return new SingleItemSketch(hash(data, seed)[0] >>> 1, seed); - } - - //ThetaSketch - - @Override //much faster - public int getCountLessThanThetaLong(final long thetaLong) { - return (hash_ < thetaLong) ? 1 : 0; - } - - @Override - public int getCurrentBytes() { - return 16; - } - - @Override - public double getEstimate() { - return 1.0; - } - - @Override - public HashIterator iterator() { - return new HeapCompactHashIterator(new long[] { hash_ }); - } - - @Override - public double getLowerBound(final int numStdDev) { - return 1.0; - } - - @Override - public int getRetainedEntries(final boolean valid) { //valid is only relevant for the AlphaSketch - return 1; - } - - @Override - public long getThetaLong() { - return Long.MAX_VALUE; - } - - @Override - public double getUpperBound(final int numStdDev) { - return 1.0; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public boolean isOrdered() { - return true; - } - - @Override - public byte[] toByteArray() { - final byte[] out = new byte[16]; - putLongLE(out, 0, pre0_); - putLongLE(out, 8, hash_); - return out; - } - - //restricted methods - - @Override - long[] getCache() { - return new long[] { hash_ }; - } - - @Override - int getCompactPreambleLongs() { - return 1; - } - - @Override - int getCurrentPreambleLongs() { - return 1; - } - - @Override - short getSeedHash() { - return (short) (pre0_ >>> 48); - } - - static boolean checkForSingleItem(final MemorySegment seg) { - final int preLongs = checkSegPreambleCap(seg); - return checkForSingleItem(preLongs, extractSerVer(seg), extractFamilyID(seg), extractFlags(seg) ); - } - - static boolean checkForSingleItem( - final int preLongs, - final int serVer, - final int famId, - final int flags) { - // Flags byte: SI=X, Ordered=T, Compact=T, Empty=F, ReadOnly=T, Reserved(BE)=F = X11010 = 0x1A. - // Flags mask will be 0x1F. - // SingleItem flag may not be set due to a historical bug, so we can't depend on it for now. - // However, if the above flags are correct, preLongs == 1, SerVer >= 3, FamilyID == 3, - // and the hash seed matches (not done here), it is virtually guaranteed that we have a - // SingleItemThetaSketch. - final boolean preLongsOK = preLongs == 1; - final boolean serVerOK = serVer >= 3; - final boolean famIdOK = famId == Family.COMPACT.getID(); - final boolean flagsOK = (flags & 0x1F) == 0x1A; //no SI, yet - final boolean singleFlagOK = (flags & SINGLEITEM_FLAG_MASK) > 0; - return (preLongsOK && serVerOK && famIdOK && flagsOK) || singleFlagOK; - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/ThetaAnotB.java b/src/main/java/org/apache/datasketches/theta/ThetaAnotB.java deleted file mode 100644 index afac16dee..000000000 --- a/src/main/java/org/apache/datasketches/theta/ThetaAnotB.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; - -/** - * Computes a set difference, A-AND-NOT-B, of two ThetaSketches. - * This class includes both stateful and stateless operations. - * - *

The stateful operation is as follows:

- *

- * ThetaAnotB anotb = ThetaSetOperationBuilder.buildAnotB();
- *
- * anotb.setA(ThetaSketch skA); //The first argument.
- * anotb.notB(ThetaSketch skB); //The second (subtraction) argument.
- * anotb.notB(ThetaSketch skC); // ...any number of additional subtractions...
- * anotb.getResult(false); //Get an interim result.
- * anotb.notB(ThetaSketch skD); //Additional subtractions.
- * anotb.getResult(true);  //Final result and resets the ThetaAnotB operator.
- * 
- * - *

The stateless operation is as follows:

- *

- * ThetaAnotB anotb = ThetaSetOperationBuilder.buildAnotB();
- *
- * CompactThetaSketch csk = anotb.aNotB(ThetaSketch skA, ThetaSketch skB);
- * 
- * - *

Calling the setA operation a second time essentially clears the internal state and loads - * the new ThetaSketch.

- * - *

The stateless and stateful operations are independent of each other with the exception of - * sharing the same update hash seed loaded as the default seed or specified by the user as an - * argument to the builder.

- * - * @author Lee Rhodes - */ -public abstract class ThetaAnotB extends ThetaSetOperation { - - /** - * Constructor - */ - ThetaAnotB() {} - - @Override - public Family getFamily() { - return Family.A_NOT_B; - } - - /** - * This is part of a multistep, stateful ThetaAnotB operation and sets the given ThetaSketch as the - * first argument A of A-AND-NOT-B. This overwrites the internal state of this - * ThetaAnotB operator with the contents of the given sketch. - * This sets the stage for multiple following notB steps. - * - *

An input argument of null will throw an exception.

- * - *

Rationale: In mathematics a "null set" is a set with no members, which we call an empty set. - * That is distinctly different from the java null, which represents a nonexistent object. - * In most cases it is a programming error due to some object that was not properly initialized. - * With a null as the first argument, we cannot know what the user's intent is. - * Since it is very likely that a null is a programming error, we throw a an exception.

- * - *

An empty input argument will set the internal state to empty.

- * - *

Rationale: An empty set is a mathematically legal concept. Although it makes any subsequent, - * valid argument for B irrelevant, we must allow this and assume the user knows what they are - * doing.

- * - *

Performing {@link #getResult(boolean)} just after this step will return a compact form of - * the given argument.

- * - * @param skA The incoming sketch for the first argument, A. - */ - public abstract void setA(ThetaSketch skA); - - /** - * This is part of a multistep, stateful ThetaAnotB operation and sets the given ThetaSketch as the - * second (or n+1th) argument B of A-AND-NOT-B. - * Performs an AND NOT operation with the existing internal state of this ThetaAnotB operator. - * - *

An input argument of null or empty is ignored.

- * - *

Rationale: A null for the second or following arguments is more tolerable because - * A NOT null is still A even if we don't know exactly what the null represents. It - * clearly does not have any content that overlaps with A. Also, because this can be part of - * a multistep operation with multiple notB steps. Other following steps can still produce - * a valid result.

- * - *

Use {@link #getResult(boolean)} to obtain the result.

- * - * @param skB The incoming ThetaSketch for the second (or following) argument B. - */ - public abstract void notB(ThetaSketch skB); - - /** - * Gets the result of the multistep, stateful operation ThetaAnotB that have been executed with calls - * to {@link #setA(ThetaSketch)} and ({@link #notB(ThetaSketch)} or - * {@link #notB(org.apache.datasketches.theta.ThetaSketch)}). - * - * @param reset If true, clears this operator to the empty state after this result is - * returned. Set this to false if you wish to obtain an intermediate result. - * - * @return the result of this operation as an ordered, on-heap {@link CompactThetaSketch}. - */ - public abstract CompactThetaSketch getResult(boolean reset); - - /** - * Gets the result of the multistep, stateful operation ThetaAnotB that have been executed with calls - * to {@link #setA(ThetaSketch)} and ({@link #notB(ThetaSketch)} or - * {@link #notB(org.apache.datasketches.theta.ThetaSketch)}). - * - * @param dstOrdered If true, the result will be an ordered {@link CompactThetaSketch}. - * See Destination Ordered. - * - * @param dstSeg if not null the given MemorySegment will be the target location of the result. - * - * @param reset If true, clears this operator to the empty state after this result is - * returned. Set this to false if you wish to obtain an intermediate result. - * - * @return the result of this operation as a {@link CompactThetaSketch} in the given dstSeg. - */ - public abstract CompactThetaSketch getResult(boolean dstOrdered, MemorySegment dstSeg, boolean reset); - - /** - * Perform A-and-not-B set operation on the two given sketches and return the result as an - * ordered CompactThetaSketch on the heap. - * - *

This a stateless operation and has no impact on the internal state of this operator. - * Thus, this is not an accumulating update and does not interact with the {@link #setA(ThetaSketch)}, - * {@link #notB(ThetaSketch)}, {@link #getResult(boolean)}, or - * {@link #getResult(boolean, MemorySegment, boolean)} methods.

- * - *

If either argument is null an exception is thrown.

- * - *

Rationale: In mathematics a "null set" is a set with no members, which we call an empty set. - * That is distinctly different from the java null, which represents a nonexistent object. - * In most cases null is a programming error due to a non-initialized object.

- * - *

With a null as the first argument we cannot know what the user's intent is and throw an - * exception. With a null as the second argument for this method we must return a result and - * there is no following possible viable arguments for the second argument so we thrown an - * exception.

- * - * @param skA The incoming sketch for the first argument. It must not be null. - * @param skB The incoming sketch for the second argument. It must not be null. - * @return an ordered CompactThetaSketch on the heap - */ - public CompactThetaSketch aNotB(final ThetaSketch skA, final ThetaSketch skB) { - return aNotB(skA, skB, true, null); - } - - /** - * Perform A-and-not-B set operation on the two given sketches and return the result as a - * CompactThetaSketch. - * - *

This a stateless operation and has no impact on the internal state of this operator. - * Thus, this is not an accumulating update and does not interact with the {@link #setA(ThetaSketch)}, - * {@link #notB(ThetaSketch)}, {@link #getResult(boolean)}, or - * {@link #getResult(boolean, MemorySegment, boolean)} methods.

- * - *

If either argument is null an exception is thrown.

- * - *

Rationale: In mathematics a "null set" is a set with no members, which we call an empty set. - * That is distinctly different from the java null, which represents a nonexistent object. - * In most cases null is a programming error due to a non-initialized object.

- * - *

With a null as the first argument we cannot know what the user's intent is and throw an - * exception. With a null as the second argument for this method we must return a result and - * there is no following possible viable arguments for the second argument so we thrown an - * exception.

- * - * @param skA The incoming sketch for the first argument. It must not be null. - * @param skB The incoming sketch for the second argument. It must not be null. - * @param dstOrdered - * See Destination Ordered. - * @param dstSeg the destination MemorySegment - * @return the result as a CompactThetaSketch. - */ - public abstract CompactThetaSketch aNotB(ThetaSketch skA, ThetaSketch skB, boolean dstOrdered, - MemorySegment dstSeg); - -} diff --git a/src/main/java/org/apache/datasketches/theta/ThetaAnotBimpl.java b/src/main/java/org/apache/datasketches/theta/ThetaAnotBimpl.java deleted file mode 100644 index 5fcefdad0..000000000 --- a/src/main/java/org/apache/datasketches/theta/ThetaAnotBimpl.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.apache.datasketches.common.Util.exactLog2OfLong; -import static org.apache.datasketches.thetacommon.HashOperations.checkThetaCorruption; -import static org.apache.datasketches.thetacommon.HashOperations.continueCondition; -import static org.apache.datasketches.thetacommon.HashOperations.hashSearch; -import static org.apache.datasketches.thetacommon.HashOperations.hashSearchOrInsert; -import static org.apache.datasketches.thetacommon.HashOperations.minLgHashTableSize; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * Implements the A-and-not-B operations. - * @author Lee Rhodes - * @author Kevin Lang - */ -final class ThetaAnotBimpl extends ThetaAnotB { - private final short seedHash_; - private boolean empty_; - private long thetaLong_; - private long[] hashArr_ = {}; //compact array w curCount_ entries - private int curCount_; - - /** - * Construct a new ThetaAnotB on the java heap. Called by ThetaSetOperationBuilder. - * - * @param seed See seed - */ - ThetaAnotBimpl(final long seed) { - this(Util.computeSeedHash(seed)); - } - - /** - * Construct a new ThetaAnotB on the java heap. - * - * @param seedHash 16 bit hash of the chosen update seed. - */ - private ThetaAnotBimpl(final short seedHash) { - seedHash_ = seedHash; - reset(); - } - - @Override - public void setA(final ThetaSketch skA) { - if (skA == null) { - reset(); - throw new SketchesArgumentException("The input argument A must not be null"); - } - if (skA.isEmpty()) { - reset(); - return; - } - //skA is not empty - Util.checkSeedHashes(seedHash_, skA.getSeedHash()); - - //process A - hashArr_ = getHashArrA(skA); - empty_ = false; - thetaLong_ = skA.getThetaLong(); - curCount_ = hashArr_.length; - } - - @Override - public void notB(final ThetaSketch skB) { - if (empty_ || (skB == null) || skB.isEmpty()) { return; } - //local and skB is not empty - Util.checkSeedHashes(seedHash_, skB.getSeedHash()); - - thetaLong_ = Math.min(thetaLong_, skB.getThetaLong()); - - //process B - hashArr_ = getResultHashArr(thetaLong_, curCount_, hashArr_, skB); - curCount_ = hashArr_.length; - empty_ = (curCount_ == 0) && (thetaLong_ == Long.MAX_VALUE); - } - - @Override - public CompactThetaSketch getResult(final boolean reset) { - return getResult(true, null, reset); - } - - @Override - public CompactThetaSketch getResult(final boolean dstOrdered, final MemorySegment dstSeg, - final boolean reset) { - final CompactThetaSketch result = CompactOperations.componentsToCompact( - thetaLong_, curCount_, seedHash_, empty_, true, false, dstOrdered, dstSeg, hashArr_.clone()); - if (reset) { reset(); } - return result; - } - - @Override - public CompactThetaSketch aNotB(final ThetaSketch skA, final ThetaSketch skB, final boolean dstOrdered, - final MemorySegment dstSeg) { - if ((skA == null) || (skB == null)) { - throw new SketchesArgumentException("Neither argument may be null"); - } - //Both skA & skB are not null - - final long minThetaLong = Math.min(skA.getThetaLong(), skB.getThetaLong()); - - if (skA.isEmpty()) { return skA.compact(dstOrdered, dstSeg); } - //A is not Empty - Util.checkSeedHashes(skA.getSeedHash(), seedHash_); - - if (skB.isEmpty()) { - return skA.compact(dstOrdered, dstSeg); - } - Util.checkSeedHashes(skB.getSeedHash(), seedHash_); - //Both skA & skB are not empty - - //process A - final long[] hashArrA = getHashArrA(skA); - final int countA = hashArrA.length; - - //process B - final long[] hashArrOut = getResultHashArr(minThetaLong, countA, hashArrA, skB); //out is clone - final int countOut = hashArrOut.length; - final boolean empty = (countOut == 0) && (minThetaLong == Long.MAX_VALUE); - - return CompactOperations.componentsToCompact( - minThetaLong, countOut, seedHash_, empty, true, false, dstOrdered, dstSeg, hashArrOut); - } - - @Override - int getRetainedEntries() { - return curCount_; - } - - //restricted - - private static long[] getHashArrA(final ThetaSketch skA) { //returns a new array - //Get skA cache as array - final CompactThetaSketch cskA = skA.compact(false, null); //sorting not required - return cskA.getCache().clone(); - } - - private static long[] getResultHashArr( //returns a new array - final long minThetaLong, - final int countA, - final long[] hashArrA, - final ThetaSketch skB) { - - // Rebuild or get hashtable of skB - final long[] hashTableB; //read only - if (skB instanceof CompactThetaSketch) { - hashTableB = convertToHashTable(skB, minThetaLong, ThetaUtil.REBUILD_THRESHOLD); - } else { - hashTableB = skB.getCache(); - } - - //build temporary result arrays of skA - final long[] tmpHashArrA = new long[countA]; - - //search for non matches and build temp arrays - final int lgHTBLen = exactLog2OfLong(hashTableB.length); - int nonMatches = 0; - for (int i = 0; i < countA; i++) { - final long hash = hashArrA[i]; - if ((hash != 0) && (hash < minThetaLong)) { //only allows hashes of A < minTheta - final int index = hashSearch(hashTableB, lgHTBLen, hash); - if (index == -1) { - tmpHashArrA[nonMatches] = hash; - nonMatches++; - } - } - } - return Arrays.copyOfRange(tmpHashArrA, 0, nonMatches); - } - - private static long[] convertToHashTable( - final ThetaSketch sketch, - final long thetaLong, - final double rebuildThreshold) { - final int lgArrLongs = minLgHashTableSize(sketch.getRetainedEntries(true), rebuildThreshold); - final int arrLongs = 1 << lgArrLongs; - final long[] hashTable = new long[arrLongs]; - checkThetaCorruption(thetaLong); - final HashIterator it = sketch.iterator(); - while (it.next()) { - final long hash = it.get(); - if (continueCondition(thetaLong, hash) ) { - continue; - } - hashSearchOrInsert(hashTable, lgArrLongs, hash); - } - return hashTable; - } - - private void reset() { - thetaLong_ = Long.MAX_VALUE; - empty_ = true; - hashArr_ = new long[0]; - curCount_ = 0; - } - - @Override - long[] getCache() { - return hashArr_.clone(); - } - - @Override - short getSeedHash() { - return seedHash_; - } - - @Override - long getThetaLong() { - return thetaLong_; - } - - @Override - public boolean hasMemorySegment() { return false; } - - @Override - public boolean isOffHeap() { return false; } - - @Override - public boolean isSameResource( final MemorySegment that) { return false; } - - @Override - boolean isEmpty() { - return empty_; - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/ThetaIntersection.java b/src/main/java/org/apache/datasketches/theta/ThetaIntersection.java deleted file mode 100644 index e72aa62ff..000000000 --- a/src/main/java/org/apache/datasketches/theta/ThetaIntersection.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; - -/** - * The API for intersection operations - * - * @author Lee Rhodes - */ -public abstract class ThetaIntersection extends ThetaSetOperation { - - /** - * No argument constructor. - */ - public ThetaIntersection() { } - - @Override - public Family getFamily() { - return Family.INTERSECTION; - } - - /** - * Gets the result of this operation as an ordered CompactThetaSketch on the Java heap. - * This does not disturb the underlying data structure of this intersection. - * The {@link #intersect(ThetaSketch)} method must have been called at least once, otherwise an - * exception will be thrown. This is because a virgin intersection represents the - * Universal Set, which has an infinite number of values. - * @return the result of this operation as an ordered CompactThetaSketch on the Java heap - */ - public CompactThetaSketch getResult() { - return getResult(true, null); - } - - /** - * Gets the result of this operation as a CompactThetaSketch in the given dstSeg. - * This does not disturb the underlying data structure of this intersection. - * The {@link #intersect(ThetaSketch)} method must have been called at least once, otherwise an - * exception will be thrown. This is because a virgin intersection represents the - * Universal Set, which has an infinite number of values. - * - *

Note that presenting an intersection with an empty sketch sets the internal - * state of the intersection to empty = true, and current count = 0. This is consistent with - * the mathematical definition of the intersection of any set with the empty set is - * always empty.

- * - *

Presenting an intersection with a null argument will throw an exception.

- * - * @param dstOrdered - * See Destination Ordered - * - * @param dstSeg the destination MemorySegment. - * - * @return the result of this operation as a CompactThetaSketch stored in the given dstSeg, - * which can be either on or off-heap.. - */ - public abstract CompactThetaSketch getResult(boolean dstOrdered, MemorySegment dstSeg); - - /** - * Returns true if there is a valid intersection result available - * @return true if there is a valid intersection result available - */ - public abstract boolean hasResult(); - - /** - * Resets this ThetaIntersection for stateful operations only. - * The seed remains intact, otherwise reverts to - * the Universal Set: theta = 1.0, no retained data and empty = false. - */ - public abstract void reset(); - - /** - * Serialize this intersection to a byte array form. - * @return byte array of this intersection - */ - public abstract byte[] toByteArray(); - - /** - * Intersect the given sketch with the internal state. - * This method can be repeatedly called. - * If the given sketch is null the internal state becomes the empty sketch. - * Theta will become the minimum of thetas seen so far. - * @param sketchIn the given sketch - */ - public abstract void intersect(ThetaSketch sketchIn); - - /** - * Perform intersect set operation on the two given sketch arguments and return the result as an - * ordered CompactThetaSketch on the heap. - * @param a The first sketch argument - * @param b The second sketch argument - * @return an ordered CompactThetaSketch on the heap - */ - public CompactThetaSketch intersect(final ThetaSketch a, final ThetaSketch b) { - return intersect(a, b, true, null); - } - - /** - * Perform intersect set operation on the two given sketches and return the result as a - * CompactThetaSketch. - * @param a The first sketch argument - * @param b The second sketch argument - * @param dstOrdered - * See Destination Ordered. - * @param dstSeg the destination MemorySegment. - * @return the result as a CompactThetaSketch. - */ - public abstract CompactThetaSketch intersect(ThetaSketch a, ThetaSketch b, boolean dstOrdered, - MemorySegment dstSeg); - - /** - * Factory: Wrap a ThetaIntersection target around the given source MemorySegment containing intersection data. - * This method assumes the Default Update Seed. - * If the given source MemorySegment is read-only, the returned object will also be read-only. - * @param srcSeg The source MemorySegment image. - * @return a ThetaIntersection that wraps a source MemorySegment that contains a ThetaIntersection image - */ - public static ThetaIntersection wrap(final MemorySegment srcSeg) { - return wrap(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Factory: Wrap a ThetaIntersection target around the given source MemorySegment containing intersection data. - * If the given source MemorySegment is read-only, the returned object will also be read-only. - * @param srcSeg The source MemorySegment image. - * @param expectedSeed See seed - * @return a ThetaIntersection that wraps a source MemorySegment that contains a ThetaIntersection image - */ - public static ThetaIntersection wrap(final MemorySegment srcSeg, final long expectedSeed) { - final int serVer = srcSeg.get(JAVA_BYTE, SER_VER_BYTE); - if (serVer != 3) { - throw new SketchesArgumentException("SerVer must be 3: " + serVer); - } - return ThetaIntersectionImpl.wrapInstance(srcSeg, expectedSeed, srcSeg.isReadOnly() ); - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/ThetaIntersectionImpl.java b/src/main/java/org/apache/datasketches/theta/ThetaIntersectionImpl.java deleted file mode 100644 index 3dfdf4fa1..000000000 --- a/src/main/java/org/apache/datasketches/theta/ThetaIntersectionImpl.java +++ /dev/null @@ -1,646 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.Math.min; -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.common.Util.clearBits; -import static org.apache.datasketches.common.Util.floorPowerOf2; -import static org.apache.datasketches.common.Util.setBits; -import static org.apache.datasketches.theta.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.FLAGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.LG_ARR_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.LG_NOM_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.P_FLOAT; -import static org.apache.datasketches.theta.PreambleUtil.RETAINED_ENTRIES_INT; -import static org.apache.datasketches.theta.PreambleUtil.SEED_HASH_SHORT; -import static org.apache.datasketches.theta.PreambleUtil.SER_VER; -import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.THETA_LONG; -import static org.apache.datasketches.theta.PreambleUtil.clearEmpty; -import static org.apache.datasketches.theta.PreambleUtil.extractCurCount; -import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.extractFlags; -import static org.apache.datasketches.theta.PreambleUtil.extractLgArrLongs; -import static org.apache.datasketches.theta.PreambleUtil.extractSerVer; -import static org.apache.datasketches.theta.PreambleUtil.extractThetaLong; -import static org.apache.datasketches.theta.PreambleUtil.insertCurCount; -import static org.apache.datasketches.theta.PreambleUtil.insertFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.insertLgArrLongs; -import static org.apache.datasketches.theta.PreambleUtil.insertP; -import static org.apache.datasketches.theta.PreambleUtil.insertPreLongs; -import static org.apache.datasketches.theta.PreambleUtil.insertSerVer; -import static org.apache.datasketches.theta.PreambleUtil.insertThetaLong; -import static org.apache.datasketches.theta.PreambleUtil.setEmpty; -import static org.apache.datasketches.thetacommon.HashOperations.continueCondition; -import static org.apache.datasketches.thetacommon.HashOperations.hashInsertOnly; -import static org.apache.datasketches.thetacommon.HashOperations.hashInsertOnlyMemorySegment; -import static org.apache.datasketches.thetacommon.HashOperations.hashSearch; -import static org.apache.datasketches.thetacommon.HashOperations.minLgHashTableSize; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesReadOnlyException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * The intersection operation for ThetaSketches. - * - *

This implementation uses data either on-heap or off-heap in a given MemorySegment - * that is owned and managed by the caller. - * The off-heap MemorySegment, which if managed properly, will greatly reduce the need for - * the JVM to perform garbage collection.

- * - * @author Lee Rhodes - * @author Kevin Lang - */ -final class ThetaIntersectionImpl extends ThetaIntersection { - private final short seedHash_; - private final boolean readOnly_; //True if this sketch is to be treated as read only - private final MemorySegment wseg_; - private final int maxLgArrLongs_; //only used with MemorySegment, not serialized - - //Note: intersection operation does not use lgNomLongs or k, per se. - private int lgArrLongs_; //current size of hash table - private int curCount_; //curCount of HT, if < 0 means Universal Set (US) is true - private long thetaLong_; - private boolean empty_; //A virgin intersection represents the Universal Set, so empty is FALSE! - private long[] hashTable_; //retained entries of the intersection, on-heap only. - - /** - * Constructor: Sets the class finals and computes, sets and checks the seedHash. - * @param wseg Can be either a Source(e.g. wrap) or Destination (new offHeap) MemorySegment. - * @param seed Used to validate incoming sketch arguments. - * @param dstSegFlag The given MemorySegment is a Destination (new offHeap) MemorySegment. - * @param readOnly True if MemorySegment is to be treated as read only. - */ - private ThetaIntersectionImpl(final MemorySegment wseg, final long seed, final boolean dstSegFlag, - final boolean readOnly) { - readOnly_ = readOnly; - if (wseg != null) { - wseg_ = wseg; - if (dstSegFlag) { //DstSeg: compute & store seedHash, no seedHash checking - ThetaIntersectionImpl.checkMinSizeMemorySegment(wseg); - maxLgArrLongs_ = !readOnly ? ThetaIntersectionImpl.getMaxLgArrLongs(wseg) : 0; //Only Off Heap - seedHash_ = Util.computeSeedHash(seed); - wseg_.set(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT, seedHash_); - } else { //SrcSeg:gets and stores the seedHash, checks seg_seedHash against the seed - seedHash_ = wseg_.get(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT); - Util.checkSeedHashes(seedHash_, Util.computeSeedHash(seed)); //check for seed hash conflict - maxLgArrLongs_ = 0; - } - } else { //compute & store seedHash - wseg_ = null; - maxLgArrLongs_ = 0; - seedHash_ = Util.computeSeedHash(seed); - } - } - - /** - * Factory: Construct a new ThetaIntersection target on the java heap. - * Called by ThetaSetOperationBuilder, test. - * - * @param seed See Seed - * @return a new IntersectionImpl on the Java heap - */ - static ThetaIntersectionImpl initNewHeapInstance(final long seed) { - final boolean dstSegFlag = false; - final boolean readOnly = false; - final ThetaIntersectionImpl impl = new ThetaIntersectionImpl(null, seed, dstSegFlag, readOnly); - impl.hardReset(); - return impl; - } - - /** - * Factory: Construct a new ThetaIntersection target direct to the given destination MemorySegment. - * Called by ThetaSetOperationBuilder, test. - * - * @param seed See Seed - * @param dstSeg destination MemorySegment - * @return a new IntersectionImpl that may be off-heap - */ - static ThetaIntersectionImpl initNewDirectInstance(final long seed, final MemorySegment dstSeg) { - //Load Preamble - //Pre0 - dstSeg.asSlice(0, CONST_PREAMBLE_LONGS << 3).fill((byte)0); - insertPreLongs(dstSeg, CONST_PREAMBLE_LONGS); //RF not used = 0 - insertSerVer(dstSeg, SER_VER); - insertFamilyID(dstSeg, Family.INTERSECTION.getID()); - //lgNomLongs not used by this intersection operation - //lgArrLongs set by hardReset - //flags are already 0: reserved = readOnly = compact = ordered = empty = false; - //seedHash loaded and checked in IntersectionImpl constructor - //Pre1 - //CurCount set by hardReset - insertP(dstSeg, (float) 1.0); //not used by intersection - //Pre2 - //thetaLong set by hardReset - - //Initialize - final boolean dstSegFlag = true; - final boolean readOnly = false; - final ThetaIntersectionImpl impl = new ThetaIntersectionImpl(dstSeg, seed, dstSegFlag, readOnly); - impl.hardReset(); - return impl; - } - - /** - * Factory: Heapify an intersection target from a MemorySegment image containing data. - * @param srcSeg The source MemorySegment object. - * @param seed See seed - * @return a IntersectionImpl instance on the Java heap - */ - static ThetaIntersectionImpl heapifyInstance(final MemorySegment srcSeg, final long seed) { - final boolean dstSegFlag = false; - final boolean readOnly = false; - ThetaIntersectionImpl.segChecks(srcSeg); - final ThetaIntersectionImpl impl = new ThetaIntersectionImpl(null, seed, dstSegFlag, readOnly); - - //Initialize - impl.lgArrLongs_ = extractLgArrLongs(srcSeg); - impl.curCount_ = extractCurCount(srcSeg); - impl.thetaLong_ = extractThetaLong(srcSeg); - impl.empty_ = (extractFlags(srcSeg) & EMPTY_FLAG_MASK) > 0; - if (!impl.empty_ && (impl.curCount_ > 0)) { - impl.hashTable_ = new long[1 << impl.lgArrLongs_]; - MemorySegment.copy(srcSeg, JAVA_LONG_UNALIGNED, CONST_PREAMBLE_LONGS << 3, impl.hashTable_, 0, 1 << impl.lgArrLongs_); - } - return impl; - } - - /** - * Factory: Wrap a ThetaIntersection target around the given source MemorySegment containing intersection data. - * If the given source MemorySegment is read-only, the returned object will also be read-only. - * @param srcSeg The source MemorySegment image. - * @param seed See seed - * @param readOnly True if MemorySegment is to be treated as read only - * @return a IntersectionImpl that wraps a source MemorySegment that contains a ThetaIntersection image - */ - static ThetaIntersectionImpl wrapInstance( - final MemorySegment srcSeg, - final long seed, - final boolean readOnly) { - final boolean dstSegFlag = false; - ThetaIntersectionImpl.segChecks(srcSeg); - final ThetaIntersectionImpl impl = new ThetaIntersectionImpl(srcSeg, seed, dstSegFlag, readOnly); - impl.lgArrLongs_ = extractLgArrLongs(srcSeg); - impl.curCount_ = extractCurCount(srcSeg); - impl.thetaLong_ = extractThetaLong(srcSeg); - impl.empty_ = (extractFlags(srcSeg) & EMPTY_FLAG_MASK) > 0; - return impl; - } - - @Override - public CompactThetaSketch intersect(final ThetaSketch a, final ThetaSketch b, final boolean dstOrdered, final MemorySegment dstSeg) { - if ((wseg_ != null) && readOnly_) { throw new SketchesReadOnlyException(); } - hardReset(); - intersect(a); - intersect(b); - final CompactThetaSketch csk = getResult(dstOrdered, dstSeg); - hardReset(); - return csk; - } - - @Override - public void intersect(final ThetaSketch sketchIn) { - if (sketchIn == null) { - throw new SketchesArgumentException("The input argument must not be null."); - } - if ((wseg_ != null) && readOnly_) { throw new SketchesReadOnlyException(); } - if (empty_ || sketchIn.isEmpty()) { //empty rule - //Because of the def of null above and the Empty Rule (which is OR), empty_ must be true. - //Whatever the current internal state, we make our local empty. - resetToEmpty(); - return; - } - Util.checkSeedHashes(seedHash_, sketchIn.getSeedHash()); - //Set minTheta - thetaLong_ = min(thetaLong_, sketchIn.getThetaLong()); //Theta rule - empty_ = false; - if (wseg_ != null) { - insertThetaLong(wseg_, thetaLong_); - clearEmpty(wseg_); //false - } - - // The truth table for the following state machine. MinTheta is set above. - // Incoming sketch is not null and not empty, but could have 0 count and Theta < 1.0 - // Case curCount sketchInEntries | Actions - // 1 <0 0 | First intersect, set curCount = 0; HT = null; minTh; exit - // 2 0 0 | set curCount = 0; HT = null; minTh; exit - // 3 >0 0 | set curCount = 0; HT = null; minTh; exit - // 4 | Not used - // 5 <0 >0 | First intersect, clone SketchIn; exit - // 6 0 >0 | set curCount = 0; HT = null; minTh; exit - // 7 >0 >0 | Perform full intersect - final int sketchInEntries = sketchIn.getRetainedEntries(true); - - //states 1,2,3,6 - if ((curCount_ == 0) || (sketchInEntries == 0)) { - curCount_ = 0; - if (wseg_ != null) { insertCurCount(wseg_, 0); } - hashTable_ = null; //No need for a HT. Don't bother clearing seg if valid - } //end of states 1,2,3,6 - - // state 5 - else if ((curCount_ < 0) && (sketchInEntries > 0)) { - curCount_ = sketchIn.getRetainedEntries(true); - final int requiredLgArrLongs = minLgHashTableSize(curCount_, ThetaUtil.REBUILD_THRESHOLD); - final int priorLgArrLongs = lgArrLongs_; //prior only used in error message - lgArrLongs_ = requiredLgArrLongs; - - if (wseg_ != null) { //Off heap, check if current dstSeg is large enough - insertCurCount(wseg_, curCount_); - insertLgArrLongs(wseg_, lgArrLongs_); - if (requiredLgArrLongs <= maxLgArrLongs_) { - wseg_.asSlice(CONST_PREAMBLE_LONGS << 3, 8 << lgArrLongs_).fill((byte)0); - } - else { //not enough space in dstSeg - final int requiredBytes = (8 << requiredLgArrLongs) + 24; - final int givenBytes = (8 << priorLgArrLongs) + 24; - throw new SketchesArgumentException( - "Insufficient internal MemorySegment space: " + requiredBytes + " > " + givenBytes); - } - } - else { //On the heap, allocate a HT - hashTable_ = new long[1 << lgArrLongs_]; - } - moveDataToTgt(sketchIn); - } //end of state 5 - - //state 7 - else if ((curCount_ > 0) && (sketchInEntries > 0)) { - //Sets resulting hashTable, curCount and adjusts lgArrLongs - performIntersect(sketchIn); - } //end of state 7 - - else { - assert false : "Should not happen"; - } - } - - @Override - MemorySegment getMemorySegment() { return wseg_; } - - @Override - public CompactThetaSketch getResult(final boolean dstOrdered, final MemorySegment dstSeg) { - if (curCount_ < 0) { - throw new SketchesStateException( - "Calling getResult() with no intervening intersections would represent the infinite set, " - + "which is not a legal result."); - } - long[] compactCache; - final boolean srcOrdered, srcCompact; - if (curCount_ == 0) { - compactCache = new long[0]; - srcCompact = true; - srcOrdered = false; //hashTable, even though empty - return CompactOperations.componentsToCompact( - thetaLong_, curCount_, seedHash_, empty_, srcCompact, srcOrdered, dstOrdered, - dstSeg, compactCache); - } - //else curCount > 0 - final long[] hashTable; - if (wseg_ != null) { - final int htLen = 1 << lgArrLongs_; - hashTable = new long[htLen]; - MemorySegment.copy(wseg_, JAVA_LONG_UNALIGNED, CONST_PREAMBLE_LONGS << 3, hashTable, 0, htLen); - } else { - hashTable = hashTable_; - } - compactCache = ThetaIntersectionImpl.compactCachePart(hashTable, lgArrLongs_, curCount_, thetaLong_, dstOrdered); - srcCompact = true; - srcOrdered = dstOrdered; - return CompactOperations.componentsToCompact( - thetaLong_, curCount_, seedHash_, empty_, srcCompact, srcOrdered, dstOrdered, - dstSeg, compactCache); - } - - @Override - public boolean hasMemorySegment() { - return (wseg_ != null) && wseg_.scope().isAlive(); - } - - @Override - public boolean hasResult() { - return hasMemorySegment() ? wseg_.get(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT) >= 0 : curCount_ >= 0; - } - - @Override - public boolean isOffHeap() { - return hasMemorySegment() && wseg_.isNative(); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return hasMemorySegment() && MemorySegmentStatus.isSameResource(wseg_, that); - } - - @Override - public void reset() { - hardReset(); - } - - @Override - public byte[] toByteArray() { - final int preBytes = CONST_PREAMBLE_LONGS << 3; - final int dataBytes = curCount_ > 0 ? 8 << lgArrLongs_ : 0; - final byte[] byteArrOut = new byte[preBytes + dataBytes]; - if (wseg_ != null) { - MemorySegment.copy(wseg_, JAVA_BYTE, 0, byteArrOut, 0, preBytes + dataBytes); - } - else { - final MemorySegment segOut = MemorySegment.ofArray(byteArrOut); - - //preamble - segOut.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) CONST_PREAMBLE_LONGS); //RF not used = 0 - segOut.set(JAVA_BYTE, SER_VER_BYTE, (byte) SER_VER); - segOut.set(JAVA_BYTE, FAMILY_BYTE, (byte) Family.INTERSECTION.getID()); - segOut.set(JAVA_BYTE, LG_NOM_LONGS_BYTE, (byte) 0); //not used - segOut.set(JAVA_BYTE, LG_ARR_LONGS_BYTE, (byte) lgArrLongs_); - if (empty_) { setBits(segOut, FLAGS_BYTE, (byte) EMPTY_FLAG_MASK); } - else { clearBits(segOut, FLAGS_BYTE, (byte) EMPTY_FLAG_MASK); } - segOut.set(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT, seedHash_); - segOut.set(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT, curCount_); - segOut.set(JAVA_FLOAT_UNALIGNED, P_FLOAT, (float) 1.0); - segOut.set(JAVA_LONG_UNALIGNED, THETA_LONG, thetaLong_); - - //data - if (curCount_ > 0) { - MemorySegment.copy(hashTable_, 0, segOut, JAVA_LONG_UNALIGNED, preBytes, 1 << lgArrLongs_); - } - } - return byteArrOut; - } - - //restricted - - /** - * Gets the number of retained entries from this operation. If negative, it is interpreted - * as the infinite Universal Set. - */ - @Override - int getRetainedEntries() { - return curCount_; - } - - @Override - boolean isEmpty() { - return empty_; - } - - @Override - long[] getCache() { - if (wseg_ == null) { - return hashTable_ != null ? hashTable_ : new long[0]; - } - //offHeap - final int arrLongs = 1 << lgArrLongs_; - final long[] outArr = new long[arrLongs]; - MemorySegment.copy(wseg_, JAVA_LONG_UNALIGNED, CONST_PREAMBLE_LONGS << 3, outArr, 0, arrLongs); - return outArr; - } - - @Override - short getSeedHash() { - return seedHash_; - } - - @Override - long getThetaLong() { - return thetaLong_; - } - - private void performIntersect(final ThetaSketch sketchIn) { - // curCount and input data are nonzero, match against HT - assert (curCount_ > 0) && !empty_; - final long[] hashTable; - if (wseg_ != null) { - final int htLen = 1 << lgArrLongs_; - hashTable = new long[htLen]; - MemorySegment.copy(wseg_, JAVA_LONG_UNALIGNED, CONST_PREAMBLE_LONGS << 3, hashTable, 0, htLen); - } else { - hashTable = hashTable_; - } - //allocate space for matching - final long[] matchSet = new long[ min(curCount_, sketchIn.getRetainedEntries(true)) ]; - - int matchSetCount = 0; - final boolean isOrdered = sketchIn.isOrdered(); - final HashIterator it = sketchIn.iterator(); - while (it.next()) { - final long hashIn = it.get(); - if (hashIn < thetaLong_) { - final int foundIdx = hashSearch(hashTable, lgArrLongs_, hashIn); - if (foundIdx != -1) { - matchSet[matchSetCount++] = hashIn; - } - } else if (isOrdered) { break; } // early stop - } - //reduce effective array size to minimum - curCount_ = matchSetCount; - lgArrLongs_ = minLgHashTableSize(matchSetCount, ThetaUtil.REBUILD_THRESHOLD); - if (wseg_ != null) { - insertCurCount(wseg_, matchSetCount); - insertLgArrLongs(wseg_, lgArrLongs_); - wseg_.asSlice(CONST_PREAMBLE_LONGS << 3, 8 << lgArrLongs_).fill((byte)0); //clear for rebuild - } else { - Arrays.fill(hashTable_, 0, 1 << lgArrLongs_, 0L); //clear for rebuild - } - - if (curCount_ > 0) { - moveDataToTgt(matchSet, matchSetCount); //move matchSet to target - } else if (thetaLong_ == Long.MAX_VALUE) { - empty_ = true; - } - } - - private void moveDataToTgt(final long[] arr, final int count) { - final int arrLongsIn = arr.length; - int tmpCnt = 0; - if (wseg_ != null) { //Off Heap puts directly into mem - final int preBytes = CONST_PREAMBLE_LONGS << 3; - final int lgArrLongs = lgArrLongs_; - final long thetaLong = thetaLong_; - for (int i = 0; i < arrLongsIn; i++ ) { - final long hashIn = arr[i]; - if (continueCondition(thetaLong, hashIn)) { continue; } - hashInsertOnlyMemorySegment(wseg_, lgArrLongs, hashIn, preBytes); - tmpCnt++; - } - } else { //On Heap. Assumes HT exists and is large enough - for (int i = 0; i < arrLongsIn; i++ ) { - final long hashIn = arr[i]; - if (continueCondition(thetaLong_, hashIn)) { continue; } - hashInsertOnly(hashTable_, lgArrLongs_, hashIn); - tmpCnt++; - } - } - assert tmpCnt == count : "ThetaIntersection Count Check: got: " + tmpCnt + ", expected: " + count; - } - - private void moveDataToTgt(final ThetaSketch sketch) { - final int count = sketch.getRetainedEntries(); - int tmpCnt = 0; - if (wseg_ != null) { //Off Heap puts directly into mem - final int preBytes = CONST_PREAMBLE_LONGS << 3; - final int lgArrLongs = lgArrLongs_; - final long thetaLong = thetaLong_; - final HashIterator it = sketch.iterator(); - while (it.next()) { - final long hash = it.get(); - if (continueCondition(thetaLong, hash)) { continue; } - hashInsertOnlyMemorySegment(wseg_, lgArrLongs, hash, preBytes); - tmpCnt++; - } - } else { //On Heap. Assumes HT exists and is large enough - final HashIterator it = sketch.iterator(); - while (it.next()) { - final long hash = it.get(); - if (continueCondition(thetaLong_, hash)) { continue; } - hashInsertOnly(hashTable_, lgArrLongs_, hash); - tmpCnt++; - } - } - assert tmpCnt == count : "ThetaIntersection Count Check: got: " + tmpCnt + ", expected: " + count; - } - - private void hardReset() { - resetCommon(); - if (wseg_ != null) { - insertCurCount(wseg_, -1); //Universal Set - clearEmpty(wseg_); //false - } - curCount_ = -1; //Universal Set - empty_ = false; - } - - private void resetToEmpty() { - resetCommon(); - if (wseg_ != null) { - insertCurCount(wseg_, 0); - setEmpty(wseg_); //true - } - curCount_ = 0; - empty_ = true; - } - - private void resetCommon() { - if (wseg_ != null) { - if (readOnly_) { throw new SketchesReadOnlyException(); } - wseg_.asSlice(CONST_PREAMBLE_LONGS << 3, 8 << ThetaUtil.MIN_LG_ARR_LONGS).fill((byte)0); - insertLgArrLongs(wseg_, ThetaUtil.MIN_LG_ARR_LONGS); - insertThetaLong(wseg_, Long.MAX_VALUE); - } - lgArrLongs_ = ThetaUtil.MIN_LG_ARR_LONGS; - thetaLong_ = Long.MAX_VALUE; - hashTable_ = null; - } - - /** - * Compact first 2^lgArrLongs of given array - * @param srcCache anything - * @param lgArrLongs The correct - * lgArrLongs. - * @param curCount must be correct - * @param thetaLong The correct - * thetaLong. - * @param dstOrdered true if output array must be sorted - * @return the compacted array - */ //used in Test - static final long[] compactCachePart(final long[] srcCache, final int lgArrLongs, - final int curCount, final long thetaLong, final boolean dstOrdered) { - if (curCount == 0) { - return new long[0]; - } - final long[] cacheOut = new long[curCount]; - final int len = 1 << lgArrLongs; - int j = 0; - for (int i = 0; i < len; i++) { - final long v = srcCache[i]; - if (v <= 0L || v >= thetaLong ) { continue; } - cacheOut[j++] = v; - } - assert curCount == j; - if (dstOrdered) { - Arrays.sort(cacheOut); - } - return cacheOut; - } - - private static void checkMinSizeMemorySegment(final MemorySegment seg) { - final int minBytes = (CONST_PREAMBLE_LONGS << 3) + (8 << ThetaUtil.MIN_LG_ARR_LONGS);//280 - final long cap = seg.byteSize(); - if (cap < minBytes) { - throw new SketchesArgumentException( - "MemorySegment must be at least " + minBytes + " bytes. Actual capacity: " + cap); - } - } - - /** - * Returns the maximum lgArrLongs given the capacity of the MemorySegment. - * @param dstSeg the given MemorySegment - * @return the maximum lgArrLongs given the capacity of the MemorySegment - */ - private static int getMaxLgArrLongs(final MemorySegment dstSeg) { - final int preBytes = CONST_PREAMBLE_LONGS << 3; - final long cap = dstSeg.byteSize(); - return Integer.numberOfTrailingZeros(floorPowerOf2((int)(cap - preBytes)) >>> 3); - } - - private static void segChecks(final MemorySegment srcSeg) { - //Get Preamble - //Note: This intersection operation does not use lgNomLongs (or k), per se. - //seedHash loaded and checked in private constructor - final int preLongs = ThetaSketch.getPreambleLongs(srcSeg); - final int serVer = extractSerVer(srcSeg); - final int famID = extractFamilyID(srcSeg); - final boolean empty = (extractFlags(srcSeg) & EMPTY_FLAG_MASK) > 0; - final int curCount = extractCurCount(srcSeg); - //Checks - if (preLongs != CONST_PREAMBLE_LONGS) { - throw new SketchesArgumentException( - "MemorySegment PreambleLongs must equal " + CONST_PREAMBLE_LONGS + ": " + preLongs); - } - if (serVer != SER_VER) { - throw new SketchesArgumentException("Serialization Version must equal " + SER_VER); - } - Family.INTERSECTION.checkFamilyID(famID); - if (empty) { - if (curCount != 0) { - throw new SketchesArgumentException( - "srcSeg empty state inconsistent with curCount: " + empty + "," + curCount); - } - //empty = true AND curCount_ = 0: OK - } //else empty = false, curCount could be anything - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/ThetaSetOperation.java b/src/main/java/org/apache/datasketches/theta/ThetaSetOperation.java deleted file mode 100644 index 4361b794e..000000000 --- a/src/main/java/org/apache/datasketches/theta/ThetaSetOperation.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.common.Family.idToFamily; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.theta.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; - -/** - * The parent API for all Set Operations - * - * @author Lee Rhodes - */ -public abstract class ThetaSetOperation implements MemorySegmentStatus { - static final int CONST_PREAMBLE_LONGS = 3; - - /** - * Constructor - */ - ThetaSetOperation() {} - - /** - * Makes a new builder - * - * @return a new builder - */ - public static final ThetaSetOperationBuilder builder() { - return new ThetaSetOperationBuilder(); - } - - /** - * Heapify takes the ThetaSetOperation image in MemorySegment and instantiates an on-heap - * ThetaSetOperation using the - * Default Update Seed. - * The resulting ThetaSetOperation will not retain any link to the source MemorySegment. - * - *

Note: Only certain set operators during stateful operations can be serialized and thus - * heapified.

- * - * @param srcSeg an image of a ThetaSetOperation where the image seed hash matches the default seed hash. - * @return a Heap-based ThetaSetOperation from the given MemorySegment - */ - public static ThetaSetOperation heapify(final MemorySegment srcSeg) { - return heapify(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Heapify takes the ThetaSetOperation image in MemorySegment and instantiates an on-heap - * ThetaSetOperation using the given expectedSeed. - * The resulting ThetaSetOperation will not retain any link to the source MemorySegment. - * - *

Note: Only certain set operators during stateful operations can be serialized and thus - * heapified.

- * - * @param srcSeg an image of a ThetaSetOperation where the hash of the given expectedSeed matches the image seed hash. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See Update Hash Seed. - * @return a Heap-based ThetaSetOperation from the given MemorySegment - */ - public static ThetaSetOperation heapify(final MemorySegment srcSeg, final long expectedSeed) { - final byte famID = srcSeg.get(JAVA_BYTE, FAMILY_BYTE); - final Family family = idToFamily(famID); - switch (family) { - case UNION : { - return ThetaUnionImpl.heapifyInstance(srcSeg, expectedSeed); - } - case INTERSECTION : { - return ThetaIntersectionImpl.heapifyInstance(srcSeg, expectedSeed); - } - default: { - throw new SketchesArgumentException("ThetaSetOperation cannot heapify family: " - + family.toString()); - } - } - } - - /** - * Wrap takes the ThetaSetOperation image in MemorySegment and refers to it directly. - * There is no data copying onto the java heap. - * This method assumes the Default Update Seed. - * If the given source MemorySegment is read-only, the returned object will also be read-only. - * - *

Note: Only certain set operators during stateful operations can be serialized and thus wrapped.

- * - * @param srcSeg an image of a ThetaSetOperation where the image seed hash matches the default seed hash. - * @return a ThetaSetOperation backed by the given MemorySegment - */ - public static ThetaSetOperation wrap(final MemorySegment srcSeg) { - return wrap(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Wrap takes the ThetaSetOperation image in MemorySegment and refers to it directly. - * There is no data copying onto the java heap. - * If the given source MemorySegment is read-only, the returned object will also be read-only. - * - *

Note: Only certain set operators during stateful operations can be serialized and thus wrapped.

- * - * @param srcSeg an image of a ThetaSetOperation where the hash of the given expectedSeed matches the image seed hash. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See Update Hash Seed. - * @return a ThetaSetOperation backed by the given MemorySegment - */ - public static ThetaSetOperation wrap(final MemorySegment srcSeg, final long expectedSeed) { - final byte famID = srcSeg.get(JAVA_BYTE, FAMILY_BYTE); - final Family family = idToFamily(famID); - final int serVer = srcSeg.get(JAVA_BYTE, SER_VER_BYTE); - if (serVer != 3) { - throw new SketchesArgumentException("SerVer must be 3: " + serVer); - } - switch (family) { - case UNION : { - return ThetaUnionImpl.wrapInstance(srcSeg, expectedSeed); - } - case INTERSECTION : { - return ThetaIntersectionImpl.wrapInstance(srcSeg, expectedSeed, srcSeg.isReadOnly() ); - } - default: - throw new SketchesArgumentException("ThetaSetOperation cannot wrap family: " + family.toString()); - } - } - - /** - * Returns the maximum required storage bytes given a nomEntries parameter for ThetaUnion operations - * @param nomEntries Nominal Entries - * This will become the ceiling power of 2 if it is not. - * @return the maximum required storage bytes given a nomEntries parameter - */ - public static int getMaxUnionBytes(final int nomEntries) { - final int nomEnt = ceilingPowerOf2(nomEntries); - return (nomEnt << 4) + (Family.UNION.getMaxPreLongs() << 3); - } - - /** - * Returns the maximum required storage bytes given a nomEntries parameter for intersection - * operations - * @param nomEntries Nominal Entries - * This will become the ceiling power of 2 if it is not. - * @return the maximum required storage bytes given a nomEntries parameter - */ - public static int getMaxIntersectionBytes(final int nomEntries) { - final int nomEnt = ceilingPowerOf2(nomEntries); - return (nomEnt << 4) + (Family.INTERSECTION.getMaxPreLongs() << 3); - } - - /** - * Returns the maximum number of bytes for the returned CompactThetaSketch, given the - * value of nomEntries of the first sketch A of ThetaAnotB. - * @param nomEntries this value must be a power of 2. - * @return the maximum number of bytes. - */ - public static int getMaxAnotBResultBytes(final int nomEntries) { - final int ceil = ceilingPowerOf2(nomEntries); - return 24 + (15 * ceil); - } - - /** - * Gets the Family of this ThetaSetOperation - * @return the Family of this ThetaSetOperation - */ - public abstract Family getFamily(); - - //restricted - - /** - * Gets the hash array in compact form. - * This is only useful during stateful operations. - * This should never be made public. - * @return the hash array - */ - abstract long[] getCache(); - - /** - * Returns the backing MemorySegment object if it exists, otherwise null. - * @return the backing MemorySegment object if it exists, otherwise null. - */ - MemorySegment getMemorySegment() { return null; } - - /** - * Gets the current count of retained entries. - * This is only useful during stateful operations. - * Intentionally not made public because behavior will be confusing to end user. - * - * @return Gets the current count of retained entries. - */ - abstract int getRetainedEntries(); - - /** - * Returns the seedHash established during class construction. - * @return the seedHash. - */ - abstract short getSeedHash(); - - /** - * Gets the current value of ThetaLong. - * Only useful during stateful operations. - * Intentionally not made public because behavior will be confusing to end user. - * @return the current value of ThetaLong. - */ - abstract long getThetaLong(); - - /** - * Returns true if this set operator is empty. - * Only useful during stateful operations. - * Intentionally not made public because behavior will be confusing to end user. - * @return true if this set operator is empty. - */ - abstract boolean isEmpty(); - -} diff --git a/src/main/java/org/apache/datasketches/theta/ThetaSetOperationBuilder.java b/src/main/java/org/apache/datasketches/theta/ThetaSetOperationBuilder.java deleted file mode 100644 index d56462fd4..000000000 --- a/src/main/java/org/apache/datasketches/theta/ThetaSetOperationBuilder.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.TAB; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * For building a new ThetaSetOperation. - * - * @author Lee Rhodes - */ -public final class ThetaSetOperationBuilder { - private int bLgNomLongs; - private long bSeed; - private ResizeFactor bRF; - private float bP; - - /** - * Constructor for building a new ThetaSetOperation. The default configuration is - *
    - *
  • Max Nominal Entries (max K): - * {@value org.apache.datasketches.thetacommon.ThetaUtil#DEFAULT_NOMINAL_ENTRIES}
  • - *
  • Seed: {@value org.apache.datasketches.common.Util#DEFAULT_UPDATE_SEED}
  • - *
  • {@link ResizeFactor#X8}
  • - *
  • Input Sampling Probability: 1.0
  • - *
  • MemorySegment: null
  • - *
- */ - public ThetaSetOperationBuilder() { - bLgNomLongs = Integer.numberOfTrailingZeros(ThetaUtil.DEFAULT_NOMINAL_ENTRIES); - bSeed = Util.DEFAULT_UPDATE_SEED; - bP = (float) 1.0; - bRF = ResizeFactor.X8; - } - - /** - * Sets the Maximum Nominal Entries (max K) for this set operation. The effective value of K of the result of a - * Set Operation can be less than max K, but never greater. - * The minimum value is 16 and the maximum value is 67,108,864, which is 2^26. - * @param nomEntries Nominal Entries - * This will become the ceiling power of 2 if it is not a power of 2. - * @return this ThetaSetOperationBuilder - */ - public ThetaSetOperationBuilder setNominalEntries(final int nomEntries) { - bLgNomLongs = Integer.numberOfTrailingZeros(ceilingPowerOf2(nomEntries)); - if ((bLgNomLongs > ThetaUtil.MAX_LG_NOM_LONGS) || (bLgNomLongs < ThetaUtil.MIN_LG_NOM_LONGS)) { - throw new SketchesArgumentException("Nominal Entries must be >= 16 and <= 67108864: " - + nomEntries); - } - return this; - } - - /** - * Alternative method of setting the Nominal Entries for this set operation from the log_base2 value. - * The minimum value is 4 and the maximum value is 26. - * Be aware that set operations as large as this maximum value may not have been - * thoroughly characterized for performance. - * - * @param lgNomEntries the log_base2 Nominal Entries. - * @return this ThetaSetOperationBuilder - */ - public ThetaSetOperationBuilder setLogNominalEntries(final int lgNomEntries) { - bLgNomLongs = ThetaUtil.checkNomLongs(1 << lgNomEntries); - return this; - } - - /** - * Returns Log-base 2 Nominal Entries - * @return Log-base 2 Nominal Entries - */ - public int getLgNominalEntries() { - return bLgNomLongs; - } - - /** - * Sets the long seed value that is require by the hashing function. - * @param seed See seed - * @return this ThetaSetOperationBuilder - */ - public ThetaSetOperationBuilder setSeed(final long seed) { - bSeed = seed; - return this; - } - - /** - * Returns the seed - * @return the seed - */ - public long getSeed() { - return bSeed; - } - - /** - * Sets the upfront uniform sampling probability, p. Although this functionality is - * implemented for ThetaUnions only, it rarely makes sense to use it. The proper use of upfront - * sampling is when building the sketches. - * @param p See Sampling Probability, p - * @return this ThetaSetOperationBuilder - */ - public ThetaSetOperationBuilder setP(final float p) { - if ((p <= 0.0) || (p > 1.0)) { - throw new SketchesArgumentException("p must be > 0 and <= 1.0: " + p); - } - bP = p; - return this; - } - - /** - * Returns the pre-sampling probability p - * @return the pre-sampling probability p - */ - public float getP() { - return bP; - } - - /** - * Sets the cache Resize Factor - * @param rf See Resize Factor - * @return this ThetaSetOperationBuilder - */ - public ThetaSetOperationBuilder setResizeFactor(final ResizeFactor rf) { - bRF = rf; - return this; - } - - /** - * Returns the Resize Factor - * @return the Resize Factor - */ - public ResizeFactor getResizeFactor() { - return bRF; - } - - /** - * Returns a ThetaSetOperation with the current configuration of this Builder and the given Family. - * @param family the chosen ThetaSetOperation family - * @return a ThetaSetOperation - */ - public ThetaSetOperation build(final Family family) { - return build(family, null); - } - - /** - * Returns a ThetaSetOperation with the current configuration of this Builder, the given Family - * and the given destination MemorySegment. Note that the destination MemorySegment cannot be used with ThetaAnotB. - * @param family the chosen ThetaSetOperation family - * @param dstSeg The destination MemorySegment. - * @return a ThetaSetOperation - */ - public ThetaSetOperation build(final Family family, final MemorySegment dstSeg) { - ThetaSetOperation setOp = null; - switch (family) { - case UNION: { - if (dstSeg == null) { - setOp = ThetaUnionImpl.initNewHeapInstance(bLgNomLongs, bSeed, bP, bRF); - } - else { - setOp = ThetaUnionImpl.initNewDirectInstance(bLgNomLongs, bSeed, bP, bRF, dstSeg); - } - break; - } - case INTERSECTION: { - if (dstSeg == null) { - setOp = ThetaIntersectionImpl.initNewHeapInstance(bSeed); - } - else { - setOp = ThetaIntersectionImpl.initNewDirectInstance(bSeed, dstSeg); - } - break; - } - case A_NOT_B: { - if (dstSeg == null) { - setOp = new ThetaAnotBimpl(bSeed); - } - else { - throw new SketchesArgumentException( - "ThetaAnotB can not be persisted."); - } - break; - } - default: - throw new SketchesArgumentException( - "Given Family cannot be built as a ThetaSetOperation: " + family.toString()); - } - return setOp; - } - - /** - * Convenience method, returns a configured ThetaSetOperation ThetaUnion with - * Default Nominal Entries - * @return a ThetaUnion object - */ - public ThetaUnion buildUnion() { - return (ThetaUnion) build(Family.UNION); - } - - /** - * Convenience method, returns a configured ThetaSetOperation ThetaUnion with - * Default Nominal Entries - * and the given destination MemorySegment. - * @param dstSeg The destination MemorySegment. - * @return a ThetaUnion object - */ - public ThetaUnion buildUnion(final MemorySegment dstSeg) { - return (ThetaUnion) build(Family.UNION, dstSeg); - } - - /** - * Convenience method, returns a configured ThetaIntersection with - * Default Nominal Entries - * @return a ThetaIntersection object - */ - public ThetaIntersection buildIntersection() { - return (ThetaIntersection) build(Family.INTERSECTION); - } - - /** - * Convenience method, returns a configured ThetaIntersection with - * Default Nominal Entries - * and the given destination MemorySegment. - * @param dstSeg The destination MemorySegment. - * @return a ThetaIntersection object - */ - public ThetaIntersection buildIntersection(final MemorySegment dstSeg) { - return (ThetaIntersection) build(Family.INTERSECTION, dstSeg); - } - - /** - * Convenience method, returns a configured ThetaSetOperation ANotB with - * Default Update Seed - * @return a ThetaANotB object - */ - public ThetaAnotB buildANotB() { - return (ThetaAnotB) build(Family.A_NOT_B); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("SetOperationBuilder configuration:").append(LS); - sb.append("LgK:").append(TAB).append(bLgNomLongs).append(LS); - sb.append("K:").append(TAB).append(1 << bLgNomLongs).append(LS); - sb.append("Seed:").append(TAB).append(bSeed).append(LS); - sb.append("p:").append(TAB).append(bP).append(LS); - sb.append("ResizeFactor:").append(TAB).append(bRF).append(LS); - return sb.toString(); - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/ThetaSketch.java b/src/main/java/org/apache/datasketches/theta/ThetaSketch.java deleted file mode 100644 index 1b82ec76b..000000000 --- a/src/main/java/org/apache/datasketches/theta/ThetaSketch.java +++ /dev/null @@ -1,690 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.apache.datasketches.common.Family.idToFamily; -import static org.apache.datasketches.common.Util.LONG_MAX_VALUE_AS_DOUBLE; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.common.Util.zeroPad; -import static org.apache.datasketches.theta.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.checkSegPreambleCap; -import static org.apache.datasketches.theta.PreambleUtil.extractCurCount; -import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.extractFlags; -import static org.apache.datasketches.theta.PreambleUtil.extractSerVer; -import static org.apache.datasketches.theta.PreambleUtil.extractThetaLong; -import static org.apache.datasketches.thetacommon.HashOperations.count; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.BinomialBoundsN; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * The top-level class for all theta sketches. This class is never constructed directly. - * Use the UpdatableThetaSketchBuilder() methods to create UpdatableThetaSketches. - * - * @author Lee Rhodes - */ -public abstract class ThetaSketch implements MemorySegmentStatus { - - ThetaSketch() {} - - //public static factory constructor-type methods - - /** - * Heapify takes the sketch image in MemorySegment and instantiates an on-heap ThetaSketch. - * - *

The resulting sketch will not retain any link to the source MemorySegment.

- * - *

For UpdatableThetaSketches this method checks if the - * Default Update Seed

- * was used to create the source MemorySegment image. - * - * @param srcSeg an image of a ThetaSketch. - * - * @return a ThetaSketch on the heap. - */ - public static ThetaSketch heapify(final MemorySegment srcSeg) { - return heapify(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Heapify takes the sketch image in MemorySegment and instantiates an on-heap ThetaSketch. - * - *

The resulting sketch will not retain any link to the source MemorySegment.

- * - *

For UpdatableThetaSketches this method checks if the expectedSeed - * was used to create the source MemorySegment image.

- * - * @param srcSeg an image of a ThetaSketch that was created using the given expectedSeed. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See Update Hash Seed. - * Compact sketches store a 16-bit hash of the seed, but not the seed itself. - * @return a ThetaSketch on the heap. - */ - public static ThetaSketch heapify(final MemorySegment srcSeg, final long expectedSeed) { - checkSegPreambleCap(srcSeg); - final int familyID = extractFamilyID(srcSeg); - if (familyID == Family.COMPACT.getID()) { - return CompactThetaSketch.heapify(srcSeg, expectedSeed); - } - return heapifyUpdateSketchFromMemorySegment(srcSeg, expectedSeed); - } - - /** - * Wrap takes the sketch image in the given MemorySegment and refers to it directly. - * There is no data copying onto the java heap. - * The wrap operation enables fast read-only merging and access to all the public read-only API. - * - *

Only sketches that have been explicitly stored as direct sketches can be wrapped.

- * - *

Wrapping any subclass of this class that is empty or contains only a single item will - * result in on-heap equivalent forms of empty and single item sketch respectively. - * This is actually faster and consumes less overall space.

- * - *

This method checks if the - * Default Update Seed - * was used to create the source MemorySegment image.

- * - * @param srcSeg a MemorySegment with an image of a ThetaSketch. - * @return a read-only ThetaSketch backed by the given MemorySegment - */ - public static ThetaSketch wrap(final MemorySegment srcSeg) { - return wrap(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Wrap takes the sketch image in the given MemorySegment and refers to it directly. - * There is no data copying onto the java heap. - * The wrap operation enables fast read-only merging and access to all the public read-only API. - * - *

Only sketches that have been explicitly stored as direct sketches can be wrapped.

- * - *

Wrapping any subclass of this class that is empty or contains only a single item will - * result in on-heap equivalent forms of empty and single item sketch respectively. - * This is actually faster and consumes less overall space.

- * - *

This method checks if the given expectedSeed - * was used to create the source MemorySegment image.

- * - * @param srcSeg a MemorySegment with an image of a ThetaSketch. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See Update Hash Seed. - * @return a read-only ThetaSketch backed by the given MemorySegment. - */ - public static ThetaSketch wrap(final MemorySegment srcSeg, final long expectedSeed) { - checkSegPreambleCap(srcSeg); - final int familyID = extractFamilyID(srcSeg); - if (familyID == Family.QUICKSELECT.getID()) { - return DirectQuickSelectSketchR.readOnlyWrap(srcSeg, expectedSeed); - } - if (familyID == Family.COMPACT.getID()) { - return CompactThetaSketch.wrap(srcSeg, expectedSeed); - } - final Family family = Family.idToFamily(familyID); - throw new SketchesArgumentException( - "Cannot wrap family: " + family + " as a ThetaSketch"); - } - - //ThetaSketch interface - - /** - * Converts this sketch to a ordered CompactThetaSketch. - * - *

If this.isCompact() == true this method returns this, - * otherwise, this method is equivalent to - * {@link #compact(boolean, MemorySegment) compact(true, null)}. - * - *

A CompactThetaSketch is always immutable.

- * - * @return this sketch as an ordered CompactThetaSketch. - */ - public CompactThetaSketch compact() { - return isCompact() ? (CompactThetaSketch)this : compact(true, null); - } - - /** - * Convert this sketch to a CompactThetaSketch. - * - *

If this sketch is a type of UpdatableThetaSketch, the compacting process converts the hash table - * of the UpdatableThetaketch to a simple list of the valid hash values. - * Any hash values of zero or equal-to or greater than theta will be discarded. - * The number of valid values remaining in the CompactThetaSketch depends on a number of factors, - * but may be larger or smaller than Nominal Entries (or k). - * It will never exceed 2k. - * If it is critical to always limit the size to no more than k, - * then rebuild() should be called on the UpdatableThetaSketch prior to calling this method.

- * - *

A CompactThetaSketch is always immutable.

- * - *

A new CompactThetaSketch object is created:

- *
  • if dstSeg!= null
  • - *
  • if dstSeg == null and this.hasMemorySegment() == true
  • - *
  • if dstSeg == null and this has more than 1 item and this.isOrdered() == false - * and dstOrdered == true.
  • - *
- * - *

Otherwise, this operation returns this.

- * - * @param dstOrdered assumed true if this sketch is empty or has only one value - * See Destination Ordered - * - * @param dstSeg - * See Destination MemorySegment. - * - * @return this sketch as a CompactThetaSketch. - */ - public abstract CompactThetaSketch compact(final boolean dstOrdered, final MemorySegment dstSeg); - - /** - * Returns the number of storage bytes required for this ThetaSketch if its current state were - * compacted. It this sketch is already in the compact form this is equivalent to - * calling {@link #getCurrentBytes()}. - * @return number of compact bytes - */ - public abstract int getCompactBytes(); - - /** - * Gets the number of hash values less than the given theta expressed as a long. - * @param thetaLong the given theta as a long between zero and Long.MAX_VALUE. - * @return the number of hash values less than the given thetaLong. - */ - public int getCountLessThanThetaLong(final long thetaLong) { - return count(getCache(), thetaLong); - } - - /** - * Returns the number of storage bytes required for this sketch in its current state. - * - * @return the number of storage bytes required for this sketch - */ - public abstract int getCurrentBytes(); - - /** - * Gets the unique count estimate. - * @return the sketch's best estimate of the cardinality of the input stream. - */ - public abstract double getEstimate(); - - /** - * Gets the estimate from the given MemorySegment - * @param srcSeg the given MemorySegment - * @return the result estimate - */ - public static double getEstimate(final MemorySegment srcSeg) { - checkSegPreambleCap(srcSeg); - final int familyId = extractFamilyID(srcSeg); - if (!isValidSketchID(familyId)) { - throw new SketchesArgumentException("Source MemorySegment is not a valid ThetaSketch Family: " - + Family.idToFamily(familyId).toString()); - } - return ThetaSketch.estimate(extractThetaLong(srcSeg), getRetainedEntries(srcSeg)); - } - - /** - * Returns the Family that this sketch belongs to - * @return the Family that this sketch belongs to - */ - public abstract Family getFamily(); - - /** - * Gets the approximate lower error bound given the specified number of Standard Deviations. - * This will return getEstimate() if isEmpty() is true. - * - * @param numStdDev - * See Number of Standard Deviations - * @return the lower bound. - */ - public double getLowerBound(final int numStdDev) { - return isEstimationMode() - ? lowerBound(getRetainedEntries(true), getThetaLong(), numStdDev, isEmpty()) - : getRetainedEntries(true); - } - - /** - * Returns the maximum number of storage bytes required for a CompactThetaSketch with the given - * number of actual entries. - * @param numberOfEntries the actual number of retained entries stored in the sketch. - * @return the maximum number of storage bytes required for a CompactThetaSketch with the given number - * of retained entries. - */ - public static int getMaxCompactSketchBytes(final int numberOfEntries) { - if (numberOfEntries == 0) { return 8; } - if (numberOfEntries == 1) { return 16; } - return (numberOfEntries << 3) + 24; - } - - /** - * Returns the maximum number of storage bytes required for a CompactThetaSketch given the configured - * log_base2 of the number of nominal entries, which is a power of 2. - * @param lgNomEntries Nominal Entries - * @return the maximum number of storage bytes required for a CompactThetaSketch with the given - * lgNomEntries. - */ - public static int getCompactSketchMaxBytes(final int lgNomEntries) { - return (int)((2 << lgNomEntries) * ThetaUtil.REBUILD_THRESHOLD - + Family.QUICKSELECT.getMaxPreLongs()) * Long.BYTES; - } - - /** - * Returns the maximum number of storage bytes required for an UpdatableThetaSketch with the given - * number of nominal entries (power of 2). - * @param nomEntries Nominal Entries - * This will become the ceiling power of 2 if it is not. - * @return the maximum number of storage bytes required for a UpdatableThetaSketch with the given - * nomEntries - */ - public static int getMaxUpdateSketchBytes(final int nomEntries) { - final int nomEnt = ceilingPowerOf2(nomEntries); - return (nomEnt << 4) + (Family.QUICKSELECT.getMaxPreLongs() << 3); - } - - /** - * Returns the maximum number of storage bytes required for an UpdatableThetaSketch with the given - * log_base2 of the nominal entries. - * @param lgNomEntries log_base2 of Nominal Entries - * @return the maximum number of storage bytes required for a UpdatableThetaSketch with the given lgNomEntries - */ - public static int getUpdateSketchMaxBytes(final int lgNomEntries) { - return (16 << lgNomEntries) + (Family.QUICKSELECT.getMaxPreLongs() << 3); - } - - /** - * Returns the number of valid entries that have been retained by the sketch. - * For the AlphaSketch this returns only valid entries. - * @return the number of valid retained entries. - */ - public int getRetainedEntries() { - return getRetainedEntries(true); - } - - /** - * Returns the number of entries that have been retained by the sketch. - * @param valid This parameter is only relevant for the AlphaSketch. - * if true, returns the number of valid entries, which are less than theta and used - * for estimation. Otherwise, return the number of all entries, valid or not, that are currently in the - * internal sketch cache. - * @return the number of retained entries - */ - public abstract int getRetainedEntries(final boolean valid); - - /** - * Returns the number of valid entries that have been retained by the sketch from the given MemorySegment - * @param srcSeg the given MemorySegment that has an image of a ThetaSketch - * @return the number of valid retained entries - */ - public static int getRetainedEntries(final MemorySegment srcSeg) { - final int preLongs = checkSegPreambleCap(srcSeg); - final boolean empty = (extractFlags(srcSeg) & EMPTY_FLAG_MASK) != 0; - return (preLongs == 1) ? (empty ? 0 : 1) : extractCurCount(srcSeg); - } - - /** - * Returns the serialization version from the given MemorySegment - * @param seg the sketch MemorySegment - * @return the serialization version from the MemorySegment - */ - public static int getSerializationVersion(final MemorySegment seg) { - checkSegPreambleCap(seg); - return extractSerVer(seg); - } - - /** - * Gets the value of theta as a double with a value between zero and one - * @return the value of theta as a double - */ - public double getTheta() { - return getThetaLong() / LONG_MAX_VALUE_AS_DOUBLE; - } - - /** - * Gets the value of theta as a long - * @return the value of theta as a long - */ - public abstract long getThetaLong(); - - /** - * Gets the approximate upper error bound given the specified number of Standard Deviations. - * This will return getEstimate() if isEmpty() is true. - * - * @param numStdDev - * See Number of Standard Deviations - * @return the upper bound. - */ - public double getUpperBound(final int numStdDev) { - return isEstimationMode() - ? upperBound(getRetainedEntries(true), getThetaLong(), numStdDev, isEmpty()) - : getRetainedEntries(true); - } - - /** - * Returns true if this sketch is in compact form. - * @return true if this sketch is in compact form. - */ - public abstract boolean isCompact(); - - /** - * See Empty - * @return true if empty. - */ - public abstract boolean isEmpty(); - - /** - * Returns true if the sketch is Estimation Mode (as opposed to Exact Mode). - * This is true if theta < 1.0 AND isEmpty() is false. - * @return true if the sketch is in estimation mode. - */ - public boolean isEstimationMode() { - return getThetaLong() < Long.MAX_VALUE && !isEmpty(); - } - - /** - * Returns true if internal cache is ordered - * @return true if internal cache is ordered - */ - public abstract boolean isOrdered(); - - /** - * Returns a HashIterator that can be used to iterate over the retained hash values of the - * Theta sketch. - * @return a HashIterator that can be used to iterate over the retained hash values of the - * Theta sketch. - */ - public abstract HashIterator iterator(); - - /** - * Serialize this sketch to a byte array form. - * @return byte array of this sketch - */ - public abstract byte[] toByteArray(); - - /** - * Returns a human readable summary of the sketch. This method is equivalent to the parameterized - * call:
- * ThetaSketch.toString(ThetaSketch, true, false, 8, true); - * @return summary - */ - @Override - public String toString() { - return toString(true, false, 8, true); - } - - /** - * Gets a human readable listing of contents and summary of the given sketch. - * This can be a very long string. If this sketch is in a "dirty" state there - * may be values in the dataDetail view that are ≥ theta. - * - * @param sketchSummary If true the sketch summary will be output at the end. - * @param dataDetail If true, includes all valid hash values in the sketch. - * @param width The number of columns of hash values. Default is 8. - * @param hexMode If true, hashes will be output in hex. - * @return The result string, which can be very long. - */ - public String toString( - final boolean sketchSummary, - final boolean dataDetail, - final int width, - final boolean hexMode) { - final StringBuilder sb = new StringBuilder(); - - int nomLongs = 0; - int arrLongs = 0; - float p = 0; - int rf = 0; - final boolean updateSketch = this instanceof UpdatableThetaSketch; - - final long thetaLong = getThetaLong(); - final int curCount = this.getRetainedEntries(true); - - if (updateSketch) { - final UpdatableThetaSketch uis = (UpdatableThetaSketch)this; - nomLongs = 1 << uis.getLgNomLongs(); - arrLongs = 1 << uis.getLgArrLongs(); - p = uis.getP(); - rf = uis.getResizeFactor().getValue(); - } - - if (dataDetail) { - final int w = width > 0 ? width : 8; // default is 8 wide - if (curCount > 0) { - sb.append("### SKETCH DATA DETAIL"); - final HashIterator it = iterator(); - int j = 0; - while (it.next()) { - final long h = it.get(); - if (j % w == 0) { - sb.append(LS).append(String.format(" %6d", j + 1)); - } - if (hexMode) { - sb.append(" " + zeroPad(Long.toHexString(h), 16) + ","); - } - else { - sb.append(String.format(" %20d,", h)); - } - j++ ; - } - sb.append(LS).append("### END DATA DETAIL").append(LS + LS); - } - } - - if (sketchSummary) { - final double thetaDbl = thetaLong / LONG_MAX_VALUE_AS_DOUBLE; - final String thetaHex = zeroPad(Long.toHexString(thetaLong), 16); - final String thisSimpleName = this.getClass().getSimpleName(); - final int seedHash = Short.toUnsignedInt(getSeedHash()); - - sb.append(LS); - sb.append("### ").append(thisSimpleName).append(" SUMMARY: ").append(LS); - if (updateSketch) { - sb.append(" Nominal Entries (k) : ").append(nomLongs).append(LS); - } - sb.append(" Estimate : ").append(getEstimate()).append(LS); - sb.append(" Upper Bound, 95% conf : ").append(getUpperBound(2)).append(LS); - sb.append(" Lower Bound, 95% conf : ").append(getLowerBound(2)).append(LS); - if (updateSketch) { - sb.append(" p : ").append(p).append(LS); - } - sb.append(" Theta (double) : ").append(thetaDbl).append(LS); - sb.append(" Theta (long) : ").append(thetaLong).append(LS); - sb.append(" Theta (long) hex : ").append(thetaHex).append(LS); - sb.append(" EstMode? : ").append(isEstimationMode()).append(LS); - sb.append(" Empty? : ").append(isEmpty()).append(LS); - sb.append(" Ordered? : ").append(isOrdered()).append(LS); - if (updateSketch) { - sb.append(" Resize Factor : ").append(rf).append(LS); - sb.append(" Array Size Entries : ").append(arrLongs).append(LS); - } - sb.append(" Retained Entries : ").append(curCount).append(LS); - sb.append(" Seed Hash : ").append(Integer.toHexString(seedHash)) - .append(" | ").append(seedHash).append(LS); - sb.append("### END SKETCH SUMMARY").append(LS); - - } - return sb.toString(); - } - - /** - * Returns a human readable string of the preamble of a byte array image of a ThetaSketch. - * @param byteArr the given byte array - * @return a human readable string of the preamble of a byte array image of a ThetaSketch. - */ - public static String toString(final byte[] byteArr) { - return PreambleUtil.preambleToString(byteArr); - } - - /** - * Returns a human readable string of the preamble of a MemorySegment image of a ThetaSketch. - * @param seg the given MemorySegment object - * @return a human readable string of the preamble of a MemorySegment image of a ThetaSketch. - */ - public static String toString(final MemorySegment seg) { - return PreambleUtil.preambleToString(seg); - } - - //Restricted methods - - /** - * Gets the internal cache array. For on-heap sketches this will return a reference to the actual - * cache array. For MemorySegment-based sketches this returns a copy. - * - *

This can be an expensive operation and is intended for diagnostic & test applications. - * Use {@link #iterator() iterator()} instead.

- * @return the internal cache array. - */ - abstract long[] getCache(); - - /** - * Gets preamble longs if stored in compact form. If this sketch is already in compact form, - * this is identical to the call {@link #getCurrentPreambleLongs()}. - * @return preamble longs if stored in compact form. - */ - abstract int getCompactPreambleLongs(); - - /** - * Gets the number of data longs if stored in current state. - * @return the number of data longs if stored in current state. - */ - abstract int getCurrentDataLongs(); - - /** - * Returns preamble longs if stored in current state. - * @return number of preamble longs if stored. - */ - abstract int getCurrentPreambleLongs(); - - /** - * Returns the backing MemorySegment object if it exists, otherwise null. - * This is overridden where relevant. - * @return the backing MemorySegment object if it exists, otherwise null. - */ - MemorySegment getMemorySegment() { return null; } - - /** - * Gets the 16-bit seed hash - * @return the seed hash - */ - abstract short getSeedHash(); - - static boolean getEmpty(final MemorySegment srcSeg) { - checkSegPreambleCap(srcSeg); - final int serVer = extractSerVer(srcSeg); - if (serVer == 1) { - return getThetaLong(srcSeg) == Long.MAX_VALUE && getRetainedEntries(srcSeg) == 0; - } - return (extractFlags(srcSeg) & EMPTY_FLAG_MASK) != 0; - } - - static int getPreambleLongs(final MemorySegment srcSeg) { - return checkSegPreambleCap(srcSeg); - } - - static long getThetaLong(final MemorySegment srcSeg) { - final int preLongs = checkSegPreambleCap(srcSeg); - return preLongs < 3 ? Long.MAX_VALUE : extractThetaLong(srcSeg); - } - - /** - * Returns true if given Family id is one of the theta sketches - * @param id the given Family id - * @return true if given Family id is one of the theta sketches - */ - static final boolean isValidSketchID(final int id) { - return id == Family.ALPHA.getID() - || id == Family.QUICKSELECT.getID() - || id == Family.COMPACT.getID(); - } - - static final double estimate(final long thetaLong, final int curCount) { - return curCount * (LONG_MAX_VALUE_AS_DOUBLE / thetaLong); - } - - /** - * Gets the approximate lower error bound from a valid MemorySegment image of a ThetaSketch - * given the specified number of Standard Deviations. - * This will return getEstimate() if isEmpty() is true. - * - * @param numStdDev - * See Number of Standard Deviations - * @param srcSeg the source MemorySegment - * @return the lower bound. - */ - public static double getLowerBound(final int numStdDev, final MemorySegment srcSeg) { - return lowerBound(getRetainedEntries(srcSeg), ThetaSketch.getThetaLong(srcSeg), numStdDev, ThetaSketch.getEmpty(srcSeg)); - } - - static final double lowerBound(final int curCount, final long thetaLong, final int numStdDev, final boolean empty) { - final double theta = thetaLong / LONG_MAX_VALUE_AS_DOUBLE; - return BinomialBoundsN.getLowerBound(curCount, theta, numStdDev, empty); - } - - /** - * Gets the approximate upper error bound from a valid MemorySegment image of a ThetaSketch - * given the specified number of Standard Deviations. - * This will return getEstimate() if isEmpty() is true. - * - * @param numStdDev - * See Number of Standard Deviations - * @param srcSeg the source MemorySegment - * @return the upper bound. - */ - public static double getUpperBound(final int numStdDev, final MemorySegment srcSeg) { - return upperBound(getRetainedEntries(srcSeg), ThetaSketch.getThetaLong(srcSeg), numStdDev, ThetaSketch.getEmpty(srcSeg)); - } - - static final double upperBound(final int curCount, final long thetaLong, final int numStdDev, - final boolean empty) { - final double theta = thetaLong / LONG_MAX_VALUE_AS_DOUBLE; - return BinomialBoundsN.getUpperBound(curCount, theta, numStdDev, empty); - } - - /** - * Instantiates a Heap UpdatableThetaSketch from MemorySegment. - * @param srcSeg the source MemorySegment - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See Update Hash Seed. - * @return a ThetaSketch - */ - private static final ThetaSketch heapifyUpdateSketchFromMemorySegment(final MemorySegment srcSeg, final long expectedSeed) { - final Family family = idToFamily(extractFamilyID(srcSeg)); - - if (family == Family.ALPHA) { - final int flags = extractFlags(srcSeg); - final boolean compactFlag = (flags & COMPACT_FLAG_MASK) != 0; - if (compactFlag) { - throw new SketchesArgumentException( - "Corrupted: An ALPHA family image cannot be compact"); - } - return HeapAlphaSketch.heapifyInstance(srcSeg, expectedSeed); - } - if (family == Family.QUICKSELECT) { - return HeapQuickSelectSketch.heapifyInstance(srcSeg, expectedSeed); - } - throw new SketchesArgumentException( - "Cannot heapify family: " + family + " as a ThetaSketch"); - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/ThetaUnion.java b/src/main/java/org/apache/datasketches/theta/ThetaUnion.java deleted file mode 100644 index 5ba80d14c..000000000 --- a/src/main/java/org/apache/datasketches/theta/ThetaUnion.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; - -/** - * Compute the union of two or more theta sketches. - * A new instance represents an empty set. - * - * @author Lee Rhodes - */ -public abstract class ThetaUnion extends ThetaSetOperation { - - /** - * No argument constructor. - */ - public ThetaUnion() { } - - /** - * Wrap a ThetaUnion object around a ThetaUnion MemorySegment object containing data. - * This method assumes the Default Update Seed. - * This does NO validity checking of the given MemorySegment. - * If the given source MemorySegment is read-only, the returned ThetaUnion object will also be read-only. - * @param srcSeg The source MemorySegment object. - * @return this class - */ - public static ThetaUnion fastWrap(final MemorySegment srcSeg) { - return fastWrap(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Wrap a ThetaUnion object around a ThetaUnion MemorySegment object containing data. - * This does NO validity checking of the given MemorySegment. - * If the given source MemorySegment is read-only, the returned ThetaUnion object will also be read-only. - * @param srcSeg The source MemorySegment object. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See seed - * @return this class - */ - public static ThetaUnion fastWrap(final MemorySegment srcSeg, final long expectedSeed) { - final int serVer = srcSeg.get(JAVA_BYTE, SER_VER_BYTE); - if (serVer != 3) { - throw new SketchesArgumentException("SerVer must be 3: " + serVer); - } - return ThetaUnionImpl.fastWrapInstance(srcSeg, expectedSeed); - } - - /** - * Wrap a ThetaUnion object around a ThetaUnion MemorySegment object containing data. - * This method assumes the Default Update Seed. - * If the given source MemorySegment is read-only, the returned ThetaUnion object will also be read-only. - * @param srcSeg The source MemorySegment object. - * @return this class - */ - public static ThetaUnion wrap(final MemorySegment srcSeg) { - return wrap(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Wrap a ThetaUnion object around a ThetaUnion MemorySegment object containing data. - * If the given source MemorySegment is read-only, the returned ThetaUnion object will also be read-only. - * @param srcSeg The source MemorySegment object. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See seed - * @return this class - */ - public static ThetaUnion wrap(final MemorySegment srcSeg, final long expectedSeed) { - final int serVer = srcSeg.get(JAVA_BYTE, SER_VER_BYTE); - if (serVer != 3) { - throw new SketchesArgumentException("SerVer must be 3: " + serVer); - } - return ThetaUnionImpl.wrapInstance(srcSeg, expectedSeed); - } - - /** - * Returns the number of storage bytes required for this union in its current state. - * - * @return the number of storage bytes required for this union in its current state. - */ - public abstract int getCurrentBytes(); - - @Override - public Family getFamily() { - return Family.UNION; - } - - /** - * Returns the maximum required storage bytes for this union. - * @return the maximum required storage bytes for this union. - */ - public abstract int getMaxUnionBytes(); - - /** - * Gets the result of this operation as an ordered CompactThetaSketch on the Java heap. - * This does not disturb the underlying data structure of the union. - * Therefore, it is OK to continue updating the union after this operation. - * @return the result of this operation as an ordered CompactThetaSketch on the Java heap - */ - public abstract CompactThetaSketch getResult(); - - /** - * Gets the result of this operation as a CompactThetaSketch of the chosen form. - * This does not disturb the underlying data structure of the union. - * Therefore, it is OK to continue updating the union after this operation. - * - * @param dstOrdered - * See Destination Ordered - * - * @param dstSeg destination MemorySegment - * - * @return the result of this operation as a CompactThetaSketch of the chosen form - */ - public abstract CompactThetaSketch getResult(boolean dstOrdered, MemorySegment dstSeg); - - /** - * Resets this ThetaUnion. The seed remains intact, everything else reverts back to its virgin state. - */ - public abstract void reset(); - - /** - * Returns a byte array image of this ThetaUnion object - * @return a byte array image of this ThetaUnion object - */ - public abstract byte[] toByteArray(); - - /** - * This implements a stateless, pair-wise union operation. The returned sketch will be cut back to - * the smaller of the two k values if required. - * - *

Nulls and empty sketches are ignored.

- * - * @param sketchA The first argument - * @param sketchB The second argument - * @return the result ordered CompactThetaSketch on the heap. - */ - public CompactThetaSketch union(final ThetaSketch sketchA, final ThetaSketch sketchB) { - return union(sketchA, sketchB, true, null); - } - - /** - * This implements a stateless, pair-wise union operation. The returned sketch will be cut back to - * k if required, similar to the regular ThetaUnion operation. - * - *

Nulls and empty sketches are ignored.

- * - * @param sketchA The first argument - * @param sketchB The second argument - * @param dstOrdered If true, the returned CompactThetaSketch will be ordered. - * @param dstSeg If not null, the returned CompactThetaSketch will be placed in this MemorySegment. - * @return the result CompactThetaSketch. - */ - public abstract CompactThetaSketch union(ThetaSketch sketchA, ThetaSketch sketchB, boolean dstOrdered, - MemorySegment dstSeg); - - /** - * Perform a union operation with this ThetaUnion and the given on-heap sketch of the Theta Family. - * - *

This method can be repeatedly called. - * - *

Nulls and empty sketches are ignored.

- * - * @param sketchIn The incoming sketch. - */ - public abstract void union(ThetaSketch sketchIn); - - /** - * Perform a union operation with this ThetaUnion and the given MemorySegment image of any sketch of the - * Theta Family. - * - *

This method can be repeatedly called. - * - *

Nulls and empty sketches are ignored.

- * - * @param seg MemorySegment image of sketch to be merged - */ - public abstract void union(MemorySegment seg); - - /** - * Update this union with the given long data item. - * - * @param datum The given long datum. - */ - public abstract void update(long datum); - - /** - * Update this union with the given double (or float) data item. - * The double will be converted to a long using Double.doubleToLongBits(datum), - * which normalizes all NaN values to a single NaN representation. - * Plus and minus zero will be normalized to plus zero. - * Each of the special floating-point values NaN and +/- Infinity are treated as distinct. - * - * @param datum The given double datum. - */ - public abstract void update(double datum); - - /** - * Update this union with the with the given String data item. - * The string is converted to a byte array using UTF8 encoding. - * If the string is null or empty no update attempt is made and the method returns. - * - *

Note: this will not produce the same output hash values as the {@link #update(char[])} - * method and will generally be a little slower depending on the complexity of the UTF8 encoding. - *

- * - *

Note: this is not a union operation. This treats the given string as a data item.

- * - * @param datum The given String. - */ - public abstract void update(String datum); - - /** - * Update this union with the given byte array item. - * If the byte array is null or empty no update attempt is made and the method returns. - * - *

Note: this is not a union operation. This treats the given byte array as a data - * item.

- * - * @param data The given byte array. - */ - public abstract void update(byte[] data); - - /** - * Update this union with the given ByteBuffer item. - * If the ByteBuffer is null or empty no update attempt is made and the method returns. - * - *

Note: this is not a union operation. This treats the given ByteBuffer as a data - * item.

- * - * @param data The given ByteBuffer. - */ - public abstract void update(ByteBuffer data); - - /** - * Update this union with the given integer array item. - * If the integer array is null or empty no update attempt is made and the method returns. - * - *

Note: this is not a union operation. This treats the given integer array as a data - * item.

- * - * @param data The given int array. - */ - public abstract void update(int[] data); - - /** - * Update this union with the given char array item. - * If the char array is null or empty no update attempt is made and the method returns. - * - *

Note: this will not produce the same output hash values as the {@link #update(String)} - * method but will be a little faster as it avoids the complexity of the UTF8 encoding.

- * - *

Note: this is not a union operation. This treats the given char array as a data - * item.

- * - * @param data The given char array. - */ - public abstract void update(char[] data); - - /** - * Update this union with the given long array item. - * If the long array is null or empty no update attempt is made and the method returns. - * - *

Note: this is not a union operation. This treats the given char array as a data - * item.

- * - * @param data The given long array. - */ - public abstract void update(long[] data); - -} diff --git a/src/main/java/org/apache/datasketches/theta/ThetaUnionImpl.java b/src/main/java/org/apache/datasketches/theta/ThetaUnionImpl.java deleted file mode 100644 index be0ef0014..000000000 --- a/src/main/java/org/apache/datasketches/theta/ThetaUnionImpl.java +++ /dev/null @@ -1,396 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.Math.min; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.QuickSelect.selectExcludingZeros; -import static org.apache.datasketches.theta.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.ORDERED_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.UNION_THETA_LONG; -import static org.apache.datasketches.theta.PreambleUtil.clearEmpty; -import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.extractUnionThetaLong; -import static org.apache.datasketches.theta.PreambleUtil.insertUnionThetaLong; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; -import java.util.Objects; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.HashOperations; - -/** - * Shared code for the heap union and direct union implementations. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -final class ThetaUnionImpl extends ThetaUnion { - - /** - * Although the gadget object is initially an UpdatableThetaSketch, in the context of a union it is used - * as a specialized buffer that happens to leverage much of the machinery of an UpdatableThetaSketch. - * However, in this context some of the key invariants of the sketch algorithm are intentionally - * violated as an optimization. As a result this object can not be considered as an UpdatableThetaSketch - * and should never be exported as an UpdatableThetaSketch. It's internal state is not necessarily - * finalized and may contain garbage. Also its internal concept of "nominal entries" or "k" can - * be meaningless. It is private for very good reasons. - */ - private final UpdatableThetaSketch gadget_; - private final short expectedSeedHash_; //eliminates having to compute the seedHash on every union. - private long unionThetaLong_; //when on-heap, this is the only copy - private boolean unionEmpty_; //when on-heap, this is the only copy - - private ThetaUnionImpl(final UpdatableThetaSketch gadget, final long seed) { - gadget_ = gadget; - expectedSeedHash_ = Util.computeSeedHash(seed); - } - - /** - * Construct a new ThetaUnion on the java heap. - * Called by ThetaSetOperationBuilder. - * - * @param lgNomLongs See lgNomLongs - * @param seed See seed - * @param p See Sampling Probability, p - * @param rf See Resize Factor - * @return instance of this sketch - */ - static ThetaUnionImpl initNewHeapInstance( - final int lgNomLongs, - final long seed, - final float p, - final ResizeFactor rf) { - final UpdatableThetaSketch gadget = //create with UNION family - new HeapQuickSelectSketch(lgNomLongs, seed, p, rf, true); - final ThetaUnionImpl unionImpl = new ThetaUnionImpl(gadget, seed); - unionImpl.unionThetaLong_ = gadget.getThetaLong(); - unionImpl.unionEmpty_ = gadget.isEmpty(); - return unionImpl; - } - - /** - * Construct a new direct union in the destination MemorySegment. - * Called by ThetaSetOperationBuilder. - * - * @param lgNomLongs See lgNomLongs. - * @param seed See seed - * @param p See Sampling Probability, p - * @param rf See Resize Factor - * @param dstSeg the given MemorySegment object destination. It will be cleared prior to use. - * @return this class - */ - static ThetaUnionImpl initNewDirectInstance( - final int lgNomLongs, - final long seed, - final float p, - final ResizeFactor rf, - final MemorySegment dstSeg) { - final UpdatableThetaSketch gadget = //create with UNION family - new DirectQuickSelectSketch(lgNomLongs, seed, p, rf, dstSeg, null, true); - final ThetaUnionImpl unionImpl = new ThetaUnionImpl(gadget, seed); - unionImpl.unionThetaLong_ = gadget.getThetaLong(); - unionImpl.unionEmpty_ = gadget.isEmpty(); - return unionImpl; - } - - /** - * Heapify a ThetaUnion from a MemorySegment object containing data. - * Called by ThetaSetOperation. - * @param srcSeg The source MemorySegment ThetaUnion object. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See seed - * @return this class - */ - static ThetaUnionImpl heapifyInstance(final MemorySegment srcSeg, final long expectedSeed) { - final MemorySegment srcSegRO = srcSeg.asReadOnly(); - Family.UNION.checkFamilyID(extractFamilyID(srcSegRO)); - final UpdatableThetaSketch gadget = HeapQuickSelectSketch.heapifyInstance(srcSegRO, expectedSeed); - final ThetaUnionImpl unionImpl = new ThetaUnionImpl(gadget, expectedSeed); - unionImpl.unionThetaLong_ = extractUnionThetaLong(srcSegRO); - unionImpl.unionEmpty_ = PreambleUtil.isEmptyFlag(srcSegRO); - return unionImpl; - } - - /** - * Fast-wrap a ThetaUnion object around a MemorySegment object containing data. - * This does NO validity checking of the given MemorySegment. - * @param srcSeg The source MemorySegment object. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See seed - * @return this class - */ - static ThetaUnionImpl fastWrapInstance(final MemorySegment srcSeg, final long expectedSeed) { - Family.UNION.checkFamilyID(extractFamilyID(srcSeg)); - final UpdatableThetaSketch gadget = srcSeg.isReadOnly() - ? DirectQuickSelectSketchR.fastReadOnlyWrap(srcSeg, expectedSeed) - : DirectQuickSelectSketch.fastWritableWrap(srcSeg, null, expectedSeed); - final ThetaUnionImpl unionImpl = new ThetaUnionImpl(gadget, expectedSeed); - unionImpl.unionThetaLong_ = extractUnionThetaLong(srcSeg); - unionImpl.unionEmpty_ = PreambleUtil.isEmptyFlag(srcSeg); - return unionImpl; - } - - /** - * Wrap a ThetaUnion object around a MemorySegment object containing data. - * @param srcSeg The source MemorySegment object. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See seed - * @return this class - */ - //Called by ThetaSetOperation and ThetaUnion - static ThetaUnionImpl wrapInstance(final MemorySegment srcSeg, final long expectedSeed) { - Family.UNION.checkFamilyID(extractFamilyID(srcSeg)); - final UpdatableThetaSketch gadget = srcSeg.isReadOnly() - ? DirectQuickSelectSketchR.readOnlyWrap(srcSeg, expectedSeed) - : DirectQuickSelectSketch.writableWrap(srcSeg, null, expectedSeed); - final ThetaUnionImpl unionImpl = new ThetaUnionImpl(gadget, expectedSeed); - unionImpl.unionThetaLong_ = extractUnionThetaLong(srcSeg); - unionImpl.unionEmpty_ = PreambleUtil.isEmptyFlag(srcSeg); - return unionImpl; - } - - @Override - public int getCurrentBytes() { - return gadget_.getCurrentBytes(); - } - - @Override - public int getMaxUnionBytes() { - final int lgK = gadget_.getLgNomLongs(); - return (16 << lgK) + (Family.UNION.getMaxPreLongs() << 3); - } - - @Override - MemorySegment getMemorySegment() { - return hasMemorySegment() ? gadget_.getMemorySegment() : null; - } - - @Override - public CompactThetaSketch getResult() { - return getResult(true, null); - } - - @Override - public CompactThetaSketch getResult(final boolean dstOrdered, final MemorySegment dstSeg) { - final int gadgetCurCount = gadget_.getRetainedEntries(true); - final int k = 1 << gadget_.getLgNomLongs(); - final long[] gadgetCacheCopy = - gadget_.hasMemorySegment() ? gadget_.getCache() : gadget_.getCache().clone(); - - //Pull back to k - final long curGadgetThetaLong = gadget_.getThetaLong(); - final long adjGadgetThetaLong = gadgetCurCount > k - ? selectExcludingZeros(gadgetCacheCopy, gadgetCurCount, k + 1) : curGadgetThetaLong; - - //Finalize Theta and curCount - final long unionThetaLong = gadget_.hasMemorySegment() - ? gadget_.getMemorySegment().get(JAVA_LONG_UNALIGNED, UNION_THETA_LONG) - : unionThetaLong_; - - final long minThetaLong = min(min(curGadgetThetaLong, adjGadgetThetaLong), unionThetaLong); - final int curCountOut = minThetaLong < curGadgetThetaLong - ? HashOperations.count(gadgetCacheCopy, minThetaLong) - : gadgetCurCount; - - //Compact the cache - final long[] compactCacheOut = - CompactOperations.compactCache(gadgetCacheCopy, curCountOut, minThetaLong, dstOrdered); - final boolean empty = gadget_.isEmpty() && unionEmpty_; - final short seedHash = gadget_.getSeedHash(); - return CompactOperations.componentsToCompact( - minThetaLong, curCountOut, seedHash, empty, true, dstOrdered, dstOrdered, dstSeg, compactCacheOut); - } - - @Override - public boolean hasMemorySegment() { - return gadget_.hasMemorySegment(); - } - - @Override - public boolean isOffHeap() { - return gadget_.isOffHeap(); - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return gadget_.isSameResource(that); - } - - @Override - public void reset() { - gadget_.reset(); - unionThetaLong_ = gadget_.getThetaLong(); - unionEmpty_ = gadget_.isEmpty(); - } - - @Override - public byte[] toByteArray() { - final byte[] gadgetByteArr = gadget_.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(gadgetByteArr); - insertUnionThetaLong(seg, unionThetaLong_); - if (gadget_.isEmpty() != unionEmpty_) { - clearEmpty(seg); - unionEmpty_ = false; - } - return gadgetByteArr; - } - - @Override //Stateless ThetaUnion - public CompactThetaSketch union(final ThetaSketch sketchA, final ThetaSketch sketchB, final boolean dstOrdered, - final MemorySegment dstSeg) { - reset(); - union(sketchA); - union(sketchB); - final CompactThetaSketch csk = getResult(dstOrdered, dstSeg); - reset(); - return csk; - } - - @Override - public void union(final ThetaSketch sketchIn) { - //UNION Empty Rule: AND the empty states. - - if (sketchIn == null || sketchIn.isEmpty()) { - //null and empty is interpreted as (Theta = 1.0, count = 0, empty = T). Nothing changes - return; - } - //sketchIn is valid and not empty - Util.checkSeedHashes(expectedSeedHash_, sketchIn.getSeedHash()); - if (sketchIn instanceof SingleItemSketch) { - gadget_.hashUpdate(sketchIn.getCache()[0]); - return; - } - ThetaUnionImpl.checkSketchAndMemorySegmentFlags(sketchIn); - - unionThetaLong_ = min(min(unionThetaLong_, sketchIn.getThetaLong()), gadget_.getThetaLong()); //Theta rule - unionEmpty_ = false; - final boolean isOrdered = sketchIn.isOrdered(); - final HashIterator it = sketchIn.iterator(); - while (it.next()) { - final long hash = it.get(); - if (hash < unionThetaLong_ && hash < gadget_.getThetaLong()) { - gadget_.hashUpdate(hash); // backdoor update, hash function is bypassed - } else if (isOrdered) { break; } - } - unionThetaLong_ = min(unionThetaLong_, gadget_.getThetaLong()); //Theta rule with gadget - if (gadget_.hasMemorySegment()) { - final MemorySegment wseg = gadget_.getMemorySegment(); - PreambleUtil.insertUnionThetaLong(wseg, unionThetaLong_); - PreambleUtil.clearEmpty(wseg); - } - } - - @Override - public void union(final MemorySegment seg) { - Objects.requireNonNull(seg, "MemorySegment must be non-null"); - union(ThetaSketch.wrap(seg.asReadOnly())); - } - - @Override - public void update(final long datum) { - gadget_.update(datum); - } - - @Override - public void update(final double datum) { - gadget_.update(datum); - } - - @Override - public void update(final String datum) { - gadget_.update(datum); - } - - @Override - public void update(final byte[] data) { - gadget_.update(data); - } - - @Override - public void update(final ByteBuffer data) { - gadget_.update(data); - } - - @Override - public void update(final char[] data) { - gadget_.update(data); - } - - @Override - public void update(final int[] data) { - gadget_.update(data); - } - - @Override - public void update(final long[] data) { - gadget_.update(data); - } - - //Restricted - - @Override - long[] getCache() { - return gadget_.getCache(); - } - - @Override - int getRetainedEntries() { - return gadget_.getRetainedEntries(true); - } - - @Override - short getSeedHash() { - return gadget_.getSeedHash(); - } - - @Override - long getThetaLong() { - return min(unionThetaLong_, gadget_.getThetaLong()); - } - - @Override - boolean isEmpty() { - return gadget_.isEmpty() && unionEmpty_; - } - - /** - * Checks Ordered and Compact flags for integrity between sketch and its MemorySegment - * @param sketch the given sketch - */ - private static final void checkSketchAndMemorySegmentFlags(final ThetaSketch sketch) { - final MemorySegment seg = sketch.getMemorySegment(); - if (seg == null) { return; } - final int flags = PreambleUtil.extractFlags(seg); - if ((flags & COMPACT_FLAG_MASK) > 0 ^ sketch.isCompact()) { - throw new SketchesArgumentException("Possible corruption: " - + "MemorySegment Compact Flag inconsistent with ThetaSketch Compact Flag"); - } - if ((flags & ORDERED_FLAG_MASK) > 0 ^ sketch.isOrdered()) { - throw new SketchesArgumentException("Possible corruption: " - + "MemorySegment Ordered Flag inconsistent with ThetaSketch Ordered Flag"); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/UpdatableThetaSketch.java b/src/main/java/org/apache/datasketches/theta/UpdatableThetaSketch.java deleted file mode 100644 index 8b75c7883..000000000 --- a/src/main/java/org/apache/datasketches/theta/UpdatableThetaSketch.java +++ /dev/null @@ -1,505 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.datasketches.common.Util.LONG_MAX_VALUE_AS_DOUBLE; -import static org.apache.datasketches.hash.MurmurHash3.hash; -import static org.apache.datasketches.theta.CompactOperations.componentsToCompact; -import static org.apache.datasketches.theta.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.ORDERED_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.READ_ONLY_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.SER_VER; -import static org.apache.datasketches.theta.PreambleUtil.checkSegPreambleCap; -import static org.apache.datasketches.theta.PreambleUtil.checkSegmentSeedHash; -import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.theta.PreambleUtil.extractFlags; -import static org.apache.datasketches.theta.PreambleUtil.extractLgResizeFactor; -import static org.apache.datasketches.theta.PreambleUtil.extractP; -import static org.apache.datasketches.theta.PreambleUtil.extractSerVer; -import static org.apache.datasketches.theta.PreambleUtil.extractThetaLong; -import static org.apache.datasketches.theta.PreambleUtil.getUpdatableSegBytes; -import static org.apache.datasketches.theta.UpdateReturnState.RejectedNullOrEmpty; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; -import java.util.Objects; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * The parent class for the UpdatableThetaSketch families, such as QuickSelectThetaSketch and AlphaSketch. - * The primary task of an UpdatableThetaSketch is to consider datums presented via the update() methods - * for inclusion in its internal cache. This is the sketch building process. - * - * @author Lee Rhodes - */ -public abstract class UpdatableThetaSketch extends ThetaSketch { - private final long seed_; - - UpdatableThetaSketch(final long seed) { - seed_ = seed; //kept only on heap, never serialized. Hoisted here for performance. - } - - /** - * Wrap takes the writable sketch image in MemorySegment and refers to it directly. There is no data copying onto - * the java heap. Only "Direct" Serialization Version 3 (i.e, OpenSource) sketches that have - * been explicitly stored as writable, direct objects can be wrapped. This method assumes the - * {@link org.apache.datasketches.common.Util#DEFAULT_UPDATE_SEED}. - * Default Update Seed. - * @param srcWSeg an image of a writable sketch where the image seed hash matches the default seed hash. - * It must have a size of at least 24 bytes. - * @return an UpdatableThetaSketch backed by the given MemorySegment - * @throws SketchesArgumentException if the provided MemorySegment - * is invalid, corrupted, or incompatible with this sketch type. - * Callers must treat this as a fatal error for that segment. - */ - public static UpdatableThetaSketch wrap(final MemorySegment srcWSeg) { - return wrap(srcWSeg, null, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Wrap takes the sketch image in MemorySegment and refers to it directly. There is no data copying onto - * the java heap. Only "Direct" Serialization Version 3 (i.e, OpenSource) sketches that have - * been explicitly stored as writable direct objects can be wrapped. - * An attempt to "wrap" earlier version sketches will result in a "heapified", normal - * Java Heap version of the sketch where all data will be copied to the heap. - * @param srcWSeg an image of a writable sketch where the image seed hash matches the given seed hash. - * It must have a size of at least 24 bytes. - * @param mSegReq an implementation of the MemorySegmentRequest interface or null. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See Update Hash Seed. - * Compact sketches store a 16-bit hash of the seed, but not the seed itself. - * @return a UpdatableThetaSketch backed by the given MemorySegment - * @throws SketchesArgumentException if the provided MemorySegment - * is invalid, corrupted, or incompatible with this sketch type. - * Callers must treat this as a fatal error for that segment. - */ - public static UpdatableThetaSketch wrap( - final MemorySegment srcWSeg, - final MemorySegmentRequest mSegReq, - final long expectedSeed) { - Objects.requireNonNull(srcWSeg, "Source MemorySegment must not be null"); - final int preLongs = checkSegPreambleCap(srcWSeg) & 0X3F; //mask to 6 bits; - final int serVer = extractSerVer(srcWSeg); - final int familyID = extractFamilyID(srcWSeg); - if (familyID != Family.QUICKSELECT.getID()) { - final Family family = Family.idToFamily(familyID); - throw new SketchesArgumentException( - "A " + family + " sketch cannot be wrapped as an UpdatableThetaSketch."); - } - if (serVer == 3 && preLongs == 3) { - return DirectQuickSelectSketch.writableWrap(srcWSeg, mSegReq, expectedSeed); - } else { - throw new SketchesArgumentException( - "Corrupted: An UpdatableThetaSketch image must have SerVer = 3 and preLongs = 3"); - } - } - - /** - * Instantiates an on-heap UpdatableThetaSketch from a MemorySegment. This method assumes the - * {@link org.apache.datasketches.common.Util#DEFAULT_UPDATE_SEED}. - * @param srcSeg the given MemorySegment with a sketch image. - * It must have a size of at least 24 bytes. - * @return an UpdatableThetaSketch - * @throws SketchesArgumentException if the provided MemorySegment - * is invalid, corrupted, or incompatible with this sketch type. - * Callers must treat this as a fatal error for that segment. - */ - public static UpdatableThetaSketch heapify(final MemorySegment srcSeg) { - return heapify(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Instantiates an on-heap UpdatableThetaSketch from a MemorySegment. - * @param srcSeg the given MemorySegment. - * It must have a size of at least 24 bytes. - * @param expectedSeed the seed used to validate the given MemorySegment image. - * See Update Hash Seed. - * @return an UpdatableThetaSketch - * @throws SketchesArgumentException if the provided MemorySegment - * is invalid, corrupted, or incompatible with this sketch type. - * Callers must treat this as a fatal error for that segment. - */ - public static UpdatableThetaSketch heapify(final MemorySegment srcSeg, final long expectedSeed) { - Objects.requireNonNull(srcSeg, "Source MemorySegment must not be null"); - checkSegPreambleCap(srcSeg); - final int familyID = extractFamilyID(srcSeg); - if (familyID == Family.ALPHA.getID()) { - return HeapAlphaSketch.heapifyInstance(srcSeg, expectedSeed); - } - return HeapQuickSelectSketch.heapifyInstance(srcSeg, expectedSeed); - } - - //ThetaSketch interface - - @Override - public CompactThetaSketch compact(final boolean dstOrdered, final MemorySegment dstWSeg) { - return componentsToCompact( - getThetaLong(), - getRetainedEntries(true), - getSeedHash(), - isEmpty(), - false, //is src compact - false, //is src ordered - dstOrdered, - dstWSeg, - getCache()); - } - - @Override - public int getCompactBytes() { - final int preLongs = getCompactPreambleLongs(); - final int dataLongs = getRetainedEntries(true); - return (preLongs + dataLongs) << 3; - } - - @Override - int getCurrentDataLongs() { - return 1 << getLgArrLongs(); - } - - @Override - public boolean hasMemorySegment() { - return this instanceof final DirectQuickSelectSketchR dqssr && dqssr.hasMemorySegment(); - } - - @Override - public boolean isCompact() { - return false; - } - - @Override - public boolean isOffHeap() { - return this instanceof final DirectQuickSelectSketchR dqssr && dqssr.isOffHeap(); - } - - @Override - public boolean isOrdered() { - return false; - } - - @Override - public boolean isSameResource(final MemorySegment that) { - return this instanceof final DirectQuickSelectSketchR dqssr && dqssr.isSameResource(that); - } - - //UpdatableThetaSketch interface - - /** - * Returns a new builder - * @return a new builder - */ - public static final UpdatableThetaSketchBuilder builder() { - return new UpdatableThetaSketchBuilder(); - } - - /** - * Returns the configured ResizeFactor - * @return the configured ResizeFactor - */ - public abstract ResizeFactor getResizeFactor(); - - /** - * Gets the configured sampling probability, p. - * See Sampling Probability, p - * @return the sampling probability, p - */ - abstract float getP(); - - /** - * Gets the configured seed - * @return the configured seed - */ - public long getSeed() { return seed_; } - - /** - * Resets this sketch back to a virgin empty state. - */ - public abstract void reset(); - - /** - * Rebuilds the hash table to remove dirty values or to reduce the size - * to nominal entries. - * @return this sketch - */ - public abstract UpdatableThetaSketch rebuild(); - - /** - * Present this sketch with a long. - * - * @param datum The given long datum. - * @return - * See Update Return State - */ - public UpdateReturnState update(final long datum) { - return hashUpdate(hash(datum, seed_)[0] >>> 1); - } - - /** - * Present this sketch with the given double (or float) datum. - * The double will be converted to a long using Double.doubleToLongBits(datum), - * which normalizes all NaN values to a single NaN representation. - * Plus and minus zero will be normalized to plus zero. - * The special floating-point values NaN and +/- Infinity are treated as distinct. - * - * @param datum The given double datum. - * @return - * See Update Return State - */ - public UpdateReturnState update(final double datum) { - final double d = datum == 0.0 ? 0.0 : datum; // canonicalize -0.0, 0.0 - final long data = Double.doubleToLongBits(d);// canonicalize all NaN & +/- infinity forms - return hashUpdate(hash(data, seed_)[0] >>> 1); - } - - /** - * Present this sketch with the given String. - * The string is converted to a byte array using UTF8 encoding. - * If the string is null or empty no update attempt is made and the method returns. - * - *

Note: this will not produce the same output hash values as the {@link #update(char[])} - * method and will generally be a little slower depending on the complexity of the UTF8 encoding. - *

- * - * @param datum The given String. - * @return - * See Update Return State - */ - public UpdateReturnState update(final String datum) { - if (datum == null || datum.isEmpty()) { - return RejectedNullOrEmpty; - } - final byte[] data = datum.getBytes(UTF_8); - return hashUpdate(hash(data, seed_)[0] >>> 1); - } - - /** - * Present this sketch with the given byte array. - * If the byte array is null or empty no update attempt is made and the method returns. - * - * @param data The given byte array. - * @return - * See Update Return State - */ - public UpdateReturnState update(final byte[] data) { - if (data == null || data.length == 0) { - return RejectedNullOrEmpty; - } - return hashUpdate(hash(data, seed_)[0] >>> 1); - } - - /** - * Present this sketch with the given ByteBuffer - * If the ByteBuffer is null or empty, no update attempt is made and the method returns. - * - * @param buffer the input ByteBuffer - * @return - * See Update Return State - */ - public UpdateReturnState update(final ByteBuffer buffer) { - if (buffer == null || !buffer.hasRemaining()) { - return RejectedNullOrEmpty; - } - return hashUpdate(hash(buffer, seed_)[0] >>> 1); - } - - /** - * Present this sketch with the given char array. - * If the char array is null or empty no update attempt is made and the method returns. - * - *

Note: this will not produce the same output hash values as the {@link #update(String)} - * method but will be a little faster as it avoids the complexity of the UTF8 encoding.

- * - * @param data The given char array. - * @return - * See Update Return State - */ - public UpdateReturnState update(final char[] data) { - if (data == null || data.length == 0) { - return RejectedNullOrEmpty; - } - return hashUpdate(hash(data, seed_)[0] >>> 1); - } - - /** - * Present this sketch with the given integer array. - * If the integer array is null or empty no update attempt is made and the method returns. - * - * @param data The given int array. - * @return - * See Update Return State - */ - public UpdateReturnState update(final int[] data) { - if (data == null || data.length == 0) { - return RejectedNullOrEmpty; - } - return hashUpdate(hash(data, seed_)[0] >>> 1); - } - - /** - * Present this sketch with the given long array. - * If the long array is null or empty no update attempt is made and the method returns. - * - * @param data The given long array. - * @return - * See Update Return State - */ - public UpdateReturnState update(final long[] data) { - if (data == null || data.length == 0) { - return RejectedNullOrEmpty; - } - return hashUpdate(hash(data, seed_)[0] >>> 1); - } - - //restricted methods - - /** - * All potential updates converge here. - * - *

Don't ever call this unless you really know what you are doing!

- * - * @param hash the given input hash value. A hash of zero or Long.MAX_VALUE is ignored. - * A negative hash value will throw an exception. - * @return See Update Return State - */ - abstract UpdateReturnState hashUpdate(long hash); - - /** - * Gets the Log base 2 of the current size of the internal cache - * @return the Log base 2 of the current size of the internal cache - */ - abstract int getLgArrLongs(); - - /** - * Gets the Log base 2 of the configured nominal entries - * @return the Log base 2 of the configured nominal entries - */ - public abstract int getLgNomLongs(); - - /** - * Returns true if the internal cache contains "dirty" values that are greater than or equal - * to thetaLong. - * @return true if the internal cache is dirty. - */ - abstract boolean isDirty(); - - /** - * Returns true if numEntries (curCount) is greater than the hashTableThreshold. - * @param numEntries the given number of entries (or current count). - * @return true if numEntries (curCount) is greater than the hashTableThreshold. - */ - abstract boolean isOutOfSpace(int numEntries); - - static void checkUnionAndQuickSelectFamily(final MemorySegment seg, final int preambleLongs, final int lgNomLongs) { - - //Check Family - final int familyID = extractFamilyID(seg); //byte 2 - if (familyID == Family.UNION.getID()) { - if (preambleLongs != Family.UNION.getMinPreLongs()) { - throw new SketchesArgumentException( - "Possible corruption: Invalid PreambleLongs value for UNION: " + preambleLongs); - } - } - else if (familyID == Family.QUICKSELECT.getID()) { - if (preambleLongs != Family.QUICKSELECT.getMinPreLongs()) { - throw new SketchesArgumentException( - "Possible corruption: Invalid PreambleLongs value for QUICKSELECT: " + preambleLongs); - } - } else { - final Family family = Family.idToFamily(familyID); - throw new SketchesArgumentException( - "Possible corruption: Invalid Family: " + family.toString()); - } - - //Check lgNomLongs - if (lgNomLongs < ThetaUtil.MIN_LG_NOM_LONGS) { - throw new SketchesArgumentException( - "Possible corruption: Current MemorySegment lgNomLongs < min required size: " - + lgNomLongs + " < " + ThetaUtil.MIN_LG_NOM_LONGS); - } - } - - static void checkSegIntegrity(final MemorySegment srcSeg, final long expectedSeed, final int preambleLongs, - final int lgNomLongs, final int lgArrLongs) { - - //Check SerVer - final int serVer = extractSerVer(srcSeg); //byte 1 - if (serVer != SER_VER) { - throw new SketchesArgumentException( - "Possible corruption: Invalid Serialization Version: " + serVer); - } - - //Check flags - final int flags = extractFlags(srcSeg); //byte 5 - final int badFlagsMask = ORDERED_FLAG_MASK | COMPACT_FLAG_MASK | READ_ONLY_FLAG_MASK; - if ((flags & badFlagsMask) > 0) { - throw new SketchesArgumentException( - "Possible corruption: Input srcSeg cannot be: compact, ordered, nor read-only"); - } - - //Check seed hashes - final short seedHash = checkSegmentSeedHash(srcSeg, expectedSeed); //byte 6,7 - Util.checkSeedHashes(seedHash, Util.computeSeedHash(expectedSeed)); - - //Check seg capacity, lgArrLongs - final long curCapBytes = srcSeg.byteSize(); - final int minReqBytes = getUpdatableSegBytes(lgArrLongs, preambleLongs); - if (curCapBytes < minReqBytes) { - throw new SketchesArgumentException( - "Possible corruption: Current MemorySegment size < min required size: " - + curCapBytes + " < " + minReqBytes); - } - //check Theta, p - final float p = extractP(srcSeg); //bytes 12-15 - final long thetaLong = extractThetaLong(srcSeg); //bytes 16-23 - final double theta = thetaLong / LONG_MAX_VALUE_AS_DOUBLE; - //if (lgArrLongs <= lgNomLongs) the sketch is still resizing, thus theta cannot be < p. - if (lgArrLongs <= lgNomLongs && theta < p ) { - throw new SketchesArgumentException( - "Possible corruption: Theta cannot be < p and lgArrLongs <= lgNomLongs. " - + lgArrLongs + " <= " + lgNomLongs + ", Theta: " + theta + ", p: " + p); - } - } - - /** - * This checks to see if the MemorySegment RF factor was set correctly as early versions may not - * have set it. - * @param srcSeg the source MemorySegment - * @param lgNomLongs the current lgNomLongs - * @param lgArrLongs the current lgArrLongs - * @return true if the the MemorySegment RF factor is incorrect and the caller can either - * correct it or throw an error. - */ - static boolean isResizeFactorIncorrect(final MemorySegment srcSeg, final int lgNomLongs, - final int lgArrLongs) { - final int lgT = lgNomLongs + 1; - final int lgA = lgArrLongs; - final int lgR = extractLgResizeFactor(srcSeg); - if (lgR == 0) { return lgA != lgT; } - return (lgT - lgA) % lgR != 0; - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/UpdatableThetaSketchBuilder.java b/src/main/java/org/apache/datasketches/theta/UpdatableThetaSketchBuilder.java deleted file mode 100644 index 1493c1209..000000000 --- a/src/main/java/org/apache/datasketches/theta/UpdatableThetaSketchBuilder.java +++ /dev/null @@ -1,533 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.TAB; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.SuppressFBWarnings; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * For building a new UpdatableThetaSketch. - * - * @author Lee Rhodes - */ -public final class UpdatableThetaSketchBuilder { - private int bLgNomLongs; - private long bSeed; - private ResizeFactor bRF; - private Family bFam; - private float bP; - private MemorySegmentRequest bMemorySegmentRequest; - - //Fields for concurrent theta sketch - private int bNumPoolThreads; - private int bConCurLgNomLongs; - private boolean bPropagateOrderedCompact; - private double bMaxConcurrencyError; - private int bMaxNumLocalThreads; - - /** - * Constructor for building a new UpdatableThetaSketch. The default configuration is - *
    - *
  • Nominal Entries: {@value org.apache.datasketches.thetacommon.ThetaUtil#DEFAULT_NOMINAL_ENTRIES}
  • - *
  • Seed: {@value org.apache.datasketches.common.Util#DEFAULT_UPDATE_SEED}
  • - *
  • Resize Factor: The default for sketches on the Java heap is {@link ResizeFactor#X8}. - * For direct sketches, which are targeted for off-heap, this value will - * be fixed at either {@link ResizeFactor#X1} or {@link ResizeFactor#X2}.
  • - *
  • Family: {@link org.apache.datasketches.common.Family#QUICKSELECT}
  • - *
  • Input Sampling Probability, p: 1.0
  • - *
  • MemorySegmentRequest implementation: null
  • - *
- * Parameters unique to the concurrent sketches only: - *
    - *
  • Concurrent NumPoolThreads: 3
  • - *
  • Number of local Nominal Entries: 4
  • - *
  • Concurrent PropagateOrderedCompact: true
  • - *
  • Concurrent MaxConcurrencyError: 0
  • - *
  • Concurrent MaxNumLocalThreads: 1
  • - *
- */ - public UpdatableThetaSketchBuilder() { - bLgNomLongs = Integer.numberOfTrailingZeros(ThetaUtil.DEFAULT_NOMINAL_ENTRIES); - bSeed = Util.DEFAULT_UPDATE_SEED; - bRF = ResizeFactor.X8; - bFam = Family.QUICKSELECT; - bP = (float) 1.0; - bMemorySegmentRequest = null; - - // Default values for concurrent sketch - bNumPoolThreads = ConcurrentPropagationService.NUM_POOL_THREADS; - bConCurLgNomLongs = 4; //default is smallest legal QS sketch - bPropagateOrderedCompact = true; - bMaxConcurrencyError = 0; - bMaxNumLocalThreads = 1; - } - - /** - * Sets the local Nominal Entries for this builder. - * This value is also used for building a shared concurrent sketch. - * The minimum value is 16 (2^4) and the maximum value is 67,108,864 (2^26). - * Be aware that sketches as large as this maximum value may not have been - * thoroughly tested or characterized for performance. - * - * @param nomEntries Nominal Entries - * This will become the ceiling power of 2 if the given value is not. - * @return this UpdatableThetaSketchBuilder - */ - public UpdatableThetaSketchBuilder setNominalEntries(final int nomEntries) { - bLgNomLongs = ThetaUtil.checkNomLongs(nomEntries); - return this; - } - - /** - * Alternative method of setting the local Nominal Entries for this builder from the log_base2 value. - * This value is also used for building a shared concurrent sketch. - * The minimum value is 4 and the maximum value is 26. - * Be aware that sketches as large as this maximum value may not have been - * thoroughly characterized for performance. - * - * @param lgNomEntries the Log Nominal Entries. Also for the concurrent shared sketch - * @return this UpdatableThetaSketchBuilder - */ - public UpdatableThetaSketchBuilder setLogNominalEntries(final int lgNomEntries) { - bLgNomLongs = ThetaUtil.checkNomLongs(1 << lgNomEntries); - return this; - } - - /** - * Alternative method of setting the Nominal Entries for this builder from the log_base2 value, commonly called LgK. - * This value is also used for building a shared concurrent sketch. - * The minimum value is 4 and the maximum value is 26. - * Be aware that sketches as large as 26 may not have been - * thoroughly characterized for performance. - * - * @param lgK the Log Nominal Entries. Also for the concurrent shared sketch. - * @return this UpdatableThetaSketchBuilder - */ - public UpdatableThetaSketchBuilder setLgK(final int lgK) { - bLgNomLongs = ThetaUtil.checkNomLongs(1 << lgK); - return this; - } - - /** - * Returns the local Log-base 2 Nominal Entries - * @return Log-base 2 Nominal Entries - */ - public int getLgNominalEntries() { - return bLgNomLongs; - } - - /** - * Sets the local (default) Concurrent Nominal Entries for the concurrent local sketch. The minimum value is 16 and the - * maximum value is 67,108,864, which is 2^26. - * Be aware that sketches as large as this maximum - * value have not been thoroughly tested or characterized for performance. - * - * @param nomEntries Nominal Entries - * This will become the ceiling power of 2 if it is not. - * @return this UpdatableThetaSketchBuilder - */ - public UpdatableThetaSketchBuilder setConCurNominalEntries(final int nomEntries) { - bConCurLgNomLongs = Integer.numberOfTrailingZeros(ceilingPowerOf2(nomEntries)); - if (bConCurLgNomLongs > ThetaUtil.MAX_LG_NOM_LONGS || bConCurLgNomLongs < ThetaUtil.MIN_LG_NOM_LONGS) { - throw new SketchesArgumentException( - "Nominal Entries must be >= 16 and <= 67108864: " + nomEntries); - } - return this; - } - - /** - * Alternative method of setting the local (default) Nominal Entries for a local concurrent sketch from the log_base2 value. - * The minimum value is 4 and the maximum value is 26. - * Be aware that sketches as large as this maximum - * value have not been thoroughly tested or characterized for performance. - * - * @param lgNomEntries the Log Nominal Entries for a concurrent local sketch - * @return this UpdatableThetaSketchBuilder - */ - public UpdatableThetaSketchBuilder setConCurLogNominalEntries(final int lgNomEntries) { - bConCurLgNomLongs = lgNomEntries; - if (bConCurLgNomLongs > ThetaUtil.MAX_LG_NOM_LONGS || bConCurLgNomLongs < ThetaUtil.MIN_LG_NOM_LONGS) { - throw new SketchesArgumentException( - "Log Nominal Entries must be >= 4 and <= 26: " + lgNomEntries); - } - return this; - } - - /** - * Returns local Log-base 2 Nominal Entries for the concurrent local sketch - * @return Log-base 2 Nominal Entries for the concurrent local sketch - */ - public int getConCurLgNominalEntries() { - return bConCurLgNomLongs; - } - - /** - * Sets the local long seed value that is required by the hashing function. - * @param seed See seed - * @return this UpdatableThetaSketchBuilder - */ - public UpdatableThetaSketchBuilder setSeed(final long seed) { - bSeed = seed; - return this; - } - - /** - * Returns the local long seed value that is required by the hashing function. - * @return the seed - */ - public long getSeed() { - return bSeed; - } - - /** - * Sets the local upfront uniform pre-sampling probability, p - * @param p See Sampling Probability, p - * @return this UpdatableThetaSketchBuilder - */ - public UpdatableThetaSketchBuilder setP(final float p) { - if (p <= 0.0 || p > 1.0) { - throw new SketchesArgumentException("p must be > 0 and <= 1.0: " + p); - } - bP = p; - return this; - } - - /** - * Returns the local upfront uniform pre-sampling probability p - * @return the pre-sampling probability p - */ - public float getP() { - return bP; - } - - /** - * Sets the local cache Resize Factor. - * @param rf See Resize Factor - * @return this UpdatableThetaSketchBuilder - */ - public UpdatableThetaSketchBuilder setResizeFactor(final ResizeFactor rf) { - bRF = rf; - return this; - } - - /** - * Returns the local Resize Factor - * @return the Resize Factor - */ - public ResizeFactor getResizeFactor() { - return bRF; - } - - /** - * Set the local Family. Choose either Family.ALPHA or Family.QUICKSELECT. - * @param family the family for this builder - * @return this UpdatableThetaSketchBuilder - */ - public UpdatableThetaSketchBuilder setFamily(final Family family) { - bFam = family; - return this; - } - - /** - * Returns the local Family - * @return the Family - */ - public Family getFamily() { - return bFam; - } - - /** - * Sets the local MemorySegmentRequest - * @param mSegReq the given MemorySegmentRequest - * @return this UpdatableThetaSketchBuilder - */ - public UpdatableThetaSketchBuilder setMemorySegmentRequest(final MemorySegmentRequest mSegReq) { - bMemorySegmentRequest = mSegReq; - return this; - } - - /** - * Returns the local MemorySegmentRequest - * @return the local MemorySegmentRequest - */ - public MemorySegmentRequest getMemorySegmentRequest() { - return bMemorySegmentRequest; - } - - //Concurrent related - - /** - * Sets the local number of pool threads used for background propagation in the concurrent sketches. - * @param numPoolThreads the given number of pool threads - */ - public void setNumPoolThreads(final int numPoolThreads) { - bNumPoolThreads = numPoolThreads; - } - - /** - * Gets the local number of background pool threads used for propagation in the concurrent sketches. - * @return the number of background pool threads - */ - public int getNumPoolThreads() { - return bNumPoolThreads; - } - - /** - * Sets the local Propagate Ordered Compact flag to the given value. Used with concurrent sketches. - * - * @param prop the given value - * @return this UpdatableThetaSketchBuilder - */ - public UpdatableThetaSketchBuilder setPropagateOrderedCompact(final boolean prop) { - bPropagateOrderedCompact = prop; - return this; - } - - /** - * Gets the local Propagate Ordered Compact flag used with concurrent sketches. - * @return the Propagate Ordered Compact flag - */ - public boolean getPropagateOrderedCompact() { - return bPropagateOrderedCompact; - } - - /** - * Sets the local Maximum Concurrency Error. - * @param maxConcurrencyError the given Maximum Concurrency Error. - */ - public void setMaxConcurrencyError(final double maxConcurrencyError) { - bMaxConcurrencyError = maxConcurrencyError; - } - - /** - * Gets the local Maximum Concurrency Error - * @return the Maximum Concurrency Error - */ - public double getMaxConcurrencyError() { - return bMaxConcurrencyError; - } - - /** - * Sets the local Maximum Number of Local Threads. - * This is used to set the size of the local concurrent buffers. - * @param maxNumLocalThreads the given Maximum Number of Local Threads - */ - public void setMaxNumLocalThreads(final int maxNumLocalThreads) { - bMaxNumLocalThreads = maxNumLocalThreads; - } - - /** - * Gets the local Maximum Number of Local Threads. - * @return the Maximum Number of Local Threads. - */ - public int getMaxNumLocalThreads() { - return bMaxNumLocalThreads; - } - - // BUILD FUNCTIONS - - /** - * Returns an UpdatableThetaSketch with the current configuration of this Builder. - * @return an UpdatableThetaSketch - */ - public UpdatableThetaSketch build() { - return build(null); - } - - /** - * Returns an UpdatableThetaSketch with the current configuration of this Builder - * with the specified backing destination MemorySegment store. - * Note: this can only be used with the QUICKSELECT Family of sketches - * and cannot be used with the Alpha Family of sketches. - * @param dstSeg The destination MemorySegment. - * @return an UpdatableThetaSketch - */ - public UpdatableThetaSketch build(final MemorySegment dstSeg) { - UpdatableThetaSketch sketch = null; - final boolean unionGadget = false; - switch (bFam) { - case ALPHA: { - if (dstSeg == null) { - sketch = HeapAlphaSketch.newHeapInstance(bLgNomLongs, bSeed, bP, bRF); - } - else { - throw new SketchesArgumentException("AlphaSketch cannot be backed by a MemorySegment."); - } - break; - } - case QUICKSELECT: { - if (dstSeg == null) { - sketch = new HeapQuickSelectSketch(bLgNomLongs, bSeed, bP, bRF, unionGadget); - } - else { - sketch = new DirectQuickSelectSketch(bLgNomLongs, bSeed, bP, bRF, dstSeg, bMemorySegmentRequest, unionGadget); - } - break; - } - default: { - throw new SketchesArgumentException( - "Given Family cannot be built as an UpdatableThetaSketch: " + bFam.toString()); - } - } - return sketch; - } - - /** - * Returns an on-heap concurrent shared UpdatableThetaSketch with the current configuration of the - * Builder. - * - *

The parameters unique to the shared concurrent sketch are: - *

    - *
  • Number of Pool Threads (default is 3)
  • - *
  • Maximum Concurrency Error
  • - *
- * - *

Key parameters that are in common with other ThetaSketches: - *

    - *
  • Nominal Entries or Log Nominal Entries (for the shared concurrent sketch)
  • - *
- * - * @return an on-heap concurrent UpdatableThetaSketch with the current configuration of the Builder. - */ - public UpdatableThetaSketch buildShared() { - return buildShared(null); - } - - /** - * Returns a concurrent shared UpdatableThetaSketch with the current - * configuration of the Builder and the given destination MemorySegment. If the destination - * MemorySegment is null, this defaults to an on-heap concurrent shared UpdatableThetaSketch. - * - *

The parameters unique to the shared concurrent sketch are: - *

    - *
  • Number of Pool Threads (default is 3)
  • - *
  • Maximum Concurrency Error
  • - *
- * - *

Key parameters that are in common with other Theta sketches: - *

    - *
  • Nominal Entries or Log Nominal Entries (for the shared concurrent sketch)
  • - *
  • Destination MemorySegment (if not null, returned sketch is Direct. Default is null.)
  • - *
- * - * @param dstSeg the given MemorySegment for Direct, otherwise null. - * @return a concurrent UpdatableThetaSketch with the current configuration of the Builder - * and the given destination MemorySegment. - */ - @SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", - justification = "Harmless in Builder, fix later") - public UpdatableThetaSketch buildShared(final MemorySegment dstSeg) { - ConcurrentPropagationService.NUM_POOL_THREADS = bNumPoolThreads; - if (dstSeg == null) { - return new ConcurrentHeapQuickSelectSketch(bLgNomLongs, bSeed, bMaxConcurrencyError); - } else { - return new ConcurrentDirectQuickSelectSketch(bLgNomLongs, bSeed, bMaxConcurrencyError, dstSeg); - } - } - - /** - * Returns a direct (potentially off-heap) concurrent shared UpdatableThetaSketch with the current - * configuration of the Builder, the data from the given sketch, and the given destination - * MemorySegment. If the destination MemorySegment is null, this defaults to an on-heap - * concurrent shared UpdatableThetaSketch. - * - *

The parameters unique to the shared concurrent sketch are: - *

    - *
  • Number of Pool Threads (default is 3)
  • - *
  • Maximum Concurrency Error
  • - *
- * - *

Key parameters that are in common with other Theta sketches: - *

    - *
  • Nominal Entries or Log Nominal Entries (for the shared concurrent sketch)
  • - *
  • Destination MemorySegment (if not null, returned sketch is Direct. Default is null.)
  • - *
- * - * @param sketch a given UpdatableThetaSketch from which the data is used to initialize the returned - * shared sketch. - * @param dstSeg the given MemorySegment for Direct, otherwise null. - * @return a concurrent UpdatableThetaSketch with the current configuration of the Builder - * and the given destination MemorySegment. - */ - @SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", - justification = "Harmless in Builder, fix later") - public UpdatableThetaSketch buildSharedFromSketch(final UpdatableThetaSketch sketch, final MemorySegment dstSeg) { - ConcurrentPropagationService.NUM_POOL_THREADS = bNumPoolThreads; - if (dstSeg == null) { - return new ConcurrentHeapQuickSelectSketch(sketch, bSeed, bMaxConcurrencyError); - } else { - return new ConcurrentDirectQuickSelectSketch(sketch, bSeed, bMaxConcurrencyError, dstSeg); - } - } - - /** - * Returns a local, on-heap, concurrent UpdatableThetaSketch to be used as a per-thread local buffer - * along with the given concurrent shared UpdatableThetaSketch and the current configuration of this - * Builder. - * - *

The parameters unique to the local concurrent sketch are: - *

    - *
  • Local Nominal Entries or Local Log Nominal Entries
  • - *
  • Propagate Ordered Compact flag
  • - *
- * - * @param shared the concurrent shared sketch to be accessed via the concurrent local sketch. - * @return an UpdatableThetaSketch to be used as a per-thread local buffer. - */ - public UpdatableThetaSketch buildLocal(final UpdatableThetaSketch shared) { - if (shared == null || !(shared instanceof ConcurrentSharedThetaSketch)) { - throw new SketchesStateException("The concurrent shared sketch must be built first."); - } - return new ConcurrentHeapThetaBuffer(bConCurLgNomLongs, bSeed, - (ConcurrentSharedThetaSketch) shared, bPropagateOrderedCompact, bMaxNumLocalThreads); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("UpdatableThetaSketchBuilder configuration:").append(LS); - sb.append("LgK:").append(TAB).append(bLgNomLongs).append(LS); - sb.append("K:").append(TAB).append(1 << bLgNomLongs).append(LS); - sb.append("LgLocalK:").append(TAB).append(bConCurLgNomLongs).append(LS); - sb.append("LocalK:").append(TAB).append(1 << bConCurLgNomLongs).append(LS); - sb.append("Seed:").append(TAB).append(bSeed).append(LS); - sb.append("p:").append(TAB).append(bP).append(LS); - sb.append("ResizeFactor:").append(TAB).append(bRF).append(LS); - sb.append("Family:").append(TAB).append(bFam).append(LS); - sb.append("Propagate Ordered Compact").append(TAB).append(bPropagateOrderedCompact).append(LS); - sb.append("NumPoolThreads").append(TAB).append(bNumPoolThreads).append(LS); - sb.append("MaxConcurrencyError").append(TAB).append(bMaxConcurrencyError).append(LS); - sb.append("MaxNumLocalThreads").append(TAB).append(bMaxNumLocalThreads).append(LS); - return sb.toString(); - } - -} diff --git a/src/main/java/org/apache/datasketches/theta/UpdateReturnState.java b/src/main/java/org/apache/datasketches/theta/UpdateReturnState.java deleted file mode 100644 index b929cfb7d..000000000 --- a/src/main/java/org/apache/datasketches/theta/UpdateReturnState.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -/** - * See Update Return State - * - * @author Lee Rhodes - */ -public enum UpdateReturnState { - - /** - * The hash was accepted into the sketch and the retained count was incremented. - */ - InsertedCountIncremented, //all UpdatableThetaSketches - - /** - * The hash was accepted into the sketch, the retained count was incremented. - * The current cache was out of room and resized larger based on the Resize Factor. - */ - InsertedCountIncrementedResized, //used by HeapQuickSelectSketch - - /** - * The hash was accepted into the sketch, the retained count was incremented. - * The current cache was out of room and at maximum size, so the cache was rebuilt. - */ - InsertedCountIncrementedRebuilt, //used by HeapQuickSelectSketch - - /** - * The hash was accepted into the sketch and the retained count was not incremented. - */ - InsertedCountNotIncremented, //used by enhancedHashInsert for Alpha - - /** - * The hash was inserted into the local concurrent buffer, - * but has not yet been propagated to the concurrent shared sketch. - */ - ConcurrentBufferInserted, //used by ConcurrentHeapThetaBuffer - - /** - * The hash has been propagated to the concurrent shared sketch. - * This does not reflect the action taken by the shared sketch. - */ - ConcurrentPropagated, //used by ConcurrentHeapThetaBuffer - - /** - * The hash was rejected as a duplicate. - */ - RejectedDuplicate, //all UpdatableThetaSketches hashUpdate(), enhancedHashInsert - - /** - * The hash was rejected because it was null or empty. - */ - RejectedNullOrEmpty, //UpdatableThetaSketch.update(arr[]) - - /** - * The hash was rejected because the value was negative, zero or - * greater than theta. - */ - RejectedOverTheta; //all UpdatableThetaSketches hashUpdate() - -} diff --git a/src/main/java/org/apache/datasketches/theta/WrappedCompactCompressedSketch.java b/src/main/java/org/apache/datasketches/theta/WrappedCompactCompressedSketch.java deleted file mode 100644 index d709188ed..000000000 --- a/src/main/java/org/apache/datasketches/theta/WrappedCompactCompressedSketch.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.apache.datasketches.theta.PreambleUtil.ENTRY_BITS_BYTE_V4; -import static org.apache.datasketches.theta.PreambleUtil.NUM_ENTRIES_BYTES_BYTE_V4; -import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.wholeBytesToHoldBits; - -import org.apache.datasketches.common.ByteArrayUtil; -import org.apache.datasketches.common.Util; - -/** - * A wrapper around a serialized compact compressed read-only sketch in the form of a byte array. - * It is not an empty nor a single item sketch. - * - *

This sketch can only be associated with a Serialization Version 4 format binary image.

- */ -final class WrappedCompactCompressedSketch extends WrappedCompactSketch { - - /** - * Construct this sketch with the given bytes. - * @param bytes containing serialized compact compressed sketch. - */ - WrappedCompactCompressedSketch(final byte[] bytes) { - super(bytes); - } - - /** - * Wraps the given bytes, which must be a SerVer 4 compressed CompactThetaSketch image. - * @param bytes representation of serialized compressed CompactThetaSketch. - * @param seedHash The update seedHash. - * See Seed Hash. - * @return this sketch - */ - static WrappedCompactCompressedSketch wrapInstance(final byte[] bytes, final short seedHash) { - Util.checkSeedHashes(ByteArrayUtil.getShortLE(bytes, PreambleUtil.SEED_HASH_SHORT), seedHash); - return new WrappedCompactCompressedSketch(bytes); - } - - //ThetaSketch Overrides - - @Override - public int getCurrentBytes() { - final int preLongs = bytes_[PREAMBLE_LONGS_BYTE]; - final int entryBits = bytes_[ENTRY_BITS_BYTE_V4]; - final int numEntriesBytes = bytes_[NUM_ENTRIES_BYTES_BYTE_V4]; - return preLongs * Long.BYTES + numEntriesBytes + wholeBytesToHoldBits(getRetainedEntries() * entryBits); - } - - private static final int START_PACKED_DATA_EXACT_MODE = 8; - private static final int START_PACKED_DATA_ESTIMATION_MODE = 16; - - @Override - public int getRetainedEntries(final boolean valid) { //valid is only relevant for the AlphaSketch - // number of entries is stored using variable length encoding - // most significant bytes with all zeros are not stored - // one byte in the preamble has the number of non-zero bytes used - final int preLongs = bytes_[PREAMBLE_LONGS_BYTE]; // if > 1 then the second long has theta - final int numEntriesBytes = bytes_[NUM_ENTRIES_BYTES_BYTE_V4]; - int offsetBytes = preLongs > 1 ? START_PACKED_DATA_ESTIMATION_MODE : START_PACKED_DATA_EXACT_MODE; - int numEntries = 0; - for (int i = 0; i < numEntriesBytes; i++) { - numEntries |= Byte.toUnsignedInt(bytes_[offsetBytes++]) << (i << 3); - } - return numEntries; - } - - @Override - public long getThetaLong() { - final int preLongs = bytes_[PREAMBLE_LONGS_BYTE]; - return (preLongs > 1) ? ByteArrayUtil.getLongLE(bytes_, 8) : Long.MAX_VALUE; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public boolean isOrdered() { - return true; - } - - @Override - public HashIterator iterator() { - return new BytesCompactCompressedHashIterator( - bytes_, - (bytes_[PREAMBLE_LONGS_BYTE] > 1 ? START_PACKED_DATA_ESTIMATION_MODE : START_PACKED_DATA_EXACT_MODE) - + bytes_[NUM_ENTRIES_BYTES_BYTE_V4], - bytes_[ENTRY_BITS_BYTE_V4], - getRetainedEntries() - ); - } -} diff --git a/src/main/java/org/apache/datasketches/theta/WrappedCompactSketch.java b/src/main/java/org/apache/datasketches/theta/WrappedCompactSketch.java deleted file mode 100644 index 2a33a386a..000000000 --- a/src/main/java/org/apache/datasketches/theta/WrappedCompactSketch.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.apache.datasketches.common.ByteArrayUtil.getIntLE; -import static org.apache.datasketches.common.ByteArrayUtil.getLongLE; -import static org.apache.datasketches.common.ByteArrayUtil.getShortLE; -import static org.apache.datasketches.theta.CompactOperations.segmentToCompact; -import static org.apache.datasketches.theta.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.FLAGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.ORDERED_FLAG_MASK; -import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.RETAINED_ENTRIES_INT; -import static org.apache.datasketches.theta.PreambleUtil.SEED_HASH_SHORT; -import static org.apache.datasketches.theta.PreambleUtil.THETA_LONG; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.Util; - -/** - * A wrapper around a serialized compact read-only sketch in the form of a byte array. - * It is not an empty nor a single item sketch. - * - *

This sketch can only be associated with a Serialization Version 3 binary image format.

- */ -class WrappedCompactSketch extends CompactThetaSketch { - final byte[] bytes_; - - /** - * Construct this sketch with the given bytes. - * @param bytes containing serialized compact sketch. - */ - WrappedCompactSketch(final byte[] bytes) { - bytes_ = bytes; - } - - /** - * Wraps the given byteArray, which must be a SerVer 3 CompactThetaSketch image. - * @param bytes representation of serialized CompactThetaSketch. - * @param seedHash The update seedHash. - * See Seed Hash. - * @return this sketch - */ - static WrappedCompactSketch wrapInstance(final byte[] bytes, final short seedHash) { - Util.checkSeedHashes(getShortLE(bytes, SEED_HASH_SHORT), seedHash); - return new WrappedCompactSketch(bytes); - } - - //ThetaSketch Overrides - - @Override - public CompactThetaSketch compact(final boolean dstOrdered, final MemorySegment dstSeg) { - return segmentToCompact(MemorySegment.ofArray(bytes_), dstOrdered, dstSeg); - } - - @Override - public int getCurrentBytes() { - final int preLongs = bytes_[PreambleUtil.PREAMBLE_LONGS_BYTE]; - final int numEntries = (preLongs == 1) ? 0 : getIntLE(bytes_, RETAINED_ENTRIES_INT); - return (preLongs + numEntries) << 3; - } - - @Override - public int getRetainedEntries(final boolean valid) { //valid is only relevant for the AlphaSketch - final int preLongs = bytes_[PREAMBLE_LONGS_BYTE]; - return (preLongs == 1) ? 0 : getIntLE(bytes_, RETAINED_ENTRIES_INT); - } - - @Override - public long getThetaLong() { - final int preLongs = bytes_[PREAMBLE_LONGS_BYTE]; - return (preLongs > 2) ? getLongLE(bytes_, THETA_LONG) : Long.MAX_VALUE; - } - - @Override - public boolean isEmpty() { - return (bytes_[FLAGS_BYTE] & EMPTY_FLAG_MASK) > 0; - } - - @Override - public boolean isOrdered() { - return (bytes_[FLAGS_BYTE] & ORDERED_FLAG_MASK) > 0; - } - - @Override - public HashIterator iterator() { - return new BytesCompactHashIterator( - bytes_, - bytes_[PREAMBLE_LONGS_BYTE] << 3, - getRetainedEntries() - ); - } - - @Override - public byte[] toByteArray() { - return Arrays.copyOf(bytes_, getCurrentBytes()); - } - - //restricted methods - - @Override - long[] getCache() { - final long[] cache = new long[getRetainedEntries()]; - int i = 0; - final HashIterator it = iterator(); - while (it.next()) { - cache[i++] = it.get(); - } - return cache; - } - - @Override - int getCompactPreambleLongs() { - return bytes_[PREAMBLE_LONGS_BYTE]; - } - - @Override - int getCurrentPreambleLongs() { - return bytes_[PREAMBLE_LONGS_BYTE]; - } - - @Override - short getSeedHash() { - return getShortLE(bytes_, SEED_HASH_SHORT); - } -} diff --git a/src/main/java/org/apache/datasketches/theta/package-info.java b/src/main/java/org/apache/datasketches/theta/package-info.java deleted file mode 100644 index 6da1a6a62..000000000 --- a/src/main/java/org/apache/datasketches/theta/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * The theta package contains the basic sketch classes that are members of the - * Theta-Sketch Framework. - * - *

There is a separate /tuple/ package for many of the sketches that are derived from the - * same algorithms defined in the Theta-Sketch Framework paper.

- */ -package org.apache.datasketches.theta; diff --git a/src/main/java/org/apache/datasketches/thetacommon/BinomialBoundsN.java b/src/main/java/org/apache/datasketches/thetacommon/BinomialBoundsN.java deleted file mode 100644 index 767a43e92..000000000 --- a/src/main/java/org/apache/datasketches/thetacommon/BinomialBoundsN.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * This class enables the estimation of error bounds given a sample set size, the sampling - * probability theta, the number of standard deviations and a simple noDataSeen flag. This can - * be used to estimate error bounds for fixed threshold sampling as well as the error bounds - * calculations for sketches. - * - * @author Kevin Lang - */ -// BTW, the suffixes "NStar", "NPrimeB", and "NPrimeF" correspond to variables in the formal -// writeup of this scheme. -public final class BinomialBoundsN { - - private BinomialBoundsN() {} - - private static final double[] deltaOfNumSDev = - { - 0.5000000000000000000, // = 0.5 (1 + erf(0) - 0.1586553191586026479, // = 0.5 (1 + erf((-1/sqrt(2)))) - 0.0227502618904135701, // = 0.5 (1 + erf((-2/sqrt(2)))) - 0.0013498126861731796 // = 0.5 (1 + erf((-3/sqrt(2)))) - }; - - // our "classic" bounds, but now with continuity correction - - private static double contClassicLB(final double numSamplesF, final double theta, - final double numSDev) { - final double nHat = (numSamplesF - 0.5) / theta; - final double b = numSDev * Math.sqrt((1.0 - theta) / theta); - final double d = 0.5 * b * Math.sqrt((b * b) + (4.0 * nHat)); - final double center = nHat + (0.5 * (b * b)); - return (center - d); - } - - private static double contClassicUB(final double numSamplesF, final double theta, - final double numSDev) { - final double nHat = (numSamplesF + 0.5) / theta; - final double b = numSDev * Math.sqrt((1.0 - theta) / theta); - final double d = 0.5 * b * Math.sqrt((b * b) + (4.0 * nHat)); - final double center = nHat + (0.5 * (b * b)); - return (center + d); - } - - // This is a special purpose calculator for NStar, using a computational - // strategy inspired by its Bayesian definition. It is only appropriate - // for a very limited set of inputs. However, the procedure computeApproxBinoLB () - // below does in fact only call it for suitably limited inputs. - // Outside of this limited range, two different bad things will happen. - // First, because we are not using logarithms, the values of intermediate - // quantities will exceed the dynamic range of doubles. Second, even if that - // problem were fixed, the running time of this procedure is essentially linear - // in est = (numSamples / p), and that can be Very, Very Big. - - private static long specialNStar(final long numSamplesI, final double p, final double delta) { - final double q, numSamplesF; - double tot, curTerm; - long m; - assertTrue(numSamplesI >= 1); - assertTrue((0.0 < p) && (p < 1.0)); - assertTrue((0.0 < delta) && (delta < 1.0)); - q = 1.0 - p; - numSamplesF = numSamplesI; - // Use a different algorithm if the following isn't true; this one will be too slow, or worse. - assertTrue((numSamplesF / p) < 500.0); - curTerm = Math.pow(p, numSamplesF); // curTerm = posteriorProbability (k, k, p) - assertTrue(curTerm > 1e-100); // sanity check for non-use of logarithms - tot = curTerm; - m = numSamplesI; - while (tot <= delta) { // this test can fail even the first time - curTerm = (curTerm * q * (m)) / ((m + 1) - numSamplesI); - tot += curTerm; - m += 1; - } - // we have reached a state where tot > delta, so back up one - return (m - 1); - } - - // The following procedure has very limited applicability. - // The above remarks about specialNStar() also apply here. - private static long specialNPrimeB(final long numSamplesI, final double p, final double delta) { - final double q, numSamplesF, oneMinusDelta; - double tot, curTerm; - long m; - assertTrue(numSamplesI >= 1); - assertTrue((0.0 < p) && (p < 1.0)); - assertTrue((0.0 < delta) && (delta < 1.0)); - q = 1.0 - p; - oneMinusDelta = 1.0 - delta; - numSamplesF = numSamplesI; - curTerm = Math.pow(p, numSamplesF); // curTerm = posteriorProbability (k, k, p) - assertTrue(curTerm > 1e-100); // sanity check for non-use of logarithms - tot = curTerm; - m = numSamplesI; - while (tot < oneMinusDelta) { - curTerm = (curTerm * q * (m)) / ((m + 1) - numSamplesI); - tot += curTerm; - m += 1; - } - return (m); // don't need to back up - } - - private static long specialNPrimeF(final long numSamplesI, final double p, final double delta) { - // Use a different algorithm if the following isn't true; this one will be too slow, or worse. - assertTrue(((numSamplesI) / p) < 500.0); //A super-small delta could also make it slow. - return (specialNPrimeB(numSamplesI + 1, p, delta)); - } - - // The following computes an approximation to the lower bound of - // a Frequentist confidence interval based on the tails of the Binomial distribution. - private static double computeApproxBinoLB(final long numSamplesI, final double theta, - final int numSDev) { - if (theta == 1.0) { - return (numSamplesI); - } - - else if (numSamplesI == 0) { - return (0.0); - } - - else if (numSamplesI == 1) { - final double delta = deltaOfNumSDev[numSDev]; - final double rawLB = (Math.log(1.0 - delta)) / (Math.log(1.0 - theta)); - return (Math.floor(rawLB)); // round down - } - - else if (numSamplesI > 120) { - // plenty of samples, so gaussian approximation to binomial distribution isn't too bad - final double rawLB = contClassicLB( numSamplesI, theta, numSDev); - return (rawLB - 0.5); // fake round down - } - - // at this point we know 2 <= numSamplesI <= 120 - - else if (theta > (1.0 - 1e-5)) { // empirically-determined threshold - return (numSamplesI); - } - - else if (theta < ((numSamplesI) / 360.0)) { // empirically-determined threshold - // here we use the gaussian approximation, but with a modified "numSDev" - final int index; - final double rawLB; - index = (3 * ((int) numSamplesI)) + (numSDev - 1); - rawLB = contClassicLB(numSamplesI, theta, EquivTables.getLB(index)); - return (rawLB - 0.5); // fake round down - } - - else { // This is the most difficult range to approximate; we will compute an "exact" LB. - // We know that est <= 360, so specialNStar() shouldn't be ridiculously slow. - final double delta = deltaOfNumSDev[numSDev]; - final long nstar = specialNStar(numSamplesI, theta, delta); - return (nstar); // don't need to round - } - } - - // The following computes an approximation to the upper bound of - // a Frequentist confidence interval based on the tails of the Binomial distribution. - private static double computeApproxBinoUB(final long numSamplesI, final double theta, - final int numSDev) { - if (theta == 1.0) { - return (numSamplesI); - } - - else if (numSamplesI == 0) { - final double delta = deltaOfNumSDev[numSDev]; - final double rawUB = (Math.log(delta)) / (Math.log(1.0 - theta)); - return (Math.ceil(rawUB)); // round up - } - - else if (numSamplesI > 120) { - // plenty of samples, so gaussian approximation to binomial distribution isn't too bad - final double rawUB = contClassicUB(numSamplesI, theta, numSDev); - return (rawUB + 0.5); // fake round up - } - - // at this point we know 1 <= numSamplesI <= 120 - - else if (theta > (1.0 - 1e-5)) { // empirically-determined threshold - return (numSamplesI + 1); - } - - else if (theta < ((numSamplesI) / 360.0)) { // empirically-determined threshold - // here we use the gaussian approximation, but with a modified "numSDev" - final int index; - final double rawUB; - index = (3 * ((int) numSamplesI)) + (numSDev - 1); - rawUB = contClassicUB(numSamplesI, theta, EquivTables.getUB(index)); - return (rawUB + 0.5); // fake round up - } - - else { // This is the most difficult range to approximate; we will compute an "exact" UB. - // We know that est <= 360, so specialNPrimeF() shouldn't be ridiculously slow. - final double delta = deltaOfNumSDev[numSDev]; - final long nprimef = specialNPrimeF(numSamplesI, theta, delta); - return (nprimef); // don't need to round - } - } - - // The following two procedures enforce some extra rules that help - // to prevent the return of bounds that might be confusing to users. - /** - * Returns the approximate lower bound value - * @param numSamples the number of samples in the sample set - * @param theta the sampling probability - * @param numSDev the number of "standard deviations" from the mean for the tail bounds. - * This must be an integer value of 1, 2 or 3. - * @param noDataSeen this is normally false. However, in the case where you have zero samples - * and a theta < 1.0, this flag enables the distinction between a virgin case when no actual - * data has been seen and the case where the estimate may be zero but an upper error bound may - * still exist. - * @return the approximate lower bound value - */ - public static double getLowerBound(final long numSamples, final double theta, final int numSDev, - final boolean noDataSeen) { - //in earlier code numSamples was called numSamplesI - if (noDataSeen) { return 0.0; } - checkArgs(numSamples, theta, numSDev); - final double lb = computeApproxBinoLB(numSamples, theta, numSDev); - final double numSamplesF = numSamples; - final double est = numSamplesF / theta; - return (Math.min(est, Math.max(numSamplesF, lb))); - } - - /** - * Returns the approximate upper bound value - * @param numSamples the number of samples in the sample set - * @param theta the sampling probability - * @param numSDev the number of "standard deviations" from the mean for the tail bounds. - * This must be an integer value of 1, 2 or 3. - * @param noDataSeen this is normally false. However, in the case where you have zero samples - * and a theta < 1.0, this flag enables the distinction between a virgin case when no actual - * data has been seen and the case where the estimate may be zero but an upper error bound may - * still exist. - * @return the approximate upper bound value - */ - public static double getUpperBound(final long numSamples, final double theta, final int numSDev, - final boolean noDataSeen) { - //in earlier code numSamples was called numSamplesI - if (noDataSeen) { return 0.0; } - checkArgs(numSamples, theta, numSDev); - final double ub = computeApproxBinoUB(numSamples, theta, numSDev); - final double numSamplesF = numSamples; - final double est = numSamplesF / theta; - return (Math.max(est, ub)); - } - - //exposed only for test - static void checkArgs(final long numSamples, final double theta, final int numSDev) { - if ((numSDev | (numSDev - 1) | (3 - numSDev) | numSamples) < 0) { - throw new SketchesArgumentException( - "numSDev must only be 1,2, or 3 and numSamples must >= 0: numSDev=" - + numSDev + ", numSamples=" + numSamples); - } - if ((theta <= 0.0) || (theta > 1.0)) { - throw new SketchesArgumentException("0.0 < theta <= 1.0: " + theta); - } - } - - private static void assertTrue(final boolean truth) { - assert (truth); - } - -} // end of class "BinomialBoundsN" diff --git a/src/main/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInThetaSketchedSets.java b/src/main/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInThetaSketchedSets.java deleted file mode 100644 index 5337efc44..000000000 --- a/src/main/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInThetaSketchedSets.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -import static org.apache.datasketches.common.Util.LONG_MAX_VALUE_AS_DOUBLE; - -import org.apache.datasketches.common.BoundsOnRatiosInSampledSets; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.theta.ThetaSketch; - -/** - * This class is used to compute the bounds on the estimate of the ratio B / A, where: - *
    - *
  • A is a Theta Sketch of population PopA.
  • - *
  • B is a Theta Sketch of population PopB that is a subset of A, - * obtained by an intersection of A with some other Theta Sketch C, - * which acts like a predicate or selection clause.
  • - *
  • The estimate of the ratio PopB/PopA is - * BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(A, B).
  • - *
  • The Upper Bound estimate on the ratio PopB/PopA is - * BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(A, B).
  • - *
  • The Lower Bound estimate on the ratio PopB/PopA is - * BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(A, B).
  • - *
- * Note: The theta of A cannot be greater than the theta of B. - * If B is formed as an intersection of A and some other set C, - * then the theta of B is guaranteed to be less than or equal to the theta of B. - * - * @author Kevin Lang - * @author Lee Rhodes - */ -public final class BoundsOnRatiosInThetaSketchedSets { - - private BoundsOnRatiosInThetaSketchedSets() {} - - /** - * Gets the approximate lower bound for B over A based on a 95% confidence interval - * @param sketchA the sketch A - * @param sketchB the sketch B - * @return the approximate lower bound for B over A - */ - public static double getLowerBoundForBoverA(final ThetaSketch sketchA, final ThetaSketch sketchB) { - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - checkThetas(thetaLongA, thetaLongB); - - final int countB = sketchB.getRetainedEntries(true); - final int countA = (thetaLongB == thetaLongA) - ? sketchA.getRetainedEntries(true) - : sketchA.getCountLessThanThetaLong(thetaLongB); - - if (countA <= 0) { return 0; } - final double f = thetaLongB / LONG_MAX_VALUE_AS_DOUBLE; - return BoundsOnRatiosInSampledSets.getLowerBoundForBoverA(countA, countB, f); - } - - /** - * Gets the approximate upper bound for B over A based on a 95% confidence interval - * @param sketchA the sketch A - * @param sketchB the sketch B - * @return the approximate upper bound for B over A - */ - public static double getUpperBoundForBoverA(final ThetaSketch sketchA, final ThetaSketch sketchB) { - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - checkThetas(thetaLongA, thetaLongB); - - final int countB = sketchB.getRetainedEntries(true); - final int countA = (thetaLongB == thetaLongA) - ? sketchA.getRetainedEntries(true) - : sketchA.getCountLessThanThetaLong(thetaLongB); - - if (countA <= 0) { return 1.0; } - final double f = thetaLongB / LONG_MAX_VALUE_AS_DOUBLE; - return BoundsOnRatiosInSampledSets.getUpperBoundForBoverA(countA, countB, f); - } - - /** - * Gets the estimate for B over A - * @param sketchA the sketch A - * @param sketchB the sketch B - * @return the estimate for B over A - */ - public static double getEstimateOfBoverA(final ThetaSketch sketchA, final ThetaSketch sketchB) { - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - checkThetas(thetaLongA, thetaLongB); - - final int countB = sketchB.getRetainedEntries(true); - final int countA = (thetaLongB == thetaLongA) - ? sketchA.getRetainedEntries(true) - : sketchA.getCountLessThanThetaLong(thetaLongB); - - if (countA <= 0) { return 0.5; } - - return (double) countB / (double) countA; - } - - static void checkThetas(final long thetaLongA, final long thetaLongB) { - if (thetaLongB > thetaLongA) { - throw new SketchesArgumentException("ThetaLongB cannot be > ThetaLongA."); - } - } -} diff --git a/src/main/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInTupleSketchedSets.java b/src/main/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInTupleSketchedSets.java deleted file mode 100644 index 992921bb7..000000000 --- a/src/main/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInTupleSketchedSets.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -import static org.apache.datasketches.common.Util.LONG_MAX_VALUE_AS_DOUBLE; - -import org.apache.datasketches.common.BoundsOnRatiosInSampledSets; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.TupleSketch; -import org.apache.datasketches.tuple.Summary; - -/** - * This class is used to compute the bounds on the estimate of the ratio B / A, where: - *
    - *
  • A is a Tuple Sketch of population PopA.
  • - *
  • B is a Tuple or Theta Sketch of population PopB that is a subset of A, - * obtained by an intersection of A with some other Tuple or Theta Sketch C, - * which acts like a predicate or selection clause.
  • - *
  • The estimate of the ratio PopB/PopA is - * BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(A, B).
  • - *
  • The Upper Bound estimate on the ratio PopB/PopA is - * BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(A, B).
  • - *
  • The Lower Bound estimate on the ratio PopB/PopA is - * BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(A, B).
  • - *
- * Note: The theta of A cannot be greater than the theta of B. - * If B is formed as an intersection of A and some other set C, - * then the theta of B is guaranteed to be less than or equal to the theta of B. - * - * @author Kevin Lang - * @author Lee Rhodes - * @author David Cromberge - */ -public final class BoundsOnRatiosInTupleSketchedSets { - - private BoundsOnRatiosInTupleSketchedSets() {} - - /** - * Gets the approximate lower bound for B over A based on a 95% confidence interval - * @param sketchA the Tuple sketch A with summary type S - * @param sketchB the Tuple sketch B with summary type S - * @param Summary - * @return the approximate lower bound for B over A - */ - public static double getLowerBoundForBoverA( - final TupleSketch sketchA, - final TupleSketch sketchB) { - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - checkThetas(thetaLongA, thetaLongB); - - final int countB = sketchB.getRetainedEntries(); - final int countA = thetaLongB == thetaLongA - ? sketchA.getRetainedEntries() - : sketchA.getCountLessThanThetaLong(thetaLongB); - - if (countA <= 0) { return 0; } - final double f = thetaLongB / LONG_MAX_VALUE_AS_DOUBLE; - return BoundsOnRatiosInSampledSets.getLowerBoundForBoverA(countA, countB, f); - } - - /** - * Gets the approximate lower bound for B over A based on a 95% confidence interval - * @param sketchA the Tuple sketch A with summary type S - * @param sketchB the Theta sketch B - * @param Summary - * @return the approximate lower bound for B over A - */ - public static double getLowerBoundForBoverA( - final TupleSketch sketchA, - final org.apache.datasketches.theta.ThetaSketch sketchB) { - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - checkThetas(thetaLongA, thetaLongB); - - final int countB = sketchB.getRetainedEntries(); - final int countA = thetaLongB == thetaLongA - ? sketchA.getRetainedEntries() - : sketchA.getCountLessThanThetaLong(thetaLongB); - - if (countA <= 0) { return 0; } - final double f = thetaLongB / LONG_MAX_VALUE_AS_DOUBLE; - return BoundsOnRatiosInSampledSets.getLowerBoundForBoverA(countA, countB, f); - } - - /** - * Gets the approximate upper bound for B over A based on a 95% confidence interval - * @param sketchA the Tuple sketch A with summary type S - * @param sketchB the Tuple sketch B with summary type S - * @param Summary - * @return the approximate upper bound for B over A - */ - public static double getUpperBoundForBoverA( - final TupleSketch sketchA, - final TupleSketch sketchB) { - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - checkThetas(thetaLongA, thetaLongB); - - final int countB = sketchB.getRetainedEntries(); - final int countA = thetaLongB == thetaLongA - ? sketchA.getRetainedEntries() - : sketchA.getCountLessThanThetaLong(thetaLongB); - - if (countA <= 0) { return 1.0; } - final double f = thetaLongB / LONG_MAX_VALUE_AS_DOUBLE; - return BoundsOnRatiosInSampledSets.getUpperBoundForBoverA(countA, countB, f); - } - - /** - * Gets the approximate upper bound for B over A based on a 95% confidence interval - * @param sketchA the Tuple sketch A with summary type S - * @param sketchB the Theta sketch B - * @param Summary - * @return the approximate upper bound for B over A - */ - public static double getUpperBoundForBoverA( - final TupleSketch sketchA, - final org.apache.datasketches.theta.ThetaSketch sketchB) { - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - checkThetas(thetaLongA, thetaLongB); - - final int countB = sketchB.getRetainedEntries(true); - final int countA = thetaLongB == thetaLongA - ? sketchA.getRetainedEntries() - : sketchA.getCountLessThanThetaLong(thetaLongB); - - if (countA <= 0) { return 1.0; } - final double f = thetaLongB / LONG_MAX_VALUE_AS_DOUBLE; - return BoundsOnRatiosInSampledSets.getUpperBoundForBoverA(countA, countB, f); - } - - /** - * Gets the estimate for B over A - * @param sketchA the Tuple sketch A with summary type S - * @param sketchB the Tuple sketch B with summary type S - * @param Summary - * @return the estimate for B over A - */ - public static double getEstimateOfBoverA( - final TupleSketch sketchA, - final TupleSketch sketchB) { - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - checkThetas(thetaLongA, thetaLongB); - - final int countB = sketchB.getRetainedEntries(); - final int countA = thetaLongB == thetaLongA - ? sketchA.getRetainedEntries() - : sketchA.getCountLessThanThetaLong(thetaLongB); - - if (countA <= 0) { return 0.5; } - - return (double) countB / (double) countA; - } - - /** - * Gets the estimate for B over A - * @param sketchA the Tuple sketch A with summary type S - * @param sketchB the Theta sketch B - * @param Summary - * @return the estimate for B over A - */ - public static double getEstimateOfBoverA( - final TupleSketch sketchA, - final org.apache.datasketches.theta.ThetaSketch sketchB) { - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - checkThetas(thetaLongA, thetaLongB); - - final int countB = sketchB.getRetainedEntries(true); - final int countA = thetaLongB == thetaLongA - ? sketchA.getRetainedEntries() - : sketchA.getCountLessThanThetaLong(thetaLongB); - - if (countA <= 0) { return 0.5; } - - return (double) countB / (double) countA; - } - - static void checkThetas(final long thetaLongA, final long thetaLongB) { - if (thetaLongB > thetaLongA) { - throw new SketchesArgumentException("ThetaLongB cannot be > ThetaLongA."); - } - } -} diff --git a/src/main/java/org/apache/datasketches/thetacommon/EquivTables.java b/src/main/java/org/apache/datasketches/thetacommon/EquivTables.java deleted file mode 100644 index 364533290..000000000 --- a/src/main/java/org/apache/datasketches/thetacommon/EquivTables.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -/** - * Tables for BinomialBoundsN calculations. - * - *

These equivTables contain modified values for numSDevs that if used - * WHEN THETA IS VERY SMALL will cause the continuity-corrected version - * of our "classic" confidence intervals to be very close to "exact" confidence - * intervals based on the tails of the actual binomial distirbution.

- * - * @author Kevin Lang - */ -final class EquivTables { - - private EquivTables() {} - - static double getLB(final int index) { - return lbEquivTable[index]; - } - - static double getUB(final int index) { - return ubEquivTable[index]; - } - - private static double[] lbEquivTable = { - 1.0, 2.0, 3.0, // fake values for k = 0 - 0.78733703534118149, 3.14426768537558132, 13.56789685109913535, // k = 1 - 0.94091379266077979, 2.64699271711145911, 6.29302733018320737, // k = 2 - 0.96869128474958188, 2.46531676590527127, 4.97375283467403051, // k = 3 - 0.97933572521046131, 2.37418810664669877, 4.44899975481712318, // k = 4 - 0.98479165917274258, 2.31863116255024693, 4.16712379778553554, // k = 5 - 0.98806033915698777, 2.28075536565225434, 3.99010556144099837, // k = 6 - 0.99021896790580399, 2.25302005857281529, 3.86784477136922078, // k = 7 - 0.99174267079089873, 2.23168103978522936, 3.77784896945266269, // k = 8 - 0.99287147837287648, 2.21465899260871879, 3.70851932988722410, // k = 9 - 0.99373900046805375, 2.20070155496262032, 3.65326029076638292, // k = 10 - 0.99442519013851438, 2.18900651202670815, 3.60803817612955413, // k = 11 - 0.99498066823221620, 2.17903457780744247, 3.57024330407946877, // k = 12 - 0.99543899410224412, 2.17040883161922693, 3.53810982030634591, // k = 13 - 0.99582322541263579, 2.16285726913676513, 3.51039837124298515, // k = 14 - 0.99614973311747690, 2.15617827879603396, 3.48621230377099778, // k = 15 - 0.99643042892560629, 2.15021897666090922, 3.46488605693562590, // k = 16 - 0.99667418783778317, 2.14486114872480016, 3.44591466064832730, // k = 17 - 0.99688774875812669, 2.14001181420209718, 3.42890765690452781, // k = 18 - 0.99707632299691795, 2.13559675336844634, 3.41355809420343803, // k = 19 - 0.99724399084971083, 2.13155592217421486, 3.39962113251016262, // k = 20 - 0.99739400151915447, 2.12784018863251845, 3.38689892877548004, // k = 21 - 0.99752896842633731, 2.12440890875851096, 3.37522975271599535, // k = 22 - 0.99765101725122918, 2.12122815311133195, 3.36448003577621080, // k = 23 - 0.99776189496810730, 2.11826934724291505, 3.35453840911279144, // k = 24 - 0.99786304821586214, 2.11550823850916458, 3.34531123809287578, // k = 25 - 0.99795568665180667, 2.11292409529477254, 3.33671916527694634, // k = 26 - 0.99804083063483517, 2.11049908609763293, 3.32869446834217797, // k = 27 - 0.99811933910984862, 2.10821776918189130, 3.32117898316676019, // k = 28 - 0.99819195457286014, 2.10606671027090897, 3.31412243534683171, // k = 29 - 0.99825930555178388, 2.10403415237001923, 3.30748113008135647, // k = 30 - 0.99832193858154028, 2.10210975877822648, 3.30121691946897045, // k = 31 - 0.99838032666573895, 2.10028440670842542, 3.29529629751144171, // k = 32 - 0.99843488390555990, 2.09855000145353188, 3.28968974413223236, // k = 33 - 0.99848596721417948, 2.09689934193824001, 3.28437111460505093, // k = 34 - 0.99853390005924325, 2.09532599155502908, 3.27931717312372939, // k = 35 - 0.99857895741078551, 2.09382418262592296, 3.27450718840060517, // k = 36 - 0.99862138880970974, 2.09238872751677718, 3.26992261182860489, // k = 37 - 0.99866141580770318, 2.09101494715108061, 3.26554677962434425, // k = 38 - 0.99869923565267982, 2.08969860402822860, 3.26136468165239535, // k = 39 - 0.99873502010169091, 2.08843585627218431, 3.25736275677081721, // k = 40 - 0.99876893292508839, 2.08722321436752623, 3.25352872241415980, // k = 41 - 0.99880111078502409, 2.08605749165553789, 3.24985141664350863, // k = 42 - 0.99883168573342118, 2.08493577529222307, 3.24632068399498053, // k = 43 - 0.99886077231613513, 2.08385540129560809, 3.24292724848112357, // k = 44 - 0.99888847451828155, 2.08281392374021834, 3.23966263299664092, // k = 45 - 0.99891488795844907, 2.08180908991394631, 3.23651906111521726, // k = 46 - 0.99894010085196783, 2.08083882998420222, 3.23348939240611344, // k = 47 - 0.99896419358239541, 2.07990122528650545, 3.23056705515594444, // k = 48 - 0.99898723510594323, 2.07899450946285924, 3.22774598963252402, // k = 49 - 0.99900929266780736, 2.07811704477046533, 3.22502059972006805, // k = 50 - 0.99903043086155208, 2.07726730587160091, 3.22238570890294795, // k = 51 - 0.99905070073845081, 2.07644388314946582, 3.21983651940365689, // k = 52 - 0.99907015770423868, 2.07564546080757850, 3.21736857351049821, // k = 53 - 0.99908884779227947, 2.07487081196367740, 3.21497773796417619, // k = 54 - 0.99910681586905525, 2.07411879634256024, 3.21266015316183484, // k = 55 - 0.99912410177549305, 2.07338834403498140, 3.21041222805715165, // k = 56 - 0.99914074347179849, 2.07267845454973099, 3.20823061166797174, // k = 57 - 0.99915677607464204, 2.07198819052374006, 3.20611216970604573, // k = 58 - 0.99917223149395795, 2.07131667846186929, 3.20405396962596001, // k = 59 - 0.99918714153457699, 2.07066309019154460, 3.20205326110445299, // k = 60 - 0.99920153247185794, 2.07002665203046377, 3.20010746990493544, // k = 61 - 0.99921543193525508, 2.06940663431663552, 3.19821417453343315, // k = 62 - 0.99922886570365677, 2.06880235245998279, 3.19637109973109546, // k = 63 - 0.99924185357357942, 2.06821315729285971, 3.19457610621114441, // k = 64 - 0.99925441845175555, 2.06763843812092318, 3.19282717869864996, // k = 65 - 0.99926658263325407, 2.06707761824370095, 3.19112241228646099, // k = 66 - 0.99927836173816331, 2.06653015295219689, 3.18946001739936946, // k = 67 - 0.99928977431994781, 2.06599552505539918, 3.18783829446098821, // k = 68 - 0.99930083753795884, 2.06547324585920933, 3.18625564538041317, // k = 69 - 0.99931156864562354, 2.06496285191821016, 3.18471055124089730, // k = 70 - 0.99932197985521043, 2.06446390392778767, 3.18320157510865442, // k = 71 - 0.99933208559809827, 2.06397598606787369, 3.18172735837393361, // k = 72 - 0.99934190032416836, 2.06349869971447220, 3.18028661102792398, // k = 73 - 0.99935143390791836, 2.06303166975550312, 3.17887810481605015, // k = 74 - 0.99936070171270330, 2.06257453607466346, 3.17750067581857820, // k = 75 - 0.99936971103502970, 2.06212696042919674, 3.17615321728274580, // k = 76 - 0.99937847392385493, 2.06168861430600714, 3.17483467831510779, // k = 77 - 0.99938700168914352, 2.06125918927764928, 3.17354405480557489, // k = 78 - 0.99939530099953799, 2.06083838987589729, 3.17228039269048168, // k = 79 - 0.99940338278830154, 2.06042593411496000, 3.17104278166036124, // k = 80 - 0.99941125463777780, 2.06002155276328835, 3.16983035274597569, // k = 81 - 0.99941892470027938, 2.05962498741951094, 3.16864227952240185, // k = 82 - 0.99942640059737187, 2.05923599161263837, 3.16747776846497686, // k = 83 - 0.99943368842187397, 2.05885433061945378, 3.16633606416374391, // k = 84 - 0.99944079790603269, 2.05847977868873500, 3.16521644518826406, // k = 85 - 0.99944773295734990, 2.05811212058944193, 3.16411821883858124, // k = 86 - 0.99945450059186669, 2.05775114781260982, 3.16304072400711789, // k = 87 - 0.99946110646314423, 2.05739666442039493, 3.16198332650733960, // k = 88 - 0.99946755770463369, 2.05704847678819647, 3.16094541781455973, // k = 89 - 0.99947385746861528, 2.05670640500335367, 3.15992641851471490, // k = 90 - 0.99948001256305474, 2.05637027420314666, 3.15892576988736096, // k = 91 - 0.99948602689656241, 2.05603991286400856, 3.15794293484717059, // k = 92 - 0.99949190674294641, 2.05571516158917689, 3.15697740043813724, // k = 93 - 0.99949765436329585, 2.05539586490317561, 3.15602867309343083, // k = 94 - 0.99950327557880314, 2.05508187237845164, 3.15509627710042651, // k = 95 - 0.99950877461972709, 2.05477304104951486, 3.15417975753007340, // k = 96 - 0.99951415481862682, 2.05446923022574879, 3.15327867462917766, // k = 97 - 0.99951942042375208, 2.05417030908833453, 3.15239260700215596, // k = 98 - 0.99952457390890004, 2.05387614661762541, 3.15152114915238712, // k = 99 - 0.99952962005008317, 2.05358662050909402, 3.15066390921020911, // k = 100 - 0.99953456216121594, 2.05330161104427589, 3.14982051097524618, // k = 101 - 0.99953940176368405, 2.05302100378725072, 3.14899059183684926, // k = 102 - 0.99954414373920031, 2.05274468493067275, 3.14817379948561893, // k = 103 - 0.99954879047621148, 2.05247255013657082, 3.14736979964868624, // k = 104 - 0.99955334485656522, 2.05220449388099269, 3.14657826610371671, // k = 105 - 0.99955780993869325, 2.05194041831310869, 3.14579888316276879, // k = 106 - 0.99956218652590678, 2.05168022402710903, 3.14503134811607765, // k = 107 - 0.99956647932785359, 2.05142381889103831, 3.14427536967733090, // k = 108 - 0.99957069025060719, 2.05117111251445294, 3.14353066260227365, // k = 109 - 0.99957482032178291, 2.05092201793428330, 3.14279695558593630, // k = 110 - 0.99957887261450651, 2.05067645094720774, 3.14207398336887422, // k = 111 - 0.99958284988383639, 2.05043432833224415, 3.14136149076028914, // k = 112 - 0.99958675435604505, 2.05019557189746138, 3.14065923143530767, // k = 113 - 0.99959058650074439, 2.04996010556124020, 3.13996696426707445, // k = 114 - 0.99959434898201494, 2.04972785368377686, 3.13928445867830419, // k = 115 - 0.99959804437042976, 2.04949874512311681, 3.13861149103462367, // k = 116 - 0.99960167394553423, 2.04927271043337100, 3.13794784369528656, // k = 117 - 0.99960523957651048, 2.04904968140490951, 3.13729330661277572, // k = 118 - 0.99960874253329735, 2.04882959397491504, 3.13664767767019725, // k = 119 - 0.99961218434327748, 2.04861238220240693, 3.13601075688413289 // k = 120 - }; - - private static double[] ubEquivTable = { - 1.0, 2.0, 3.0, // fake values for k = 0 - 0.99067760836669549, 1.75460517119302040, 2.48055626001627161, // k = 1 - 0.99270518097577565, 1.78855957509907171, 2.53863835259832626, // k = 2 - 0.99402032633599902, 1.81047286499563143, 2.57811676180597260, // k = 3 - 0.99492607629539975, 1.82625928017762362, 2.60759550546498531, // k = 4 - 0.99558653966013821, 1.83839160339161367, 2.63086812358551470, // k = 5 - 0.99608981951632813, 1.84812399034444752, 2.64993712523727254, // k = 6 - 0.99648648035983456, 1.85617372053235385, 2.66598485907860550, // k = 7 - 0.99680750790483330, 1.86298655802610824, 2.67976541374471822, // k = 8 - 0.99707292880049181, 1.86885682585270274, 2.69178781407745760, // k = 9 - 0.99729614928489241, 1.87398826101983218, 2.70241106542158604, // k = 10 - 0.99748667952445658, 1.87852708449801753, 2.71189717290596377, // k = 11 - 0.99765127712748836, 1.88258159501103250, 2.72044290303773550, // k = 12 - 0.99779498340305395, 1.88623391878036273, 2.72819957382063194, // k = 13 - 0.99792160418357412, 1.88954778748873764, 2.73528576807902368, // k = 14 - 0.99803398604944960, 1.89257337682371940, 2.74179612106766513, // k = 15 - 0.99813449883217231, 1.89535099316557876, 2.74780718300419835, // k = 16 - 0.99822494122659577, 1.89791339232732525, 2.75338173141955167, // k = 17 - 0.99830679915913834, 1.90028752122407241, 2.75857186416826039, // k = 18 - 0.99838117410831728, 1.90249575897183831, 2.76342117562634826, // k = 19 - 0.99844913407071090, 1.90455689090418900, 2.76796659454200267, // k = 20 - 0.99851147736424650, 1.90648682834171268, 2.77223944710058845, // k = 21 - 0.99856879856019987, 1.90829917277082473, 2.77626682032629901, // k = 22 - 0.99862183849734265, 1.91000561415842185, 2.78007199816156003, // k = 23 - 0.99867096266018507, 1.91161621560812023, 2.78367524259661536, // k = 24 - 0.99871656986212543, 1.91313978579765376, 2.78709435016625662, // k = 25 - 0.99875907577771272, 1.91458400425526065, 2.79034488416175463, // k = 26 - 0.99879885565047744, 1.91595563175945927, 2.79344064132371273, // k = 27 - 0.99883610756373287, 1.91726064301425936, 2.79639384757751941, // k = 28 - 0.99887095169674467, 1.91850441099725799, 2.79921543574803877, // k = 29 - 0.99890379414739527, 1.91969155477030995, 2.80191513182441554, // k = 30 - 0.99893466279047516, 1.92082633358913313, 2.80450167352080371, // k = 31 - 0.99896392088177777, 1.92191254955568525, 2.80698295731653502, // k = 32 - 0.99899147889385631, 1.92295362479495680, 2.80936614404217266, // k = 33 - 0.99901764688726757, 1.92395267400968351, 2.81165765979318394, // k = 34 - 0.99904238606342233, 1.92491244978191389, 2.81386337393604435, // k = 35 - 0.99906590152386343, 1.92583552644848055, 2.81598868034527072, // k = 36 - 0.99908829040739988, 1.92672418013918900, 2.81803841726804194, // k = 37 - 0.99910959420023460, 1.92758051694144683, 2.82001709302821268, // k = 38 - 0.99912996403594434, 1.92840654943159961, 2.82192875763732332, // k = 39 - 0.99914930224576892, 1.92920397044028391, 2.82377730628954282, // k = 40 - 0.99916781270195543, 1.92997447498220254, 2.82556612075063640, // k = 41 - 0.99918553179077207, 1.93071949211818605, 2.82729843191989971, // k = 42 - 0.99920250730914972, 1.93144048613876862, 2.82897728689417249, // k = 43 - 0.99921873345181211, 1.93213870990595638, 2.83060537017752267, // k = 44 - 0.99923435180002684, 1.93281536508689555, 2.83218527795750674, // k = 45 - 0.99924930425362390, 1.93347145882316340, 2.83371938965598247, // k = 46 - 0.99926370394567243, 1.93410820221384938, 2.83520990872793277, // k = 47 - 0.99927750755296074, 1.93472643138986200, 2.83665891945119597, // k = 48 - 0.99929082941537217, 1.93532697329771963, 2.83806833931606661, // k = 49 - 0.99930366295501472, 1.93591074716263734, 2.83943997143404658, // k = 50 - 0.99931598804721489, 1.93647857274021362, 2.84077557836653227, // k = 51 - 0.99932789059798210, 1.93703110239354714, 2.84207662106302905, // k = 52 - 0.99933946180485123, 1.93756904936378760, 2.84334468086129277, // k = 53 - 0.99935053819703512, 1.93809302131219852, 2.84458116874117195, // k = 54 - 0.99936126637970801, 1.93860365411038060, 2.84578731838604426, // k = 55 - 0.99937166229284458, 1.93910149816429112, 2.84696443486512862, // k = 56 - 0.99938169190727422, 1.93958709548454067, 2.84811369085281285, // k = 57 - 0.99939136927613959, 1.94006085573701625, 2.84923617230361970, // k = 58 - 0.99940074328745254, 1.94052339623206649, 2.85033291216254270, // k = 59 - 0.99940993070470086, 1.94097508636855309, 2.85140492437699322, // k = 60 - 0.99941868577388959, 1.94141633372043998, 2.85245314430358121, // k = 61 - 0.99942734443487780, 1.94184757038001976, 2.85347839582286156, // k = 62 - 0.99943556385736088, 1.94226915100517772, 2.85448160365493209, // k = 63 - 0.99944374522542034, 1.94268143723749631, 2.85546346373061510, // k = 64 - 0.99945159955424856, 1.94308482059116727, 2.85642486111805738, // k = 65 - 0.99945915301904620, 1.94347956957849988, 2.85736639994965458, // k = 66 - 0.99946660663832176, 1.94386600964031686, 2.85828887832701639, // k = 67 - 0.99947383703224091, 1.94424436597356021, 2.85919278275500233, // k = 68 - 0.99948075442870277, 1.94461502153473020, 2.86007887186090670, // k = 69 - 0.99948766082269458, 1.94497821937304138, 2.86094774077355396, // k = 70 - 0.99949422748713346, 1.94533411296001191, 2.86179981848076181, // k = 71 - 0.99950070756119658, 1.94568300035135167, 2.86263579405672886, // k = 72 - 0.99950704321753392, 1.94602523449961495, 2.86345610449197352, // k = 73 - 0.99951320334216121, 1.94636083782822311, 2.86426125541271404, // k = 74 - 0.99951920293474927, 1.94669011080745236, 2.86505169255406145, // k = 75 - 0.99952501670378524, 1.94701327348536779, 2.86582788270862920, // k = 76 - 0.99953071209267819, 1.94733044372333097, 2.86659027602854621, // k = 77 - 0.99953632734991515, 1.94764180764266825, 2.86733927778843167, // k = 78 - 0.99954171164873173, 1.94794766430732125, 2.86807526143834934, // k = 79 - 0.99954699274462655, 1.94824807472994621, 2.86879864789403882, // k = 80 - 0.99955216611081710, 1.94854317889829076, 2.86950970901679625, // k = 81 - 0.99955730019613043, 1.94883320227168610, 2.87020887436986527, // k = 82 - 0.99956213770650493, 1.94911826561721568, 2.87089648477021342, // k = 83 - 0.99956704264963037, 1.94939848545763539, 2.87157281693902178, // k = 84 - 0.99957166306481327, 1.94967401618316671, 2.87223821840905202, // k = 85 - 0.99957632713136491, 1.94994497791333288, 2.87289293193450135, // k = 86 - 0.99958087233392234, 1.95021155752212394, 2.87353731228213860, // k = 87 - 0.99958532555996271, 1.95047376805584349, 2.87417154907075201, // k = 88 - 0.99958956246481989, 1.95073180380688882, 2.87479599765507032, // k = 89 - 0.99959389351869277, 1.95098572880579013, 2.87541081987382086, // k = 90 - 0.99959807862052230, 1.95123574036898617, 2.87601637401948551, // k = 91 - 0.99960214057801977, 1.95148186921983324, 2.87661283691068093, // k = 92 - 0.99960607527256684, 1.95172415829728152, 2.87720042968334155, // k = 93 - 0.99960996433179616, 1.95196280898670693, 2.87777936649376898, // k = 94 - 0.99961379137860717, 1.95219787713926962, 2.87834989933620022, // k = 95 - 0.99961756088146103, 1.95242944583677058, 2.87891216133900230, // k = 96 - 0.99962125605327401, 1.95265762420910960, 2.87946647367488140, // k = 97 - 0.99962486179100551, 1.95288245314810638, 2.88001290210658567, // k = 98 - 0.99962843240297161, 1.95310404286672679, 2.88055166523392359, // k = 99 - 0.99963187276145504, 1.95332251980147475, 2.88108300006589957, // k = 100 - 0.99963525453173929, 1.95353785898848287, 2.88160703591438505, // k = 101 - 0.99963855412988778, 1.95375019354571577, 2.88212393551896184, // k = 102 - 0.99964190254169694, 1.95395953472205974, 2.88263389761985422, // k = 103 - 0.99964506565942202, 1.95416607430155409, 2.88313700661564098, // k = 104 - 0.99964834424233118, 1.95436972855640079, 2.88363350163803034, // k = 105 - 0.99965136548857458, 1.95457068540693513, 2.88412349413960101, // k = 106 - 0.99965436594726498, 1.95476896383092935, 2.88460710620208260, // k = 107 - 0.99965736463468602, 1.95496457504532373, 2.88508450078833789, // k = 108 - 0.99966034130443404, 1.95515761150707590, 2.88555580586194083, // k = 109 - 0.99966326130828520, 1.95534810382198998, 2.88602118761679094, // k = 110 - 0.99966601446035952, 1.95553622237747504, 2.88648066384146773, // k = 111 - 0.99966887679593697, 1.95572186728168163, 2.88693444915907094, // k = 112 - 0.99967161286551232, 1.95590523410490391, 2.88738271495714116, // k = 113 - 0.99967435412270333, 1.95608626483223702, 2.88782540459769166, // k = 114 - 0.99967701261934394, 1.95626497627117146, 2.88826277189363623, // k = 115 - 0.99967963265157778, 1.95644153684824573, 2.88869486674335008, // k = 116 - 0.99968216317182623, 1.95661589936000269, 2.88912184353694101, // k = 117 - 0.99968479674396349, 1.95678821614791332, 2.88954376359643561, // k = 118 - 0.99968729031337489, 1.95695842061650183, 2.88996069422501023, // k = 119 - 0.99968963358631413, 1.95712651709766305, 2.89037285320668502 // k = 120 - }; - -} diff --git a/src/main/java/org/apache/datasketches/thetacommon/HashOperations.java b/src/main/java/org/apache/datasketches/thetacommon/HashOperations.java deleted file mode 100644 index 7cf22bb3b..000000000 --- a/src/main/java/org/apache/datasketches/thetacommon/HashOperations.java +++ /dev/null @@ -1,401 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.Math.max; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; - -/** - * Helper class for the common hash table methods. - * - * @author Lee Rhodes - * @author Kevin Lang - */ -public final class HashOperations { - private static final int STRIDE_HASH_BITS = 7; - private static final int EMPTY = 0; - - /** - * The stride mask for the Open Address, Double Hashing (OADH) hash table algorithm. - */ - public static final int STRIDE_MASK = (1 << STRIDE_HASH_BITS) - 1; - - private HashOperations() {} - - //Make odd and independent of index assuming lgArrLongs lowest bits of the hash were used for - // index. This results in a 8 bit value that is always odd. - private static int getStride(final long hash, final int lgArrLongs) { - return (2 * (int) ((hash >>> lgArrLongs) & STRIDE_MASK) ) + 1; - } - - //ON-HEAP - - /** - * This is a classical Knuth-style Open Addressing, Double Hash (OADH) search scheme for on-heap. - * Returns the index if found, -1 if not found. - * - * @param hashTable The hash table to search. Its size must be a power of 2. - * @param lgArrLongs The log_base2(hashTable.length). - * See lgArrLongs. - * @param hash The hash value to search for. It must not be zero. - * @return Current probe index if found, -1 if not found. - */ - public static int hashSearch(final long[] hashTable, final int lgArrLongs, final long hash) { - if (hash == 0) { - throw new SketchesArgumentException("Given hash must not be zero: " + hash); - } - final int arrayMask = (1 << lgArrLongs) - 1; // current Size -1 - final int stride = getStride(hash, lgArrLongs); - int curProbe = (int) (hash & arrayMask); - - // search for duplicate or empty slot - final int loopIndex = curProbe; - do { - final long arrVal = hashTable[curProbe]; - if (arrVal == EMPTY) { - return -1; // not found - } else if (arrVal == hash) { - return curProbe; // found - } - curProbe = (curProbe + stride) & arrayMask; - } while (curProbe != loopIndex); - return -1; - } - - /** - * This is a classical Knuth-style Open Addressing, Double Hash (OADH) insert scheme for on-heap. - * This method assumes that the input hash is not a duplicate. - * Useful for rebuilding tables to avoid unnecessary comparisons. - * Returns the index of insertion, which is always positive or zero. - * Throws an exception if the table has no empty slot. - * - * @param hashTable the hash table to insert into. Its size must be a power of 2. - * @param lgArrLongs The log_base2(hashTable.length). - * See lgArrLongs. - * @param hash The hash value to be potentially inserted into an empty slot. It must not be zero. - * @return index of insertion. Always positive or zero. - */ - public static int hashInsertOnly(final long[] hashTable, final int lgArrLongs, final long hash) { - final int arrayMask = (1 << lgArrLongs) - 1; // current Size -1 - final int stride = getStride(hash, lgArrLongs); - int curProbe = (int) (hash & arrayMask); - - final long loopIndex = curProbe; - do { - final long arrVal = hashTable[curProbe]; - if (arrVal == EMPTY) { - hashTable[curProbe] = hash; - return curProbe; - } - curProbe = (curProbe + stride) & arrayMask; - } while (curProbe != loopIndex); - throw new SketchesArgumentException("No empty slot in table!"); - } - - /** - * This is a classical Knuth-style Open Addressing, Double Hash (OADH) insert scheme for on-heap. - * Returns index ≥ 0 if found (duplicate); < 0 if inserted, inserted at -(index + 1). - * Throws an exception if the value is not found and table has no empty slot. - * - * @param hashTable The hash table to insert into. Its size must be a power of 2. - * @param lgArrLongs The log_base2(hashTable.length). - * See lgArrLongs. - * @param hash The hash value to be potentially inserted into an empty slot only if it is not - * a duplicate of any other hash value in the table. It must not be zero. - * @return index ≥ 0 if found (duplicate); < 0 if inserted, inserted at -(index + 1). - */ - public static int hashSearchOrInsert(final long[] hashTable, final int lgArrLongs, - final long hash) { - final int arrayMask = (1 << lgArrLongs) - 1; // current Size -1 - final int stride = getStride(hash, lgArrLongs); - int curProbe = (int) (hash & arrayMask); - - // search for duplicate or zero - final int loopIndex = curProbe; - do { - final long arrVal = hashTable[curProbe]; - if (arrVal == EMPTY) { - hashTable[curProbe] = hash; // insert value - return ~curProbe; - } else if (arrVal == hash) { - return curProbe; // found a duplicate - } - curProbe = (curProbe + stride) & arrayMask; - } while (curProbe != loopIndex); - throw new SketchesArgumentException("Hash not found and no empty slots!"); - } - - /** - * Inserts the given long array into the given OADH hashTable of the target size, - * ignores duplicates and counts the values inserted. - * The hash values must not be negative, zero values and values ≥ thetaLong are ignored. - * The given hash table may have values, but they must have been inserted by this method or one - * of the other OADH insert methods in this class. - * This method performs additional checks against potentially invalid hash values or theta values. - * Returns the count of values actually inserted. - * - * @param srcArr the source hash array to be potentially inserted - * @param hashTable The hash table to insert into. Its size must be a power of 2. - * @param lgArrLongs The log_base2(hashTable.length). - * See lgArrLongs. - * @param thetaLong The theta value that all input hash values are compared against. - * It must greater than zero. - * See Theta Long - * @return the count of values actually inserted - */ - public static int hashArrayInsert(final long[] srcArr, final long[] hashTable, - final int lgArrLongs, final long thetaLong) { - int count = 0; - final int arrLen = srcArr.length; - checkThetaCorruption(thetaLong); - for (int i = 0; i < arrLen; i++ ) { // scan source array, build target array - final long hash = srcArr[i]; - checkHashCorruption(hash); - if (continueCondition(thetaLong, hash) ) { - continue; - } - if (hashSearchOrInsert(hashTable, lgArrLongs, hash) < 0) { - count++ ; - } - } - return count; - } - - //With MemorySegment - - /** - * This is a classical Knuth-style Open Addressing, Double Hash (OADH) search scheme for MemorySegment. - * Returns the index if found, -1 if not found. The input MemorySegment may be read only. - * - * @param seg The MemorySegment containing the hash table to search. - * The hash table portion must be a power of 2 in size. - * @param lgArrLongs The log_base2(hashTable.length). - * See lgArrLongs. - * @param hash The hash value to search for. Must not be zero. - * @param segOffsetBytes offset in the MemorySegment where the hashTable starts - * @return Current probe index if found, -1 if not found. - */ - public static int hashSearchMemorySegment(final MemorySegment seg, final int lgArrLongs, final long hash, - final int segOffsetBytes) { - if (hash == 0) { - throw new SketchesArgumentException("Given hash must not be zero: " + hash); - } - final int arrayMask = (1 << lgArrLongs) - 1; - final int stride = getStride(hash, lgArrLongs); - int curProbe = (int) (hash & arrayMask); - final int loopIndex = curProbe; - do { - final int curProbeOffsetBytes = (curProbe << 3) + segOffsetBytes; - final long curArrayHash = seg.get(JAVA_LONG_UNALIGNED, curProbeOffsetBytes); - if (curArrayHash == EMPTY) { return -1; } - else if (curArrayHash == hash) { return curProbe; } - curProbe = (curProbe + stride) & arrayMask; - } while (curProbe != loopIndex); - return -1; - } - - /** - * This is a classical Knuth-style Open Addressing, Double Hash (OADH) insert scheme for MemorySegment. - * This method assumes that the input hash is not a duplicate. - * Useful for rebuilding tables to avoid unnecessary comparisons. - * Returns the index of insertion, which is always positive or zero. - * Throws an exception if table has no empty slot. - * - * @param wseg The writable MemorySegment that contains the hashTable to insert into. - * The size of the hashTable portion must be a power of 2. - * @param lgArrLongs The log_base2(hashTable.length. - * See lgArrLongs. - * @param hash value that must not be zero and will be inserted into the array into an empty slot. - * @param segOffsetBytes offset in the writable MemorySegment where the hashTable starts - * @return index of insertion. Always positive or zero. - */ - public static int hashInsertOnlyMemorySegment(final MemorySegment wseg, final int lgArrLongs, - final long hash, final int segOffsetBytes) { - final int arrayMask = (1 << lgArrLongs) - 1; // current Size -1 - final int stride = getStride(hash, lgArrLongs); - int curProbe = (int) (hash & arrayMask); - // search for duplicate or zero - final int loopIndex = curProbe; - do { - final int curProbeOffsetBytes = (curProbe << 3) + segOffsetBytes; - final long curArrayHash = wseg.get(JAVA_LONG_UNALIGNED, curProbeOffsetBytes); - if (curArrayHash == EMPTY) { - wseg.set(JAVA_LONG_UNALIGNED, curProbeOffsetBytes, hash); - return curProbe; - } - curProbe = (curProbe + stride) & arrayMask; - } while (curProbe != loopIndex); - throw new SketchesArgumentException("No empty slot in table!"); - } - - /** - * This is a classical Knuth-style Open Addressing, Double Hash insert scheme, but inserts - * values directly into a writable MemorySegment. - * Returns index ≥ 0 if found (duplicate); < 0 if inserted, inserted at -(index + 1). - * Throws an exception if the value is not found and table has no empty slot. - * - * @param wseg The writable MemorySegment that contains the hashTable to insert into. - * @param lgArrLongs The log_base2(hashTable.length). - * See lgArrLongs. - * @param hash The hash value to be potentially inserted into an empty slot only if it is not - * a duplicate of any other hash value in the table. It must not be zero. - * @param segOffsetBytes offset in the writable MemorySegment where the hash array starts - * @return index ≥ 0 if found (duplicate); < 0 if inserted, inserted at -(index + 1). - */ - public static int hashSearchOrInsertMemorySegment(final MemorySegment wseg, final int lgArrLongs, - final long hash, final int segOffsetBytes) { - final int arrayMask = (1 << lgArrLongs) - 1; // current Size -1 - final int stride = getStride(hash, lgArrLongs); - int curProbe = (int) (hash & arrayMask); - // search for duplicate or zero - final int loopIndex = curProbe; - do { - final int curProbeOffsetBytes = (curProbe << 3) + segOffsetBytes; - final long curArrayHash = wseg.get(JAVA_LONG_UNALIGNED, curProbeOffsetBytes); - if (curArrayHash == EMPTY) { - wseg.set(JAVA_LONG_UNALIGNED, curProbeOffsetBytes, hash); - return ~curProbe; - } else if (curArrayHash == hash) { return curProbe; } // curArrayHash is a duplicate - // curArrayHash is not a duplicate and not zero, continue searching - curProbe = (curProbe + stride) & arrayMask; - } while (curProbe != loopIndex); - throw new SketchesArgumentException("Key not found and no empty slot in table!"); - } - - //Other related methods - - /** - * Checks that the given theta is not negative nor zero. - * @param thetaLong must be greater than zero otherwise throws an exception. - * See Theta Long - */ - public static void checkThetaCorruption(final long thetaLong) { - //if any one of the groups go negative it fails. - if (( thetaLong | (thetaLong - 1) ) < 0L ) { - throw new SketchesStateException( - "Data Corruption: thetaLong was negative or zero: " + "ThetaLong: " + thetaLong); - } - } - - /** - * Checks that the given hash value is not negative. - * @param hash must be greater than -1 otherwise throws an exception. - * Note a hash of zero is normally ignored, but a negative hash is never allowed. - */ - public static void checkHashCorruption(final long hash) { - if ( hash < 0L ) { - throw new SketchesArgumentException( - "Data Corruption: hash was negative: " + "Hash: " + hash); - } - } - - /** - * Return true (continue) if hash is greater than or equal to thetaLong, or if hash == 0, - * or if hash == Long.MAX_VALUE. - * @param thetaLong must be greater than the hash value - * See Theta Long - * @param hash must be less than thetaLong and not less than or equal to zero. - * @return true (continue) if hash is greater than or equal to thetaLong, or if hash == 0, - * or if hash == Long.MAX_VALUE. - */ - public static boolean continueCondition(final long thetaLong, final long hash) { - //if any one of the groups go negative it returns true - return (( (hash - 1L) | (thetaLong - hash - 1L)) < 0L ); - } - - /** - * Converts the given array to a hash table. - * @param hashArr The given array of hashes. Gaps are OK. - * @param count The number of valid hashes in the array - * @param thetaLong Any hashes equal to or greater than thetaLong will be ignored - * @param rebuildThreshold The fill fraction for the hash table forcing a rebuild or resize. - * @return a HashTable - */ - public static long[] convertToHashTable( - final long[] hashArr, - final int count, - final long thetaLong, - final double rebuildThreshold) { - final int lgArrLongs = minLgHashTableSize(count, rebuildThreshold); - final int arrLongs = 1 << lgArrLongs; - final long[] hashTable = new long[arrLongs]; - hashArrayInsert(hashArr, hashTable, lgArrLongs, thetaLong); - return hashTable; - } - - /** - * Returns the smallest log hash table size given the count of items and the rebuild threshold. - * @param count the given count of items - * @param rebuild_threshold the rebuild threshold as a fraction between zero and one. - * @return the smallest log hash table size - */ - public static int minLgHashTableSize(final int count, final double rebuild_threshold) { - final int upperCount = (int) Math.ceil(count / rebuild_threshold); - final int arrLongs = max(ceilingPowerOf2(upperCount), 1 << ThetaUtil.MIN_LG_ARR_LONGS); - final int newLgArrLongs = Integer.numberOfTrailingZeros(arrLongs); - return newLgArrLongs; - } - - /** - * Counts the cardinality of the first Log2 values of the given source array. - * @param srcArr the given source array - * @param lgArrLongs See lgArrLongs - * @param thetaLong See Theta Long - * @return the cardinality - */ - public static int countPart(final long[] srcArr, final int lgArrLongs, final long thetaLong) { - int cnt = 0; - final int len = 1 << lgArrLongs; - for (int i = len; i-- > 0;) { - final long hash = srcArr[i]; - if (continueCondition(thetaLong, hash) ) { - continue; - } - cnt++ ; - } - return cnt; - } - - /** - * Counts the cardinality of the given source array. - * @param srcArr the given source array - * @param thetaLong See Theta Long - * @return the cardinality - */ - public static int count(final long[] srcArr, final long thetaLong) { - int cnt = 0; - final int len = srcArr.length; - for (int i = len; i-- > 0;) { - final long hash = srcArr[i]; - if (continueCondition(thetaLong, hash) ) { - continue; - } - cnt++ ; - } - return cnt; - } - -} diff --git a/src/main/java/org/apache/datasketches/thetacommon/SetOperationCornerCases.java b/src/main/java/org/apache/datasketches/thetacommon/SetOperationCornerCases.java deleted file mode 100644 index d77496bc2..000000000 --- a/src/main/java/org/apache/datasketches/thetacommon/SetOperationCornerCases.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Simplifies and speeds up set operations by resolving specific corner cases. - * @author Lee Rhodes - */ - -public class SetOperationCornerCases { - private static final long MAX = Long.MAX_VALUE; - - /** - * No argument constructor. - */ - public SetOperationCornerCases() { } - - /** Intersection actions */ - public enum IntersectAction { - /** Degenerate{MinTheta, 0, F} */ - DEGEN_MIN_0_F("D", "Degenerate{MinTheta, 0, F}"), - /** Empty{1.0, 0, T */ - EMPTY_1_0_T("E", "Empty{1.0, 0, T}"), - /** Full Intersect */ - FULL_INTERSECT("I", "Full Intersect"); - - private String actionId; - private String actionDescription; - - private IntersectAction(final String actionId, final String actionDescription) { - this.actionId = actionId; - this.actionDescription = actionDescription; - } - - /** - * Gets the Action ID - * @return the actionId - */ - public String getActionId() { - return actionId; - } - - /** - * Gets the Action Description - * @return the actionDescription - */ - public String getActionDescription() { - return actionDescription; - } - } - - /** A not B actions */ - public enum AnotbAction { - /** Sketch A Exact */ - SKETCH_A("A", "Sketch A Exactly"), - /** Trim Sketch A by MinTheta */ - TRIM_A("TA", "Trim Sketch A by MinTheta"), - /** Degenerate{MinTheta, 0, F} */ - DEGEN_MIN_0_F("D", "Degenerate{MinTheta, 0, F}"), - /** Degenerate{ThetaA, 0, F} */ - DEGEN_THA_0_F("DA", "Degenerate{ThetaA, 0, F}"), - /** Empty{1.0, 0, T} */ - EMPTY_1_0_T("E", "Empty{1.0, 0, T}"), - /** Full AnotB */ - FULL_ANOTB("N", "Full AnotB"); - - private String actionId; - private String actionDescription; - - private AnotbAction(final String actionId, final String actionDescription) { - this.actionId = actionId; - this.actionDescription = actionDescription; - } - - /** - * Gets the Action ID - * @return the actionId - */ - public String getActionId() { - return actionId; - } - - /** - * Gets the action description - * @return the action description - */ - public String getActionDescription() { - return actionDescription; - } - } - - /** List of union actions */ - public enum UnionAction { - /** Sketch A Exactly */ - SKETCH_A("A", "Sketch A Exactly"), - /** Trim Sketch A by MinTheta */ - TRIM_A("TA", "Trim Sketch A by MinTheta"), - /** Sketch B Exactly */ - SKETCH_B("B", "Sketch B Exactly"), - /** Trim Sketch B by MinTheta */ - TRIM_B("TB", "Trim Sketch B by MinTheta"), - /** Degenerate{MinTheta, 0, F} */ - DEGEN_MIN_0_F("D", "Degenerate{MinTheta, 0, F}"), - /** Degenerate{ThetaA, 0, F} */ - DEGEN_THA_0_F("DA", "Degenerate{ThetaA, 0, F}"), - /** Degenerate{ThetaB, 0, F} */ - DEGEN_THB_0_F("DB", "Degenerate{ThetaB, 0, F}"), - /** Empty{1.0, 0, T} */ - EMPTY_1_0_T("E", "Empty{1.0, 0, T}"), - /** Full Union */ - FULL_UNION("N", "Full Union"); - - private String actionId; - private String actionDescription; - - private UnionAction(final String actionId, final String actionDescription) { - this.actionId = actionId; - this.actionDescription = actionDescription; - } - - /** - * Gets the action ID - * @return the actionId - */ - public String getActionId() { - return actionId; - } - - /** - * Gets the action description - * @return the actionDescription - */ - public String getActionDescription() { - return actionDescription; - } - } - - /** List of corner cases */ - public enum CornerCase { - /** Empty Empty */ - Empty_Empty(055, "A{ 1.0, 0, T} ; B{ 1.0, 0, T}", - IntersectAction.EMPTY_1_0_T, AnotbAction.EMPTY_1_0_T, UnionAction.EMPTY_1_0_T), - /** Empty Exact */ - Empty_Exact(056, "A{ 1.0, 0, T} ; B{ 1.0,>0, F}", - IntersectAction.EMPTY_1_0_T, AnotbAction.EMPTY_1_0_T, UnionAction.SKETCH_B), - /** Empty Estimation */ - Empty_Estimation(052, "A{ 1.0, 0, T} ; B{<1.0,>0, F", - IntersectAction.EMPTY_1_0_T, AnotbAction.EMPTY_1_0_T, UnionAction.SKETCH_B), - /** Empty Degen */ - Empty_Degen(050, "A{ 1.0, 0, T} ; B{<1.0, 0, F}", - IntersectAction.EMPTY_1_0_T, AnotbAction.EMPTY_1_0_T, UnionAction.DEGEN_THB_0_F), - - /** Exact Empty */ - Exact_Empty(065, "A{ 1.0,>0, F} ; B{ 1.0, 0, T}", - IntersectAction.EMPTY_1_0_T, AnotbAction.SKETCH_A, UnionAction.SKETCH_A), - /** Exact Exact */ - Exact_Exact(066, "A{ 1.0,>0, F} ; B{ 1.0,>0, F}", - IntersectAction.FULL_INTERSECT, AnotbAction.FULL_ANOTB, UnionAction.FULL_UNION), - /** Exact Estimation */ - Exact_Estimation(062, "A{ 1.0,>0, F} ; B{<1.0,>0, F}", - IntersectAction.FULL_INTERSECT, AnotbAction.FULL_ANOTB, UnionAction.FULL_UNION), - /** Exact Degen */ - Exact_Degen(060, "A{ 1.0,>0, F} ; B{<1.0, 0, F}", - IntersectAction.DEGEN_MIN_0_F, AnotbAction.TRIM_A, UnionAction.TRIM_A), - - /** Estimation_Empty */ - Estimation_Empty(025, "A{<1.0,>0, F} ; B{ 1.0, 0, T}", - IntersectAction.EMPTY_1_0_T, AnotbAction.SKETCH_A, UnionAction.SKETCH_A), - /** Estimation_Exact */ - Estimation_Exact(026, "A{<1.0,>0, F} ; B{ 1.0,>0, F}", - IntersectAction.FULL_INTERSECT, AnotbAction.FULL_ANOTB, UnionAction.FULL_UNION), - /** Estimation_Estimation */ - Estimation_Estimation(022, "A{<1.0,>0, F} ; B{<1.0,>0, F}", - IntersectAction.FULL_INTERSECT, AnotbAction.FULL_ANOTB, UnionAction.FULL_UNION), - /** Estimation_Degen */ - Estimation_Degen(020, "A{<1.0,>0, F} ; B{<1.0, 0, F}", - IntersectAction.DEGEN_MIN_0_F, AnotbAction.TRIM_A, UnionAction.TRIM_A), - - /** Degen_Empty */ - Degen_Empty(005, "A{<1.0, 0, F} ; B{ 1.0, 0, T}", - IntersectAction.EMPTY_1_0_T, AnotbAction.DEGEN_THA_0_F, UnionAction.DEGEN_THA_0_F), - /** Degen_Exact */ - Degen_Exact(006, "A{<1.0, 0, F} ; B{ 1.0,>0, F}", - IntersectAction.DEGEN_MIN_0_F, AnotbAction.DEGEN_THA_0_F, UnionAction.TRIM_B), - /** Degen_Estimation */ - Degen_Estimation(002, "A{<1.0, 0, F} ; B{<1.0,>0, F}", - IntersectAction.DEGEN_MIN_0_F, AnotbAction.DEGEN_MIN_0_F, UnionAction.TRIM_B), - /** Degen_Degen */ - Degen_Degen(000, "A{<1.0, 0, F} ; B{<1.0, 0, F}", - IntersectAction.DEGEN_MIN_0_F, AnotbAction.DEGEN_MIN_0_F, UnionAction.DEGEN_MIN_0_F); - - private static final Map caseIdToCornerCaseMap = new HashMap<>(); - private int caseId; - private String caseDescription; - private IntersectAction intersectAction; - private AnotbAction anotbAction; - private UnionAction unionAction; - - static { - for (final CornerCase cc : values()) { - caseIdToCornerCaseMap.put(cc.getId(), cc); - } - } - - private CornerCase(final int caseId, final String caseDescription, - final IntersectAction intersectAction, final AnotbAction anotbAction, final UnionAction unionAction) { - this.caseId = caseId; - this.caseDescription = caseDescription; - this.intersectAction = intersectAction; - this.anotbAction = anotbAction; - this.unionAction = unionAction; - } - - /** - * Gets the case ID - * @return the caseId - */ - public int getId() { - return caseId; - } - - /** - * Gets the case description - * @return the caseDescription - */ - public String getCaseDescription() { - return caseDescription; - } - - /** - * Gets the intersect action - * @return the intersectAction - */ - public IntersectAction getIntersectAction() { - return intersectAction; - } - - /** - * Gets the AnotB action - * @return the anotbAction - */ - public AnotbAction getAnotbAction() { - return anotbAction; - } - - /** - * Gets the union action - * @return the unionAction - */ - public UnionAction getUnionAction() { - return unionAction; - } - - //See checkById test in /tuple/MiscTest. - /** - * Converts caseId to CornerCaseId - * @param id the case ID - * @return the Corner Case ID - */ - public static CornerCase caseIdToCornerCase(final int id) { - final CornerCase cc = caseIdToCornerCaseMap.get(id); - if (cc == null) { - throw new SketchesArgumentException("Possible Corruption: Illegal CornerCase ID: " + Integer.toOctalString(id)); - } - return cc; - } - } //end of enum CornerCase - - /** - * Creates the CornerCase ID - * @param thetaLongA the theta of A as a long - * @param countA the count of A - * @param emptyA true if A is empty - * @param thetaLongB the theta of B as a long - * @param countB the count of B - * @param emptyB true if B is empty - * @return the Corner Case ID - */ - public static int createCornerCaseId( - final long thetaLongA, final int countA, final boolean emptyA, - final long thetaLongB, final int countB, final boolean emptyB) { - return (sketchStateId(emptyA, countA, thetaLongA) << 3) | sketchStateId(emptyB, countB, thetaLongB); - } - - /** - * Returns the sketch state ID - * @param isEmpty true if empty - * @param numRetained the number of items retained - * @param thetaLong the value of theta as a long - * @return the sketch state ID - */ - public static int sketchStateId(final boolean isEmpty, final int numRetained, final long thetaLong) { - // assume thetaLong = MAX if empty - return (((thetaLong == MAX) || isEmpty) ? 4 : 0) | ((numRetained > 0) ? 2 : 0) | (isEmpty ? 1 : 0); - } -} diff --git a/src/main/java/org/apache/datasketches/thetacommon/ThetaUtil.java b/src/main/java/org/apache/datasketches/thetacommon/ThetaUtil.java deleted file mode 100644 index 778dc02f2..000000000 --- a/src/main/java/org/apache/datasketches/thetacommon/ThetaUtil.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; - -/** - * Utility methods for the Theta Family of sketches - * @author Lee Rhodes - * - */ -public final class ThetaUtil { - - /** - * The smallest Log2 nom entries allowed: 4. - */ - public static final int MIN_LG_NOM_LONGS = 4; - /** - * The largest Log2 nom entries allowed: 26. - */ - public static final int MAX_LG_NOM_LONGS = 26; - /** - * The hash table rebuild threshold = 15.0/16.0. - */ - public static final double REBUILD_THRESHOLD = 15.0 / 16.0; - /** - * The resize threshold = 0.5; tuned for speed. - */ - public static final double RESIZE_THRESHOLD = 0.5; - /** - * The default nominal entries is provided as a convenience for those cases where the - * nominal sketch size in number of entries is not provided. - * A sketch of 4096 entries has a Relative Standard Error (RSE) of +/- 1.56% at a confidence of - * 68%; or equivalently, a Relative Error of +/- 3.1% at a confidence of 95.4%. - * See Default Nominal Entries - */ - public static final int DEFAULT_NOMINAL_ENTRIES = 4096; - - private ThetaUtil() {} - - /** - * The smallest Log2 cache size allowed: 5. - */ - public static final int MIN_LG_ARR_LONGS = 5; - - /** - * Gets the smallest allowed exponent of 2 that it is a sub-multiple of the target by zero, - * one or more resize factors. - * - * @param lgTarget Log2 of the target size - * @param lgRF Log_base2 of Resize Factor. - * See Resize Factor - * @param lgMin Log2 of the minimum allowed starting size - * @return The Log2 of the starting size - */ - public static int startingSubMultiple(final int lgTarget, final int lgRF, final int lgMin) { - return lgTarget <= lgMin ? lgMin : lgRF == 0 ? lgTarget : (lgTarget - lgMin) % lgRF + lgMin; - } - - /** - * Checks that the given nomLongs is within bounds and returns the Log2 of the ceiling power of 2 - * of the given nomLongs. - * @param nomLongs the given number of nominal longs. This can be any value from 16 to - * 67108864, inclusive. - * @return The Log2 of the ceiling power of 2 of the given nomLongs. - */ - public static int checkNomLongs(final int nomLongs) { - final int lgNomLongs = Integer.numberOfTrailingZeros(Util.ceilingPowerOf2(nomLongs)); - if (lgNomLongs > MAX_LG_NOM_LONGS || lgNomLongs < MIN_LG_NOM_LONGS) { - throw new SketchesArgumentException("Nominal Entries must be >= 16 and <= 67108864: " - + nomLongs); - } - return lgNomLongs; - } - -} - diff --git a/src/main/java/org/apache/datasketches/thetacommon/package-info.java b/src/main/java/org/apache/datasketches/thetacommon/package-info.java deleted file mode 100644 index 52cc8dc45..000000000 --- a/src/main/java/org/apache/datasketches/thetacommon/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package contains common tools and methods for the theta, - * tuple, tuple/* and fdt packages. - */ -package org.apache.datasketches.thetacommon; diff --git a/src/main/java/org/apache/datasketches/tuple/CompactTupleSketch.java b/src/main/java/org/apache/datasketches/tuple/CompactTupleSketch.java deleted file mode 100644 index 030eae7e5..000000000 --- a/src/main/java/org/apache/datasketches/tuple/CompactTupleSketch.java +++ /dev/null @@ -1,251 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.thetacommon.HashOperations.count; - -import java.lang.foreign.MemorySegment; -import java.lang.reflect.Array; - -import org.apache.datasketches.common.ByteArrayUtil; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * CompactTupleSketches are never created directly. They are created as a result of - * the compact() method of an UpdatableTupleSketch or as a result of the getResult() - * method of a set operation like TupleUnion, TupleIntersection or TupleAnotB. - * CompactTupleSketch consists of a compact list (i.e. no intervening spaces) of hash values, - * corresponding list of Summaries, and a value for theta. The lists may or may - * not be ordered. CompactTupleSketch is read-only. - * - * @param type of Summary - */ -public final class CompactTupleSketch extends TupleSketch { - private static final byte serialVersionWithSummaryClassNameUID = 1; - private static final byte serialVersionUIDLegacy = 2; - private static final byte serialVersionUID = 3; - private static final short defaultSeedHash = (short) 37836; // for compatibility with C++ - private final long[] hashArr_; - private S[] summaryArr_; - - private enum FlagsLegacy { IS_BIG_ENDIAN, IS_EMPTY, HAS_ENTRIES, IS_THETA_INCLUDED } - - private enum Flags { IS_RESERVED, IS_READ_ONLY, IS_EMPTY, IS_COMPACT, IS_ORDERED } - - /** - * Create a CompactTupleSketch from correct components - * @param hashArr compacted hash array - * @param summaryArr compacted summary array - * @param thetaLong long value of theta - * @param empty empty flag - */ - CompactTupleSketch(final long[] hashArr, final S[] summaryArr, final long thetaLong, final boolean empty) { - super(thetaLong, empty, null); - super.thetaLong_ = thetaLong; - super.empty_ = empty; - hashArr_ = hashArr; - summaryArr_ = summaryArr; - } - - /** - * This is to create an instance of a CompactTupleSketch given a serialized form - * - * @param seg MemorySegment object with serialized CompactTupleSketch - * @param deserializer the SummaryDeserializer - */ - CompactTupleSketch(final MemorySegment seg, final SummaryDeserializer deserializer) { - super(Long.MAX_VALUE, true, null); - int offset = 0; - final byte preambleLongs = seg.get(JAVA_BYTE, offset++); - final byte version = seg.get(JAVA_BYTE, offset++); - final byte familyId = seg.get(JAVA_BYTE, offset++); - SerializerDeserializer.validateFamily(familyId, preambleLongs); - if (version > serialVersionUID) { - throw new SketchesArgumentException( - "Unsupported serial version. Expected: " + serialVersionUID + " or lower, actual: " + version); - } - SerializerDeserializer - .validateType(seg.get(JAVA_BYTE, offset++), SerializerDeserializer.SketchType.CompactTupleSketch); - if (version <= serialVersionUIDLegacy) { // legacy serial format - final byte flags = seg.get(JAVA_BYTE, offset++); - empty_ = (flags & (1 << FlagsLegacy.IS_EMPTY.ordinal())) > 0; - final boolean isThetaIncluded = (flags & (1 << FlagsLegacy.IS_THETA_INCLUDED.ordinal())) > 0; - if (isThetaIncluded) { - thetaLong_ = seg.get(JAVA_LONG_UNALIGNED, offset); - offset += Long.BYTES; - } else { - thetaLong_ = Long.MAX_VALUE; - } - final boolean hasEntries = (flags & (1 << FlagsLegacy.HAS_ENTRIES.ordinal())) > 0; - if (hasEntries) { - int classNameLength = 0; - if (version == serialVersionWithSummaryClassNameUID) { - classNameLength = seg.get(JAVA_BYTE, offset++); - } - final int count = seg.get(JAVA_INT_UNALIGNED, offset); - offset += Integer.BYTES; - if (version == serialVersionWithSummaryClassNameUID) { - offset += classNameLength; - } - hashArr_ = new long[count]; - - for (int i = 0; i < count; i++) { - hashArr_[i] = seg.get(JAVA_LONG_UNALIGNED, offset); - offset += Long.BYTES; - } - for (int i = 0; i < count; i++) { - offset += readSummary(seg, offset, i, count, deserializer); - } - } else { - hashArr_ = new long[0]; - summaryArr_ = null; - } - } else { // current serial format - offset++; //skip unused byte - final byte flags = seg.get(JAVA_BYTE, offset++); - offset += 2; //skip 2 unused bytes - empty_ = (flags & (1 << Flags.IS_EMPTY.ordinal())) > 0; - thetaLong_ = Long.MAX_VALUE; - int count = 0; - if (!empty_) { - if (preambleLongs == 1) { - count = 1; - } else { - count = seg.get(JAVA_INT_UNALIGNED, offset); - offset += Integer.BYTES; - offset += 4; // unused - if (preambleLongs > 2) { - thetaLong_ = seg.get(JAVA_LONG_UNALIGNED, offset); - offset += Long.BYTES; - } - } - } - hashArr_ = new long[count]; - - for (int i = 0; i < count; i++) { - hashArr_[i] = seg.get(JAVA_LONG_UNALIGNED, offset); - offset += Long.BYTES; - offset += readSummary(seg, offset, i, count, deserializer); - } - } - } - - @SuppressWarnings({"unchecked"}) - private int readSummary(final MemorySegment seg, final int offset, final int i, final int count, - final SummaryDeserializer deserializer) { - final MemorySegment segRegion = seg.asSlice(offset, seg.byteSize() - offset); - final DeserializeResult result = deserializer.heapifySummary(segRegion); - final S summary = result.getObject(); - final Class summaryType = (Class) result.getObject().getClass(); - if (summaryArr_ == null) { - summaryArr_ = (S[]) Array.newInstance(summaryType, count); - } - summaryArr_[i] = summary; - return result.getSize(); - } - - @Override - public CompactTupleSketch compact() { - return this; - } - - long[] getHashArr() { - return hashArr_; - } - - S[] getSummaryArr() { - return summaryArr_; - } - - @Override - public int getRetainedEntries() { - return hashArr_ == null ? 0 : hashArr_.length; - } - - @Override - public int getCountLessThanThetaLong(final long thetaLong) { - return count(hashArr_, thetaLong); - } - - // Layout of first 8 bytes: - // Long || Start Byte Adr: - // Adr: - // || 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | - // 0 || seed hash | Flags | unused | SkType | FamID | SerVer | Preamble_Longs | - @Override - public byte[] toByteArray() { - final int count = getRetainedEntries(); - final boolean isSingleItem = (count == 1) && !isEstimationMode(); - final int preambleLongs = isEmpty() || isSingleItem ? 1 : isEstimationMode() ? 3 : 2; - - int summariesSizeBytes = 0; - final byte[][] summariesBytes = new byte[count][]; - if (count > 0) { - for (int i = 0; i < count; i++) { - summariesBytes[i] = summaryArr_[i].toByteArray(); - summariesSizeBytes += summariesBytes[i].length; - } - } - - final int sizeBytes = (Long.BYTES * preambleLongs) + (Long.BYTES * count) + summariesSizeBytes; - final byte[] bytes = new byte[sizeBytes]; - int offset = 0; - bytes[offset++] = (byte) preambleLongs; - bytes[offset++] = serialVersionUID; - bytes[offset++] = (byte) Family.TUPLE.getID(); - bytes[offset++] = (byte) SerializerDeserializer.SketchType.CompactTupleSketch.ordinal(); - offset++; // unused - bytes[offset++] = (byte) ( - (1 << Flags.IS_COMPACT.ordinal()) - | (1 << Flags.IS_READ_ONLY.ordinal()) - | (isEmpty() ? 1 << Flags.IS_EMPTY.ordinal() : 0) - ); - ByteArrayUtil.putShortLE(bytes, offset, defaultSeedHash); - offset += Short.BYTES; - if (!isEmpty()) { - if (!isSingleItem) { - ByteArrayUtil.putIntLE(bytes, offset, count); - offset += Integer.BYTES; - offset += 4; // unused - if (isEstimationMode()) { - ByteArrayUtil.putLongLE(bytes, offset, thetaLong_); - offset += Long.BYTES; - } - } - } - for (int i = 0; i < count; i++) { - ByteArrayUtil.putLongLE(bytes, offset, hashArr_[i]); - offset += Long.BYTES; - System.arraycopy(summariesBytes[i], 0, bytes, offset, summariesBytes[i].length); - offset += summariesBytes[i].length; - } - return bytes; - } - - @Override - public TupleSketchIterator iterator() { - return new TupleSketchIterator<>(hashArr_, summaryArr_); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/DeserializeResult.java b/src/main/java/org/apache/datasketches/tuple/DeserializeResult.java deleted file mode 100644 index db8ad682b..000000000 --- a/src/main/java/org/apache/datasketches/tuple/DeserializeResult.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -/** - * Returns an object and its size in bytes as a result of a deserialize operation - * @param Type of object - */ -public class DeserializeResult { - private final T object; - private final int size; - - /** - * Creates an instance. - * @param object Deserialized object. - * @param size Deserialized size in bytes. - */ - public DeserializeResult(final T object, final int size) { - this.object = object; - this.size = size; - } - - /** - * Returns Deserialized object - * @return Deserialized object - */ - public T getObject() { - return object; - } - - /** - * Returns size in bytes occupied by the object in the serialized form - * @return size in bytes occupied by the object in the serialized form - */ - public int getSize() { - return size; - } -} diff --git a/src/main/java/org/apache/datasketches/tuple/Filter.java b/src/main/java/org/apache/datasketches/tuple/Filter.java deleted file mode 100644 index 8706043c1..000000000 --- a/src/main/java/org/apache/datasketches/tuple/Filter.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import java.lang.reflect.Array; -import java.util.Arrays; -import java.util.function.Predicate; - -/** - * Class for filtering entries from a {@link TupleSketch} given a {@link Summary} - * - * @param Summary type against which apply the {@link Predicate} - */ -public class Filter { - private final Predicate predicate; - - /** - * Filter constructor with a {@link Predicate} - * @param predicate Predicate to use in this filter. If the Predicate returns False, the - * element is discarded. If the Predicate returns True, then the element is kept in the - * {@link TupleSketch} - */ - public Filter(final Predicate predicate) { - this.predicate = predicate; - } - - /** - * Filters elements on the provided {@link TupleSketch} - * - * @param sketchIn The sketch against which to apply the {@link Predicate} - * @return A new CompactTupleSketch with some of the entries filtered out based on the {@link Predicate} - */ - @SuppressWarnings("unchecked") - public CompactTupleSketch filter(final TupleSketch sketchIn) { - if (sketchIn == null) { - return new CompactTupleSketch<>(null, null, Long.MAX_VALUE, true); - } - final long[] hashes = new long[sketchIn.getRetainedEntries()]; - T[] summaries = null; // lazy init to get class from the first entry - int i = 0; - final TupleSketchIterator it = sketchIn.iterator(); - while (it.next()) { - final T summary = it.getSummary(); - if (predicate.test(summary)) { - hashes[i] = it.getHash(); - if (summaries == null) { - summaries = (T[]) Array.newInstance(summary.getClass(), sketchIn.getRetainedEntries()); - } - summaries[i++] = (T) summary.copy(); - } - } - final boolean isEmpty = i == 0 && !sketchIn.isEstimationMode(); - if (i == 0) { - return new CompactTupleSketch<>(null, null, sketchIn.getThetaLong(), isEmpty); - } - return new CompactTupleSketch<>(Arrays.copyOf(hashes, i), Arrays.copyOf(summaries, i), sketchIn.getThetaLong(), isEmpty); - } -} - diff --git a/src/main/java/org/apache/datasketches/tuple/HashTables.java b/src/main/java/org/apache/datasketches/tuple/HashTables.java deleted file mode 100644 index 877ce3d55..000000000 --- a/src/main/java/org/apache/datasketches/tuple/HashTables.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static java.lang.Math.ceil; -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.thetacommon.HashOperations.hashInsertOnly; -import static org.apache.datasketches.thetacommon.HashOperations.hashSearch; - -import java.lang.reflect.Array; - -import org.apache.datasketches.theta.HashIterator; -import org.apache.datasketches.theta.ThetaSketch; -import org.apache.datasketches.thetacommon.ThetaUtil; - -@SuppressWarnings("unchecked") -class HashTables { - long[] hashTable = null; - S[] summaryTable = null; - int lgTableSize = 0; - int numKeys = 0; - - HashTables() { } - - //must have valid entries - void fromSketch(final TupleSketch sketch) { - numKeys = sketch.getRetainedEntries(); - lgTableSize = getLgTableSize(numKeys); - - hashTable = new long[1 << lgTableSize]; - final TupleSketchIterator it = sketch.iterator(); - while (it.next()) { - final long hash = it.getHash(); - final int index = hashInsertOnly(hashTable, lgTableSize, hash); - final S mySummary = (S)it.getSummary().copy(); - if (summaryTable == null) { - summaryTable = (S[]) Array.newInstance(mySummary.getClass(), 1 << lgTableSize); - } - summaryTable[index] = mySummary; - } - } - - //must have valid entries - void fromSketch(final ThetaSketch sketch, final S summary) { - numKeys = sketch.getRetainedEntries(true); - lgTableSize = getLgTableSize(numKeys); - - hashTable = new long[1 << lgTableSize]; - final HashIterator it = sketch.iterator(); - while (it.next()) { - final long hash = it.get(); - final int index = hashInsertOnly(hashTable, lgTableSize, hash); - final S mySummary = (S)summary.copy(); - if (summaryTable == null) { - summaryTable = (S[]) Array.newInstance(mySummary.getClass(), 1 << lgTableSize); - } - summaryTable[index] = mySummary; - } - } - - private void fromArrays(final long[] hashArr, final S[] summaryArr, final int count) { - numKeys = count; - lgTableSize = getLgTableSize(count); - - summaryTable = null; - hashTable = new long[1 << lgTableSize]; - for (int i = 0; i < count; i++) { - final long hash = hashArr[i]; - final int index = hashInsertOnly(hashTable, lgTableSize, hash); - final S mySummary = summaryArr[i]; - if (summaryTable == null) { - summaryTable = (S[]) Array.newInstance(mySummary.getClass(), 1 << lgTableSize); - } - summaryTable[index] = summaryArr[i]; - } - } - - //For TupleSketches - HashTables getIntersectHashTables( - final TupleSketch nextTupleSketch, - final long thetaLong, - final SummarySetOperations summarySetOps) { - - //Match nextSketch data with local instance data, filtering by theta - final int maxMatchSize = min(numKeys, nextTupleSketch.getRetainedEntries()); - final long[] matchHashArr = new long[maxMatchSize]; - final S[] matchSummariesArr = Util.newSummaryArray(summaryTable, maxMatchSize); - int matchCount = 0; - final TupleSketchIterator it = nextTupleSketch.iterator(); - - while (it.next()) { - final long hash = it.getHash(); - if (hash >= thetaLong) { continue; } - final int index = hashSearch(hashTable, lgTableSize, hash); - if (index < 0) { continue; } - //Copy the intersecting items from local hashTables_ - // sequentially into local matchHashArr_ and matchSummaries_ - matchHashArr[matchCount] = hash; - matchSummariesArr[matchCount] = summarySetOps.intersection(summaryTable[index], it.getSummary()); - matchCount++; - } - final HashTables resultHT = new HashTables<>(); - resultHT.fromArrays(matchHashArr, matchSummariesArr, matchCount); - return resultHT; - } - - //For ThetaSketches - HashTables getIntersectHashTables( - final ThetaSketch nextThetaSketch, - final long thetaLong, - final SummarySetOperations summarySetOps, - final S summary) { - - final Class summaryType = (Class) summary.getClass(); - - //Match nextSketch data with local instance data, filtering by theta - final int maxMatchSize = min(numKeys, nextThetaSketch.getRetainedEntries()); - final long[] matchHashArr = new long[maxMatchSize]; - final S[] matchSummariesArr = (S[]) Array.newInstance(summaryType, maxMatchSize); - int matchCount = 0; - final HashIterator it = nextThetaSketch.iterator(); - - //scan B & search A(hashTable) for match - while (it.next()) { - final long hash = it.get(); - if (hash >= thetaLong) { continue; } - final int index = hashSearch(hashTable, lgTableSize, hash); - if (index < 0) { continue; } - //Copy the intersecting items from local hashTables_ - // sequentially into local matchHashArr_ and matchSummaries_ - matchHashArr[matchCount] = hash; - matchSummariesArr[matchCount] = summarySetOps.intersection(summaryTable[index], summary); - matchCount++; - } - final HashTables resultHT = new HashTables<>(); - resultHT.fromArrays(matchHashArr, matchSummariesArr, matchCount); - return resultHT; - } - - void clear() { - hashTable = null; - summaryTable = null; - lgTableSize = 0; - numKeys = 0; - } - - static int getLgTableSize(final int count) { - final int tableSize = max(ceilingPowerOf2((int) ceil(count / 0.75)), 1 << ThetaUtil.MIN_LG_NOM_LONGS); - return Integer.numberOfTrailingZeros(tableSize); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/JaccardSimilarity.java b/src/main/java/org/apache/datasketches/tuple/JaccardSimilarity.java deleted file mode 100644 index bc0c1e5b3..000000000 --- a/src/main/java/org/apache/datasketches/tuple/JaccardSimilarity.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA; -import static org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA; -import static org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.theta.ThetaSketch; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * Jaccard similarity of two TupleSketches, or alternatively, of a TupleSketch and a ThetaSketch. - * - *

Note: only retained hash values are compared, and the Tuple summary values are not accounted for in the - * similarity measure.

- * - * @author Lee Rhodes - * @author David Cromberge - */ -public final class JaccardSimilarity { - private static final double[] ZEROS = {0.0, 0.0, 0.0}; // LB, Estimate, UB - private static final double[] ONES = {1.0, 1.0, 1.0}; - - /** - * No argument constructor. - */ - public JaccardSimilarity() { } - - /** - * Computes the Jaccard similarity index with upper and lower bounds. The Jaccard similarity index - * J(A,B) = (A ^ B)/(A U B) is used to measure how similar the two sketches are to each - * other. If J = 1.0, the sketches are considered equal. If J = 0, the two sketches are - * distinct from each other. A Jaccard of .95 means the overlap between the two - * populations is 95% of the union of the two populations. - * - *

Note: For very large pairs of sketches, where the configured nominal entries of the sketches - * are 2^25 or 2^26, this method may produce unpredictable results. - * - * @param sketchA The first argument, a TupleSketch with summary type S - * @param sketchB The second argument, a TupleSketch with summary type S - * @param summarySetOps instance of SummarySetOperations used to unify or intersect summaries. - * @param Summary - * @return a double array {LowerBound, Estimate, UpperBound} of the Jaccard index. - * The Upper and Lower bounds are for a confidence interval of 95.4% or +/- 2 standard deviations. - */ - public static double[] jaccard( - final TupleSketch sketchA, - final TupleSketch sketchB, - final SummarySetOperations summarySetOps) { - //Corner case checks - if (sketchA == null || sketchB == null) { return ZEROS.clone(); } - if (sketchA.isEmpty() && sketchB.isEmpty()) { return ONES.clone(); } - if (sketchA.isEmpty() || sketchB.isEmpty()) { return ZEROS.clone(); } - - final int countA = sketchA.getRetainedEntries(); - final int countB = sketchB.getRetainedEntries(); - - //Create the TupleUnion - final int minK = 1 << ThetaUtil.MIN_LG_NOM_LONGS; - final int maxK = 1 << ThetaUtil.MAX_LG_NOM_LONGS; - final int newK = max(min(ceilingPowerOf2(countA + countB), maxK), minK); - final TupleUnion union = new TupleUnion<>(newK, summarySetOps); - union.union(sketchA); - union.union(sketchB); - - final TupleSketch unionAB = union.getResult(); - final long thetaLongUAB = unionAB.getThetaLong(); - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - final int countUAB = unionAB.getRetainedEntries(); - - //Check for identical data - if (countUAB == countA && countUAB == countB - && thetaLongUAB == thetaLongA && thetaLongUAB == thetaLongB) { - return ONES.clone(); - } - - //Create the TupleIntersection - final TupleIntersection inter = new TupleIntersection<>(summarySetOps); - inter.intersect(sketchA); - inter.intersect(sketchB); - inter.intersect(unionAB); //ensures that intersection is a subset of the union - final TupleSketch interABU = inter.getResult(); - - final double lb = getLowerBoundForBoverA(unionAB, interABU); - final double est = getEstimateOfBoverA(unionAB, interABU); - final double ub = getUpperBoundForBoverA(unionAB, interABU); - return new double[] {lb, est, ub}; - } - - /** - * Computes the Jaccard similarity index with upper and lower bounds. The Jaccard similarity index - * J(A,B) = (A ^ B)/(A U B) is used to measure how similar the two sketches are to each - * other. If J = 1.0, the sketches are considered equal. If J = 0, the two sketches are - * distinct from each other. A Jaccard of .95 means the overlap between the two - * populations is 95% of the union of the two populations. - * - *

Note: For very large pairs of sketches, where the configured nominal entries of the sketches - * are 2^25 or 2^26, this method may produce unpredictable results. - * - * @param sketchA The first argument, a TupleSketch with summary type S - * @param sketchB The second argument, a ThetaSketch - * @param summary the given proxy summary for the ThetaSketch, which doesn't have one. - * This may not be null. - * @param summarySetOps instance of SummarySetOperations used to unify or intersect summaries. - * @param Summary - * @return a double array {LowerBound, Estimate, UpperBound} of the Jaccard index. - * The Upper and Lower bounds are for a confidence interval of 95.4% or +/- 2 standard deviations. - */ - public static double[] jaccard( - final TupleSketch sketchA, - final ThetaSketch sketchB, - final S summary, final SummarySetOperations summarySetOps) { - // Null case checks - if (summary == null) { - throw new SketchesArgumentException("Summary cannot be null."); } - - //Corner case checks - if (sketchA == null || sketchB == null) { return ZEROS.clone(); } - if (sketchA.isEmpty() && sketchB.isEmpty()) { return ONES.clone(); } - if (sketchA.isEmpty() || sketchB.isEmpty()) { return ZEROS.clone(); } - - final int countA = sketchA.getRetainedEntries(); - final int countB = sketchB.getRetainedEntries(true); - - //Create the Tuple/Theta Union - final int minK = 1 << ThetaUtil.MIN_LG_NOM_LONGS; - final int maxK = 1 << ThetaUtil.MAX_LG_NOM_LONGS; - final int newK = max(min(ceilingPowerOf2(countA + countB), maxK), minK); - final TupleUnion union = new TupleUnion<>(newK, summarySetOps); - union.union(sketchA); - union.union(sketchB, summary); - - final TupleSketch unionAB = union.getResult(); - final long thetaLongUAB = unionAB.getThetaLong(); - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - final int countUAB = unionAB.getRetainedEntries(); - - //Check for identical data - if (countUAB == countA && countUAB == countB - && thetaLongUAB == thetaLongA && thetaLongUAB == thetaLongB) { - return ONES.clone(); - } - - //Create the Tuple/Theta Intersection - final TupleIntersection inter = new TupleIntersection<>(summarySetOps); - inter.intersect(sketchA); - inter.intersect(sketchB, summary); - inter.intersect(unionAB); //ensures that intersection is a subset of the union - final TupleSketch interABU = inter.getResult(); - - final double lb = getLowerBoundForBoverA(unionAB, interABU); - final double est = getEstimateOfBoverA(unionAB, interABU); - final double ub = getUpperBoundForBoverA(unionAB, interABU); - return new double[] {lb, est, ub}; - } - - /** - * Returns true if the two given sketches have exactly the same hash values and the same - * theta values. Thus, they are equivalent. - * @param sketchA The first argument, a TupleSketch with summary type S - * @param sketchB The second argument, a TupleSketch with summary type S - * @param summarySetOps instance of SummarySetOperations used to unify or intersect summaries. - * @param Summary - * @return true if the two given sketches have exactly the same hash values and the same - * theta values. - */ - public static boolean exactlyEqual( - final TupleSketch sketchA, - final TupleSketch sketchB, - final SummarySetOperations summarySetOps) { - //Corner case checks - if (sketchA == null || sketchB == null) { return false; } - if (sketchA == sketchB) { return true; } - if (sketchA.isEmpty() && sketchB.isEmpty()) { return true; } - if (sketchA.isEmpty() || sketchB.isEmpty()) { return false; } - - final int countA = sketchA.getRetainedEntries(); - final int countB = sketchB.getRetainedEntries(); - - //Create the TupleUnion - final TupleUnion union = new TupleUnion<>(ceilingPowerOf2(countA + countB), summarySetOps); - union.union(sketchA); - union.union(sketchB); - final TupleSketch unionAB = union.getResult(); - final long thetaLongUAB = unionAB.getThetaLong(); - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - final int countUAB = unionAB.getRetainedEntries(); - - //Check for identical counts and thetas - if (countUAB == countA && countUAB == countB - && thetaLongUAB == thetaLongA && thetaLongUAB == thetaLongB) { - return true; - } - return false; - } - - /** - * Returns true if the two given sketches have exactly the same hash values and the same - * theta values. Thus, they are equivalent. - * @param sketchA The first argument, a TupleSketch with summary type S - * @param sketchB The second argument, a ThetaSketch - * @param summary the given proxy summary for the ThetaSketch, which doesn't have one. - * This may not be null. - * @param summarySetOps instance of SummarySetOperations used to unify or intersect summaries. - * @param Summary - * @return true if the two given sketches have exactly the same hash values and the same - * theta values. - */ - public static boolean exactlyEqual( - final TupleSketch sketchA, - final ThetaSketch sketchB, - final S summary, final SummarySetOperations summarySetOps) { - // Null case checks - if (summary == null) { - throw new SketchesArgumentException("Summary cannot be null."); } - - //Corner case checks - if (sketchA == null || sketchB == null) { return false; } - if (sketchA.isEmpty() && sketchB.isEmpty()) { return true; } - if (sketchA.isEmpty() || sketchB.isEmpty()) { return false; } - - final int countA = sketchA.getRetainedEntries(); - final int countB = sketchB.getRetainedEntries(true); - - //Create the TupleUnion - final TupleUnion union = new TupleUnion<>(ceilingPowerOf2(countA + countB), summarySetOps); - union.union(sketchA); - union.union(sketchB, summary); - final TupleSketch unionAB = union.getResult(); - final long thetaLongUAB = unionAB.getThetaLong(); - final long thetaLongA = sketchA.getThetaLong(); - final long thetaLongB = sketchB.getThetaLong(); - final int countUAB = unionAB.getRetainedEntries(); - - //Check for identical counts and thetas - if (countUAB == countA && countUAB == countB - && thetaLongUAB == thetaLongA && thetaLongUAB == thetaLongB) { - return true; - } - return false; - } - - /** - * Tests similarity of a measured TupleSketch against an expected TupleSketch. - * Computes the lower bound of the Jaccard index JLB of the measured and - * expected sketches. - * if JLB ≥ threshold, then the sketches are considered to be - * similar with a confidence of 97.7%. - * - * @param measured a TupleSketch with summary type S to be tested - * @param expected the reference TupleSketch with summary type S that is considered to be correct. - * @param summarySetOps instance of SummarySetOperations used to unify or intersect summaries. - * @param threshold a real value between zero and one. - * @param Summary - * @return if true, the similarity of the two sketches is greater than the given threshold - * with at least 97.7% confidence. - */ - public static boolean similarityTest( - final TupleSketch measured, final TupleSketch expected, - final SummarySetOperations summarySetOps, - final double threshold) { - //index 0: the lower bound - //index 1: the mean estimate - //index 2: the upper bound - final double jRatioLB = jaccard(measured, expected, summarySetOps)[0]; //choosing the lower bound - return jRatioLB >= threshold; - } - - /** - * Tests similarity of a measured TupleSketch against an expected ThetaSketch. - * Computes the lower bound of the Jaccard index JLB of the measured and - * expected sketches. - * if JLB ≥ threshold, then the sketches are considered to be - * similar with a confidence of 97.7%. - * - * @param measured a TupleSketch with summary type S to be tested - * @param expected the reference ThetaSketch that is considered to be correct. - * @param summary the given proxy summary for the ThetaSketch, which doesn't have one. - * This may not be null. - * @param summarySetOps instance of SummarySetOperations used to unify or intersect summaries. - * @param threshold a real value between zero and one. - * @param Summary - * @return if true, the similarity of the two sketches is greater than the given threshold - * with at least 97.7% confidence. - */ - public static boolean similarityTest( - final TupleSketch measured, final ThetaSketch expected, - final S summary, final SummarySetOperations summarySetOps, - final double threshold) { - //index 0: the lower bound - //index 1: the mean estimate - //index 2: the upper bound - final double jRatioLB = jaccard(measured, expected, summary, summarySetOps)[0]; //choosing the lower bound - return jRatioLB >= threshold; - } - - /** - * Tests dissimilarity of a measured TupleSketch against an expected TupleSketch. - * Computes the upper bound of the Jaccard index JUB of the measured and - * expected sketches. - * if JUB ≤ threshold, then the sketches are considered to be - * dissimilar with a confidence of 97.7%. - * - * @param measured a TupleSketch with summary type S to be tested - * @param expected the reference TupleSketch that is considered to be correct. - * @param summarySetOps instance of SummarySetOperations used to unify or intersect summaries. - * @param threshold a real value between zero and one. - * @param Summary - * @return if true, the dissimilarity of the two sketches is greater than the given threshold - * with at least 97.7% confidence. - */ - public static boolean dissimilarityTest( - final TupleSketch measured, final TupleSketch expected, - final SummarySetOperations summarySetOps, - final double threshold) { - //index 0: the lower bound - //index 1: the mean estimate - //index 2: the upper bound - final double jRatioUB = jaccard(measured, expected, summarySetOps)[2]; //choosing the upper bound - return jRatioUB <= threshold; - } - - /** - * Tests dissimilarity of a measured TupleSketch against an expected ThetaSketch. - * Computes the upper bound of the Jaccard index JUB of the measured and - * expected sketches. - * if JUB ≤ threshold, then the sketches are considered to be - * dissimilar with a confidence of 97.7%. - * - * @param measured a TupleSketch with summary type S to be tested - * @param expected the reference ThetaSketch that is considered to be correct. - * @param summary the given proxy summary for the ThetaSketch, which doesn't have one. - * This may not be null. - * @param summarySetOps instance of SummarySetOperations used to unify or intersect summaries. - * @param threshold a real value between zero and one. - * @param Summary - * @return if true, the dissimilarity of the two sketches is greater than the given threshold - * with at least 97.7% confidence. - */ - public static boolean dissimilarityTest( - final TupleSketch measured, final ThetaSketch expected, - final S summary, final SummarySetOperations summarySetOps, - final double threshold) { - //index 0: the lower bound - //index 1: the mean estimate - //index 2: the upper bound - final double jRatioUB = jaccard(measured, expected, summary, summarySetOps)[2]; //choosing the upper bound - return jRatioUB <= threshold; - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/QuickSelectSketch.java b/src/main/java/org/apache/datasketches/tuple/QuickSelectSketch.java deleted file mode 100644 index 64548d6c1..000000000 --- a/src/main/java/org/apache/datasketches/tuple/QuickSelectSketch.java +++ /dev/null @@ -1,602 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.common.Util.checkBounds; -import static org.apache.datasketches.common.Util.exactLog2OfLong; -import static org.apache.datasketches.thetacommon.HashOperations.count; - -import java.lang.foreign.MemorySegment; -import java.lang.reflect.Array; -import java.util.Objects; - -import org.apache.datasketches.common.ByteArrayUtil; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.QuickSelect; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.thetacommon.HashOperations; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * A generic tuple sketch using the QuickSelect algorithm. - * - * @param type of Summary - */ -class QuickSelectSketch extends TupleSketch { - private static final byte serialVersionUID = 2; - - private enum Flags { IS_RESERVED, IS_IN_SAMPLING_MODE, IS_EMPTY, HAS_ENTRIES, IS_THETA_INCLUDED } - - private static final int DEFAULT_LG_RESIZE_FACTOR = ResizeFactor.X8.lg(); - private final int nomEntries_; - private final int lgResizeFactor_; - private final float samplingProbability_; - private int lgCurrentCapacity_; - private int retEntries_; - private int rebuildThreshold_; - private long[] hashTable_; - S[] summaryTable_; - - /** - * This is to create a new instance of a QuickSelectSketch with default resize factor. - * @param nomEntries Nominal number of entries. Forced to the nearest power of 2 greater than - * given value. - * @param summaryFactory An instance of a SummaryFactory. - */ - QuickSelectSketch( - final int nomEntries, - final SummaryFactory summaryFactory) { - this(nomEntries, DEFAULT_LG_RESIZE_FACTOR, summaryFactory); - } - - /** - * This is to create a new instance of a QuickSelectSketch with custom resize factor - * @param nomEntries Nominal number of entries. Forced to the nearest power of 2 greater than - * given value. - * @param lgResizeFactor log2(resizeFactor) - value from 0 to 3: - *

-   * 0 - no resizing (max size allocated),
-   * 1 - double internal hash table each time it reaches a threshold
-   * 2 - grow four times
-   * 3 - grow eight times (default)
-   * 
- * @param summaryFactory An instance of a SummaryFactory. - */ - QuickSelectSketch( - final int nomEntries, - final int lgResizeFactor, - final SummaryFactory summaryFactory) { - this(nomEntries, lgResizeFactor, 1f, summaryFactory); - } - - /** - * This is to create a new instance of a QuickSelectSketch with custom resize factor and sampling - * probability - * @param nomEntries Nominal number of entries. Forced to the nearest power of 2 greater than - * or equal to the given value. - * @param lgResizeFactor log2(resizeFactor) - value from 0 to 3: - *
-   * 0 - no resizing (max size allocated),
-   * 1 - double internal hash table each time it reaches a threshold
-   * 2 - grow four times
-   * 3 - grow eight times (default)
-   * 
- * @param samplingProbability the given sampling probability - * @param summaryFactory An instance of a SummaryFactory. - */ - QuickSelectSketch( - final int nomEntries, - final int lgResizeFactor, - final float samplingProbability, - final SummaryFactory summaryFactory) { - this( - nomEntries, - lgResizeFactor, - samplingProbability, - summaryFactory, - Util.getStartingCapacity(nomEntries, lgResizeFactor) - ); - } - - /** - * Target constructor for above constructors for a new instance. - * @param nomEntries Nominal number of entries. - * @param lgResizeFactor log2(resizeFactor) - * @param samplingProbability the given sampling probability - * @param summaryFactory An instance of a SummaryFactory. - * @param startingSize starting size of the sketch. - */ - private QuickSelectSketch( - final int nomEntries, - final int lgResizeFactor, - final float samplingProbability, - final SummaryFactory summaryFactory, - final int startingSize) { - final long thetaLong = (long) (Long.MAX_VALUE * (double) samplingProbability); - super( - thetaLong, - true, - summaryFactory); - nomEntries_ = ceilingPowerOf2(nomEntries); - lgResizeFactor_ = lgResizeFactor; - samplingProbability_ = samplingProbability; - lgCurrentCapacity_ = Integer.numberOfTrailingZeros(startingSize); - retEntries_ = 0; - hashTable_ = new long[startingSize]; //must be before setRebuildThreshold - rebuildThreshold_ = setRebuildThreshold(hashTable_, nomEntries_); - summaryTable_ = null; // wait for the first summary to call Array.newInstance() - } - - /** - * Copy constructor - * @param sketch the QuickSelectSketch to be deep copied. - */ - QuickSelectSketch(final QuickSelectSketch sketch) { - super( - sketch.thetaLong_, - sketch.empty_, - sketch.summaryFactory_); - nomEntries_ = sketch.nomEntries_; - lgResizeFactor_ = sketch.lgResizeFactor_; - samplingProbability_ = sketch.samplingProbability_; - lgCurrentCapacity_ = sketch.lgCurrentCapacity_; - retEntries_ = sketch.retEntries_; - hashTable_ = sketch.hashTable_.clone(); - rebuildThreshold_ = sketch.rebuildThreshold_; - summaryTable_ = Util.copySummaryArray(sketch.summaryTable_); - } - - /** - * This is to create an instance of a QuickSelectSketch given a serialized form - * @param seg MemorySegment object with serialized QuickSelectSketch - * @param deserializer the SummaryDeserializer - * @param summaryFactory the SummaryFactory - * @deprecated As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. - * This capability will be removed in a future release. - * Heapifying a CompactTupleSketch is not deprecated. - */ - @Deprecated - QuickSelectSketch( - final MemorySegment seg, - final SummaryDeserializer deserializer, - final SummaryFactory summaryFactory) { - //this(new Validate<>(), seg, deserializer, summaryFactory); - final Validate val = new Validate<>(); - final long thetaLong = val.validate(seg, deserializer); - nomEntries_ = val.myNomEntries; - lgResizeFactor_ = val.myLgResizeFactor; - samplingProbability_ = val.mySamplingProbability; - lgCurrentCapacity_ = val.myLgCurrentCapacity; - retEntries_ = val.myRetEntries; - rebuildThreshold_ = val.myRebuildThreshold; - hashTable_ = val.myHashTable; - summaryTable_ = val.mySummaryTable; - super(thetaLong, val.myEmpty, summaryFactory); - } - - private static final class Validate { - //super fields - long myThetaLong; - boolean myEmpty; - //this fields - int myNomEntries; - int myLgResizeFactor; - float mySamplingProbability; - int myLgCurrentCapacity; - int myRetEntries; - int myRebuildThreshold; - long[] myHashTable; - S[] mySummaryTable; - - @SuppressWarnings("unchecked") - long validate( - final MemorySegment seg, - final SummaryDeserializer deserializer) { - Objects.requireNonNull(seg, "Source MemorySegment must not be null."); - Objects.requireNonNull(deserializer, "Deserializer must not be null."); - checkBounds(0, 8, seg.byteSize()); - - int offset = 0; - final byte preambleLongs = seg.get(JAVA_BYTE, offset++); //byte 0 PreLongs - final byte version = seg.get(JAVA_BYTE, offset++); //byte 1 SerVer - final byte familyId = seg.get(JAVA_BYTE, offset++); //byte 2 FamID - SerializerDeserializer.validateFamily(familyId, preambleLongs); - if (version > serialVersionUID) { - throw new SketchesArgumentException( - "Unsupported serial version. Expected: " + serialVersionUID + " or lower, actual: " - + version); - } - SerializerDeserializer.validateType(seg.get(JAVA_BYTE, offset++), //byte 3 - SerializerDeserializer.SketchType.QuickSelectSketch); - final byte flags = seg.get(JAVA_BYTE, offset++); //byte 4 - myNomEntries = 1 << seg.get(JAVA_BYTE, offset++); //byte 5 - myLgCurrentCapacity = seg.get(JAVA_BYTE, offset++); //byte 6 - myLgResizeFactor = seg.get(JAVA_BYTE, offset++); //byte 7 - - checkBounds(0, preambleLongs * 8L, seg.byteSize()); - final boolean isInSamplingMode = (flags & (1 << Flags.IS_IN_SAMPLING_MODE.ordinal())) > 0; - mySamplingProbability = isInSamplingMode ? seg.get(JAVA_FLOAT_UNALIGNED, offset) : 1f; //bytes 8 - 11 - if (isInSamplingMode) { - offset += Float.BYTES; - } - - final boolean isThetaIncluded = (flags & (1 << Flags.IS_THETA_INCLUDED.ordinal())) > 0; - if (isThetaIncluded) { - myThetaLong = seg.get(JAVA_LONG_UNALIGNED, offset); - offset += Long.BYTES; - } else { - myThetaLong = (long) (Long.MAX_VALUE * (double) mySamplingProbability); - } - - int count = 0; - final boolean hasEntries = (flags & (1 << Flags.HAS_ENTRIES.ordinal())) > 0; - if (hasEntries) { - count = seg.get(JAVA_INT_UNALIGNED, offset); - offset += Integer.BYTES; - } - final int currentCapacity = 1 << myLgCurrentCapacity; - myHashTable = new long[currentCapacity]; - for (int i = 0; i < count; i++) { - final long hash = seg.get(JAVA_LONG_UNALIGNED, offset); - offset += Long.BYTES; - final MemorySegment segRegion = seg.asSlice(offset, seg.byteSize() - offset); - final DeserializeResult summaryResult = deserializer.heapifySummary(segRegion); - final S summary = (S) summaryResult.getObject(); - offset += summaryResult.getSize(); - //in-place equivalent to insert(hash, summary): - final int index = HashOperations.hashInsertOnly(myHashTable, myLgCurrentCapacity, hash); - if (mySummaryTable == null) { - mySummaryTable = (S[]) Array.newInstance(summary.getClass(), myHashTable.length); - } - mySummaryTable[index] = summary; - myRetEntries++; - myEmpty = false; - } - myEmpty = (flags & (1 << Flags.IS_EMPTY.ordinal())) > 0; - myRebuildThreshold = setRebuildThreshold(myHashTable, myNomEntries); - return myThetaLong; - } - - } //end class Validate - - /** - * @return a deep copy of this sketch - */ - QuickSelectSketch copy() { - return new QuickSelectSketch<>(this); - } - - long[] getHashTable() { - return hashTable_; - } - - @Override - public int getRetainedEntries() { - return retEntries_; - } - - @Override - public int getCountLessThanThetaLong(final long thetaLong) { - return count(hashTable_, thetaLong); - } - - S[] getSummaryTable() { - return summaryTable_; - } - - /** - * Get configured nominal number of entries - * @return nominal number of entries - */ - public int getNominalEntries() { - return nomEntries_; - } - - /** - * Get log_base2 of Nominal Entries - * @return log_base2 of Nominal Entries - */ - public int getLgK() { - return exactLog2OfLong(nomEntries_); - } - - /** - * Get configured sampling probability - * @return sampling probability - */ - public float getSamplingProbability() { - return samplingProbability_; - } - - /** - * Get current capacity - * @return current capacity - */ - public int getCurrentCapacity() { - return 1 << lgCurrentCapacity_; - } - - /** - * Get configured resize factor - * @return resize factor - */ - public ResizeFactor getResizeFactor() { - return ResizeFactor.getRF(lgResizeFactor_); - } - - /** - * Rebuilds reducing the actual number of entries to the nominal number of entries if needed - */ - public void trim() { - if (retEntries_ > nomEntries_) { - updateTheta(); - resize(hashTable_.length); - } - } - - /** - * Resets this sketch an empty state. - */ - public void reset() { - empty_ = true; - retEntries_ = 0; - thetaLong_ = (long) (Long.MAX_VALUE * (double) samplingProbability_); - final int startingCapacity = Util.getStartingCapacity(nomEntries_, lgResizeFactor_); - lgCurrentCapacity_ = Integer.numberOfTrailingZeros(startingCapacity); - hashTable_ = new long[startingCapacity]; - summaryTable_ = null; // wait for the first summary to call Array.newInstance() - rebuildThreshold_ = setRebuildThreshold(hashTable_, nomEntries_); - } - - /** - * Converts the current state of the sketch into a compact sketch - * @return compact sketch - */ - @Override - @SuppressWarnings("unchecked") - public CompactTupleSketch compact() { - if (getRetainedEntries() == 0) { - if (empty_) { return new CompactTupleSketch<>(null, null, Long.MAX_VALUE, true); } - return new CompactTupleSketch<>(null, null, thetaLong_, false); - } - final long[] hashArr = new long[getRetainedEntries()]; - final S[] summaryArr = Util.newSummaryArray(summaryTable_, getRetainedEntries()); - int i = 0; - for (int j = 0; j < hashTable_.length; j++) { - if (summaryTable_[j] != null) { - hashArr[i] = hashTable_[j]; - summaryArr[i] = (S)summaryTable_[j].copy(); - i++; - } - } - return new CompactTupleSketch<>(hashArr, summaryArr, thetaLong_, empty_); - } - - // Layout of first 8 bytes: - // Long || Start Byte Adr: - // Adr: - // || 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | - // 0 || RF | lgArr | lgNom | Flags | SkType | FamID | SerVer | Preamble_Longs | - /** - * This serializes an UpdatableTupleSketch (QuickSelectSketch). - * @return serialized representation of an UpdatableTupleSketch (QuickSelectSketch). - * @deprecated As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. - * This capability will be removed in a future release. - * Serializing a CompactTupleSketch is not deprecated. - */ - @Deprecated - @Override - public byte[] toByteArray() { - byte[][] summariesBytes = null; - int summariesBytesLength = 0; - if (retEntries_ > 0) { - summariesBytes = new byte[retEntries_][]; - int i = 0; - for (int j = 0; j < summaryTable_.length; j++) { - if (summaryTable_[j] != null) { - summariesBytes[i] = summaryTable_[j].toByteArray(); - summariesBytesLength += summariesBytes[i].length; - i++; - } - } - } - int sizeBytes = - Byte.BYTES // preamble longs - + Byte.BYTES // serial version - + Byte.BYTES // family - + Byte.BYTES // sketch type - + Byte.BYTES // flags - + Byte.BYTES // log2(nomEntries) - + Byte.BYTES // log2(currentCapacity) - + Byte.BYTES; // log2(resizeFactor) - if (isInSamplingMode()) { - sizeBytes += Float.BYTES; // samplingProbability - } - final boolean isThetaIncluded = isInSamplingMode() - ? thetaLong_ < samplingProbability_ : thetaLong_ < Long.MAX_VALUE; - if (isThetaIncluded) { - sizeBytes += Long.BYTES; - } - if (retEntries_ > 0) { - sizeBytes += Integer.BYTES; // count - } - sizeBytes += (Long.BYTES * retEntries_) + summariesBytesLength; - final byte[] bytes = new byte[sizeBytes]; - int offset = 0; - bytes[offset++] = PREAMBLE_LONGS; - bytes[offset++] = serialVersionUID; - bytes[offset++] = (byte) Family.TUPLE.getID(); - bytes[offset++] = (byte) SerializerDeserializer.SketchType.QuickSelectSketch.ordinal(); - bytes[offset++] = (byte) ( - (isInSamplingMode() ? 1 << Flags.IS_IN_SAMPLING_MODE.ordinal() : 0) - | (empty_ ? 1 << Flags.IS_EMPTY.ordinal() : 0) - | (retEntries_ > 0 ? 1 << Flags.HAS_ENTRIES.ordinal() : 0) - | (isThetaIncluded ? 1 << Flags.IS_THETA_INCLUDED.ordinal() : 0) - ); - bytes[offset++] = (byte) Integer.numberOfTrailingZeros(nomEntries_); - bytes[offset++] = (byte) lgCurrentCapacity_; - bytes[offset++] = (byte) lgResizeFactor_; - if (samplingProbability_ < 1f) { - ByteArrayUtil.putFloatLE(bytes, offset, samplingProbability_); - offset += Float.BYTES; - } - if (isThetaIncluded) { - ByteArrayUtil.putLongLE(bytes, offset, thetaLong_); - offset += Long.BYTES; - } - if (retEntries_ > 0) { - ByteArrayUtil.putIntLE(bytes, offset, retEntries_); - offset += Integer.BYTES; - } - if (retEntries_ > 0) { - int i = 0; - for (int j = 0; j < hashTable_.length; j++) { - if (summaryTable_[j] != null) { - ByteArrayUtil.putLongLE(bytes, offset, hashTable_[j]); - offset += Long.BYTES; - System.arraycopy(summariesBytes[i], 0, bytes, offset, summariesBytes[i].length); - offset += summariesBytes[i].length; - i++; - } - } - } - return bytes; - } - - // non-public methods below - - // this is a special back door insert for merging - // not sufficient by itself without keeping track of theta of another sketch - @SuppressWarnings("unchecked") - void merge(final long hash, final S summary, final SummarySetOperations summarySetOps) { - empty_ = false; - if ((hash > 0) && (hash < thetaLong_)) { - final int index = findOrInsert(hash); - if (index < 0) { - insertSummary(~index, (S)summary.copy()); //did not find, so insert - } else { - insertSummary(index, summarySetOps.union(summaryTable_[index], (S) summary.copy())); - } - rebuildIfNeeded(); - } - } - - boolean isInSamplingMode() { - return samplingProbability_ < 1f; - } - - void setThetaLong(final long theta) { - thetaLong_ = theta; - } - - void setEmpty(final boolean value) { - empty_ = value; - } - - int findOrInsert(final long hash) { - final int index = HashOperations.hashSearchOrInsert(hashTable_, lgCurrentCapacity_, hash); - if (index < 0) { - retEntries_++; - } - return index; - } - - boolean rebuildIfNeeded() { - if (retEntries_ <= rebuildThreshold_) { - return false; - } - if (hashTable_.length > nomEntries_) { - updateTheta(); - rebuild(); - } else { - resize(hashTable_.length * (1 << lgResizeFactor_)); - } - return true; - } - - void rebuild() { - resize(hashTable_.length); - } - - void insert(final long hash, final S summary) { - final int index = HashOperations.hashInsertOnly(hashTable_, lgCurrentCapacity_, hash); - insertSummary(index, summary); - retEntries_++; - empty_ = false; - } - - private void updateTheta() { - final long[] hashArr = new long[retEntries_]; - int i = 0; - //Because of the association of the hashTable with the summaryTable we cannot destroy the - // hashTable structure. So we must copy. May as well compact at the same time. - // Might consider a whole table clone and use the selectExcludingZeros method instead. - // Not sure if there would be any speed advantage. - for (int j = 0; j < hashTable_.length; j++) { - if (summaryTable_[j] != null) { - hashArr[i++] = hashTable_[j]; - } - } - thetaLong_ = QuickSelect.select(hashArr, 0, retEntries_ - 1, nomEntries_); - } - - private void resize(final int newSize) { - final long[] oldHashTable = hashTable_; - final S[] oldSummaryTable = summaryTable_; - hashTable_ = new long[newSize]; - summaryTable_ = Util.newSummaryArray(summaryTable_, newSize); - lgCurrentCapacity_ = Integer.numberOfTrailingZeros(newSize); - retEntries_ = 0; - for (int i = 0; i < oldHashTable.length; i++) { - if ((oldSummaryTable[i] != null) && (oldHashTable[i] < thetaLong_)) { - insert(oldHashTable[i], oldSummaryTable[i]); - } - } - rebuildThreshold_ = setRebuildThreshold(hashTable_, nomEntries_); - } - - private static int setRebuildThreshold(final long[] hashTable, final int nomEntries) { - if (hashTable.length > nomEntries) { - return (int) (hashTable.length * ThetaUtil.REBUILD_THRESHOLD); - } else { - return (int) (hashTable.length * ThetaUtil.RESIZE_THRESHOLD); - } - } - - @SuppressWarnings("unchecked") - protected void insertSummary(final int index, final S summary) { - if (summaryTable_ == null) { - summaryTable_ = (S[]) Array.newInstance(summary.getClass(), hashTable_.length); - } - summaryTable_[index] = summary; - } - - @Override - public TupleSketchIterator iterator() { - return new TupleSketchIterator<>(hashTable_, summaryTable_); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/SerializerDeserializer.java b/src/main/java/org/apache/datasketches/tuple/SerializerDeserializer.java deleted file mode 100644 index 6088e2022..000000000 --- a/src/main/java/org/apache/datasketches/tuple/SerializerDeserializer.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Multipurpose serializer-deserializer for a collection of sketches defined by the enum. - */ -public final class SerializerDeserializer { - - /** - * No argument constructor. - */ - public SerializerDeserializer() { } - - /** - * Defines the sketch classes that this SerializerDeserializer can handle. - */ - public static enum SketchType { - /** QuickSelectSketch */ - QuickSelectSketch, - /** CompactTupleSketch */ - CompactTupleSketch, - /** ArrayOfDoublesQuickSelectSketch */ - ArrayOfDoublesQuickSelectSketch, - /** ArrayOfDoublesCompactSketch */ - ArrayOfDoublesCompactSketch, - /** ArrayOfDoublesUnion */ - ArrayOfDoublesUnion } - - static final int TYPE_BYTE_OFFSET = 3; - - /** - * Validates the preamble-Longs value given the family ID - * @param familyId the given family ID - * @param preambleLongs the given preambleLongs value - */ - public static void validateFamily(final byte familyId, final byte preambleLongs) { - final Family family = Family.idToFamily(familyId); - if (family.equals(Family.TUPLE)) { - if (preambleLongs < Family.TUPLE.getMinPreLongs() || preambleLongs > Family.TUPLE.getMaxPreLongs()) { - throw new SketchesArgumentException( - "Possible corruption: Invalid PreambleLongs value for family TUPLE: " + preambleLongs); - } - } else { - throw new SketchesArgumentException( - "Possible corruption: Invalid Family: " + family.toString()); - } - } - - /** - * Validates the sketch type byte versus the expected value - * @param sketchTypeByte the given sketch type byte - * @param expectedType the expected value - */ - public static void validateType(final byte sketchTypeByte, final SketchType expectedType) { - final SketchType sketchType = getSketchType(sketchTypeByte); - if (!sketchType.equals(expectedType)) { - throw new SketchesArgumentException("Sketch Type mismatch. Expected " + expectedType.name() - + ", got " + sketchType.name()); - } - } - - /** - * Gets the sketch type byte from the given MemorySegment image - * @param seg the given MemorySegment image - * @return the SketchType - */ - public static SketchType getSketchType(final MemorySegment seg) { - final byte sketchTypeByte = seg.get(JAVA_BYTE, TYPE_BYTE_OFFSET); - return getSketchType(sketchTypeByte); - } - - private static SketchType getSketchType(final byte sketchTypeByte) { - if ((sketchTypeByte < 0) || (sketchTypeByte >= SketchType.values().length)) { - throw new SketchesArgumentException("Invalid Sketch Type " + sketchTypeByte); - } - return SketchType.values()[sketchTypeByte]; - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/Summary.java b/src/main/java/org/apache/datasketches/tuple/Summary.java deleted file mode 100644 index 46e78a97a..000000000 --- a/src/main/java/org/apache/datasketches/tuple/Summary.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -/** - * Interface for user-defined Summary, which is associated with every hash in a tuple sketch - */ -public interface Summary { - - /** - * Deep copy. - * - *

Caution: This must implement a deep copy. - * - * @return deep copy of the Summary - */ - public Summary copy(); - - /** - * This is to serialize a Summary instance to a byte array. - * - *

The user should encode in the byte array its total size, which is used during - * deserialization, especially if the Summary has variable sized elements. - * - * @return serialized representation of the Summary - */ - public byte[] toByteArray(); - -} diff --git a/src/main/java/org/apache/datasketches/tuple/SummaryDeserializer.java b/src/main/java/org/apache/datasketches/tuple/SummaryDeserializer.java deleted file mode 100644 index 6393019b1..000000000 --- a/src/main/java/org/apache/datasketches/tuple/SummaryDeserializer.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import java.lang.foreign.MemorySegment; - -/** - * Interface for deserializing user-defined Summary - * @param type of Summary - */ -public interface SummaryDeserializer { - - /** - * This is to create an instance of a Summary given a serialized representation. - * The user may assume that the start of the given MemorySegment is the correct place to start - * deserializing. However, the user must be able to determine the number of bytes required to - * deserialize the summary as the capacity of the given MemorySegment may - * include multiple such summaries and may be much larger than required for a single summary. - * @param seg MemorySegment object with serialized representation of a Summary - * @return DeserializedResult object, which contains a Summary object and number of bytes read - * from the MemorySegment - */ - public DeserializeResult heapifySummary(MemorySegment seg); - -} diff --git a/src/main/java/org/apache/datasketches/tuple/SummaryFactory.java b/src/main/java/org/apache/datasketches/tuple/SummaryFactory.java deleted file mode 100644 index 5c5648f9d..000000000 --- a/src/main/java/org/apache/datasketches/tuple/SummaryFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -/** - * Interface for user-defined SummaryFactory - * @param type of Summary - */ -public interface SummaryFactory { - - /** - * Returns new instance of Summary - * @return new instance of Summary - */ - public S newSummary(); - -} diff --git a/src/main/java/org/apache/datasketches/tuple/SummarySetOperations.java b/src/main/java/org/apache/datasketches/tuple/SummarySetOperations.java deleted file mode 100644 index eac86a196..000000000 --- a/src/main/java/org/apache/datasketches/tuple/SummarySetOperations.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -/** - * This is to provide methods of producing unions and intersections of two Summary objects. - * @param type of Summary - */ -public interface SummarySetOperations { - - /** - * This is called by the union operator when both sketches have the same hash value. - * - *

Caution: Do not modify the input Summary objects. Also do not return them directly, - * unless they are immutable (most Summary objects are not). For mutable Summary objects, it is - * important to create a new Summary object with the correct contents to be returned. Do not - * return null summaries. - * - * @param a Summary from sketch A - * @param b Summary from sketch B - * @return union of Summary A and Summary B - */ - public S union(S a, S b); - - /** - * This is called by the intersection operator when both sketches have the same hash value. - * - *

Caution: Do not modify the input Summary objects. Also do not return them directly, - * unless they are immutable (most Summary objects are not). For mutable Summary objects, it is - * important to create a new Summary object with the correct contents to be returned. Do not - * return null summaries. - * - * @param a Summary from sketch A - * @param b Summary from sketch B - * @return intersection of Summary A and Summary B - */ - public S intersection(S a, S b); - -} diff --git a/src/main/java/org/apache/datasketches/tuple/TupleAnotB.java b/src/main/java/org/apache/datasketches/tuple/TupleAnotB.java deleted file mode 100644 index cdc6f18cf..000000000 --- a/src/main/java/org/apache/datasketches/tuple/TupleAnotB.java +++ /dev/null @@ -1,642 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static java.lang.Math.min; -import static org.apache.datasketches.common.Util.exactLog2OfLong; -import static org.apache.datasketches.thetacommon.HashOperations.convertToHashTable; -import static org.apache.datasketches.thetacommon.HashOperations.hashSearch; - -import java.lang.reflect.Method; -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.SuppressFBWarnings; -import org.apache.datasketches.theta.CompactThetaSketch; -import org.apache.datasketches.theta.ThetaSketch; -import org.apache.datasketches.thetacommon.SetOperationCornerCases; -import org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction; -import org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * Computes a set difference, A-AND-NOT-B, of two generic TupleSketches. - * This class includes both stateful and stateless operations. - * - *

The stateful operation is as in the following example:

- *

- * TupleAnotB anotb = new TupleAnotB();
- *
- * anotb.setA(TupleSketch skA); //The first argument.
- * anotb.notB(TupleSketch skB); //The second (subtraction) argument.
- * anotb.notB(TupleSketch skC); // ...any number of additional subtractions...
- * anotb.getResult(false); //Get an interim result.
- * anotb.notB(TupleSketch skD); //Additional subtractions.
- * anotb.getResult(true);  //Final result and resets the TupleAnotB operator.
- * 
- * - *

The stateless operation is as in the following example:

- *

- * TupleAnotB anotb = new TupleAnotB();
- *
- * CompactTupleSketch csk = anotb.aNotB(TupleSketch skA, TupleSketch skB);
- * 
- * - *

Calling the setA operation a second time essentially clears the internal state and loads - * the new sketch.

- * - *

The stateless and stateful operations are independent of each other.

- * - * @param Type of Summary - * - * @author Lee Rhodes - */ -public final class TupleAnotB { - private boolean empty_ = true; - private long thetaLong_ = Long.MAX_VALUE; - private long[] hashArr_ = null; //always in compact form, not necessarily sorted - private S[] summaryArr_ = null; //always in compact form, not necessarily sorted - private int curCount_ = 0; - - private static final Method GET_CACHE; - - static { - try { - GET_CACHE = ThetaSketch.class.getDeclaredMethod("getCache"); - GET_CACHE.setAccessible(true); - } catch (final Exception e) { - throw new SketchesStateException("Could not reflect getCache(): " + e); - } - } - - /** - * No argument constructor. - */ - public TupleAnotB() { } - - /** - * This is part of a multistep, stateful TupleAnotB operation and sets the given TupleSketch as the - * first argument A of A-AND-NOT-B. This overwrites the internal state of this - * TupleAnotB operator with the contents of the given sketch. - * This sets the stage for multiple following notB steps. - * - *

An input argument of null will throw an exception.

- * - *

Rationale: In mathematics a "null set" is a set with no members, which we call an empty set. - * That is distinctly different from the java null, which represents a nonexistent object. - * In most cases it is a programming error due to some object that was not properly initialized. - * With a null as the first argument, we cannot know what the user's intent is. - * Since it is very likely that a null is a programming error, we throw a an exception.

- * - *

An empty input argument will set the internal state to empty.

- * - *

Rationale: An empty set is a mathematically legal concept. Although it makes any subsequent, - * valid argument for B irrelevant, we must allow this and assume the user knows what they are - * doing.

- * - *

Performing {@link #getResult(boolean)} just after this step will return a compact form of - * the given argument.

- * - * @param skA The incoming sketch for the first argument, A. - */ - public void setA(final TupleSketch skA) { - if (skA == null) { - reset(); - throw new SketchesArgumentException("The input argument A may not be null"); - } - - empty_ = skA.isEmpty(); - thetaLong_ = skA.getThetaLong(); - final DataArrays da = getCopyOfDataArraysTuple(skA); - summaryArr_ = da.summaryArr; //it may be null - hashArr_ = da.hashArr; //it may be null - curCount_ = (hashArr_ == null) ? 0 : hashArr_.length; - } - - /** - * This is part of a multistep, stateful TupleAnotB operation and sets the given TupleSketch as the - * second (or n+1th) argument B of A-AND-NOT-B. - * Performs an AND NOT operation with the existing internal state of this TupleAnotB operator. - * - *

An input argument of null or empty is ignored.

- * - *

Rationale: A null for the second or following arguments is more tolerable because - * A NOT null is still A even if we don't know exactly what the null represents. It - * clearly does not have any content that overlaps with A. Also, because this can be part of - * a multistep operation with multiple notB steps. Other following steps can still produce - * a valid result.

- * - *

Use {@link #getResult(boolean)} to obtain the result.

- * - * @param skB The incoming Tuple sketch for the second (or following) argument B. - */ - public void notB(final TupleSketch skB) { - if (skB == null) { return; } //ignore - - final long thetaLongB = skB.getThetaLong(); - final int countB = skB.getRetainedEntries(); - final boolean emptyB = skB.isEmpty(); - - final int id = - SetOperationCornerCases.createCornerCaseId(thetaLong_, curCount_, empty_, thetaLongB, countB, emptyB); - final CornerCase cCase = CornerCase.caseIdToCornerCase(id); - final AnotbAction anotbAction = cCase.getAnotbAction(); - - switch (anotbAction) { - case EMPTY_1_0_T: { - reset(); - break; - } - case DEGEN_MIN_0_F: { - reset(); - thetaLong_ = min(thetaLong_, thetaLongB); - empty_ = false; - break; - } - case DEGEN_THA_0_F: { - empty_ = false; - curCount_ = 0; - //thetaLong_ is ok - break; - } - case TRIM_A: { - thetaLong_ = min(thetaLong_, thetaLongB); - final DataArrays da = trimAndCopyDataArrays(hashArr_, summaryArr_, thetaLong_, true); - hashArr_ = da.hashArr; - curCount_ = (hashArr_ == null) ? 0 : hashArr_.length; - summaryArr_ = da.summaryArr; - //empty_ = is whatever SkA is, - break; - } - case SKETCH_A: { - break; //result is already in A - } - case FULL_ANOTB: { //both A and B should have valid entries. - thetaLong_ = min(thetaLong_, thetaLongB); - final DataArrays daR = getCopyOfResultArraysTuple(thetaLong_, curCount_, hashArr_, summaryArr_, skB); - hashArr_ = daR.hashArr; - curCount_ = (hashArr_ == null) ? 0 : hashArr_.length; - summaryArr_ = daR.summaryArr; - //empty_ = is whatever SkA is, - } - //default: not possible - } - } - - /** - * This is part of a multistep, stateful TupleAnotB operation and sets the given ThetaSketch as the - * second (or n+1th) argument B of A-AND-NOT-B. - * Performs an AND NOT operation with the existing internal state of this TupleAnotB operator. - * Calls to this method can be intermingled with calls to - * {@link #notB(ThetaSketch)}. - * - *

An input argument of null or empty is ignored.

- * - *

Rationale: A null for the second or following arguments is more tolerable because - * A NOT null is still A even if we don't know exactly what the null represents. It - * clearly does not have any content that overlaps with A. Also, because this can be part of - * a multistep operation with multiple notB steps. Other following steps can still produce - * a valid result.

- * - *

Use {@link #getResult(boolean)} to obtain the result.

- * - * @param skB The incoming ThetaSketch for the second (or following) argument B. - */ - public void notB(final ThetaSketch skB) { - if (skB == null) { return; } //ignore - - final long thetaLongB = skB.getThetaLong(); - final int countB = skB.getRetainedEntries(); - final boolean emptyB = skB.isEmpty(); - - final int id = - SetOperationCornerCases.createCornerCaseId(thetaLong_, curCount_, empty_, thetaLongB, countB, emptyB); - final CornerCase cCase = CornerCase.caseIdToCornerCase(id); - final AnotbAction anotbAction = cCase.getAnotbAction(); - - switch (anotbAction) { - case EMPTY_1_0_T: { - reset(); - break; - } - case DEGEN_MIN_0_F: { - reset(); - thetaLong_ = min(thetaLong_, thetaLongB); - empty_ = false; - break; - } - case DEGEN_THA_0_F: { - empty_ = false; - curCount_ = 0; - //thetaLong_ is ok - break; - } - case TRIM_A: { - thetaLong_ = min(thetaLong_, thetaLongB); - final DataArrays da = trimAndCopyDataArrays(hashArr_, summaryArr_,thetaLong_, true); - hashArr_ = da.hashArr; - curCount_ = (hashArr_ == null) ? 0 : hashArr_.length; - summaryArr_ = da.summaryArr; - break; - } - case SKETCH_A: { - break; //result is already in A - } - case FULL_ANOTB: { //both A and B should have valid entries. - thetaLong_ = min(thetaLong_, thetaLongB); - final DataArrays daB = getCopyOfResultArraysTheta(thetaLong_, curCount_, hashArr_, summaryArr_, skB); - hashArr_ = daB.hashArr; - curCount_ = (hashArr_ == null) ? 0 : hashArr_.length; - summaryArr_ = daB.summaryArr; - //empty_ = is whatever SkA is, - } - //default: not possible - } - } - - /** - * Gets the result of the multistep, stateful operation TupleAnotB that have been executed with calls - * to {@link #setA(TupleSketch)} and ({@link #notB(TupleSketch)} or - * {@link #notB(ThetaSketch)}). - * - * @param reset If true, clears this operator to the empty state after this result is - * returned. Set this to false if you wish to obtain an intermediate result. - * @return the result of this operation as an unordered {@link CompactTupleSketch}. - */ - public CompactTupleSketch getResult(final boolean reset) { - final CompactTupleSketch result; - if (curCount_ == 0) { - result = new CompactTupleSketch<>(null, null, thetaLong_, thetaLong_ == Long.MAX_VALUE); - } else { - - result = new CompactTupleSketch<>(hashArr_, Util.copySummaryArray(summaryArr_), thetaLong_, false); - } - if (reset) { reset(); } - return result; - } - - /** - * Returns the A-and-not-B set operation on the two given TupleSketches. - * - *

This a stateless operation and has no impact on the internal state of this operator. - * Thus, this is not an accumulating update and is independent of the {@link #setA(TupleSketch)}, - * {@link #notB(TupleSketch)}, {@link #notB(ThetaSketch)}, and - * {@link #getResult(boolean)} methods.

- * - *

If either argument is null an exception is thrown.

- * - *

Rationale: In mathematics a "null set" is a set with no members, which we call an empty set. - * That is distinctly different from the java null, which represents a nonexistent object. - * In most cases it is a programming error due to some object that was not properly initialized. - * With a null as the first argument, we cannot know what the user's intent is. - * With a null as the second argument, we can't ignore it as we must return a result and there is - * no following possible viable arguments for the second argument. - * Since it is very likely that a null is a programming error, we throw an exception.

- * - * @param skA The incoming TupleSketch for the first argument - * @param skB The incoming TupleSketch for the second argument - * @param Type of Summary - * @return the result as an unordered {@link CompactTupleSketch} - */ - @SuppressFBWarnings(value = "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", - justification = "hashArr and summaryArr are guaranteed to be valid due to the switch on CornerCase") - public static CompactTupleSketch aNotB( - final TupleSketch skA, - final TupleSketch skB) { - if (skA == null || skB == null) { - throw new SketchesArgumentException("Neither argument may be null for this stateless operation."); - } - - final long thetaLongA = skA.getThetaLong(); - final int countA = skA.getRetainedEntries(); - final boolean emptyA = skA.isEmpty(); - - final long thetaLongB = skB.getThetaLong(); - final int countB = skB.getRetainedEntries(); - final boolean emptyB = skB.isEmpty(); - - final int id = - SetOperationCornerCases.createCornerCaseId(thetaLongA, countA, emptyA, thetaLongB, countB, emptyB); - final CornerCase cCase = CornerCase.caseIdToCornerCase(id); - final AnotbAction anotbAction = cCase.getAnotbAction(); - - CompactTupleSketch result = null; - - switch (anotbAction) { - case EMPTY_1_0_T: { - result = new CompactTupleSketch<>(null, null, Long.MAX_VALUE, true); - break; - } - case DEGEN_MIN_0_F: { - final long thetaLong = min(thetaLongA, thetaLongB); - result = new CompactTupleSketch<>(null, null, thetaLong, false); - break; - } - case DEGEN_THA_0_F: { - result = new CompactTupleSketch<>(null, null, thetaLongA, false); - break; - } - case TRIM_A: { - final DataArrays daA = getCopyOfDataArraysTuple(skA); - final long[] hashArrA = daA.hashArr; - final S[] summaryArrA = daA.summaryArr; - final long minThetaLong = min(thetaLongA, thetaLongB); - final DataArrays da = trimAndCopyDataArrays(hashArrA, summaryArrA, minThetaLong, false); - result = new CompactTupleSketch<>(da.hashArr, da.summaryArr, minThetaLong, skA.empty_); - break; - } - case SKETCH_A: { - final DataArrays daA = getCopyOfDataArraysTuple(skA); - result = new CompactTupleSketch<>(daA.hashArr, daA.summaryArr, thetaLongA, skA.empty_); - break; - } - case FULL_ANOTB: { //both A and B should have valid entries. - final DataArrays daA = getCopyOfDataArraysTuple(skA); - final long minThetaLong = min(thetaLongA, thetaLongB); - final DataArrays daR = - getCopyOfResultArraysTuple(minThetaLong, daA.hashArr.length, daA.hashArr, daA.summaryArr, skB); - final int countR = (daR.hashArr == null) ? 0 : daR.hashArr.length; - if (countR == 0) { - result = new CompactTupleSketch<>(null, null, minThetaLong, minThetaLong == Long.MAX_VALUE); - } else { - result = new CompactTupleSketch<>(daR.hashArr, daR.summaryArr, minThetaLong, false); - } - } - //default: not possible - } - return result; - } - - /** - * Returns the A-and-not-B set operation on a TupleSketch and a ThetaSketch. - * - *

This a stateless operation and has no impact on the internal state of this operator. - * Thus, this is not an accumulating update and is independent of the {@link #setA(TupleSketch)}, - * {@link #notB(TupleSketch)}, {@link #notB(ThetaSketch)}, and - * {@link #getResult(boolean)} methods.

- * - *

If either argument is null an exception is thrown.

- * - *

Rationale: In mathematics a "null set" is a set with no members, which we call an empty set. - * That is distinctly different from the java null, which represents a nonexistent object. - * In most cases it is a programming error due to some object that was not properly initialized. - * With a null as the first argument, we cannot know what the user's intent is. - * With a null as the second argument, we can't ignore it as we must return a result and there is - * no following possible viable arguments for the second argument. - * Since it is very likely that a null is a programming error for either argument - * we throw a an exception.

- * - * @param skA The incoming TupleSketch for the first argument - * @param skB The incoming ThetaSketch for the second argument - * @param Type of Summary - * @return the result as an unordered {@link CompactTupleSketch} - */ - @SuppressFBWarnings(value = "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", - justification = "hashArr and summaryArr are guaranteed to be valid due to the switch on CornerCase") - public static CompactTupleSketch aNotB( - final TupleSketch skA, - final ThetaSketch skB) { - if (skA == null || skB == null) { - throw new SketchesArgumentException("Neither argument may be null for this stateless operation."); - } - - final long thetaLongA = skA.getThetaLong(); - final int countA = skA.getRetainedEntries(); - final boolean emptyA = skA.isEmpty(); - - final long thetaLongB = skB.getThetaLong(); - final int countB = skB.getRetainedEntries(); - final boolean emptyB = skB.isEmpty(); - - final int id = - SetOperationCornerCases.createCornerCaseId(thetaLongA, countA, emptyA, thetaLongB, countB, emptyB); - final CornerCase cCase = CornerCase.caseIdToCornerCase(id); - final AnotbAction anotbAction = cCase.getAnotbAction(); - - CompactTupleSketch result = null; - - switch (anotbAction) { - case EMPTY_1_0_T: { - result = new CompactTupleSketch<>(null, null, Long.MAX_VALUE, true); - break; - } - case DEGEN_MIN_0_F: { - final long thetaLong = min(thetaLongA, thetaLongB); - result = new CompactTupleSketch<>(null, null, thetaLong, false); - break; - } - case DEGEN_THA_0_F: { - result = new CompactTupleSketch<>(null, null, thetaLongA, false); - break; - } - case TRIM_A: { - final DataArrays daA = getCopyOfDataArraysTuple(skA); - final long[] hashArrA = daA.hashArr; - final S[] summaryArrA = daA.summaryArr; - final long minThetaLong = min(thetaLongA, thetaLongB); - final DataArrays da = trimAndCopyDataArrays(hashArrA, summaryArrA, minThetaLong, false); - result = new CompactTupleSketch<>(da.hashArr, da.summaryArr, minThetaLong, skA.empty_); - break; - } - case SKETCH_A: { - final DataArrays daA = getCopyOfDataArraysTuple(skA); - result = new CompactTupleSketch<>(daA.hashArr, daA.summaryArr, thetaLongA, skA.empty_); - break; - } - case FULL_ANOTB: { //both A and B have valid entries. - final DataArrays daA = getCopyOfDataArraysTuple(skA); - final long minThetaLong = min(thetaLongA, thetaLongB); - @SuppressFBWarnings(value = "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", - justification = "hashArr and summaryArr are guaranteed to be valid due to the switch on CornerCase") - final DataArrays daR = - getCopyOfResultArraysTheta(minThetaLong, daA.hashArr.length, daA.hashArr, daA.summaryArr, skB); - final int countR = (daR.hashArr == null) ? 0 : daR.hashArr.length; - if (countR == 0) { - result = new CompactTupleSketch<>(null, null, minThetaLong, minThetaLong == Long.MAX_VALUE); - } else { - result = new CompactTupleSketch<>(daR.hashArr, daR.summaryArr, minThetaLong, false); - } - } - //default: not possible - } - return result; - } - - //restricted - - static class DataArrays { - DataArrays() {} - - long[] hashArr; - S[] summaryArr; - } - - private static DataArrays getCopyOfDataArraysTuple( - final TupleSketch sk) { - final CompactTupleSketch csk; - final DataArrays da = new DataArrays<>(); - if (sk instanceof CompactTupleSketch) { - csk = (CompactTupleSketch) sk; - } else { - csk = ((QuickSelectSketch)sk).compact(); - } - final int count = csk.getRetainedEntries(); - if (count == 0) { - da.hashArr = null; - da.summaryArr = null; - } else { - da.hashArr = csk.getHashArr().clone(); //deep copy, may not be sorted - da.summaryArr = Util.copySummaryArray(csk.getSummaryArr()); - } - return da; - } - - @SuppressWarnings("unchecked") - //Both skA and skB must have entries (count > 0) - private static DataArrays getCopyOfResultArraysTuple( - final long minThetaLong, - final int countA, - final long[] hashArrA, - final S[] summaryArrA, - final TupleSketch skB) { - final DataArrays daR = new DataArrays<>(); - - //Rebuild/get hashtable of skB - final long[] hashTableB; - - if (skB instanceof CompactTupleSketch) { - final CompactTupleSketch cskB = (CompactTupleSketch) skB; - final int countB = skB.getRetainedEntries(); - hashTableB = convertToHashTable(cskB.getHashArr(), countB, minThetaLong, ThetaUtil.REBUILD_THRESHOLD); - } else { - final QuickSelectSketch qskB = (QuickSelectSketch) skB; - hashTableB = qskB.getHashTable(); - } - - //build temporary arrays of skA - final long[] tmpHashArrA = new long[countA]; - final S[] tmpSummaryArrA = Util.newSummaryArray(summaryArrA, countA); - - //search for non matches and build temp arrays - final int lgHTBLen = exactLog2OfLong(hashTableB.length); - int nonMatches = 0; - for (int i = 0; i < countA; i++) { - final long hash = hashArrA[i]; - if (hash != 0 && hash < minThetaLong) { //skips hashes of A >= minTheta - final int index = hashSearch(hashTableB, lgHTBLen, hash); - if (index == -1) { - tmpHashArrA[nonMatches] = hash; - tmpSummaryArrA[nonMatches] = (S) summaryArrA[i].copy(); - nonMatches++; - } - } - } - daR.hashArr = Arrays.copyOfRange(tmpHashArrA, 0, nonMatches); - daR.summaryArr = Arrays.copyOfRange(tmpSummaryArrA, 0, nonMatches); - return daR; - } - - @SuppressWarnings("unchecked") - private static DataArrays getCopyOfResultArraysTheta( - final long minThetaLong, - final int countA, - final long[] hashArrA, - final S[] summaryArrA, - final ThetaSketch skB) { - final DataArrays daB = new DataArrays<>(); - - //Rebuild/get hashtable of skB - final long[] hashTableB; //read only - - final long[] hashCacheB; - try { hashCacheB = (long[])GET_CACHE.invoke(skB); - } catch (final Exception e) { throw new SketchesStateException("Reflection Exception " + e); } - - if (skB instanceof CompactThetaSketch) { - final int countB = skB.getRetainedEntries(true); - hashTableB = convertToHashTable(hashCacheB, countB, minThetaLong, ThetaUtil.REBUILD_THRESHOLD); - } else { - hashTableB = hashCacheB; - } - - //build temporary result arrays of skA - final long[] tmpHashArrA = new long[countA]; - final S[] tmpSummaryArrA = Util.newSummaryArray(summaryArrA, countA); - - //search for non matches and build temp arrays - final int lgHTBLen = exactLog2OfLong(hashTableB.length); - int nonMatches = 0; - for (int i = 0; i < countA; i++) { - final long hash = hashArrA[i]; - if (hash != 0 && hash < minThetaLong) { //skips hashes of A >= minTheta - final int index = hashSearch(hashTableB, lgHTBLen, hash); - if (index == -1) { //not found - tmpHashArrA[nonMatches] = hash; - tmpSummaryArrA[nonMatches] = (S) summaryArrA[i].copy(); - nonMatches++; - } - } - } - //trim the arrays - daB.hashArr = Arrays.copyOfRange(tmpHashArrA, 0, nonMatches); - daB.summaryArr = Arrays.copyOfRange(tmpSummaryArrA, 0, nonMatches); - return daB; - } - - @SuppressWarnings("unchecked") - private static DataArrays trimAndCopyDataArrays( - final long[] hashArr, - final S[] summaryArr, - final long minThetaLong, - final boolean copy) { - - //build temporary arrays - final int countIn = hashArr.length; - final long[] tmpHashArr = new long[countIn]; - final S[] tmpSummaryArr = Util.newSummaryArray(summaryArr, countIn); - int countResult = 0; - for (int i = 0; i < countIn; i++) { - final long hash = hashArr[i]; - if (hash < minThetaLong) { - tmpHashArr[countResult] = hash; - tmpSummaryArr[countResult] = (S) (copy ? summaryArr[i].copy() : summaryArr[i]); - countResult++; - } else { continue; } - } - //Remove empty slots - final DataArrays da = new DataArrays<>(); - da.hashArr = Arrays.copyOfRange(tmpHashArr, 0, countResult); - da.summaryArr = Arrays.copyOfRange(tmpSummaryArr, 0, countResult); - return da; - } - - /** - * Resets this operation back to the empty state. - */ - public void reset() { - empty_ = true; - thetaLong_ = Long.MAX_VALUE; - hashArr_ = null; - summaryArr_ = null; - curCount_ = 0; - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/TupleIntersection.java b/src/main/java/org/apache/datasketches/tuple/TupleIntersection.java deleted file mode 100644 index 0ddbbf294..000000000 --- a/src/main/java/org/apache/datasketches/tuple/TupleIntersection.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static java.lang.Math.ceil; -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.theta.ThetaSketch; -import org.apache.datasketches.thetacommon.ThetaUtil; - - -/** - * Computes an intersection of two or more generic TupleSketches or generic TupleSketches - * combined with ThetaSketches. - * A new instance represents the Universal Set. Because the Universal Set - * cannot be realized a getResult() on a new instance will produce an error. - * Every update() computes an intersection with the internal state, which will never - * grow larger and may be reduced to zero. - * - * @param Type of Summary - */ -@SuppressWarnings("unchecked") -public class TupleIntersection { - private final SummarySetOperations summarySetOps_; - private boolean empty_; - private long thetaLong_; - private HashTables hashTables_; - private boolean firstCall_; - - /** - * Creates new TupleIntersection instance with instructions on how to process two summaries that intersect. - * @param summarySetOps instance of SummarySetOperations - */ - public TupleIntersection(final SummarySetOperations summarySetOps) { - summarySetOps_ = summarySetOps; - empty_ = false; // universal set at the start - thetaLong_ = Long.MAX_VALUE; - hashTables_ = new HashTables<>(); - firstCall_ = true; - } - - /** - * Perform a stateless intersect set operation on the two given TupleSketches and returns the - * result as an unordered CompactTupleSketch on the heap. - * @param tupleSketchA The first sketch argument. It must not be null. - * @param tupleSketchB The second sketch argument. It must not be null. - * @return an unordered CompactTupleSketch on the heap - */ - public CompactTupleSketch intersect( - final TupleSketch tupleSketchA, - final TupleSketch tupleSketchB) { - reset(); - intersect(tupleSketchA); - intersect(tupleSketchB); - final CompactTupleSketch csk = getResult(); - reset(); - return csk; - } - - /** - * Perform a stateless intersect set operation on a TupleSketch and a ThetaSketch and returns the - * result as an unordered CompactTupleSketch on the heap. - * @param tupleSketch The first sketch argument. It must not be null. - * @param thetaSketch The second sketch argument. It must not be null. - * @param summary the given proxy summary for the ThetaSketch, which doesn't have one. - * This must not be null. - * @return an unordered CompactTupleSketch on the heap - */ - public CompactTupleSketch intersect( - final TupleSketch tupleSketch, - final ThetaSketch thetaSketch, final S summary) { - reset(); - intersect(tupleSketch); - intersect(thetaSketch, summary); - final CompactTupleSketch csk = getResult(); - reset(); - return csk; - } - - /** - * Performs a stateful intersection of the internal set with the given TupleSketch. - * @param tupleSketch input sketch to intersect with the internal state. It must not be null. - */ - public void intersect(final TupleSketch tupleSketch) { - if (tupleSketch == null) { throw new SketchesArgumentException("TupleSketch must not be null"); } - - final boolean firstCall = firstCall_; - firstCall_ = false; - - // input sketch could be first or next call - - final boolean emptyIn = tupleSketch.isEmpty(); - if (empty_ || emptyIn) { //empty rule - //Whatever the current internal state, we make our local empty. - resetToEmpty(); - return; - } - - final long thetaLongIn = tupleSketch.getThetaLong(); - thetaLong_ = min(thetaLong_, thetaLongIn); //Theta rule - - if (tupleSketch.getRetainedEntries() == 0) { - hashTables_.clear(); - return; - } - // input sketch will have valid entries > 0 - - if (firstCall) { - //Copy firstSketch data into local instance hashTables_ - hashTables_.fromSketch(tupleSketch); - } - - //Next Call - else { - if (hashTables_.numKeys == 0) { return; } - //process intersect with current hashTables - hashTables_ = hashTables_.getIntersectHashTables(tupleSketch, thetaLong_, summarySetOps_); - } - } - - /** - * Performs a stateful intersection of the internal set with the given ThetaSketch by combining entries - * using the hashes from the ThetaSketch and summary values from the given summary and rules - * from the summarySetOps defined by the TupleIntersection constructor. - * @param thetaSketch input ThetaSketch to intersect with the internal state. It must not be null. - * @param summary the given proxy summary for the theta sketch, which doesn't have one. - * It will be copied for each matching index. It must not be null. - */ - public void intersect(final ThetaSketch thetaSketch, final S summary) { - if (thetaSketch == null) { throw new SketchesArgumentException("ThetaSketch must not be null"); } - if (summary == null) { throw new SketchesArgumentException("Summary cannot be null."); } - final boolean firstCall = firstCall_; - firstCall_ = false; - // input sketch is not null, could be first or next call - - final boolean emptyIn = thetaSketch.isEmpty(); - if (empty_ || emptyIn) { //empty rule - //Whatever the current internal state, we make our local empty. - resetToEmpty(); - return; - } - - final long thetaLongIn = thetaSketch.getThetaLong(); - thetaLong_ = min(thetaLong_, thetaLongIn); //Theta rule - - final int countIn = thetaSketch.getRetainedEntries(); - if (countIn == 0) { - hashTables_.clear(); - return; - } - // input sketch will have valid entries > 0 - - if (firstCall) { - final ThetaSketch firstSketch = thetaSketch; - //Copy firstSketch data into local instance hashTables_ - hashTables_.fromSketch(firstSketch, summary); - } - - //Next Call - else { - if (hashTables_.numKeys == 0) { return; } - hashTables_ = hashTables_.getIntersectHashTables(thetaSketch, thetaLongIn, summarySetOps_, summary); - } - } - - /** - * Gets the internal set as an unordered CompactTupleSketch - * @return result of the intersections so far - */ - public CompactTupleSketch getResult() { - if (firstCall_) { - throw new SketchesStateException( - "getResult() with no intervening intersections is not a legal result."); - } - final int countIn = hashTables_.numKeys; - if (countIn == 0) { - return new CompactTupleSketch<>(null, null, thetaLong_, empty_); - } - - final int tableSize = hashTables_.hashTable.length; - - final long[] hashArr = new long[countIn]; - final S[] summaryArr = Util.newSummaryArray(hashTables_.summaryTable, countIn); - - //compact the arrays - int cnt = 0; - for (int i = 0; i < tableSize; i++) { - final long hash = hashTables_.hashTable[i]; - if (hash == 0 || hash > thetaLong_) { continue; } - hashArr[cnt] = hash; - summaryArr[cnt] = (S) hashTables_.summaryTable[i].copy(); - cnt++; - } - assert cnt == countIn; - return new CompactTupleSketch<>(hashArr, summaryArr, thetaLong_, empty_); - } - - /** - * Returns true if there is a valid intersection result available - * @return true if there is a valid intersection result available - */ - public boolean hasResult() { - return !firstCall_; - } - - /** - * Resets the internal set to the initial state, which represents the Universal Set - */ - public void reset() { - hardReset(); - } - - private void hardReset() { - empty_ = false; - thetaLong_ = Long.MAX_VALUE; - hashTables_.clear(); - firstCall_ = true; - } - - private void resetToEmpty() { - empty_ = true; - thetaLong_ = Long.MAX_VALUE; - hashTables_.clear(); - firstCall_ = false; - } - - static int getLgTableSize(final int count) { - final int tableSize = max(ceilingPowerOf2((int) ceil(count / 0.75)), 1 << ThetaUtil.MIN_LG_NOM_LONGS); - return Integer.numberOfTrailingZeros(tableSize); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/TupleSketch.java b/src/main/java/org/apache/datasketches/tuple/TupleSketch.java deleted file mode 100644 index 7ef2ebc06..000000000 --- a/src/main/java/org/apache/datasketches/tuple/TupleSketch.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static org.apache.datasketches.common.Util.LS; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.thetacommon.BinomialBoundsN; - -/** - * The top-level class for all Tuple sketches. This class is never constructed directly. - * Use the UpdatableTupleSketchBuilder() methods to create UpdatableTupleSketches. - * This is similar to {@link org.apache.datasketches.theta.ThetaSketch ThetaSketch} with - * addition of a user-defined Summary object associated with every unique entry - * in the sketch. - * @param Type of Summary - */ -@SuppressWarnings("deprecation") -public abstract class TupleSketch { - - protected static final byte PREAMBLE_LONGS = 1; - - long thetaLong_; - boolean empty_ = true; - protected SummaryFactory summaryFactory_ = null; - - TupleSketch(final long thetaLong, final boolean empty, final SummaryFactory summaryFactory) { - this.thetaLong_ = thetaLong; - this.empty_ = empty; - this.summaryFactory_ = summaryFactory; - } - - /** - * Converts this TupleSketch to a CompactTupleSketch on the Java heap. - * - *

If this sketch is already in compact form this operation returns this. - * - * @return this sketch as a CompactTupleSketch on the Java heap. - */ - public abstract CompactTupleSketch compact(); - - /** - * Estimates the cardinality of the set (number of unique values presented to the sketch) - * @return best estimate of the number of unique values - */ - public double getEstimate() { - if (!isEstimationMode()) { return getRetainedEntries(); } - return getRetainedEntries() / getTheta(); - } - - /** - * Gets the approximate upper error bound given the specified number of Standard Deviations. - * This will return getEstimate() if isEmpty() is true. - * - * @param numStdDev - * See Number of Standard Deviations - * @return the upper bound. - */ - public double getUpperBound(final int numStdDev) { - if (!isEstimationMode()) { return getRetainedEntries(); } - return BinomialBoundsN.getUpperBound(getRetainedEntries(), getTheta(), numStdDev, empty_); - } - - /** - * Gets the approximate lower error bound given the specified number of Standard Deviations. - * This will return getEstimate() if isEmpty() is true. - * - * @param numStdDev - * See Number of Standard Deviations - * @return the lower bound. - */ - public double getLowerBound(final int numStdDev) { - if (!isEstimationMode()) { return getRetainedEntries(); } - return BinomialBoundsN.getLowerBound(getRetainedEntries(), getTheta(), numStdDev, empty_); - } - - /** - * Gets the estimate of the true distinct population of subset tuples represented by the count - * of entries in a subset of the total retained entries of the sketch. - * @param numSubsetEntries number of entries for a chosen subset of the sketch. - * @return the estimate of the true distinct population of subset tuples represented by the count - * of entries in a subset of the total retained entries of the sketch. - */ - public double getEstimate(final int numSubsetEntries) { - if (!isEstimationMode()) { return numSubsetEntries; } - return numSubsetEntries / getTheta(); - } - - /** - * Gets the estimate of the lower bound of the true distinct population represented by the count - * of entries in a subset of the total retained entries of the sketch. - * @param numStdDev - * See Number of Standard Deviations - * @param numSubsetEntries number of entries for a chosen subset of the sketch. - * @return the estimate of the lower bound of the true distinct population represented by the count - * of entries in a subset of the total retained entries of the sketch. - */ - public double getLowerBound(final int numStdDev, final int numSubsetEntries) { - if (!isEstimationMode()) { return numSubsetEntries; } - return BinomialBoundsN.getLowerBound(numSubsetEntries, getTheta(), numStdDev, isEmpty()); - } - - /** - * Gets the estimate of the upper bound of the true distinct population represented by the count - * of entries in a subset of the total retained entries of the sketch. - * @param numStdDev - * See Number of Standard Deviations - * @param numSubsetEntries number of entries for a chosen subset of the sketch. - * @return the estimate of the upper bound of the true distinct population represented by the count - * of entries in a subset of the total retained entries of the sketch. - */ - public double getUpperBound(final int numStdDev, final int numSubsetEntries) { - if (!isEstimationMode()) { return numSubsetEntries; } - return BinomialBoundsN.getUpperBound(numSubsetEntries, getTheta(), numStdDev, isEmpty()); - } - - /** - * See Empty - * @return true if empty. - */ - public boolean isEmpty() { - return empty_; - } - - /** - * Returns true if the sketch is Estimation Mode (as opposed to Exact Mode). - * This is true if theta < 1.0 AND isEmpty() is false. - * @return true if the sketch is in estimation mode. - */ - public boolean isEstimationMode() { - return thetaLong_ < Long.MAX_VALUE && !isEmpty(); - } - - /** - * Returns number of retained entries - * @return number of retained entries - */ - public abstract int getRetainedEntries(); - - /** - * Gets the number of hash values less than the given theta expressed as a long. - * @param thetaLong the given theta as a long in the range (zero, Long.MAX_VALUE]. - * @return the number of hash values less than the given thetaLong. - */ - public abstract int getCountLessThanThetaLong(final long thetaLong); - - /** - * Gets the Summary Factory class of type S - * @return the Summary Factory class of type S - */ - public SummaryFactory getSummaryFactory() { - return summaryFactory_; - } - - /** - * Gets the value of theta as a double between zero and one - * @return the value of theta as a double - */ - public double getTheta() { - return getThetaLong() / (double) Long.MAX_VALUE; - } - - /** - * Serialize this sketch to a byte array. - * - *

As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. - * This capability will be removed in a future release. - * Serializing a CompactTupleSketch is not deprecated.

- * @return serialized representation of this sketch. - */ - public abstract byte[] toByteArray(); - - /** - * Returns a SketchIterator - * @return a SketchIterator - */ - public abstract TupleSketchIterator iterator(); - - /** - * Returns Theta as a long - * @return Theta as a long - */ - public long getThetaLong() { - return isEmpty() ? Long.MAX_VALUE : thetaLong_; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(); - sb.append("### ").append(this.getClass().getSimpleName()).append(" SUMMARY: ").append(LS); - sb.append(" Estimate : ").append(getEstimate()).append(LS); - sb.append(" Upper Bound, 95% conf : ").append(getUpperBound(2)).append(LS); - sb.append(" Lower Bound, 95% conf : ").append(getLowerBound(2)).append(LS); - sb.append(" Theta (double) : ").append(this.getTheta()).append(LS); - sb.append(" Theta (long) : ").append(this.getThetaLong()).append(LS); - sb.append(" EstMode? : ").append(isEstimationMode()).append(LS); - sb.append(" Empty? : ").append(isEmpty()).append(LS); - sb.append(" Retained Entries : ").append(this.getRetainedEntries()).append(LS); - if (this instanceof UpdatableTupleSketch) { - @SuppressWarnings("rawtypes") - final UpdatableTupleSketch updatable = (UpdatableTupleSketch) this; - sb.append(" Nominal Entries (k) : ").append(updatable.getNominalEntries()).append(LS); - sb.append(" Current Capacity : ").append(updatable.getCurrentCapacity()).append(LS); - sb.append(" Resize Factor : ").append(updatable.getResizeFactor().getValue()).append(LS); - sb.append(" Sampling Probability (p): ").append(updatable.getSamplingProbability()).append(LS); - } - sb.append("### END SKETCH SUMMARY").append(LS); - return sb.toString(); - } - - /** - * Instantiate an UpdatableTupleSketch from a given MemorySegment on the heap, - * @param Type of update value - * @param Type of Summary - * @param seg MemorySegment object representing an UpdatableTupleSketch - * @param deserializer instance of SummaryDeserializer - * @param summaryFactory instance of SummaryFactory - * @return UpdatableTupleSketch created from its MemorySegment representation - */ - public static > UpdatableTupleSketch heapifyUpdatableSketch( - final MemorySegment seg, - final SummaryDeserializer deserializer, - final SummaryFactory summaryFactory) { - return new UpdatableTupleSketch<>(seg, deserializer, summaryFactory); - } - - /** - * Instantiate a TupleSketch from a given MemorySegment. - * @param Type of Summary - * @param seg MemorySegment object representing a TupleSketch - * @param deserializer instance of SummaryDeserializer - * @return TupleSketch created from its MemorySegment representation - */ - public static TupleSketch heapifySketch( - final MemorySegment seg, - final SummaryDeserializer deserializer) { - final SerializerDeserializer.SketchType sketchType = SerializerDeserializer.getSketchType(seg); - if (sketchType == SerializerDeserializer.SketchType.QuickSelectSketch) { - return new QuickSelectSketch<>(seg, deserializer, null); - } - return new CompactTupleSketch<>(seg, deserializer); - } - - /** - * Creates an empty CompactTupleSketch. - * @param Type of Summary - * @return an empty instance of a CompactTupleSketch - */ - public static TupleSketch createEmptySketch() { - return new CompactTupleSketch<>(null, null, Long.MAX_VALUE, true); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/TupleSketchIterator.java b/src/main/java/org/apache/datasketches/tuple/TupleSketchIterator.java deleted file mode 100644 index db49c8630..000000000 --- a/src/main/java/org/apache/datasketches/tuple/TupleSketchIterator.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -/** - * Iterator over a generic tuple sketch - * @param Type of Summary - */ -public class TupleSketchIterator { - - private final long[] hashArrTbl_; //could be either hashArr or hashTable - private final S[] summaryArrTbl_; //could be either summaryArr or summaryTable - private int i_; - - TupleSketchIterator(final long[] hashes, final S[] summaries) { - hashArrTbl_ = hashes; - summaryArrTbl_ = summaries; - i_ = -1; - } - - /** - * Advancing the iterator and checking existence of the next entry - * is combined here for efficiency. This results in an undefined - * state of the iterator before the first call of this method. - * @return true if the next element exists - */ - public boolean next() { - if (hashArrTbl_ == null) { return false; } - i_++; - while (i_ < hashArrTbl_.length) { - if (hashArrTbl_[i_] > 0) { return true; } - i_++; - } - return false; - } - - /** - * Gets the hash from the current entry in the sketch, which is a hash - * of the original key passed to update(). The original keys are not - * retained. Don't call this before calling next() for the first time - * or after getting false from next(). - * @return hash from the current entry - */ - public long getHash() { - return hashArrTbl_[i_]; - } - - /** - * Gets a Summary object from the current entry in the sketch. - * Don't call this before calling next() for the first time - * or after getting false from next(). - * @return Summary object for the current entry (this is not a copy!) - */ - public S getSummary() { - return summaryArrTbl_[i_]; - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/TupleUnion.java b/src/main/java/org/apache/datasketches/tuple/TupleUnion.java deleted file mode 100644 index d624c017a..000000000 --- a/src/main/java/org/apache/datasketches/tuple/TupleUnion.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static java.lang.Math.min; - -import org.apache.datasketches.common.QuickSelect; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.theta.HashIterator; -import org.apache.datasketches.theta.ThetaSketch; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * Compute the union of two or more generic tuple sketches or generic TupleSketches combined with - * ThetaSketches. A new instance represents an empty set. - * @param Type of Summary - */ -public class TupleUnion { - private final SummarySetOperations summarySetOps_; - private QuickSelectSketch qsk_; - private long unionThetaLong_; // need to maintain outside of the sketch - private boolean empty_; - - /** - * Creates new TupleUnion instance with instructions on how to process two summaries that - * overlap. This will have the default nominal entries (K). - * @param summarySetOps instance of SummarySetOperations - */ - public TupleUnion(final SummarySetOperations summarySetOps) { - this(ThetaUtil.DEFAULT_NOMINAL_ENTRIES, summarySetOps); - } - - /** - * Creates new TupleUnion instance. - * @param nomEntries nominal entries (K). Forced to the nearest power of 2 greater than - * given value. - * @param summarySetOps instance of SummarySetOperations - */ - public TupleUnion(final int nomEntries, final SummarySetOperations summarySetOps) { - summarySetOps_ = summarySetOps; - qsk_ = new QuickSelectSketch<>(nomEntries, null); - unionThetaLong_ = qsk_.getThetaLong(); - empty_ = true; - } - - /** - * Perform a stateless, pair-wise union operation between two tuple sketches. - * The returned sketch will be cut back to the smaller of the two k values if required. - * - *

Nulls and empty sketches are ignored.

- * - * @param tupleSketchA The first argument - * @param tupleSketchB The second argument - * @return the result ordered CompactTupleSketch on the heap. - */ - public CompactTupleSketch union(final TupleSketch tupleSketchA, final TupleSketch tupleSketchB) { - reset(); - union(tupleSketchA); - union(tupleSketchB); - final CompactTupleSketch csk = getResult(true); - return csk; - } - - /** - * Perform a stateless, pair-wise union operation between a tupleSketch and a ThetaSketch. - * The returned sketch will be cut back to the smaller of the two k values if required. - * - *

Nulls and empty sketches are ignored.

- * - * @param tupleSketch The first argument - * @param thetaSketch The second argument - * @param summary the given proxy summary for the ThetaSketch, which doesn't have one. - * This may not be null. - * @return the result ordered CompactTupleSketch on the heap. - */ - public CompactTupleSketch union(final TupleSketch tupleSketch, - final ThetaSketch thetaSketch, final S summary) { - reset(); - union(tupleSketch); - union(thetaSketch, summary); - final CompactTupleSketch csk = getResult(true); - return csk; - } - - /** - * Performs a stateful union of the internal set with the given TupleSketch. - * @param tupleSketch input tuple sketch to merge with the internal set. - * Nulls and empty sketches are ignored. - */ - public void union(final TupleSketch tupleSketch) { - if (tupleSketch == null || tupleSketch.isEmpty()) { return; } - empty_ = false; - unionThetaLong_ = min(tupleSketch.thetaLong_, unionThetaLong_); - final TupleSketchIterator it = tupleSketch.iterator(); - while (it.next()) { - qsk_.merge(it.getHash(), it.getSummary(), summarySetOps_); - } - unionThetaLong_ = min(unionThetaLong_, qsk_.thetaLong_); - } - - /** - * Performs a stateful union of the internal set with the given ThetaSketch by combining entries - * using the hashes from the ThetaSketch and summary values from the given summary. - * @param thetaSketch the given ThetaSketch input. If null or empty, it is ignored. - * @param summary the given proxy summary for the ThetaSketch, which doesn't have one. This may - * not be null. - */ - public void union(final ThetaSketch thetaSketch, final S summary) { - if (summary == null) { - throw new SketchesArgumentException("Summary cannot be null."); } - if (thetaSketch == null || thetaSketch.isEmpty()) { return; } - empty_ = false; - final long thetaIn = thetaSketch.getThetaLong(); - unionThetaLong_ = min(thetaIn, unionThetaLong_); - final HashIterator it = thetaSketch.iterator(); - while (it.next()) { - qsk_.merge(it.get(), summary, summarySetOps_); //copies summary - } - unionThetaLong_ = min(unionThetaLong_, qsk_.thetaLong_); - } - - /** - * Gets the result of a sequence of stateful union operations as an unordered CompactTupleSketch - * @return result of the stateful unions so far. The state of this operation is not reset after the - * result is returned. - */ - public CompactTupleSketch getResult() { - return getResult(false); - } - - /** - * Gets the result of a sequence of stateful union operations as an unordered CompactTupleSketch. - * @param reset If true, clears this operator to the empty state after this result is - * returned. Set this to false if you wish to obtain an intermediate result. - * @return result of the stateful union - */ - @SuppressWarnings("unchecked") - public CompactTupleSketch getResult(final boolean reset) { - final CompactTupleSketch result; - if (empty_) { - result = qsk_.compact(); - } else if (unionThetaLong_ >= qsk_.thetaLong_ && qsk_.getRetainedEntries() <= qsk_.getNominalEntries()) { - //unionThetaLong_ >= qsk_.thetaLong_ means we can ignore unionThetaLong_. We don't need to rebuild. - //qsk_.getRetainedEntries() <= qsk_.getNominalEntries() means we don't need to pull back to k. - result = qsk_.compact(); - } else { - final long tmpThetaLong = min(unionThetaLong_, qsk_.thetaLong_); - - //count the number of valid hashes in because Alpha can have dirty values - int numHashesIn = 0; - TupleSketchIterator it = qsk_.iterator(); - while (it.next()) { //counts valid hashes - if (it.getHash() < tmpThetaLong) { numHashesIn++; } - } - - if (numHashesIn == 0) { - //numHashes == 0 && empty == false means Theta < 1.0 - //Therefore, this is a degenerate sketch: theta < 1.0, count = 0, empty = false - result = new CompactTupleSketch<>(null, null, tmpThetaLong, empty_); - } - - else { - //we know: empty == false, count > 0 - final int numHashesOut; - final long thetaLongOut; - if (numHashesIn > qsk_.getNominalEntries()) { - //we need to trim hashes and need a new thetaLong - final long[] tmpHashArr = new long[numHashesIn]; // temporary, order will be destroyed by quick select - it = qsk_.iterator(); - int i = 0; - while (it.next()) { - final long hash = it.getHash(); - if (hash < tmpThetaLong) { tmpHashArr[i++] = hash; } - } - numHashesOut = qsk_.getNominalEntries(); - thetaLongOut = QuickSelect.select(tmpHashArr, 0, numHashesIn - 1, numHashesOut); - } else { - numHashesOut = numHashesIn; - thetaLongOut = tmpThetaLong; - } - //now prepare the output arrays - final long[] hashArr = new long[numHashesOut]; - final S[] summaries = Util.newSummaryArray(qsk_.getSummaryTable(), numHashesOut); - it = qsk_.iterator(); - int i = 0; - while (it.next()) { //select the qualifying hashes from the gadget synchronized with the summaries - final long hash = it.getHash(); - if (hash < thetaLongOut) { - hashArr[i] = hash; - summaries[i] = (S) it.getSummary().copy(); - i++; - } - } - result = new CompactTupleSketch<>(hashArr, summaries, thetaLongOut, empty_); - } - } - if (reset) { reset(); } - return result; - } - - /** - * Resets the internal set to the initial state, which represents an empty set. This is only useful - * after sequences of stateful union operations. - */ - public void reset() { - qsk_.reset(); - unionThetaLong_ = qsk_.getThetaLong(); - empty_ = true; - } -} diff --git a/src/main/java/org/apache/datasketches/tuple/UpdatableSummary.java b/src/main/java/org/apache/datasketches/tuple/UpdatableSummary.java deleted file mode 100644 index 4ddb71d1b..000000000 --- a/src/main/java/org/apache/datasketches/tuple/UpdatableSummary.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -/** - * Interface for updating user-defined Summary - * @param type of update value - */ -public interface UpdatableSummary extends Summary { - - /** - * This is to provide a method of updating summaries. - * This is primarily used internally. - * @param value update value - * @return this - */ - UpdatableSummary update(U value); - -} diff --git a/src/main/java/org/apache/datasketches/tuple/UpdatableTupleSketch.java b/src/main/java/org/apache/datasketches/tuple/UpdatableTupleSketch.java deleted file mode 100644 index 45bc88dcd..000000000 --- a/src/main/java/org/apache/datasketches/tuple/UpdatableTupleSketch.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static org.apache.datasketches.common.Util.DEFAULT_UPDATE_SEED; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; - -import org.apache.datasketches.hash.MurmurHash3; - -/** - * An extension of QuickSelectSketch<S>, which can be updated with many types of keys. - * Summary objects are created using a user-defined SummaryFactory class, - * which should allow very flexible parameterization if needed. - * Keys are presented to a sketch along with values of a user-defined - * update type U. When an entry is inserted into a sketch or a duplicate key is - * presented to a sketch then summary.update(U value) method will be called. So - * any kind of user-defined accumulation is possible. Summaries also must know - * how to copy themselves. Also union and intersection of summaries can be - * implemented in a sub-class of SummarySetOperations, which will be used in - * case TupleUnion or TupleIntersection of two instances of TupleSketch is needed - * @param Type of the value, which is passed to update method of a Summary - * @param Type of the UpdatableSummary<U> - */ -public class UpdatableTupleSketch> extends QuickSelectSketch { - - /** - * This is to create a new instance of an UpdatableQuickSelectSketch. - * @param nomEntries Nominal number of entries. Forced to the nearest power of 2 greater than - * or equal to the given value. - * @param lgResizeFactor log2(resizeFactor) - value from 0 to 3: - *
-   * 0 - no resizing (max size allocated),
-   * 1 - double internal hash table each time it reaches a threshold
-   * 2 - grow four times
-   * 3 - grow eight times (default)
-   * 
- * @param samplingProbability - * See Sampling Probability - * @param summaryFactory An instance of a SummaryFactory. - */ - public UpdatableTupleSketch(final int nomEntries, final int lgResizeFactor, - final float samplingProbability, final SummaryFactory summaryFactory) { - super(nomEntries, lgResizeFactor, samplingProbability, summaryFactory); - } - - /** - * This is to create an instance of an UpdatableTupleSketch given a serialized form - * @param srcSeg MemorySegment object with data of a serialized UpdatableTupleSketch - * @param deserializer instance of SummaryDeserializer - * @param summaryFactory instance of SummaryFactory - * @deprecated As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. - * This capability will be removed in a future release. - * Heapifying a CompactTupleSketch is not deprecated. - */ - @Deprecated - public UpdatableTupleSketch( - final MemorySegment srcSeg, - final SummaryDeserializer deserializer, - final SummaryFactory summaryFactory) { - super(srcSeg, deserializer, summaryFactory); - } - - /** - * Copy Constructor - * @param sketch the sketch to copy - */ - public UpdatableTupleSketch(final UpdatableTupleSketch sketch) { - super(sketch); - } - - /** - * @return a deep copy of this sketch - */ - @Override - public UpdatableTupleSketch copy() { - return new UpdatableTupleSketch<>(this); - } - - /** - * Updates this sketch with a long key and U value. - * The value is passed to update() method of the Summary object associated with the key - * - * @param key The given long key - * @param value The given U value - */ - public void update(final long key, final U value) { - update(new long[] {key}, value); - } - - /** - * Updates this sketch with a double key and U value. - * The value is passed to update() method of the Summary object associated with the key - * - * @param key The given double key - * @param value The given U value - */ - public void update(final double key, final U value) { - update(Util.doubleToLongArray(key), value); - } - - /** - * Updates this sketch with a String key and U value. - * The value is passed to update() method of the Summary object associated with the key - * - * @param key The given String key - * @param value The given U value - */ - public void update(final String key, final U value) { - update(Util.stringToByteArray(key), value); - } - - /** - * Updates this sketch with a byte[] key and U value. - * The value is passed to update() method of the Summary object associated with the key - * - * @param key The given byte[] key - * @param value The given U value - */ - public void update(final byte[] key, final U value) { - if ((key == null) || (key.length == 0)) { return; } - insertOrIgnore(MurmurHash3.hash(key, DEFAULT_UPDATE_SEED)[0] >>> 1, value); - } - - /** - * Updates this sketch with a ByteBuffer and U value - * The value is passed to the update() method of the Summary object associated with the key - * - * @param buffer The given ByteBuffer key - * @param value The given U value - */ - public void update(final ByteBuffer buffer, final U value) { - if (buffer == null || buffer.hasRemaining() == false) { return; } - insertOrIgnore(MurmurHash3.hash(buffer, DEFAULT_UPDATE_SEED)[0] >>> 1, value); - } - - /** - * Updates this sketch with a int[] key and U value. - * The value is passed to update() method of the Summary object associated with the key - * - * @param key The given int[] key - * @param value The given U value - */ - public void update(final int[] key, final U value) { - if ((key == null) || (key.length == 0)) { return; } - insertOrIgnore(MurmurHash3.hash(key, DEFAULT_UPDATE_SEED)[0] >>> 1, value); - } - - /** - * Updates this sketch with a long[] key and U value. - * The value is passed to update() method of the Summary object associated with the key - * - * @param key The given long[] key - * @param value The given U value - */ - public void update(final long[] key, final U value) { - if ((key == null) || (key.length == 0)) { return; } - insertOrIgnore(MurmurHash3.hash(key, DEFAULT_UPDATE_SEED)[0] >>> 1, value); - } - - void insertOrIgnore(final long hash, final U value) { - setEmpty(false); - if (hash >= getThetaLong()) { return; } - int index = findOrInsert(hash); - if (index < 0) { - index = ~index; - insertSummary(index, getSummaryFactory().newSummary()); - } - summaryTable_[index].update(value); - rebuildIfNeeded(); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/UpdatableTupleSketchBuilder.java b/src/main/java/org/apache/datasketches/tuple/UpdatableTupleSketchBuilder.java deleted file mode 100644 index e83862772..000000000 --- a/src/main/java/org/apache/datasketches/tuple/UpdatableTupleSketchBuilder.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * For building a new generic tuple UpdatableTupleSketch - * @param Type of update value - * @param Type of Summary - */ -public class UpdatableTupleSketchBuilder> { - - private int nomEntries_; - private ResizeFactor resizeFactor_; - private float samplingProbability_; - private final SummaryFactory summaryFactory_; - - private static final float DEFAULT_SAMPLING_PROBABILITY = 1; - private static final ResizeFactor DEFAULT_RESIZE_FACTOR = ResizeFactor.X8; - - /** - * Creates an instance of UpdatableTupleSketchBuilder with default parameters - * @param summaryFactory An instance of SummaryFactory. - */ - public UpdatableTupleSketchBuilder(final SummaryFactory summaryFactory) { - nomEntries_ = ThetaUtil.DEFAULT_NOMINAL_ENTRIES; - resizeFactor_ = DEFAULT_RESIZE_FACTOR; - samplingProbability_ = DEFAULT_SAMPLING_PROBABILITY; - summaryFactory_ = summaryFactory; - } - - /** - * This is to set the nominal number of entries. - * @param nomEntries Nominal number of entries. Forced to the nearest power of 2 greater than - * or equal to the given value. - * @return this UpdatableTupleSketchBuilder - */ - public UpdatableTupleSketchBuilder setNominalEntries(final int nomEntries) { - nomEntries_ = 1 << ThetaUtil.checkNomLongs(nomEntries); - return this; - } - - /** - * This is to set the resize factor. - * Value of X1 means that the maximum capacity is allocated from the start. - * Default resize factor is X8. - * @param resizeFactor value of X1, X2, X4 or X8 - * @return this UpdatableTupleSketchBuilder - */ - public UpdatableTupleSketchBuilder setResizeFactor(final ResizeFactor resizeFactor) { - resizeFactor_ = resizeFactor; - return this; - } - - /** - * This is to set sampling probability. - * Default probability is 1. - * @param samplingProbability sampling probability from 0 to 1 - * @return this UpdatableTupleSketchBuilder - */ - public UpdatableTupleSketchBuilder setSamplingProbability(final float samplingProbability) { - if ((samplingProbability < 0) || (samplingProbability > 1f)) { - throw new SketchesArgumentException("sampling probability must be between 0 and 1"); - } - samplingProbability_ = samplingProbability; - return this; - } - - /** - * Returns an UpdatableTupleSketch with the current configuration of this Builder. - * @return an UpdatableTupleSketch - */ - public UpdatableTupleSketch build() { - return new UpdatableTupleSketch<>(nomEntries_, resizeFactor_.lg(), samplingProbability_, - summaryFactory_); - } - - /** - * Resets the Nominal Entries, Resize Factor and Sampling Probability to their default values. - * The assignment of U and S remain the same. - */ - public void reset() { - nomEntries_ = ThetaUtil.DEFAULT_NOMINAL_ENTRIES; - resizeFactor_ = DEFAULT_RESIZE_FACTOR; - samplingProbability_ = DEFAULT_SAMPLING_PROBABILITY; - } -} diff --git a/src/main/java/org/apache/datasketches/tuple/Util.java b/src/main/java/org/apache/datasketches/tuple/Util.java deleted file mode 100644 index 45168fa4a..000000000 --- a/src/main/java/org/apache/datasketches/tuple/Util.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.hash.XxHash.hashCharArr; -import static org.apache.datasketches.hash.XxHash.hashString; - -import java.lang.reflect.Array; - -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * Common utility functions for Tuples - */ -public final class Util { - private static final int PRIME = 0x7A3C_CA71; - - /** - * No argument constructor. - */ - public Util() { } - - /** - * Converts a double to a long[]. - * @param value the given double value - * @return the long array - */ - public static final long[] doubleToLongArray(final double value) { - final double d = (value == 0.0) ? 0.0 : value; // canonicalize -0.0, 0.0 - final long[] array = { Double.doubleToLongBits(d) }; // canonicalize all NaN & +/- infinity forms - return array; - } - - /** - * Converts a String to a UTF_8 byte array. If the given value is either null or empty this - * method returns null. - * @param value the given String value - * @return the UTF_8 byte array - */ - public static final byte[] stringToByteArray(final String value) { - if ((value == null) || value.isEmpty()) { return null; } - return value.getBytes(UTF_8); - } - - /** - * Gets the starting capacity of a new sketch given the Nominal Entries and the log Resize Factor. - * @param nomEntries the given Nominal Entries - * @param lgResizeFactor the given log Resize Factor - * @return the starting capacity - */ - public static int getStartingCapacity(final int nomEntries, final int lgResizeFactor) { - return 1 << ThetaUtil.startingSubMultiple( - // target table size is twice the number of nominal entries - Integer.numberOfTrailingZeros(ceilingPowerOf2(nomEntries) * 2), - lgResizeFactor, - ThetaUtil.MIN_LG_ARR_LONGS - ); - } - - /** - * Concatenate array of Strings to a single String. - * @param strArr the given String array - * @return the concatenated String - */ - public static String stringConcat(final String[] strArr) { - final int len = strArr.length; - final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < len; i++) { - sb.append(strArr[i]); - if ((i + 1) < len) { sb.append(','); } - } - return sb.toString(); - } - - /** - * Returns the hash of the given string - * @param s the string to hash - * @return the hash of the given string - */ - public static long stringHash(final String s) { - return hashString(s, 0, s.length(), PRIME); - } - - /** - * Returns the hash of the concatenated strings - * @param strArray array of Strings - * @return the hash of concatenated strings. - */ - public static long stringArrHash(final String[] strArray) { - final String s = stringConcat(strArray); - return hashCharArr(s.toCharArray(), 0, s.length(), PRIME); - } - - /** - * Will copy compact summary arrays as well as hashed summary tables (with nulls). - * @param type of summary - * @param summaryArr the given summary array or table - * @return the copy - */ - @SuppressWarnings("unchecked") - public static S[] copySummaryArray(final S[] summaryArr) { - final int len = summaryArr.length; - final S[] tmpSummaryArr = newSummaryArray(summaryArr, len); - for (int i = 0; i < len; i++) { - final S summary = summaryArr[i]; - if (summary == null) { continue; } - tmpSummaryArr[i] = (S) summary.copy(); - } - return tmpSummaryArr; - } - - /** - * Creates a new Summary Array with the specified length - * @param summaryArr example array, only used to obtain the component type. It has no data. - * @param length the desired length of the returned array. - * @param the summary class type - * @return a new Summary Array with the specified length - */ - @SuppressWarnings("unchecked") - public static S[] newSummaryArray(final S[] summaryArr, final int length) { - final Class summaryType = (Class) summaryArr.getClass().getComponentType(); - final S[] tmpSummaryArr = (S[]) Array.newInstance(summaryType, length); - return tmpSummaryArr; - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummary.java b/src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummary.java deleted file mode 100644 index e7268ffef..000000000 --- a/src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummary.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.adouble; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ByteArrayUtil; -import org.apache.datasketches.tuple.DeserializeResult; -import org.apache.datasketches.tuple.UpdatableSummary; - -/** - * Summary for generic tuple sketches of type Double. - * This summary keeps a double value. On update a predefined operation is performed depending on - * the mode. - * Supported modes: Sum, Min, Max, AlwaysOne, Increment. The default mode is Sum. - */ -public final class DoubleSummary implements UpdatableSummary { - private double value_; - private final Mode mode_; - - /** - * The aggregation modes for this Summary - */ - public enum Mode { - - /** - * The aggregation mode is the summation function. - * - *

New retained value = previous retained value + incoming value

- */ - Sum, - - /** - * The aggregation mode is the minimum function. - * - *

New retained value = min(previous retained value, incoming value)

- */ - Min, - - /** - * The aggregation mode is the maximum function. - * - *

New retained value = max(previous retained value, incoming value)

- */ - Max, - - /** - * The aggregation mode is always one. - * - *

New retained value = 1.0

- */ - AlwaysOne - } - - /** - * Creates an instance of DoubleSummary with a given starting value and mode - * @param value starting value - * @param mode update mode - */ - private DoubleSummary(final double value, final Mode mode) { - value_ = value; - mode_ = mode; - } - - /** - * Creates an instance of DoubleSummary with a given mode. - * @param mode update mode - */ - public DoubleSummary(final Mode mode) { - mode_ = mode; - switch (mode) { - case Sum: - value_ = 0; - break; - case Min: - value_ = Double.POSITIVE_INFINITY; - break; - case Max: - value_ = Double.NEGATIVE_INFINITY; - break; - case AlwaysOne: - value_ = 1.0; - break; - } - } - - @Override - public DoubleSummary update(final Double value) { - switch (mode_) { - case Sum: - value_ += value; - break; - case Min: - if (value < value_) { value_ = value; } - break; - case Max: - if (value > value_) { value_ = value; } - break; - case AlwaysOne: - value_ = 1.0; - break; - } - return this; - } - - @Override - public DoubleSummary copy() { - return new DoubleSummary(value_, mode_); - } - - /** - * Returns current value of the DoubleSummary - * @return current value of the DoubleSummary - */ - public double getValue() { - return value_; - } - - private static final int SERIALIZED_SIZE_BYTES = 9; - private static final int VALUE_INDEX = 0; - private static final int MODE_BYTE_INDEX = 8; - - @Override - public byte[] toByteArray() { - final byte[] bytes = new byte[SERIALIZED_SIZE_BYTES]; - ByteArrayUtil.putDoubleLE(bytes, VALUE_INDEX, value_); - bytes[MODE_BYTE_INDEX] = (byte) mode_.ordinal(); - return bytes; - } - - /** - * Creates an instance of the DoubleSummary given a serialized representation - * @param seg MemorySegment object with serialized DoubleSummary - * @return DeserializedResult object, which contains a DoubleSummary object and number of bytes - * read from the MemorySegment - */ - public static DeserializeResult fromMemorySegment(final MemorySegment seg) { - return new DeserializeResult<>(new DoubleSummary(seg.get(JAVA_DOUBLE_UNALIGNED, VALUE_INDEX), - Mode.values()[seg.get(JAVA_BYTE, MODE_BYTE_INDEX)]), SERIALIZED_SIZE_BYTES); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummaryDeserializer.java b/src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummaryDeserializer.java deleted file mode 100644 index 3027a3777..000000000 --- a/src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummaryDeserializer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.adouble; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.tuple.DeserializeResult; -import org.apache.datasketches.tuple.SummaryDeserializer; - -/** - * Implements SummaryDeserializer<DoubleSummary> - * @author Lee Rhodes - */ -public class DoubleSummaryDeserializer implements SummaryDeserializer { - - /** - * No argument constructor. - */ - public DoubleSummaryDeserializer() { } - - @Override - public DeserializeResult heapifySummary(final MemorySegment seg) { - return DoubleSummary.fromMemorySegment(seg); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummaryFactory.java b/src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummaryFactory.java deleted file mode 100644 index f97e835fc..000000000 --- a/src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummaryFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.adouble; - -import org.apache.datasketches.tuple.SummaryFactory; - -/** - * Factory for DoubleSummary. - * - * @author Lee Rhodes - */ -public final class DoubleSummaryFactory implements SummaryFactory { - - private final DoubleSummary.Mode summaryMode_; - - /** - * Creates an instance of DoubleSummaryFactory with a given mode - * @param summaryMode summary mode - */ - public DoubleSummaryFactory(final DoubleSummary.Mode summaryMode) { - summaryMode_ = summaryMode; - } - - @Override - public DoubleSummary newSummary() { - return new DoubleSummary(summaryMode_); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummarySetOperations.java b/src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummarySetOperations.java deleted file mode 100644 index 115706cdd..000000000 --- a/src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummarySetOperations.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.adouble; - -import org.apache.datasketches.tuple.SummarySetOperations; -import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode; - -/** - * Methods for defining how unions and intersections of two objects of type DoubleSummary - * are performed. - */ -public final class DoubleSummarySetOperations implements SummarySetOperations { - - private final Mode unionSummaryMode_; - - /** - * TupleIntersection is not well defined or even meaningful between numeric values. - * Nevertheless, this can be defined to be a different type of aggregation for intersecting hashes. - */ - private final Mode intersectionSummaryMode_; - - /** - * Creates an instance with default mode of sum for both union and intersection. - * This exists for backward compatibility. - */ - public DoubleSummarySetOperations() { - unionSummaryMode_ = DoubleSummary.Mode.Sum; - intersectionSummaryMode_ = DoubleSummary.Mode.Sum; - } - - /** - * Creates an instance given a DoubleSummary update mode where the mode is the same for both - * union and intersection. This exists for backward compatibility. - * @param summaryMode DoubleSummary update mode. - */ - public DoubleSummarySetOperations(final Mode summaryMode) { - unionSummaryMode_ = summaryMode; - intersectionSummaryMode_ = summaryMode; - } - - /** - * Creates an instance with two modes. - * @param unionSummaryMode for unions - * @param intersectionSummaryMode for intersections - */ - public DoubleSummarySetOperations(final Mode unionSummaryMode, final Mode intersectionSummaryMode) { - unionSummaryMode_ = unionSummaryMode; - intersectionSummaryMode_ = intersectionSummaryMode; - } - - @Override - public DoubleSummary union(final DoubleSummary a, final DoubleSummary b) { - final DoubleSummary result = new DoubleSummary(unionSummaryMode_); - result.update(a.getValue()); - result.update(b.getValue()); - return result; - } - - @Override - public DoubleSummary intersection(final DoubleSummary a, final DoubleSummary b) { - final DoubleSummary result = new DoubleSummary(intersectionSummaryMode_); - result.update(a.getValue()); - result.update(b.getValue()); - return result; - } -} diff --git a/src/main/java/org/apache/datasketches/tuple/adouble/DoubleTupleSketch.java b/src/main/java/org/apache/datasketches/tuple/adouble/DoubleTupleSketch.java deleted file mode 100644 index c5cffd744..000000000 --- a/src/main/java/org/apache/datasketches/tuple/adouble/DoubleTupleSketch.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.adouble; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.tuple.UpdatableTupleSketch; - -/** - * Extends UpdatableTupleSketch<Double, DoubleSummary> - * @author Lee Rhodes - */ -public class DoubleTupleSketch extends UpdatableTupleSketch { - - /** - * Constructs this sketch with given lgK. - * @param lgK Log_base2 of Nominal Entries. - * See Nominal Entries - * @param mode The DoubleSummary mode to be used - */ - public DoubleTupleSketch(final int lgK, final DoubleSummary.Mode mode) { - this(lgK, ResizeFactor.X8.ordinal(), 1.0F, mode); - } - - /** - * Creates this sketch with the following parameters: - * @param lgK Log_base2 of Nominal Entries. - * @param lgResizeFactor log2(resizeFactor) - value from 0 to 3: - *
-   * 0 - no resizing (max size allocated),
-   * 1 - double internal hash table each time it reaches a threshold
-   * 2 - grow four times
-   * 3 - grow eight times (default)
-   * 
- * @param samplingProbability - * See Sampling Probability - * @param mode The DoubleSummary mode to be used - */ - public DoubleTupleSketch(final int lgK, final int lgResizeFactor, final float samplingProbability, - final DoubleSummary.Mode mode) { - super(1 << lgK, lgResizeFactor, samplingProbability, new DoubleSummaryFactory(mode)); - } - - /** - * Constructs this sketch from a MemorySegment image, which must be from an DoubleTupleSketch, and - * usually with data. - * @param seg the given MemorySegment - * @param mode The DoubleSummary mode to be used - * @deprecated As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. - * This capability will be removed in a future release. - * Heapifying a CompactTupleSketch is not deprecated. - */ - @Deprecated - public DoubleTupleSketch(final MemorySegment seg, final DoubleSummary.Mode mode) { - super(seg, new DoubleSummaryDeserializer(), new DoubleSummaryFactory(mode)); - } - - @Override - public void update(final String key, final Double value) { - super.update(key, value); - } - - @Override - public void update(final long key, final Double value) { - super.update(key, value); - } -} diff --git a/src/main/java/org/apache/datasketches/tuple/adouble/package-info.java b/src/main/java/org/apache/datasketches/tuple/adouble/package-info.java deleted file mode 100644 index 8abbf2a01..000000000 --- a/src/main/java/org/apache/datasketches/tuple/adouble/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package is for a generic implementation of the Tuple sketch for single Double value. - */ -package org.apache.datasketches.tuple.adouble; diff --git a/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummary.java b/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummary.java deleted file mode 100644 index b8c7c23fb..000000000 --- a/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummary.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.aninteger; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ByteArrayUtil; -import org.apache.datasketches.tuple.DeserializeResult; -import org.apache.datasketches.tuple.UpdatableSummary; - -/** - * Summary for generic tuple sketches of type Integer. - * This summary keeps an Integer value. On update a predefined operation is performed depending on - * the mode. - * Supported modes: Sum, Min, Max, AlwaysOne, Increment. The default mode is Sum. - */ -public class IntegerSummary implements UpdatableSummary { - private int value_; - private final Mode mode_; - - /** - * The aggregation modes for this Summary - */ - public enum Mode { - - /** - * The aggregation mode is the summation function. - * - *

New retained value = previous retained value + incoming value

- */ - Sum, - - /** - * The aggregation mode is the minimum function. - * - *

New retained value = min(previous retained value, incoming value)

- */ - Min, - - /** - * The aggregation mode is the maximum function. - * - *

New retained value = max(previous retained value, incoming value)

- */ - Max, - - /** - * The aggregation mode is always one. - * - *

New retained value = 1

- */ - AlwaysOne - } - - /** - * Creates an instance of IntegerSummary with a given starting value and mode. - * @param value starting value - * @param mode update mode - */ - private IntegerSummary(final int value, final Mode mode) { - value_ = value; - mode_ = mode; - } - - /** - * Creates an instance of IntegerSummary with a given mode. - * @param mode update mode. This should not be called by a user. - */ - public IntegerSummary(final Mode mode) { - mode_ = mode; - switch (mode) { - case Sum: - value_ = 0; - break; - case Min: - value_ = Integer.MAX_VALUE; - break; - case Max: - value_ = Integer.MIN_VALUE; - break; - case AlwaysOne: - value_ = 1; - break; - } - } - - @Override - public IntegerSummary update(final Integer value) { - switch (mode_) { - case Sum: - value_ += value; - break; - case Min: - if (value < value_) { value_ = value; } - break; - case Max: - if (value > value_) { value_ = value; } - break; - case AlwaysOne: - value_ = 1; - break; - } - return this; - } - - @Override - public IntegerSummary copy() { - return new IntegerSummary(value_, mode_); - } - - /** - * Returns the current value of the IntegerSummary - * @return current value of the IntegerSummary - */ - public int getValue() { - return value_; - } - - private static final int SERIALIZED_SIZE_BYTES = 5; - private static final int VALUE_INDEX = 0; - private static final int MODE_BYTE_INDEX = 4; - - @Override - public byte[] toByteArray() { - final byte[] bytes = new byte[SERIALIZED_SIZE_BYTES]; - ByteArrayUtil.putIntLE(bytes, VALUE_INDEX, value_); - bytes[MODE_BYTE_INDEX] = (byte) mode_.ordinal(); - return bytes; - } - - /** - * Creates an instance of the IntegerSummary given a serialized representation - * @param seg MemorySegment object with serialized IntegerSummary - * @return DeserializedResult object, which contains a IntegerSummary object and number of bytes - * read from the MemorySegment - */ - public static DeserializeResult fromMemorySegment(final MemorySegment seg) { - return new DeserializeResult<>(new IntegerSummary(seg.get(JAVA_INT_UNALIGNED, VALUE_INDEX), - Mode.values()[seg.get(JAVA_BYTE, MODE_BYTE_INDEX)]), SERIALIZED_SIZE_BYTES); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummaryDeserializer.java b/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummaryDeserializer.java deleted file mode 100644 index 0fb8f55a5..000000000 --- a/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummaryDeserializer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.aninteger; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.tuple.DeserializeResult; -import org.apache.datasketches.tuple.SummaryDeserializer; - -/** - * Implements SummaryDeserializer<IntegerSummary> - * @author Lee Rhodes - */ -public class IntegerSummaryDeserializer implements SummaryDeserializer { - - /** - * No argument constructor. - */ - public IntegerSummaryDeserializer() { } - - @Override - public DeserializeResult heapifySummary(final MemorySegment seg) { - return IntegerSummary.fromMemorySegment(seg); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummaryFactory.java b/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummaryFactory.java deleted file mode 100644 index 0ebb729d5..000000000 --- a/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummaryFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.aninteger; - -import org.apache.datasketches.tuple.SummaryFactory; - -/** - * Factory for IntegerSummary. - * - * @author Lee Rhodes - */ -public class IntegerSummaryFactory implements SummaryFactory { - - private final IntegerSummary.Mode summaryMode_; - - /** - * Creates an instance of IntegerSummaryFactory with a given mode - * @param summaryMode summary mode - */ - public IntegerSummaryFactory(final IntegerSummary.Mode summaryMode) { - summaryMode_ = summaryMode; - } - - @Override - public IntegerSummary newSummary() { - return new IntegerSummary(summaryMode_); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummarySetOperations.java b/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummarySetOperations.java deleted file mode 100644 index b7c59ad01..000000000 --- a/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummarySetOperations.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.aninteger; - -import org.apache.datasketches.tuple.SummarySetOperations; -import org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode; - -/** - * Methods for defining how unions and intersections of two objects of type IntegerSummary - * are performed. - * - * @author Lee Rhodes - */ -public class IntegerSummarySetOperations implements SummarySetOperations { - - private final Mode unionSummaryMode_; - - /** - * TupleIntersection is not well defined or even meaningful between numeric values. - * Nevertheless, this can be defined to be a different type of aggregation for intersecting hashes. - */ - private final Mode intersectionSummaryMode_; - - /** - * Creates a new instance with two modes - * @param unionSummaryMode for unions - * @param intersectionSummaryMode for intersections - */ - public IntegerSummarySetOperations(final Mode unionSummaryMode, final Mode intersectionSummaryMode) { - unionSummaryMode_ = unionSummaryMode; - intersectionSummaryMode_ = intersectionSummaryMode; - } - - @Override - public IntegerSummary union(final IntegerSummary a, final IntegerSummary b) { - final IntegerSummary result = new IntegerSummary(unionSummaryMode_); - result.update(a.getValue()); - result.update(b.getValue()); - return result; - } - - @Override - public IntegerSummary intersection(final IntegerSummary a, final IntegerSummary b) { - final IntegerSummary result = new IntegerSummary(intersectionSummaryMode_); - result.update(a.getValue()); - result.update(b.getValue()); - return result; - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerTupleSketch.java b/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerTupleSketch.java deleted file mode 100644 index c261b7c31..000000000 --- a/src/main/java/org/apache/datasketches/tuple/aninteger/IntegerTupleSketch.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.aninteger; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.tuple.UpdatableTupleSketch; - -/** - * Extends UpdatableTupleSketch<Integer, IntegerSummary> - * @author Lee Rhodes - */ -public class IntegerTupleSketch extends UpdatableTupleSketch { - - /** - * Constructs this sketch with given lgK. - * @param lgK Log_base2 of Nominal Entries. - * See Nominal Entries - * @param mode The IntegerSummary mode to be used - */ - public IntegerTupleSketch(final int lgK, final IntegerSummary.Mode mode) { - this(lgK, ResizeFactor.X8.ordinal(), 1.0F, mode); - } - - /** - * Creates this sketch with the following parameters: - * @param lgK Log_base2 of Nominal Entries. - * @param lgResizeFactor log2(resizeFactor) - value from 0 to 3: - *
-   * 0 - no resizing (max size allocated),
-   * 1 - double internal hash table each time it reaches a threshold
-   * 2 - grow four times
-   * 3 - grow eight times (default)
-   * 
- * @param samplingProbability - * See Sampling Probability - * @param mode The IntegerSummary mode to be used - */ - public IntegerTupleSketch(final int lgK, final int lgResizeFactor, final float samplingProbability, - final IntegerSummary.Mode mode) { - super(1 << lgK, lgResizeFactor, samplingProbability, new IntegerSummaryFactory(mode)); - } - - /** - * Constructs this sketch from a MemorySegment image, which must be from an IntegerTupleSketch, and - * usually with data. - * @param seg the given MemorySegment - * @param mode The IntegerSummary mode to be used - * @deprecated As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. - * This capability will be removed in a future release. - * Heapifying a CompactTupleSketch is not deprecated. - */ - @Deprecated - public IntegerTupleSketch(final MemorySegment seg, final IntegerSummary.Mode mode) { - super(seg, new IntegerSummaryDeserializer(), new IntegerSummaryFactory(mode)); - } - - @Override - public void update(final String key, final Integer value) { - super.update(key, value); - } - - @Override - public void update(final long key, final Integer value) { - super.update(key, value); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/aninteger/package-info.java b/src/main/java/org/apache/datasketches/tuple/aninteger/package-info.java deleted file mode 100644 index f9c52a96f..000000000 --- a/src/main/java/org/apache/datasketches/tuple/aninteger/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package is for a generic implementation of the Tuple sketch for single Integer value. - */ -package org.apache.datasketches.tuple.aninteger; diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotB.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotB.java deleted file mode 100644 index 670038c01..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotB.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.lang.foreign.MemorySegment; - -/** - * Computes a set difference of two tuple sketches of type ArrayOfDoubles - */ -public abstract class ArrayOfDoublesAnotB { - - ArrayOfDoublesAnotB() {} - - /** - * Perform A-and-not-B set operation on the two given sketches. - * A null sketch is interpreted as an empty sketch. - * This is not an accumulating update. Calling update() more than once - * without calling getResult() will discard the result of previous update(). - * Both input sketches must have the same numValues. - * - * @param a The incoming sketch for the first argument - * @param b The incoming sketch for the second argument - */ - public abstract void update(ArrayOfDoublesSketch a, ArrayOfDoublesSketch b); - - /** - * Gets the result of this operation in the form of a ArrayOfDoublesCompactSketch - * @return compact sketch representing the result of the operation - */ - public abstract ArrayOfDoublesCompactSketch getResult(); - - /** - * Gets the result of this operation in the form of a ArrayOfDoublesCompactSketch - * @param seg MemorySegment for the result (can be null) - * @return compact sketch representing the result of the operation (off-heap if MemorySegment is - * provided) - */ - public abstract ArrayOfDoublesCompactSketch getResult(MemorySegment seg); - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotBImpl.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotBImpl.java deleted file mode 100644 index bec533a04..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotBImpl.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static java.lang.Math.min; -import static org.apache.datasketches.common.Util.exactLog2OfLong; -import static org.apache.datasketches.thetacommon.HashOperations.continueCondition; -import static org.apache.datasketches.thetacommon.HashOperations.convertToHashTable; -import static org.apache.datasketches.thetacommon.HashOperations.count; -import static org.apache.datasketches.thetacommon.HashOperations.hashSearch; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SuppressFBWarnings; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.SetOperationCornerCases; -import org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction; -import org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * Computes a set difference, A-AND-NOT-B, of two ArrayOfDoublesSketches. - * - *

This class includes a stateless operation as follows:

- * - *

- * CompactTupleSketch csk = anotb.aNotB(ArrayOfDoublesSketch skA, ArrayOfDoublesSketch skB);
- * 
- * - * @author Lee Rhodes - */ -public class ArrayOfDoublesAnotBImpl extends ArrayOfDoublesAnotB { - private int numValues_; - private short seedHash_; - - private long thetaLong_ = Long.MAX_VALUE; - private boolean empty_ = true; - private long[] keys_; - private double[] values_; - private int count_; - - ArrayOfDoublesAnotBImpl(final int numValues, final long seed) { - numValues_ = numValues; - seedHash_ = Util.computeSeedHash(seed); - } - - @Override - @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "This is OK here") - public void update(final ArrayOfDoublesSketch skA, final ArrayOfDoublesSketch skB) { - if (skA == null || skB == null) { - throw new SketchesArgumentException("Neither argument may be null."); - } - numValues_ = skA.getNumValues(); - seedHash_ = skA.getSeedHash(); - if (numValues_ != skB.getNumValues()) { - throw new SketchesArgumentException("Inputs cannot have different numValues"); - } - if (seedHash_ != skB.getSeedHash()) { - throw new SketchesArgumentException("Inputs cannot have different seedHashes"); - } - - final long thetaLongA = skA.getThetaLong(); - final int countA = skA.getRetainedEntries(); - final boolean emptyA = skA.isEmpty(); - - final long thetaLongB = skB.getThetaLong(); - final int countB = skB.getRetainedEntries(); - final boolean emptyB = skB.isEmpty(); - - final int id = - SetOperationCornerCases.createCornerCaseId(thetaLongA, countA, emptyA, thetaLongB, countB, emptyB); - final CornerCase cCase = CornerCase.caseIdToCornerCase(id); - final AnotbAction anotbAction = cCase.getAnotbAction(); - - final long minThetaLong = min(thetaLongA, thetaLongB); - - switch (anotbAction) { - case EMPTY_1_0_T: { - reset(); - break; - } - case DEGEN_MIN_0_F: { - keys_ = null; - values_ = null; - thetaLong_ = minThetaLong; - empty_ = false; - count_ = 0; - break; - } - case DEGEN_THA_0_F: { - keys_ = null; - values_ = null; - thetaLong_ = thetaLongA; - empty_ = false; - count_ = 0; - break; - } - case TRIM_A: { - final DataArrays daA = new DataArrays(skA.getKeys(), skA.getValuesAsOneDimension(), countA); - final DataArrays da = trimDataArrays(daA, minThetaLong, numValues_); - keys_ = da.hashArr; - values_ = da.valuesArr; - thetaLong_ = minThetaLong; - empty_ = skA.isEmpty(); - count_ = da.count; - break; - } - case SKETCH_A: { - final ArrayOfDoublesCompactSketch csk = skA.compact(); - keys_ = csk.getKeys(); - values_ = csk.getValuesAsOneDimension(); - thetaLong_ = csk.thetaLong_; - empty_ = csk.isEmpty(); - count_ = csk.getRetainedEntries(); - break; - } - case FULL_ANOTB: { //both A and B should have valid entries. - final long[] keysA = skA.getKeys(); - final double[] valuesA = skA.getValuesAsOneDimension(); - final DataArrays daR = getResultArrays(minThetaLong, countA, keysA, valuesA, skB); - count_ = daR.count; - keys_ = (count_ == 0) ? null : daR.hashArr; - values_ = (count_ == 0) ? null : daR.valuesArr; - thetaLong_ = minThetaLong; - empty_ = (minThetaLong == Long.MAX_VALUE) && (count_ == 0); - break; - } - //default: not possible - } - } - - @Override - public ArrayOfDoublesCompactSketch getResult() { - return new HeapArrayOfDoublesCompactSketch(keys_, values_, thetaLong_, empty_, numValues_, seedHash_); - } - - @Override - public ArrayOfDoublesCompactSketch getResult(final MemorySegment dstSeg) { - return new DirectArrayOfDoublesCompactSketch(keys_, values_, thetaLong_, empty_, numValues_, seedHash_, dstSeg); - } - - private static DataArrays getResultArrays( - final long minThetaLong, - final int countA, - final long[] hashArrA, - final double[] valuesArrA, - final ArrayOfDoublesSketch skB) { - final int numValues = skB.numValues_; - - //create hashtable of skB - final long[] hashTableB = convertToHashTable(skB.getKeys(), skB.getRetainedEntries(), minThetaLong, - ThetaUtil.REBUILD_THRESHOLD); - - //build temporary arrays of skA - long[] tmpHashArrA = new long[countA]; - double[] tmpValuesArrA = new double[countA * numValues]; - - //search for non matches and build temp arrays - final int lgHTBLen = exactLog2OfLong(hashTableB.length); - int nonMatches = 0; - for (int i = 0; i < countA; i++) { - final long hash = hashArrA[i]; - if (continueCondition(minThetaLong, hash)) { continue; } - final int index = hashSearch(hashTableB, lgHTBLen, hash); - if (index == -1) { - tmpHashArrA[nonMatches] = hash; - System.arraycopy(valuesArrA, i * numValues, tmpValuesArrA, nonMatches * numValues, numValues); - nonMatches++; - } - } - tmpHashArrA = Arrays.copyOf(tmpHashArrA, nonMatches); - tmpValuesArrA = Arrays.copyOf(tmpValuesArrA, nonMatches * numValues); - final DataArrays daR = new DataArrays(tmpHashArrA, tmpValuesArrA, nonMatches); - return daR; - } - - private static class DataArrays { - long[] hashArr; - double[] valuesArr; - int count; - - DataArrays(final long[] hashArr, final double[] valuesArr, final int count) { - this.hashArr = hashArr; - this.valuesArr = valuesArr; - this.count = count; - } - } - - private static DataArrays trimDataArrays(final DataArrays da, final long thetaLong, final int numValues) { - final long[] hashArrIn = da.hashArr; - final double[] valuesArrIn = da.valuesArr; - final int count = count(hashArrIn, thetaLong); - final long[] hashArrOut = new long[count]; - final double[] valuesArrOut = new double[count * numValues]; - int haInIdx; - int vaInIdx = 0; - int haOutIdx = 0; - int vaOutIdx = 0; - for (haInIdx = 0; haInIdx < count; haInIdx++, vaInIdx += numValues) { - final long hash = hashArrIn[haInIdx]; - if (continueCondition(thetaLong, hash)) { continue; } - hashArrOut[haOutIdx] = hashArrIn[haInIdx]; - System.arraycopy(valuesArrIn, vaInIdx, valuesArrOut, vaOutIdx, numValues); - haOutIdx++; - vaOutIdx += numValues; - } - return new DataArrays(hashArrOut, valuesArrOut, count); - } - - private void reset() { - empty_ = true; - thetaLong_ = Long.MAX_VALUE; - keys_ = null; - values_ = null; - count_ = 0; - } -} - diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCombiner.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCombiner.java deleted file mode 100644 index 6ababc5a5..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCombiner.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -/** - * Combines two arrays of double values for use with ArrayOfDoubles tuple sketches - */ -public interface ArrayOfDoublesCombiner { - - /** - * Method of combining two arrays of double values - * @param a Array A. - * @param b Array B. - * @return Result of combining A and B - */ - public double[] combine(double[] a, double[] b); - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCompactSketch.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCompactSketch.java deleted file mode 100644 index 1cf3ac040..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCompactSketch.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -/** - * Top level compact tuple sketch of type ArrayOfDoubles. Compact sketches are never created - * directly. They are created as a result of the compact() method on a QuickSelectSketch - * or the getResult() method of a set operation like TupleUnion, TupleIntersection or TupleAnotB. - * A CompactTupleSketch consists of a compact list (i.e. no intervening spaces) of hash values, - * a corresponding list of double values, and a value for theta. The lists may or may - * not be ordered. It is read-only. - */ -public abstract class ArrayOfDoublesCompactSketch extends ArrayOfDoublesSketch { - - static final byte serialVersionUID = 1; - - // Layout of retained entries: - // Long || Start Byte Adr: - // Adr: - // || 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 | - // 3 ||-----------------------------------|----------Retained Entries------------| - - static final int EMPTY_SIZE = 16; - static final int RETAINED_ENTRIES_INT = 16; - // 4 bytes of padding for 8 byte alignment - static final int ENTRIES_START = 24; - - ArrayOfDoublesCompactSketch(final int numValues) { - super(numValues); - } - - @Override - public int getCurrentBytes() { - final int count = getRetainedEntries(); - int sizeBytes = EMPTY_SIZE; - if (count > 0) { - sizeBytes = ENTRIES_START + (SIZE_OF_KEY_BYTES * count) - + (SIZE_OF_VALUE_BYTES * numValues_ * count); - } - return sizeBytes; - } - - @Override - public int getMaxBytes() { - return getCurrentBytes(); - } -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesIntersection.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesIntersection.java deleted file mode 100644 index 91d51b483..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesIntersection.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static java.lang.Math.min; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.Util; - -/** - * Computes the intersection of two or more tuple sketches of type ArrayOfDoubles. - * A new instance represents the Universal Set. - * Every update() computes an intersection with the internal set - * and can only reduce the internal set. - */ -public abstract class ArrayOfDoublesIntersection { - //not changed by resetToEmpty() or hardReset() - private final short seedHash_; - private final int numValues_; - //nulled or reset by resetToEmpty - private HashTables hashTables_; - private boolean empty_; - private boolean firstCall_; - private long thetaLong_; - - /** - * Internal constructor, called by HeapArrayOfDoublesIntersection and DirectArrayOfDoublesIntersection - * @param numValues the number of double values in the summary array - * @param seed the hash function update seed. - */ - ArrayOfDoublesIntersection(final int numValues, final long seed) { - seedHash_ = Util.computeSeedHash(seed); - numValues_ = numValues; - hashTables_ = null; - empty_ = false; - thetaLong_ = Long.MAX_VALUE; - firstCall_ = true; - } - - /** - * Performs a stateful intersection of the internal set with the given TupleSketch. - * The given TupleSketch and the internal state must have the same numValues. - * @param tupleSketch Input sketch to intersect with the internal set. - * @param combiner Method of combining two arrays of double values - */ - public void intersect(final ArrayOfDoublesSketch tupleSketch, final ArrayOfDoublesCombiner combiner) { - if (tupleSketch == null) { throw new SketchesArgumentException("TupleSketch must not be null"); } - Util.checkSeedHashes(seedHash_, tupleSketch.getSeedHash()); - if (tupleSketch.numValues_ != numValues_) { - throw new SketchesArgumentException( - "Input TupleSketch cannot have different numValues from the internal numValues."); - } - - final boolean isFirstCall = firstCall_; - firstCall_ = false; - - //could be first or next call - - final boolean emptyIn = tupleSketch.isEmpty(); - if (empty_ || emptyIn) { //empty rule - //Whatever the current internal state, we make our local empty. - resetToEmpty(); // - return; - } - - final long thetaLongIn = tupleSketch.getThetaLong(); - thetaLong_ = min(thetaLong_, thetaLongIn); //Theta rule - - if (tupleSketch.getRetainedEntries() == 0) { - if (hashTables_ != null) { - hashTables_.clear(); - } - } - // input sketch will have valid entries > 0 - - if (isFirstCall) { - //Copy first sketch data into local instance hashTables_ - hashTables_ = new HashTables(tupleSketch); - } - - //Next Call - else { - assert hashTables_ != null; - if (hashTables_.getNumKeys() == 0) { return; } - //process intersect with current hashTables - hashTables_ = hashTables_.getIntersectHashTables(tupleSketch, thetaLong_, combiner); - } - } - - /** - * Gets the internal set as an on-heap compact sketch. - * @return Result of the intersections so far as a compact sketch. - */ - public ArrayOfDoublesCompactSketch getResult() { - return getResult(null); - } - - /** - * Gets the result of stateful intersections so far. - * @param dstSeg MemorySegment for the compact sketch (can be null). - * @return Result of the intersections so far as a compact sketch. - */ - public ArrayOfDoublesCompactSketch getResult(final MemorySegment dstSeg) { - if (firstCall_) { - throw new SketchesStateException( - "getResult() with no intervening intersections is not a legal result."); - } - long[] hashArrOut = new long[0]; - double[] valuesArrOut = new double[0]; - if (hashTables_ != null && hashTables_.getHashTable() != null) { - final int numKeys = hashTables_.getNumKeys(); - - if (numKeys > 0) { - final int tableSize = hashTables_.getHashTable().length; - - hashArrOut = new long[numKeys]; - valuesArrOut = new double[numKeys * numValues_]; - - // & flatten the hash tables - int cnt = 0; - final long[] hashTable = hashTables_.getHashTable(); - final double[][] valueTable = hashTables_.getValueTable(); - for (int i = 0; i < tableSize; i++) { - final long hash = hashTable[i]; - if (hash == 0 || hash > thetaLong_) { continue; } - hashArrOut[cnt] = hash; - System.arraycopy(valueTable[i], 0, valuesArrOut, cnt * numValues_, numValues_); - cnt++; - } - assert cnt == numKeys; - } - } - - return (dstSeg == null) - ? new HeapArrayOfDoublesCompactSketch(hashArrOut, valuesArrOut, - thetaLong_, empty_, numValues_, seedHash_) - : new DirectArrayOfDoublesCompactSketch(hashArrOut, valuesArrOut, - thetaLong_, empty_, numValues_, seedHash_, dstSeg); - } - - /** - * Resets the internal set to the initial state, which represents the Universal Set - */ - public void reset() { - hardReset(); - } - - private void hardReset() { - empty_ = false; - firstCall_ = true; - thetaLong_ = Long.MAX_VALUE; - if (hashTables_ != null) { hashTables_.clear(); } - } - - private void resetToEmpty() { - empty_ = true; - firstCall_ = false; - thetaLong_ = Long.MAX_VALUE; - if (hashTables_ != null) { hashTables_.clear(); } - } - - protected abstract ArrayOfDoublesQuickSelectSketch createSketch(int nomEntries, int numValues, long seed); - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesQuickSelectSketch.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesQuickSelectSketch.java deleted file mode 100644 index ddf102451..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesQuickSelectSketch.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static org.apache.datasketches.common.Util.ceilingPowerOf2; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.QuickSelect; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * Top level class for hash table based implementations of tuple sketch of type - * ArrayOfDoubles that uses the QuickSelect algorithm. - */ -abstract class ArrayOfDoublesQuickSelectSketch extends ArrayOfDoublesUpdatableSketch { - - static final byte serialVersionUID = 1; - - // Layout of next 16 bytes: - // Long || Start Byte Adr: - // Adr: - // || 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 | - // 3 ||-----------P (float)---------------|--------|--lgRF--|--lgArr-|---lgNom---| - // || 31 | 30 | 29 | 28 | 27 | 26 | 25 | 24 | - // 4 ||-----------------------------------|----------Retained Entries------------| - - static final int LG_NOM_ENTRIES_BYTE = 16; - static final int LG_CUR_CAPACITY_BYTE = 17; - static final int LG_RESIZE_FACTOR_BYTE = 18; - // 1 byte of padding for alignment - static final int SAMPLING_P_FLOAT = 20; - static final int RETAINED_ENTRIES_INT = 24; - // 4 bytes of padding for alignment - static final int ENTRIES_START = 32; - - static final int DEFAULT_LG_RESIZE_FACTOR = 3; - - // these can be derived from other things, but are kept here for performance - int rebuildThreshold_; //absolute value relative to current capacity - int lgCurrentCapacity_; - - ArrayOfDoublesQuickSelectSketch(final int numValues, final long seed) { - super(numValues, seed); - } - - abstract void updateValues(int index, double[] values); - - abstract void setNotEmpty(); - - abstract boolean isInSamplingMode(); - - abstract void rebuild(int newCapacity); - - abstract long getKey(int index); - - abstract void setValues(int index, double[] values); - - abstract void incrementCount(); - - abstract void setThetaLong(long thetaLong); - - abstract int insertKey(long key); - - abstract int findOrInsertKey(long key); - - abstract double[] find(long key); - - abstract int getSerializedSizeBytes(); - - abstract void serializeInto(MemorySegment seg); - - @Override - public void trim() { - if (getRetainedEntries() > getNominalEntries()) { - setThetaLong(getNewThetaLong()); - rebuild(); - } - } - - @Override - public int getMaxBytes() { - final int nomEntries = getNominalEntries(); - final int numValues = getNumValues(); - return getMaxBytes(nomEntries, numValues); - } - - @Override - public int getCurrentBytes() { - return getSerializedSizeBytes(); - } - - /** - * @param nomEntries Nominal number of entries. Forced to the nearest power of 2 greater than or equal to - * given value. - * @param numValues Number of double values to keep for each key - * @return maximum required storage bytes given nomEntries and numValues - */ - static int getMaxBytes(final int nomEntries, final int numValues) { - return ENTRIES_START - + (SIZE_OF_KEY_BYTES + SIZE_OF_VALUE_BYTES * numValues) * ceilingPowerOf2(nomEntries) * 2; - } - - // non-public methods below - - // this is a special back door insert for merging - // not sufficient by itself without keeping track of theta of another sketch - void merge(final long key, final double[] values) { - setNotEmpty(); - if (key < thetaLong_) { - final int index = findOrInsertKey(key); - if (index < 0) { - incrementCount(); - setValues(~index, values); - } else { - updateValues(index, values); - } - rebuildIfNeeded(); - } - } - - void rebuildIfNeeded() { - if (getRetainedEntries() <= rebuildThreshold_) { return; } - if (getCurrentCapacity() > getNominalEntries()) { - setThetaLong(getNewThetaLong()); - rebuild(); - } else { - rebuild(getCurrentCapacity() * getResizeFactor().getValue()); - } - } - - void rebuild() { - rebuild(getCurrentCapacity()); - } - - void insert(final long key, final double[] values) { - final int index = insertKey(key); - setValues(index, values); - incrementCount(); - } - - final void setRebuildThreshold() { - if (getCurrentCapacity() > getNominalEntries()) { - rebuildThreshold_ = (int) (getCurrentCapacity() * ThetaUtil.REBUILD_THRESHOLD); - } else { - rebuildThreshold_ = (int) (getCurrentCapacity() * ThetaUtil.RESIZE_THRESHOLD); - } - } - - @Override - void insertOrIgnore(final long key, final double[] values) { - if (values.length != getNumValues()) { - throw new SketchesArgumentException("input array of values must have " + getNumValues() - + " elements, but has " + values.length); - } - setNotEmpty(); - if ((key == 0) || (key >= thetaLong_)) { return; } - final int index = findOrInsertKey(key); - if (index < 0) { - incrementCount(); - setValues(~index, values); - } else { - updateValues(index, values); - } - rebuildIfNeeded(); - } - - long getNewThetaLong() { - final long[] keys = new long[getRetainedEntries()]; - int i = 0; - for (int j = 0; j < getCurrentCapacity(); j++) { - final long key = getKey(j); - if (key != 0) { keys[i++] = key; } - } - return QuickSelect.select(keys, 0, getRetainedEntries() - 1, getNominalEntries()); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSetOperationBuilder.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSetOperationBuilder.java deleted file mode 100644 index 14177b499..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSetOperationBuilder.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Util; - -/** - * Builds set operations object for tuple sketches of type ArrayOfDoubles. - */ -public class ArrayOfDoublesSetOperationBuilder { - - private int nomEntries_; - private int numValues_; - private long seed_; - - /** - * Default Nominal Entries (a.k.a. K) - */ - public static final int DEFAULT_NOMINAL_ENTRIES = 4096; - - /** - * Default number of values - */ - public static final int DEFAULT_NUMBER_OF_VALUES = 1; - - /** - * Creates an instance of the builder with default parameters - */ - public ArrayOfDoublesSetOperationBuilder() { - nomEntries_ = DEFAULT_NOMINAL_ENTRIES; - numValues_ = DEFAULT_NUMBER_OF_VALUES; - seed_ = Util.DEFAULT_UPDATE_SEED; - } - - /** - * This is to set the nominal number of entries. - * @param nomEntries Nominal number of entries. Forced to the nearest power of 2 greater than - * given value. - * @return this builder - */ - public ArrayOfDoublesSetOperationBuilder setNominalEntries(final int nomEntries) { - nomEntries_ = nomEntries; - return this; - } - - /** - * This is to set the number of double values associated with each key - * @param numValues number of double values - * @return this builder - */ - public ArrayOfDoublesSetOperationBuilder setNumberOfValues(final int numValues) { - numValues_ = numValues; - return this; - } - - /** - * Sets the long seed value that is required by the hashing function. - * @param seed See seed - * @return this builder - */ - public ArrayOfDoublesSetOperationBuilder setSeed(final long seed) { - seed_ = seed; - return this; - } - - /** - * Creates an instance of ArrayOfDoublesUnion based on the current configuration of the builder. - * The new instance is allocated on the heap. - * @return an instance of ArrayOfDoublesUnion - */ - public ArrayOfDoublesUnion buildUnion() { - return new HeapArrayOfDoublesUnion(nomEntries_, numValues_, seed_); - } - - /** - * Creates an instance of ArrayOfDoublesUnion based on the current configuration of the builder - * and the given destination MemorySegment. - * @param dstSeg destination MemorySegment to be used by the sketch - * @return an instance of ArrayOfDoublesUnion - */ - public ArrayOfDoublesUnion buildUnion(final MemorySegment dstSeg) { - return new DirectArrayOfDoublesUnion(nomEntries_, numValues_, seed_, dstSeg); - } - - /** - * Creates an instance of ArrayOfDoublesIntersection based on the current configuration of the - * builder. - * The new instance is allocated on the heap. - * The number of nominal entries is not relevant to this, so it is ignored. - * @return an instance of ArrayOfDoublesIntersection - */ - public ArrayOfDoublesIntersection buildIntersection() { - return new HeapArrayOfDoublesIntersection(numValues_, seed_); - } - - /** - * Creates an instance of ArrayOfDoublesIntersection in the given MemorySegment and based on the - * current configuration of the builder. - * The number of nominal entries is not relevant to this, so it is ignored. - * @param dstSeg destination MemorySegment to be used by the sketch - * @return an instance of ArrayOfDoublesIntersection - */ - public ArrayOfDoublesIntersection buildIntersection(final MemorySegment dstSeg) { - return new DirectArrayOfDoublesIntersection(numValues_, seed_, dstSeg); - } - - /** - * Creates an instance of ArrayOfDoublesAnotB based on the current configuration of the builder. - * The number of nominal entries is not relevant to this, so it is ignored. - * @return an instance of ArrayOfDoublesAnotB - */ - public ArrayOfDoublesAnotB buildAnotB() { - return new ArrayOfDoublesAnotBImpl(numValues_, seed_); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketch.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketch.java deleted file mode 100644 index 6fb1aacaa..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketch.java +++ /dev/null @@ -1,414 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static org.apache.datasketches.common.Util.LS; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.BinomialBoundsN; -import org.apache.datasketches.tuple.SerializerDeserializer; - -/** - * The base class for the tuple sketch of type ArrayOfDoubles, where an array of double values - * is associated with each key. - * A primitive array of doubles is used here, as opposed to a generic Summary object, - * for improved performance. - */ -public abstract class ArrayOfDoublesSketch { - - // The concept of being empty is about representing an empty set. - // So a sketch can be non-empty, and have no entries. - // For example, as a result of a sampling, when some data was presented to the sketch, but no - // entries were retained. - enum Flags { IS_RESERVED, IS_IN_SAMPLING_MODE, IS_EMPTY, HAS_ENTRIES } - - static final int SIZE_OF_KEY_BYTES = Long.BYTES; - static final int SIZE_OF_VALUE_BYTES = Double.BYTES; - - // Common Layout of first 16 bytes and Empty AoDCompactSketch: - // Long || Start Byte Adr: - // Adr: - // || 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | - // 0 || Seed Hash | #Dbls | Flags | SkType | FamID | SerVer | Preamble_Longs | - // || 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 | - // 1 ||-------------------------Theta Long------------------------------------------------| - - static final int PREAMBLE_LONGS_BYTE = 0; // not used, always 1 - static final int SERIAL_VERSION_BYTE = 1; - static final int FAMILY_ID_BYTE = 2; - static final int SKETCH_TYPE_BYTE = 3; - static final int FLAGS_BYTE = 4; - static final int NUM_VALUES_BYTE = 5; - static final int SEED_HASH_SHORT = 6; - static final int THETA_LONG = 8; - - final int numValues_; - - long thetaLong_; - boolean isEmpty_ = true; - - ArrayOfDoublesSketch(final int numValues) { - numValues_ = numValues; - } - - /** - * Heapify the given MemorySegment as an ArrayOfDoublesSketch - * @param seg the given MemorySegment - * @return an ArrayOfDoublesSketch - */ - public static ArrayOfDoublesSketch heapify(final MemorySegment seg) { - return heapify(seg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Heapify the given MemorySegment and seed as a ArrayOfDoublesSketch - * @param seg the given MemorySegment - * @param seed the given seed - * @return an ArrayOfDoublesSketch - */ - public static ArrayOfDoublesSketch heapify(final MemorySegment seg, final long seed) { - final SerializerDeserializer.SketchType sketchType = SerializerDeserializer.getSketchType(seg); - if (sketchType == SerializerDeserializer.SketchType.ArrayOfDoublesQuickSelectSketch) { - return new HeapArrayOfDoublesQuickSelectSketch(seg, seed); - } - return new HeapArrayOfDoublesCompactSketch(seg, seed); - } - - /** - * Wrap the given MemorySegment as an ArrayOfDoublesSketch. - * If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only. - * @param seg the given MemorySegment - * @return an ArrayOfDoublesSketch - */ - public static ArrayOfDoublesSketch wrap(final MemorySegment seg) { - return wrap(seg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Wrap the given MemorySegment and seed as a ArrayOfDoublesSketch. - * If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only. - * @param seg the given MemorySegment - * @param seed the given seed - * @return an ArrayOfDoublesSketch - */ - public static ArrayOfDoublesSketch wrap(final MemorySegment seg, final long seed) { - final SerializerDeserializer.SketchType sketchType = SerializerDeserializer.getSketchType(seg); - if (sketchType == SerializerDeserializer.SketchType.ArrayOfDoublesQuickSelectSketch) { - return new DirectArrayOfDoublesQuickSelectSketchR(seg, seed); - } - return new DirectArrayOfDoublesCompactSketch(seg, seed); - } - - /** - * Estimates the cardinality of the set (number of unique values presented to the sketch) - * @return best estimate of the number of unique values - */ - public double getEstimate() { - if (!isEstimationMode()) { return getRetainedEntries(); } - return getRetainedEntries() / getTheta(); - } - - /** - * Gets the approximate upper error bound given the specified number of Standard Deviations. - * This will return getEstimate() if isEmpty() is true. - * - * @param numStdDev - * See Number of Standard Deviations - * @return the upper bound. - */ - public double getUpperBound(final int numStdDev) { - if (!isEstimationMode()) { return getRetainedEntries(); } - return BinomialBoundsN.getUpperBound(getRetainedEntries(), getTheta(), numStdDev, isEmpty_); - } - - /** - * Gets the approximate lower error bound given the specified number of Standard Deviations. - * This will return getEstimate() if isEmpty() is true. - * - * @param numStdDev - * See Number of Standard Deviations - * @return the lower bound. - */ - public double getLowerBound(final int numStdDev) { - if (!isEstimationMode()) { return getRetainedEntries(); } - return BinomialBoundsN.getLowerBound(getRetainedEntries(), getTheta(), numStdDev, isEmpty_); - } - - /** - * Returns true if this sketch's data structure is backed by MemorySegment. - * @return true if this sketch's data structure is backed by MemorySegment. - */ - public abstract boolean hasMemorySegment(); - - /** - * Returns the MemorySegment object if it exists, otherwise null. - * @return the MemorySegment object if it exists, otherwise null. - */ - abstract MemorySegment getMemorySegment(); - - /** - * See Empty - * @return true if empty. - */ - public boolean isEmpty() { - return isEmpty_; - } - - /** - * Returns number of double values associated with each key - * @return number of double values associated with each key - */ - public int getNumValues() { - return numValues_; - } - - /** - * Returns true if the sketch is Estimation Mode (as opposed to Exact Mode). - * This is true if theta < 1.0 AND isEmpty() is false. - * @return true if the sketch is in estimation mode. - */ - public boolean isEstimationMode() { - return ((thetaLong_ < Long.MAX_VALUE) && !isEmpty()); - } - - /** - * Gets the value of theta as a double between zero and one - * @return the value of theta as a double - */ - public double getTheta() { - return getThetaLong() / (double) Long.MAX_VALUE; - } - - /** - * Returns number of retained entries - * @return number of retained entries - */ - public abstract int getRetainedEntries(); - - /** - * Returns the maximum number of bytes for this sketch when serialized. - * @return the maximum number of bytes for this sketch when serialized. - */ - public abstract int getMaxBytes(); - - /** - * For compact sketches this is the same as getMaxBytes(). - * @return the current number of bytes for this sketch when serialized. - */ - public abstract int getCurrentBytes(); - - /** - * Returns serialized representation of the sketch - * @return serialized representation of the sketch - */ - public abstract byte[] toByteArray(); - - /** - * Returns array of arrays of double values in the sketch - * @return array of arrays of double values in the sketch - */ - public abstract double[][] getValues(); - - abstract double[] getValuesAsOneDimension(); - - abstract long[] getKeys(); - - /** - * Returns the value of theta as a long - * @return the value of theta as a long - */ - long getThetaLong() { - return isEmpty() ? Long.MAX_VALUE : thetaLong_; - } - - abstract short getSeedHash(); - - /** - * Returns an iterator over the sketch - * @return an iterator over the sketch - */ - public abstract ArrayOfDoublesSketchIterator iterator(); - - /** - * Returns this sketch in compact form, which is immutable. - * @return this sketch in compact form, which is immutable. - */ - public ArrayOfDoublesCompactSketch compact() { - return compact(null); - } - - /** - * Returns this sketch in compact form, which is immutable. - * @param dstSeg the destination MemorySegment - * @return this sketch in compact form, which is immutable. - */ - public abstract ArrayOfDoublesCompactSketch compact(MemorySegment dstSeg); - - @Override - public String toString() { - final int seedHash = Short.toUnsignedInt(getSeedHash()); - final StringBuilder sb = new StringBuilder(); - sb.append("### ").append(this.getClass().getSimpleName()).append(" SUMMARY: ").append(LS); - sb.append(" Estimate : ").append(getEstimate()).append(LS); - sb.append(" Upper Bound, 95% conf : ").append(getUpperBound(2)).append(LS); - sb.append(" Lower Bound, 95% conf : ").append(getLowerBound(2)).append(LS); - sb.append(" Theta (double) : ").append(getTheta()).append(LS); - sb.append(" Theta (long) : ").append(getThetaLong()).append(LS); - sb.append(" EstMode? : ").append(isEstimationMode()).append(LS); - sb.append(" Empty? : ").append(isEmpty()).append(LS); - sb.append(" Retained Entries : ").append(getRetainedEntries()).append(LS); - if (this instanceof ArrayOfDoublesUpdatableSketch) { - final ArrayOfDoublesUpdatableSketch updatable = (ArrayOfDoublesUpdatableSketch) this; - sb.append(" Nominal Entries (k) : ").append(updatable.getNominalEntries()).append(LS); - sb.append(" Current Capacity : ").append(updatable.getCurrentCapacity()).append(LS); - sb.append(" Resize Factor : ").append(updatable.getResizeFactor().getValue()).append(LS); - sb.append(" Sampling Probability (p): ").append(updatable.getSamplingProbability()).append(LS); - } - sb.append(" Seed Hash : ") - .append(Integer.toHexString(seedHash)).append(" | ").append(seedHash).append(LS); - sb.append("### END SKETCH SUMMARY").append(LS); - return sb.toString(); - } - - // Convenient static methods to instantiate tuple sketches of type ArrayOfDoubles. - - /** - * Wrap the given MemorySegment and seed as an ArrayOfDoublesUnion - * If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only. - * @param srcSeg the given source MemorySegment - * @param seed the given seed - * @return an ArrayOfDoublesUnion - */ - public static ArrayOfDoublesUnion wrapUnion(final MemorySegment srcSeg, final long seed) { - return ArrayOfDoublesUnion.wrap(srcSeg, seed); - } - - /** - * Wrap the given MemorySegment as an ArrayOfDoublesUnion - * If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only. - * @param srcSeg the given source MemorySegment - * @return an ArrayOfDoublesUnion - */ - public static ArrayOfDoublesUnion wrapUnion(final MemorySegment srcSeg) { - return ArrayOfDoublesSketch.wrapUnion(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Heapify the given MemorySegment and seed as an ArrayOfDoublesUnion - * @param srcSeg the given source MemorySegment - * @param seed the given seed - * @return an ArrayOfDoublesUnion - */ - public static ArrayOfDoublesUnion heapifyUnion(final MemorySegment srcSeg, final long seed) { - return ArrayOfDoublesUnion.heapify(srcSeg, seed); - } - - /** - * Heapify the given MemorySegment as an ArrayOfDoublesUnion - * @param srcSeg the given source MemorySegment - * @return an ArrayOfDoublesUnion - */ - public static ArrayOfDoublesUnion heapifyUnion(final MemorySegment srcSeg) { - return ArrayOfDoublesSketch.heapifyUnion(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Wrap the given MemorySegment and seed as a ArrayOfDoublesUpdatableSketch. - * If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only. - * @param srcSeg the given source MemorySegment - * @param seed the given seed - * @return an ArrayOfDoublesUpdatableSketch - */ - public static ArrayOfDoublesUpdatableSketch wrapUpdatableSketch(final MemorySegment srcSeg, final long seed) { - return ArrayOfDoublesUpdatableSketch.wrap(srcSeg, seed); - } - - /** - * Wrap the given MemorySegment as an ArrayOfDoublesUpdatableSketch. - * If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only. - * @param srcSeg the given source MemorySegment - * @return an ArrayOfDoublesUpdatableSketch - */ - public static ArrayOfDoublesUpdatableSketch wrapUpdatableSketch(final MemorySegment srcSeg) { - return ArrayOfDoublesSketch.wrapUpdatableSketch(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Wrap the given MemorySegment and seed as a ArrayOfDoublesSketch. - * If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only. - * @param srcSeg the given source MemorySegment - * @param seed the given seed - * @return an ArrayOfDoublesSketch - */ - public static ArrayOfDoublesSketch wrapSketch(final MemorySegment srcSeg, final long seed) { - return wrap(srcSeg, seed); - } - - /** - * Wrap the given MemorySegment as an ArrayOfDoublesSketch. - * If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only. - * @param srcSeg the given source MemorySegment - * @return an ArrayOfDoublesSketch - */ - public static ArrayOfDoublesSketch wrapSketch(final MemorySegment srcSeg) { - return ArrayOfDoublesSketch.wrapSketch(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Heapify the given MemorySegment and seed as a ArrayOfDoublesUpdatableSketch - * @param srcSeg the given source MemorySegment - * @param seed the given seed - * @return an ArrayOfDoublesUpdatableSketch - */ - public static ArrayOfDoublesUpdatableSketch heapifyUpdatableSketch(final MemorySegment srcSeg, final long seed) { - return ArrayOfDoublesUpdatableSketch.heapify(srcSeg, seed); - } - - /** - * Heapify the given MemorySegment as an ArrayOfDoublesUpdatableSketch - * @param srcSeg the given source MemorySegment - * @return an ArrayOfDoublesUpdatableSketch - */ - public static ArrayOfDoublesUpdatableSketch heapifyUpdatableSketch(final MemorySegment srcSeg) { - return ArrayOfDoublesSketch.heapifyUpdatableSketch(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Heapify the given MemorySegment and seed as a ArrayOfDoublesSketch - * @param srcSeg the given source MemorySegment - * @param seed the given seed - * @return an ArrayOfDoublesSketch - */ - public static ArrayOfDoublesSketch heapifySketch(final MemorySegment srcSeg, final long seed) { - return heapify(srcSeg, seed); - } - - /** - * Heapify the given MemorySegment as an ArrayOfDoublesSketch - * @param srcSeg the given source MemorySegment - * @return an ArrayOfDoublesSketch - */ - public static ArrayOfDoublesSketch heapifySketch(final MemorySegment srcSeg) { - return ArrayOfDoublesSketch.heapifySketch(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketchIterator.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketchIterator.java deleted file mode 100644 index 86b9543a1..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketchIterator.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -/** - * Interface for iterating over tuple sketches of type ArrayOfDoubles - */ -public interface ArrayOfDoublesSketchIterator { - /** - * Advancing the iterator and checking existence of the next entry - * is combined here for efficiency. This results in an undefined - * state of the iterator before the first call of this method. - * @return true if the next element exists - */ - public boolean next(); - - /** - * Gets a key from the current entry in the sketch, which is a hash - * of the original key passed to update(). The original keys are not - * retained. Don't call this before calling next() for the first time - * or after getting false from next(). - * @return hash key from the current entry - */ - public long getKey(); - - /** - * Gets an array of values from the current entry in the sketch. - * Don't call this before calling next() for the first time - * or after getting false from next(). - * @return array of double values for the current entry (may or may not be a copy) - */ - public double[] getValues(); -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUnion.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUnion.java deleted file mode 100644 index 2d11551ee..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUnion.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static java.lang.Math.min; -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.tuple.SerializerDeserializer; - -/** - * The base class for unions of tuple sketches of type ArrayOfDoubles. - */ -public abstract class ArrayOfDoublesUnion { - - static final byte serialVersionUID = 1; - //For layout see toByteArray() - static final int PREAMBLE_SIZE_BYTES = 16; - static final int PREAMBLE_LONGS_BYTE = 0; // not used, always 1 - static final int SERIAL_VERSION_BYTE = 1; - static final int FAMILY_ID_BYTE = 2; - static final int SKETCH_TYPE_BYTE = 3; - static final int FLAGS_BYTE = 4; - static final int NUM_VALUES_BYTE = 5; - static final int SEED_HASH_SHORT = 6; - static final int THETA_LONG = 8; - - ArrayOfDoublesQuickSelectSketch gadget_; - long unionThetaLong_; - - /** - * Constructs this TupleUnion initializing it with the given sketch, which can be on-heap or off-heap. - * @param sketch the given sketch. - */ - ArrayOfDoublesUnion(final ArrayOfDoublesQuickSelectSketch sketch) { - gadget_ = sketch; - unionThetaLong_ = sketch.getThetaLong(); - } - - /** - * Heapify the given MemorySegment as an ArrayOfDoublesUnion. - * @param srcSeg the given source MemorySegment - * @return an ArrayOfDoublesUnion - */ - public static ArrayOfDoublesUnion heapify(final MemorySegment srcSeg) { - return heapify(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Heapify the given MemorySegment and seed as an ArrayOfDoublesUnion. - * @param srcSeg the given source MemorySegment - * @param seed the given seed - * @return an ArrayOfDoublesUnion - */ - public static ArrayOfDoublesUnion heapify(final MemorySegment srcSeg, final long seed) { - return HeapArrayOfDoublesUnion.heapifyUnion(srcSeg, seed); - } - - /** - * Wrap the given MemorySegment as an ArrayOfDoublesUnion. - * If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only. - * @param srcSeg the given source MemorySegment - * @return an ArrayOfDoublesUnion - */ - public static ArrayOfDoublesUnion wrap(final MemorySegment srcSeg) { - return wrap(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * Wrap the given MemorySegment and seed as an ArrayOfDoublesUnion. - * If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only. - * @param srcSeg the given source MemorySegment - * @param seed the given seed - * @return an ArrayOfDoublesUnion - */ - public static ArrayOfDoublesUnion wrap(final MemorySegment srcSeg, final long seed) { - return DirectArrayOfDoublesUnion.wrapUnion(srcSeg, seed, !srcSeg.isReadOnly()); - } - - /** - * Updates the union by adding a set of entries from a given sketch, which can be on-heap or off-heap. - * Both the given tupleSketch and the internal state of the TupleUnion must have the same numValues. - * - *

Nulls and empty sketches are ignored.

- * - * @param tupleSketch sketch to add to the union. - */ - public void union(final ArrayOfDoublesSketch tupleSketch) { - if (tupleSketch == null) { return; } - Util.checkSeedHashes(gadget_.getSeedHash(), tupleSketch.getSeedHash()); - if (gadget_.getNumValues() != tupleSketch.getNumValues()) { - throw new SketchesArgumentException("Incompatible sketches: number of values mismatch " - + gadget_.getNumValues() + " and " + tupleSketch.getNumValues()); - } - - if (tupleSketch.isEmpty()) { return; } - else { gadget_.setNotEmpty(); } - - setUnionThetaLong(min(min(unionThetaLong_, tupleSketch.getThetaLong()), gadget_.getThetaLong())); - - if (tupleSketch.getRetainedEntries() == 0) { return; } - final ArrayOfDoublesSketchIterator it = tupleSketch.iterator(); - while (it.next()) { - if (it.getKey() < unionThetaLong_) { - gadget_.merge(it.getKey(), it.getValues()); - } - } - // keep the union theta as low as possible for performance - if (gadget_.getThetaLong() < unionThetaLong_) { - setUnionThetaLong(gadget_.getThetaLong()); - } - } - - /** - * Returns the resulting union in the form of a compact sketch - * @param dstSeg MemorySegment for the result (can be null) - * @return compact sketch representing the union (off-heap if MemorySegment is provided) - */ - public ArrayOfDoublesCompactSketch getResult(final MemorySegment dstSeg) { - long unionThetaLong = unionThetaLong_; - if (gadget_.getRetainedEntries() > gadget_.getNominalEntries()) { - unionThetaLong = Math.min(unionThetaLong, gadget_.getNewThetaLong()); - } - if (dstSeg == null) { - return new HeapArrayOfDoublesCompactSketch(gadget_, unionThetaLong); - } - return new DirectArrayOfDoublesCompactSketch(gadget_, unionThetaLong, dstSeg); - } - - /** - * Returns the resulting union in the form of a compact sketch - * @return on-heap compact sketch representing the union - */ - public ArrayOfDoublesCompactSketch getResult() { - return getResult(null); - } - - /** - * Resets the union to an empty state - */ - public void reset() { - gadget_.reset(); - setUnionThetaLong(gadget_.getThetaLong()); - } - - // Layout of first 16 bytes: - // Long || Start Byte Adr: - // Adr: - // || 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | - // 0 || Seed Hash=0 | #Dbls=0|Flags=0 | SkType | FamID | SerVer | Preamble_Longs | - // || 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 | - // 1 ||---------------------------TupleUnion Theta Long------------------------------------| - /** - * Returns a byte array representation of this object - * @return a byte array representation of this object - */ - public byte[] toByteArray() { - final int sizeBytes = PREAMBLE_SIZE_BYTES + gadget_.getSerializedSizeBytes(); - final byte[] byteArray = new byte[sizeBytes]; - final MemorySegment seg = MemorySegment.ofArray(byteArray); - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) 1); // unused, always 1 - seg.set(JAVA_BYTE, SERIAL_VERSION_BYTE, serialVersionUID); - seg.set(JAVA_BYTE, FAMILY_ID_BYTE, (byte) Family.TUPLE.getID()); - seg.set(JAVA_BYTE, SKETCH_TYPE_BYTE, (byte) SerializerDeserializer.SketchType.ArrayOfDoublesUnion.ordinal()); - //byte 4-7 automatically zero - seg.set(JAVA_LONG_UNALIGNED, THETA_LONG, unionThetaLong_); - gadget_.serializeInto(seg.asSlice(PREAMBLE_SIZE_BYTES, seg.byteSize() - PREAMBLE_SIZE_BYTES)); - return byteArray; - } - - /** - * Returns maximum required storage bytes given nomEntries and numValues - * @param nomEntries Nominal number of entries. Forced to the nearest power of 2 greater than or equal to - * given value. - * @param numValues Number of double values to keep for each key - * @return maximum required storage bytes given nomEntries and numValues - */ - public static int getMaxBytes(final int nomEntries, final int numValues) { - return ArrayOfDoublesQuickSelectSketch.getMaxBytes(nomEntries, numValues) + PREAMBLE_SIZE_BYTES; - } - - void setUnionThetaLong(final long thetaLong) { - unionThetaLong_ = thetaLong; - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketch.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketch.java deleted file mode 100644 index 591c67f1f..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketch.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static org.apache.datasketches.common.Util.DEFAULT_UPDATE_SEED; -import static org.apache.datasketches.common.Util.computeSeedHash; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.hash.MurmurHash3; -import org.apache.datasketches.tuple.Util; - -/** - * The top level for updatable tuple sketches of type ArrayOfDoubles. - */ -public abstract class ArrayOfDoublesUpdatableSketch extends ArrayOfDoublesSketch { - - final long seed_; - - ArrayOfDoublesUpdatableSketch(final int numValues, final long seed) { - super(numValues); - seed_ = seed; - } - - /** - * Heapify the given MemorySegment as an ArrayOfDoublesUpdatableSketch - * @param seg the given MemorySegment - * @return an ArrayOfDoublesUpdatableSketch - */ - public static ArrayOfDoublesUpdatableSketch heapify(final MemorySegment seg) { - return heapify(seg, DEFAULT_UPDATE_SEED); - } - - /** - * Heapify the given MemorySegment and seed as a ArrayOfDoublesUpdatableSketch - * @param seg the given MemorySegment - * @param seed the given seed - * @return an ArrayOfDoublesUpdatableSketch - */ - public static ArrayOfDoublesUpdatableSketch heapify(final MemorySegment seg, final long seed) { - return new HeapArrayOfDoublesQuickSelectSketch(seg, seed); - } - - /** - * Wrap the given MemorySegment as an ArrayOfDoublesUpdatableSketch. - * If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only. - * @param seg the given MemorySegment - * @return an ArrayOfDoublesUpdatableSketch - */ - public static ArrayOfDoublesUpdatableSketch wrap(final MemorySegment seg) { - return wrap(seg, DEFAULT_UPDATE_SEED); - } - - /** - * Wrap the given MemorySegment and seed as a ArrayOfDoublesUpdatableSketch. - * If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only. - * @param seg the given MemorySegment - * @param seed the given seed - * @return an ArrayOfDoublesUpdatableSketch - */ - public static ArrayOfDoublesUpdatableSketch wrap(final MemorySegment seg, final long seed) { - return new DirectArrayOfDoublesQuickSelectSketch(seg, seed); - } - - /** - * Updates this sketch with a long key and double values. - * The values will be stored or added to the ones associated with the key - * - * @param key The given long key - * @param values The given values - */ - public void update(final long key, final double[] values) { - update(new long[] {key}, values); - } - - /** - * Updates this sketch with a double key and double values. - * The values will be stored or added to the ones associated with the key - * - * @param key The given double key - * @param values The given values - */ - public void update(final double key, final double[] values) { - update(Util.doubleToLongArray(key), values); - } - - /** - * Updates this sketch with a String key and double values. - * The values will be stored or added to the ones associated with the key - * - * @param key The given String key - * @param values The given values - */ - public void update(final String key, final double[] values) { - update(Util.stringToByteArray(key), values); - } - - /** - * Updates this sketch with a byte[] key and double values. - * The values will be stored or added to the ones associated with the key - * - * @param key The given byte[] key - * @param values The given values - */ - public void update(final byte[] key, final double[] values) { - if (key == null || key.length == 0) { return; } - insertOrIgnore(MurmurHash3.hash(key, seed_)[0] >>> 1, values); - } - - /** - * Updates this sketch with a ByteBuffer key and double values. - * The values will be stored or added to the ones associated with the key - * - * @param key The given ByteBuffer key - * @param values The given values - */ - public void update(final ByteBuffer key, final double[] values) { - if (key == null || key.hasRemaining() == false) { return; } - insertOrIgnore(MurmurHash3.hash(key, seed_)[0] >>> 1, values); - } - - /** - * Updates this sketch with a int[] key and double values. - * The values will be stored or added to the ones associated with the key - * - * @param key The given int[] key - * @param values The given values - */ - public void update(final int[] key, final double[] values) { - if (key == null || key.length == 0) { return; } - insertOrIgnore(MurmurHash3.hash(key, seed_)[0] >>> 1, values); - } - - /** - * Updates this sketch with a long[] key and double values. - * The values will be stored or added to the ones associated with the key - * - * @param key The given long[] key - * @param values The given values - */ - public void update(final long[] key, final double[] values) { - if (key == null || key.length == 0) { return; } - insertOrIgnore(MurmurHash3.hash(key, seed_)[0] >>> 1, values); - } - - /** - * Gets the configured nominal number of entries - * @return nominal number of entries - */ - public abstract int getNominalEntries(); - - /** - * Gets the configured resize factor - * @return resize factor - */ - public abstract ResizeFactor getResizeFactor(); - - /** - * Gets the configured sampling probability - * @return sampling probability - */ - public abstract float getSamplingProbability(); - - /** - * Rebuilds reducing the actual number of entries to the nominal number of entries if needed - */ - public abstract void trim(); - - /** - * Resets this sketch an empty state. - */ - public abstract void reset(); - - /** - * Gets an on-heap compact representation of the sketch - * @return compact sketch - */ - @Override - public ArrayOfDoublesCompactSketch compact() { - return compact(null); - } - - /** - * Gets an off-heap compact representation of the sketch using the given MemorySegment - * @param dstSeg MemorySegment for the compact sketch (can be null) - * @return compact sketch (off-heap if MemorySegment is provided) - */ - @Override - public ArrayOfDoublesCompactSketch compact(final MemorySegment dstSeg) { - if (dstSeg == null) { - return new HeapArrayOfDoublesCompactSketch(this); - } - return new DirectArrayOfDoublesCompactSketch(this, dstSeg); - } - - abstract int getCurrentCapacity(); - - long getSeed() { - return seed_; - } - - @Override - short getSeedHash() { - return computeSeedHash(seed_); - } - - /** - * Insert if key is less than thetaLong and not a duplicate, otherwise ignore. - * @param key the hash value of the input value - * @param values array of values to update the summary - */ - abstract void insertOrIgnore(long key, double[] values); - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketchBuilder.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketchBuilder.java deleted file mode 100644 index c15bb6d3e..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketchBuilder.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.ThetaUtil; - -/** - * For building a new ArrayOfDoublesUpdatableSketch - */ -public class ArrayOfDoublesUpdatableSketchBuilder { - - private int nomEntries_; - private ResizeFactor resizeFactor_; - private int numValues_; - private float samplingProbability_; - private long seed_; - - private static final int DEFAULT_NUMBER_OF_VALUES = 1; - private static final float DEFAULT_SAMPLING_PROBABILITY = 1; - private static final ResizeFactor DEFAULT_RESIZE_FACTOR = ResizeFactor.X8; - - /** - * Creates an instance of builder with default parameters - */ - public ArrayOfDoublesUpdatableSketchBuilder() { - nomEntries_ = ThetaUtil.DEFAULT_NOMINAL_ENTRIES; - resizeFactor_ = DEFAULT_RESIZE_FACTOR; - numValues_ = DEFAULT_NUMBER_OF_VALUES; - samplingProbability_ = DEFAULT_SAMPLING_PROBABILITY; - seed_ = Util.DEFAULT_UPDATE_SEED; - } - - /** - * This is to set the nominal number of entries. - * @param nomEntries Nominal number of entries. Forced to the nearest power of 2 greater than - * or equal to given value. - * @return this builder - */ - public ArrayOfDoublesUpdatableSketchBuilder setNominalEntries(final int nomEntries) { - nomEntries_ = 1 << ThetaUtil.checkNomLongs(nomEntries); - return this; - } - - /** - * This is to set the resize factor. - * Value of X1 means that the maximum capacity is allocated from the start. - * Default resize factor is X8. - * @param resizeFactor value of X1, X2, X4 or X8 - * @return this UpdatableTupleSketchBuilder - */ - public ArrayOfDoublesUpdatableSketchBuilder setResizeFactor(final ResizeFactor resizeFactor) { - resizeFactor_ = resizeFactor; - return this; - } - - /** - * This is to set sampling probability. - * Default probability is 1. - * @param samplingProbability sampling probability from 0 to 1 - * @return this builder - */ - public ArrayOfDoublesUpdatableSketchBuilder - setSamplingProbability(final float samplingProbability) { - if ((samplingProbability < 0) || (samplingProbability > 1f)) { - throw new SketchesArgumentException("sampling probability must be between 0 and 1"); - } - samplingProbability_ = samplingProbability; - return this; - } - - /** - * This is to set the number of double values associated with each key - * @param numValues number of double values - * @return this builder - */ - public ArrayOfDoublesUpdatableSketchBuilder setNumberOfValues(final int numValues) { - numValues_ = numValues; - return this; - } - - /** - * Sets the long seed value that is required by the hashing function. - * @param seed See seed - * @return this builder - */ - public ArrayOfDoublesUpdatableSketchBuilder setSeed(final long seed) { - seed_ = seed; - return this; - } - - /** - * Returns an ArrayOfDoublesUpdatableSketch with the current configuration of this Builder. - * @return an ArrayOfDoublesUpdatableSketch - */ - public ArrayOfDoublesUpdatableSketch build() { - return new HeapArrayOfDoublesQuickSelectSketch(nomEntries_, resizeFactor_.lg(), - samplingProbability_, numValues_, seed_); - } - - /** - * Returns an ArrayOfDoublesUpdatableSketch with the current configuration of this Builder. - * @param dstSeg instance of MemorySegment to be used by the sketch - * @return an ArrayOfDoublesUpdatableSketch - */ - public ArrayOfDoublesUpdatableSketch build(final MemorySegment dstSeg) { - return new DirectArrayOfDoublesQuickSelectSketch(nomEntries_, resizeFactor_.lg(), - samplingProbability_, numValues_, seed_, dstSeg); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesCompactSketch.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesCompactSketch.java deleted file mode 100644 index 76883224e..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesCompactSketch.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.tuple.SerializerDeserializer; - -/** - * Direct CompactTupleSketch of type ArrayOfDoubles. - * - *

This implementation uses data in a given MemorySegment that is owned and managed by the caller. - * This MemorySegment can be off-heap, which if managed properly will greatly reduce the need for - * the JVM to perform garbage collection.

- */ -final class DirectArrayOfDoublesCompactSketch extends ArrayOfDoublesCompactSketch { - - // this value exists only on heap, never serialized - private final MemorySegment seg_; - - /** - * Converts the given UpdatableArrayOfDoublesSketch to this compact form. - * @param sketch the given UpdatableArrayOfDoublesSketch - * @param dstSeg the given destination MemorySegment. - */ - DirectArrayOfDoublesCompactSketch(final ArrayOfDoublesUpdatableSketch sketch, - final MemorySegment dstSeg) { - this(sketch, sketch.getThetaLong(), dstSeg); - } - - /** - * Converts the given UpdatableArrayOfDoublesSketch to this compact form - * trimming if necessary according to given theta - * @param sketch the given UpdatableArrayOfDoublesSketch - * @param thetaLong new value of thetaLong - * @param dstSeg the given destination MemorySegment. - */ - DirectArrayOfDoublesCompactSketch(final ArrayOfDoublesUpdatableSketch sketch, - final long thetaLong, final MemorySegment dstSeg) { - super(sketch.getNumValues()); - checkMemorySegmentSize(dstSeg, sketch.getRetainedEntries(), sketch.getNumValues()); - seg_ = dstSeg; - dstSeg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) 1); - dstSeg.set(JAVA_BYTE, SERIAL_VERSION_BYTE, serialVersionUID); - dstSeg.set(JAVA_BYTE, FAMILY_ID_BYTE, (byte) Family.TUPLE.getID()); - dstSeg.set(JAVA_BYTE, SKETCH_TYPE_BYTE, (byte) - SerializerDeserializer.SketchType.ArrayOfDoublesCompactSketch.ordinal()); - isEmpty_ = sketch.isEmpty(); - final int count = sketch.getRetainedEntries(); - dstSeg.set(JAVA_BYTE, FLAGS_BYTE, (byte) ( - (isEmpty_ ? 1 << Flags.IS_EMPTY.ordinal() : 0) - | (count > 0 ? 1 << Flags.HAS_ENTRIES.ordinal() : 0) - )); - dstSeg.set(JAVA_BYTE, NUM_VALUES_BYTE, (byte) numValues_); - dstSeg.set(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT, Util.computeSeedHash(sketch.getSeed())); - thetaLong_ = Math.min(sketch.getThetaLong(), thetaLong); - dstSeg.set(JAVA_LONG_UNALIGNED, THETA_LONG, thetaLong_); - if (count > 0) { - int keyOffset = ENTRIES_START; - int valuesOffset = keyOffset + (SIZE_OF_KEY_BYTES * sketch.getRetainedEntries()); - final ArrayOfDoublesSketchIterator it = sketch.iterator(); - int actualCount = 0; - while (it.next()) { - if (it.getKey() < thetaLong_) { - dstSeg.set(JAVA_LONG_UNALIGNED, keyOffset, it.getKey()); - MemorySegment.copy(it.getValues(), 0, dstSeg, JAVA_DOUBLE_UNALIGNED, valuesOffset, numValues_); - keyOffset += SIZE_OF_KEY_BYTES; - valuesOffset += SIZE_OF_VALUE_BYTES * numValues_; - actualCount++; - } - } - dstSeg.set(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT, actualCount); - } - } - - /* - * Creates an instance from components - */ - DirectArrayOfDoublesCompactSketch(final long[] keys, final double[] values, final long thetaLong, - final boolean isEmpty, final int numValues, final short seedHash, final MemorySegment dstSeg) { - super(numValues); - checkMemorySegmentSize(dstSeg, values.length, numValues); - seg_ = dstSeg; - dstSeg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) 1); - dstSeg.set(JAVA_BYTE, SERIAL_VERSION_BYTE, serialVersionUID); - dstSeg.set(JAVA_BYTE, FAMILY_ID_BYTE, (byte) Family.TUPLE.getID()); - dstSeg.set(JAVA_BYTE, SKETCH_TYPE_BYTE, (byte) - SerializerDeserializer.SketchType.ArrayOfDoublesCompactSketch.ordinal()); - isEmpty_ = isEmpty; - final int count = keys.length; - dstSeg.set(JAVA_BYTE, FLAGS_BYTE, (byte) ( - (isEmpty_ ? 1 << Flags.IS_EMPTY.ordinal() : 0) - | (count > 0 ? 1 << Flags.HAS_ENTRIES.ordinal() : 0) - )); - dstSeg.set(JAVA_BYTE, NUM_VALUES_BYTE, (byte) numValues_); - dstSeg.set(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT, seedHash); - thetaLong_ = thetaLong; - dstSeg.set(JAVA_LONG_UNALIGNED, THETA_LONG, thetaLong_); - if (count > 0) { - dstSeg.set(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT, count); - MemorySegment.copy(keys, 0, dstSeg, JAVA_LONG_UNALIGNED, ENTRIES_START, count); - MemorySegment.copy(values, 0, dstSeg, JAVA_DOUBLE_UNALIGNED, ENTRIES_START + ((long) SIZE_OF_KEY_BYTES * count), values.length); - } - } - - /** - * Wraps the given MemorySegment. - * @param seg the given MemorySegment - */ - DirectArrayOfDoublesCompactSketch(final MemorySegment seg) { - super(seg.get(JAVA_BYTE, NUM_VALUES_BYTE)); - seg_ = seg; - SerializerDeserializer.validateFamily(seg.get(JAVA_BYTE, FAMILY_ID_BYTE), - seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE)); - SerializerDeserializer.validateType(seg_.get(JAVA_BYTE, SKETCH_TYPE_BYTE), - SerializerDeserializer.SketchType.ArrayOfDoublesCompactSketch); - final byte version = seg_.get(JAVA_BYTE, SERIAL_VERSION_BYTE); - if (version != serialVersionUID) { - throw new SketchesArgumentException("Serial version mismatch. Expected: " + serialVersionUID - + ", actual: " + version); - } - - isEmpty_ = (seg_.get(JAVA_BYTE, FLAGS_BYTE) & (1 << Flags.IS_EMPTY.ordinal())) != 0; - thetaLong_ = seg_.get(JAVA_LONG_UNALIGNED, THETA_LONG); - } - - /** - * Wraps the given MemorySegment. - * @param seg the given MemorySegment. - * @param seed See seed - */ - DirectArrayOfDoublesCompactSketch(final MemorySegment seg, final long seed) { - super(seg.get(JAVA_BYTE, NUM_VALUES_BYTE)); - seg_ = seg; - SerializerDeserializer.validateFamily(seg.get(JAVA_BYTE, FAMILY_ID_BYTE), - seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE)); - SerializerDeserializer.validateType(seg_.get(JAVA_BYTE, SKETCH_TYPE_BYTE), - SerializerDeserializer.SketchType.ArrayOfDoublesCompactSketch); - final byte version = seg_.get(JAVA_BYTE, SERIAL_VERSION_BYTE); - if (version != serialVersionUID) { - throw new SketchesArgumentException("Serial version mismatch. Expected: " + serialVersionUID - + ", actual: " + version); - } - Util.checkSeedHashes(seg.get(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT), Util.computeSeedHash(seed)); - isEmpty_ = (seg_.get(JAVA_BYTE, FLAGS_BYTE) & (1 << Flags.IS_EMPTY.ordinal())) != 0; - thetaLong_ = seg.get(JAVA_LONG_UNALIGNED, THETA_LONG); - } - - @Override - public ArrayOfDoublesCompactSketch compact(final MemorySegment dstSeg) { - if (dstSeg == null) { - return new - HeapArrayOfDoublesCompactSketch(getKeys(), getValuesAsOneDimension(), thetaLong_, isEmpty_, numValues_, - getSeedHash()); - } else { - MemorySegment.copy(seg_, 0, dstSeg, 0, seg_.byteSize()); - return new DirectArrayOfDoublesCompactSketch(dstSeg); - } - } - - @Override - public int getRetainedEntries() { - final boolean hasEntries = - (seg_.get(JAVA_BYTE, FLAGS_BYTE) & (1 << Flags.HAS_ENTRIES.ordinal())) != 0; - return (hasEntries ? seg_.get(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT) : 0); - } - - @Override - //converts compact MemorySegment array of double[] to compact double[][] - public double[][] getValues() { - final int count = getRetainedEntries(); - final double[][] values = new double[count][]; - if (count > 0) { - int valuesOffset = ENTRIES_START + (SIZE_OF_KEY_BYTES * count); - for (int i = 0; i < count; i++) { - final double[] array = new double[numValues_]; - MemorySegment.copy(seg_, JAVA_DOUBLE_UNALIGNED, valuesOffset, array, 0, numValues_); - values[i] = array; - valuesOffset += SIZE_OF_VALUE_BYTES * numValues_; - } - } - return values; - } - - @Override - //converts compact MemorySegment array of double[] to compact double[] - double[] getValuesAsOneDimension() { - final int count = getRetainedEntries(); - final int numDoubles = count * numValues_; - final double[] values = new double[numDoubles]; - if (count > 0) { - final int valuesOffset = ENTRIES_START + (SIZE_OF_KEY_BYTES * count); - MemorySegment.copy(seg_, JAVA_DOUBLE_UNALIGNED, valuesOffset, values, 0, numDoubles); - } - return values; - } - - @Override - //converts compact MemorySegment array of long[] to compact long[] - long[] getKeys() { - final int count = getRetainedEntries(); - final long[] keys = new long[count]; - if (count > 0) { - for (int i = 0; i < count; i++) { - MemorySegment.copy(seg_, JAVA_LONG_UNALIGNED, ENTRIES_START, keys, 0, count); - } - } - return keys; - } - - @Override - public byte[] toByteArray() { - final int sizeBytes = getCurrentBytes(); - final byte[] byteArray = new byte[sizeBytes]; - final MemorySegment seg = MemorySegment.ofArray(byteArray); - MemorySegment.copy(seg_, 0, seg, 0, sizeBytes); - return byteArray; - } - - @Override - public ArrayOfDoublesSketchIterator iterator() { - return new DirectArrayOfDoublesSketchIterator( - seg_, ENTRIES_START, getRetainedEntries(), numValues_); - } - - @Override - short getSeedHash() { - return seg_.get(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT); - } - - @Override - public boolean hasMemorySegment() { return true; } - - @Override - MemorySegment getMemorySegment() { return seg_; } - - private static void checkMemorySegmentSize(final MemorySegment seg, final int numEntries, - final int numValues) { - final int sizeNeeded = - ENTRIES_START + ((SIZE_OF_KEY_BYTES + (SIZE_OF_VALUE_BYTES * numValues)) * numEntries); - if (sizeNeeded > seg.byteSize()) { - throw new SketchesArgumentException("Not enough space: need " + sizeNeeded - + " bytes, got " + seg.byteSize() + " bytes"); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesIntersection.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesIntersection.java deleted file mode 100644 index 74fd2abec..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesIntersection.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.lang.foreign.MemorySegment; - -/** - * Direct TupleIntersection operation for tuple sketches of type ArrayOfDoubles. - * - *

This implementation uses data in a given MemorySegment that is owned and managed by the caller. - * This MemorySegment can be off-heap, which if managed properly will greatly reduce the need for - * the JVM to perform garbage collection.

- */ -final class DirectArrayOfDoublesIntersection extends ArrayOfDoublesIntersection { - - private MemorySegment seg_; - - /** - * Creates an instance of a DirectArrayOfDoublesIntersection with a custom update seed - * @param numValues number of double values associated with each key - * @param seed See seed - * @param dstSeg the destination MemorySegment - */ - DirectArrayOfDoublesIntersection(final int numValues, final long seed, final MemorySegment dstSeg) { - super(numValues, seed); - seg_ = dstSeg; - } - - @Override - protected ArrayOfDoublesQuickSelectSketch createSketch(final int nomEntries, final int numValues, - final long seed) { - return new DirectArrayOfDoublesQuickSelectSketch(nomEntries, 0, 1f, numValues, seed, seg_); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketch.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketch.java deleted file mode 100644 index f32571d0b..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketch.java +++ /dev/null @@ -1,399 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.common.Util.checkSeedHashes; -import static org.apache.datasketches.common.Util.clear; -import static org.apache.datasketches.common.Util.clearBits; -import static org.apache.datasketches.common.Util.computeSeedHash; -import static org.apache.datasketches.common.Util.setBits; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.thetacommon.HashOperations; -import org.apache.datasketches.tuple.SerializerDeserializer; -import org.apache.datasketches.tuple.Util; - -/** - * Direct QuickSelect tuple sketch of type ArrayOfDoubles. - * - *

This implementation uses data in a given MemorySegment that is owned and managed by the caller. - * This MemorySegment can be off-heap, which if managed properly will greatly reduce the need for - * the JVM to perform garbage collection.

- */ -class DirectArrayOfDoublesQuickSelectSketch extends ArrayOfDoublesQuickSelectSketch { - - // these values exist only on heap, never serialized - private final MemorySegment seg_; - // these can be derived from the seg_ contents, but are kept here for performance - private int keysOffset_; - private int valuesOffset_; - - /** - * Construct a new sketch using the given MemorySegment as its backing store. - * - * @param nomEntries Nominal number of entries. Forced to the nearest power of 2 greater than - * given value. - * @param lgResizeFactor log2(resize factor) - value from 0 to 3: - * 0 - no resizing (max size allocated), - * 1 - double internal hash table each time it reaches a threshold - * 2 - grow four times - * 3 - grow eight times (default) - * @param samplingProbability - * See Sampling Probability - * @param numValues Number of double values to keep for each key. - * @param seed See seed - * @param dstSeg the destination MemorySegment. - */ - DirectArrayOfDoublesQuickSelectSketch( - final int nomEntries, - final int lgResizeFactor, - final float samplingProbability, - final int numValues, - final long seed, - final MemorySegment dstSeg) { - checkMemorySegment(nomEntries, lgResizeFactor, numValues, dstSeg); - super(numValues, seed); - seg_ = dstSeg; - final int startingCapacity = Util.getStartingCapacity(nomEntries, lgResizeFactor); - seg_.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) 1); - seg_.set(JAVA_BYTE, SERIAL_VERSION_BYTE, serialVersionUID); - seg_.set(JAVA_BYTE, FAMILY_ID_BYTE, (byte) Family.TUPLE.getID()); - seg_.set(JAVA_BYTE, SKETCH_TYPE_BYTE, (byte) - SerializerDeserializer.SketchType.ArrayOfDoublesQuickSelectSketch.ordinal()); - seg_.set(JAVA_BYTE, FLAGS_BYTE, (byte) ( - (samplingProbability < 1f ? 1 << Flags.IS_IN_SAMPLING_MODE.ordinal() : 0) - | (1 << Flags.IS_EMPTY.ordinal()) - )); - seg_.set(JAVA_BYTE, NUM_VALUES_BYTE, (byte) numValues); - seg_.set(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT, computeSeedHash(seed)); - thetaLong_ = (long) (Long.MAX_VALUE * (double) samplingProbability); - seg_.set(JAVA_LONG_UNALIGNED, THETA_LONG, thetaLong_); - seg_.set(JAVA_BYTE, LG_NOM_ENTRIES_BYTE, (byte) Integer.numberOfTrailingZeros(nomEntries)); - seg_.set(JAVA_BYTE, LG_CUR_CAPACITY_BYTE, (byte) Integer.numberOfTrailingZeros(startingCapacity)); - seg_.set(JAVA_BYTE, LG_RESIZE_FACTOR_BYTE, (byte) lgResizeFactor); - seg_.set(JAVA_FLOAT_UNALIGNED, SAMPLING_P_FLOAT, samplingProbability); - seg_.set(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT, 0); - keysOffset_ = ENTRIES_START; - valuesOffset_ = keysOffset_ + (SIZE_OF_KEY_BYTES * startingCapacity); - clear(seg_, keysOffset_, (long) SIZE_OF_KEY_BYTES * startingCapacity); //clear keys only - lgCurrentCapacity_ = Integer.numberOfTrailingZeros(startingCapacity); - setRebuildThreshold(); - } - - private static final void checkMemorySegment( - final int nomEntries, - final int lgResizeFactor, - final int numValues, - final MemorySegment dstSeg) { - final int startingCapacity = Util.getStartingCapacity(nomEntries, lgResizeFactor); - checkMemorySegmentSize(dstSeg, startingCapacity, numValues); - } - - /** - * Wraps the given MemorySegment. - * @param seg the given MemorySegment - * @param seed update seed - */ - DirectArrayOfDoublesQuickSelectSketch( - final MemorySegment seg, - final long seed) { - checkSerVer(seg); - super(seg.get(JAVA_BYTE, NUM_VALUES_BYTE), seed); - seg_ = seg; - SerializerDeserializer.validateFamily(seg.get(JAVA_BYTE, FAMILY_ID_BYTE), - seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE)); - SerializerDeserializer.validateType(seg_.get(JAVA_BYTE, SKETCH_TYPE_BYTE), - SerializerDeserializer.SketchType.ArrayOfDoublesQuickSelectSketch); - - checkSeedHashes(seg.get(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT), computeSeedHash(seed)); - keysOffset_ = ENTRIES_START; - valuesOffset_ = keysOffset_ + (SIZE_OF_KEY_BYTES * getCurrentCapacity()); - // to do: make parent take care of its own parts - lgCurrentCapacity_ = Integer.numberOfTrailingZeros(getCurrentCapacity()); - thetaLong_ = seg_.get(JAVA_LONG_UNALIGNED, THETA_LONG); - isEmpty_ = (seg_.get(JAVA_BYTE, FLAGS_BYTE) & (1 << Flags.IS_EMPTY.ordinal())) != 0; - setRebuildThreshold(); - } - - private static final void checkSerVer(final MemorySegment seg) { - final byte version = seg.get(JAVA_BYTE, SERIAL_VERSION_BYTE); - if (version != serialVersionUID) { - throw new SketchesArgumentException("Serial version mismatch. Expected: " + serialVersionUID - + ", actual: " + version); - } - } - - @Override - //converts MemorySegment hashTable of double[] to compacted double[][] - public double[][] getValues() { - final int count = getRetainedEntries(); - final double[][] values = new double[count][]; - if (count > 0) { - long keyOffset = keysOffset_; - long valuesOffset = valuesOffset_; - int cnt = 0; - for (int j = 0; j < getCurrentCapacity(); j++) { - if (seg_.get(JAVA_LONG_UNALIGNED, keyOffset) != 0) { - final double[] array = new double[numValues_]; - MemorySegment.copy(seg_, JAVA_DOUBLE_UNALIGNED, valuesOffset, array, 0, numValues_); - values[cnt++] = array; - } - keyOffset += SIZE_OF_KEY_BYTES; - valuesOffset += (long)SIZE_OF_VALUE_BYTES * numValues_; - } - } - return values; - } - - @Override - //converts heap hashTable of double[] to compacted double[] - double[] getValuesAsOneDimension() { - final int count = getRetainedEntries(); - final double[] values = new double[count * numValues_]; - final int cap = getCurrentCapacity(); - if (count > 0) { - long keyOffsetBytes = keysOffset_; - long valuesOffsetBytes = valuesOffset_; - int cnt = 0; - for (int j = 0; j < cap; j++) { - if (seg_.get(JAVA_LONG_UNALIGNED, keyOffsetBytes) != 0) { - MemorySegment.copy(seg_, JAVA_DOUBLE_UNALIGNED, valuesOffsetBytes, values, cnt++ * numValues_, numValues_); - } - keyOffsetBytes += SIZE_OF_KEY_BYTES; - valuesOffsetBytes += (long)SIZE_OF_VALUE_BYTES * numValues_; - } - assert cnt == count; - } - return values; - } - - @Override - //converts heap hashTable of long[] to compacted long[] - long[] getKeys() { - final int count = getRetainedEntries(); - final long[] keys = new long[count]; - final int cap = getCurrentCapacity(); - if (count > 0) { - long keyOffsetBytes = keysOffset_; - int cnt = 0; - for (int j = 0; j < cap; j++) { - final long key; - if ((key = seg_.get(JAVA_LONG_UNALIGNED, keyOffsetBytes)) != 0) { - keys[cnt++] = key; - } - keyOffsetBytes += SIZE_OF_KEY_BYTES; - } - assert cnt == count; - } - return keys; - } - - @Override - public int getRetainedEntries() { - return seg_.get(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT); - } - - @Override - public int getNominalEntries() { - return 1 << seg_.get(JAVA_BYTE, LG_NOM_ENTRIES_BYTE); - } - - @Override - public ResizeFactor getResizeFactor() { - return ResizeFactor.getRF(seg_.get(JAVA_BYTE, LG_RESIZE_FACTOR_BYTE)); - } - - @Override - public float getSamplingProbability() { - return seg_.get(JAVA_FLOAT_UNALIGNED, SAMPLING_P_FLOAT); - } - - @Override - public byte[] toByteArray() { - final int sizeBytes = getSerializedSizeBytes(); - final byte[] byteArray = new byte[sizeBytes]; - final MemorySegment seg = MemorySegment.ofArray(byteArray); - serializeInto(seg); - return byteArray; - } - - @Override - public ArrayOfDoublesSketchIterator iterator() { - return new DirectArrayOfDoublesSketchIterator(seg_, keysOffset_, getCurrentCapacity(), numValues_); - } - - @Override - public boolean hasMemorySegment() { return true; } - - @Override - MemorySegment getMemorySegment() { return seg_; } - - @Override - int getSerializedSizeBytes() { - return valuesOffset_ + (SIZE_OF_VALUE_BYTES * numValues_ * getCurrentCapacity()); - } - - @Override - void serializeInto(final MemorySegment seg) { - MemorySegment.copy(seg_, 0, seg, 0, seg.byteSize()); - } - - @Override - public void reset() { - if (!isEmpty_) { - isEmpty_ = true; - setBits(seg_, FLAGS_BYTE, (byte) (1 << Flags.IS_EMPTY.ordinal())); - } - final int lgResizeFactor = seg_.get(JAVA_BYTE, LG_RESIZE_FACTOR_BYTE); - final float samplingProbability = seg_.get(JAVA_FLOAT_UNALIGNED, SAMPLING_P_FLOAT); - final int startingCapacity = Util.getStartingCapacity(getNominalEntries(), lgResizeFactor); - thetaLong_ = (long) (Long.MAX_VALUE * (double) samplingProbability); - seg_.set(JAVA_LONG_UNALIGNED, THETA_LONG, thetaLong_); - seg_.set(JAVA_BYTE, LG_CUR_CAPACITY_BYTE, (byte) Integer.numberOfTrailingZeros(startingCapacity)); - seg_.set(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT, 0); - keysOffset_ = ENTRIES_START; - valuesOffset_ = keysOffset_ + (SIZE_OF_KEY_BYTES * startingCapacity); - clear(seg_, keysOffset_, (long) SIZE_OF_KEY_BYTES * startingCapacity); //clear keys only - lgCurrentCapacity_ = Integer.numberOfTrailingZeros(startingCapacity); - setRebuildThreshold(); - } - - @Override - protected long getKey(final int index) { - return seg_.get(JAVA_LONG_UNALIGNED, keysOffset_ + ((long) SIZE_OF_KEY_BYTES * index)); - } - - @Override - protected void incrementCount() { - final int count = seg_.get(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT); - if (count == 0) { - setBits(seg_, FLAGS_BYTE, (byte) (1 << Flags.HAS_ENTRIES.ordinal())); - } - seg_.set(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT, count + 1); - } - - @Override - protected final int getCurrentCapacity() { - return 1 << seg_.get(JAVA_BYTE, LG_CUR_CAPACITY_BYTE); - } - - @Override - protected void setThetaLong(final long thetaLong) { - thetaLong_ = thetaLong; - seg_.set(JAVA_LONG_UNALIGNED, THETA_LONG, thetaLong_); - } - - @Override - protected void setValues(final int index, final double[] values) { - long offset = valuesOffset_ + ((long) SIZE_OF_VALUE_BYTES * numValues_ * index); - for (int i = 0; i < numValues_; i++) { - seg_.set(JAVA_DOUBLE_UNALIGNED, offset, values[i]); - offset += SIZE_OF_VALUE_BYTES; - } - } - - @Override - protected void updateValues(final int index, final double[] values) { - long offset = valuesOffset_ + ((long) SIZE_OF_VALUE_BYTES * numValues_ * index); - for (int i = 0; i < numValues_; i++) { - seg_.set(JAVA_DOUBLE_UNALIGNED, offset, seg_.get(JAVA_DOUBLE_UNALIGNED, offset) + values[i]); - offset += SIZE_OF_VALUE_BYTES; - } - } - - @Override - protected void setNotEmpty() { - if (isEmpty_) { - isEmpty_ = false; - clearBits(seg_, FLAGS_BYTE, (byte) (1 << Flags.IS_EMPTY.ordinal())); - - } - } - - @Override - protected boolean isInSamplingMode() { - return (seg_.get(JAVA_BYTE, FLAGS_BYTE) & (1 << Flags.IS_IN_SAMPLING_MODE.ordinal())) != 0; - } - - // rebuild in the same MemorySegment - @Override - protected void rebuild(final int newCapacity) { - final int numValues = getNumValues(); - checkMemorySegmentSize(seg_, newCapacity, numValues); - final int currCapacity = getCurrentCapacity(); - final long[] keys = new long[currCapacity]; - final double[] values = new double[currCapacity * numValues]; - MemorySegment.copy(seg_, JAVA_LONG_UNALIGNED, keysOffset_, keys, 0, currCapacity); - MemorySegment.copy(seg_, JAVA_DOUBLE_UNALIGNED, valuesOffset_, values, 0, currCapacity * numValues); - - clear(seg_, keysOffset_, ((long) SIZE_OF_KEY_BYTES * newCapacity) + ((long) SIZE_OF_VALUE_BYTES * newCapacity * numValues)); - seg_.set(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT, 0); - seg_.set(JAVA_BYTE, LG_CUR_CAPACITY_BYTE, (byte)Integer.numberOfTrailingZeros(newCapacity)); - valuesOffset_ = keysOffset_ + (SIZE_OF_KEY_BYTES * newCapacity); - lgCurrentCapacity_ = Integer.numberOfTrailingZeros(newCapacity); - for (int i = 0; i < keys.length; i++) { - if ((keys[i] != 0) && (keys[i] < thetaLong_)) { - insert(keys[i], Arrays.copyOfRange(values, i * numValues, (i + 1) * numValues)); - } - } - setRebuildThreshold(); - } - - @Override - protected int insertKey(final long key) { - return HashOperations.hashInsertOnlyMemorySegment(seg_, lgCurrentCapacity_, key, ENTRIES_START); - } - - @Override - protected int findOrInsertKey(final long key) { - return HashOperations.hashSearchOrInsertMemorySegment(seg_, lgCurrentCapacity_, key, ENTRIES_START); - } - - @Override - protected double[] find(final long key) { - final int index = HashOperations.hashSearchMemorySegment(seg_, lgCurrentCapacity_, key, ENTRIES_START); - if (index == -1) { return null; } - final double[] array = new double[numValues_]; - MemorySegment.copy(seg_, JAVA_DOUBLE_UNALIGNED, valuesOffset_ - + ((long) SIZE_OF_VALUE_BYTES * numValues_ * index), array, 0, numValues_); - return array; - } - - private static void checkMemorySegmentSize(final MemorySegment seg, final int numEntries, final int numValues) { - final int sizeNeeded = - ENTRIES_START + ((SIZE_OF_KEY_BYTES + (SIZE_OF_VALUE_BYTES * numValues)) * numEntries); - if (sizeNeeded > seg.byteSize()) { - throw new SketchesArgumentException("Not enough space: need " - + sizeNeeded + " bytes, got " + seg.byteSize() + " bytes"); - } - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketchR.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketchR.java deleted file mode 100644 index 3ff1a260c..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketchR.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesReadOnlyException; - -final class DirectArrayOfDoublesQuickSelectSketchR extends DirectArrayOfDoublesQuickSelectSketch { - - DirectArrayOfDoublesQuickSelectSketchR(final MemorySegment seg, final long seed) { - super(seg, seed); - } - - @Override - void insertOrIgnore(final long key, final double[] values) { - throw new SketchesReadOnlyException(); - } - - @Override - public void trim() { - throw new SketchesReadOnlyException(); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesSketchIterator.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesSketchIterator.java deleted file mode 100644 index 35f172c3f..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesSketchIterator.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -/** - * Iterator over the off-heap, Direct tuple sketch of type ArrayOfDoubles (compact or hash table). - * - *

This implementation uses data in a given MemorySegment that is owned and managed by the caller. - * This MemorySegment can be off-heap, which if managed properly will greatly reduce the need for - * the JVM to perform garbage collection.

- */ -final class DirectArrayOfDoublesSketchIterator implements ArrayOfDoublesSketchIterator { - - private MemorySegment seg_; - private int offset_; - private int numEntries_; - private int numValues_; - private int i_; - private static final int SIZE_OF_KEY_BYTES = 8; - private static final int SIZE_OF_VALUE_BYTES = 8; - - DirectArrayOfDoublesSketchIterator(final MemorySegment seg, final int offset, final int numEntries, - final int numValues) { - seg_ = seg; - offset_ = offset; - numEntries_ = numEntries; - numValues_ = numValues; - i_ = -1; - } - - @Override - public boolean next() { - i_++; - while (i_ < numEntries_) { - final long off = offset_ + ((long) SIZE_OF_KEY_BYTES * i_); - if (seg_.get(JAVA_LONG_UNALIGNED, off) != 0) { return true; } - i_++; - } - return false; - } - - @Override - public long getKey() { - final long off = offset_ + ((long) SIZE_OF_KEY_BYTES * i_); - return seg_.get(JAVA_LONG_UNALIGNED, off); - } - - @Override - public double[] getValues() { - long off; - if (numValues_ == 1) { - off = offset_ + ((long) SIZE_OF_KEY_BYTES * numEntries_) + ((long) SIZE_OF_VALUE_BYTES * i_); - return new double[] { seg_.get(JAVA_DOUBLE_UNALIGNED, off) }; - } - final double[] array = new double[numValues_]; - off = offset_ + ((long) SIZE_OF_KEY_BYTES * numEntries_) + ((long) SIZE_OF_VALUE_BYTES * i_ * numValues_); - MemorySegment.copy(seg_, JAVA_DOUBLE_UNALIGNED, off, array, 0, numValues_); - return array; - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesUnion.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesUnion.java deleted file mode 100644 index 5e00b9910..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesUnion.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.SerializerDeserializer; - -/** - * Direct TupleUnion operation for tuple sketches of type ArrayOfDoubles. - * - *

This implementation uses data in a given MemorySegment that is owned and managed by the caller. - * This MemorySegment can be off-heap, which if managed properly will greatly reduce the need for - * the JVM to perform garbage collection.

- */ -class DirectArrayOfDoublesUnion extends ArrayOfDoublesUnion { - - final MemorySegment seg_; - - /** - * Creates an instance of DirectArrayOfDoublesUnion - * @param nomEntries Nominal number of entries. Forced to the nearest power of 2 greater than given value. - * @param numValues Number of double values to keep for each key. - * @param seed See seed - * @param dstSeg the destination MemorySegment - */ - DirectArrayOfDoublesUnion(final int nomEntries, final int numValues, final long seed, - final MemorySegment dstSeg) { - super(new DirectArrayOfDoublesQuickSelectSketch(nomEntries, 3, 1f, numValues, seed, - dstSeg.asSlice(PREAMBLE_SIZE_BYTES, dstSeg.byteSize() - PREAMBLE_SIZE_BYTES))); - seg_ = dstSeg; - seg_.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) 1); // unused, always 1 - seg_.set(JAVA_BYTE, SERIAL_VERSION_BYTE, serialVersionUID); - seg_.set(JAVA_BYTE, FAMILY_ID_BYTE, (byte) Family.TUPLE.getID()); - seg_.set(JAVA_BYTE, SKETCH_TYPE_BYTE, (byte) SerializerDeserializer.SketchType.ArrayOfDoublesUnion.ordinal()); - seg_.set(JAVA_LONG_UNALIGNED, THETA_LONG, gadget_.getThetaLong()); - } - - //Called from wrapUnion below and extended by DirectArrayOfDoublesUnionR - DirectArrayOfDoublesUnion(final ArrayOfDoublesQuickSelectSketch gadget, final MemorySegment seg) { - super(gadget); - seg_ = seg; - unionThetaLong_ = seg.get(JAVA_LONG_UNALIGNED, THETA_LONG); - } - - @Override - void setUnionThetaLong(final long thetaLong) { - super.setUnionThetaLong(thetaLong); - seg_.set(JAVA_LONG_UNALIGNED, THETA_LONG, thetaLong); - } - - static ArrayOfDoublesUnion wrapUnion(final MemorySegment seg, final long seed, final boolean isWritable) { - final byte version = seg.get(JAVA_BYTE, ArrayOfDoublesUnion.SERIAL_VERSION_BYTE); - if (version != ArrayOfDoublesUnion.serialVersionUID) { - throw new SketchesArgumentException("Serial version mismatch. Expected: " - + serialVersionUID + ", actual: " + version); - } - SerializerDeserializer.validateFamily(seg.get(JAVA_BYTE, FAMILY_ID_BYTE), seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE)); - SerializerDeserializer.validateType(seg.get(JAVA_BYTE, SKETCH_TYPE_BYTE), - SerializerDeserializer.SketchType.ArrayOfDoublesUnion); - - if (isWritable) { - final MemorySegment sketchSeg = seg.asSlice(PREAMBLE_SIZE_BYTES, seg.byteSize() - PREAMBLE_SIZE_BYTES); - return new DirectArrayOfDoublesUnion(new DirectArrayOfDoublesQuickSelectSketch(sketchSeg, seed), seg); - } - final MemorySegment sketchSeg = seg.asSlice(PREAMBLE_SIZE_BYTES, seg.byteSize() - PREAMBLE_SIZE_BYTES); - return new DirectArrayOfDoublesUnionR(new DirectArrayOfDoublesQuickSelectSketchR(sketchSeg, seed), seg); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesUnionR.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesUnionR.java deleted file mode 100644 index 164526c96..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesUnionR.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesReadOnlyException; - -final class DirectArrayOfDoublesUnionR extends DirectArrayOfDoublesUnion { - - /** - * Wraps the given MemorySegment. - * @param gadget the ArrayOfDoublesQuickSelectSketch - * @param seg the destination MemorySegment - */ - DirectArrayOfDoublesUnionR(final ArrayOfDoublesQuickSelectSketch gadget, final MemorySegment seg) { - super(gadget, seg); - } - - @Override - public void union(final ArrayOfDoublesSketch tupleSketch) { - throw new SketchesReadOnlyException(); - } - - @Override - public void reset() { - throw new SketchesReadOnlyException(); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HashTables.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HashTables.java deleted file mode 100644 index 0b93316b3..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HashTables.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static java.lang.Math.ceil; -import static java.lang.Math.max; -import static java.lang.Math.min; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.thetacommon.HashOperations.hashInsertOnly; -import static org.apache.datasketches.thetacommon.HashOperations.hashSearch; - -import org.apache.datasketches.thetacommon.ThetaUtil; - -class HashTables { - private long[] hashTable = null; - private double[][] valueTable = null; - private int numValues = 0; - private int lgTableSize = 0; - private int numKeys = 0; - - //Construct from sketch - HashTables(final ArrayOfDoublesSketch sketchIn) { - numKeys = sketchIn.getRetainedEntries(); - numValues = sketchIn.getNumValues(); - - lgTableSize = getLgTableSize(numKeys); - final int tableSize = 1 << lgTableSize; - hashTable = new long[tableSize]; - valueTable = new double[tableSize][]; - final ArrayOfDoublesSketchIterator it = sketchIn.iterator(); - - while (it.next()) { - final long hash = it.getKey(); - final int index = hashInsertOnly(hashTable, lgTableSize, hash); - valueTable[index] = new double[numValues]; - System.arraycopy(it.getValues(), 0, valueTable[index], 0, numValues); - } - } - - //Construct: Load the hash and value tables from packed hash and value arrays - private HashTables(final long[] hashArr, final double[][] valuesArr, final int numKeys, final int numValues) { - this.numValues = numValues; - this.numKeys = numKeys; - lgTableSize = getLgTableSize(numKeys); - - final int tableSize = 1 << lgTableSize; - hashTable = new long[tableSize]; - valueTable = new double[tableSize][]; - - for (int i = 0; i < numKeys; i++) { - final long hash = hashArr[i]; - final int index = hashInsertOnly(hashTable, lgTableSize, hash); - valueTable[index] = new double[numValues]; - System.arraycopy(valuesArr[i], 0, valueTable[index], 0, numValues); - } - } - - HashTables getIntersectHashTables( - final ArrayOfDoublesSketch nextTupleSketch, - final long thetaLong, - final ArrayOfDoublesCombiner combiner) { - //Match nextSketch data with local instance data, filtering by theta - final int maxMatchSize = min(numKeys, nextTupleSketch.getRetainedEntries()); - assert numValues == nextTupleSketch.numValues_; - final long[] matchHashArr = new long[maxMatchSize]; - final double[][] matchValuesArr = new double[maxMatchSize][]; - - //Copy the intersecting items from local hashTables_ - // sequentially into local packed matchHashArr_ and matchValuesArr - int matchCount = 0; - final ArrayOfDoublesSketchIterator it = nextTupleSketch.iterator(); - while (it.next()) { - final long hash = it.getKey(); - if (hash >= thetaLong) { continue; } - final int index = hashSearch(hashTable, lgTableSize, hash); - if (index < 0) { continue; } - matchHashArr[matchCount] = hash; - matchValuesArr[matchCount] = combiner.combine(valueTable[index], it.getValues()); - matchCount++; - } - return new HashTables(matchHashArr, matchValuesArr, matchCount, numValues); - } - - int getNumKeys() { - return numKeys; - } - - int getNumValues() { - return numValues; - } - - long[] getHashTable() { - return hashTable; - } - - double[][] getValueTable() { - return valueTable; - } - - void clear() { - hashTable = null; - valueTable = null; - numValues = 0; - lgTableSize = 0; - numKeys = 0; - } - - static int getLgTableSize(final int numKeys) { - final int tableSize = max(ceilingPowerOf2((int) ceil(numKeys / 0.75)), 1 << ThetaUtil.MIN_LG_NOM_LONGS); - return Integer.numberOfTrailingZeros(tableSize); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesCompactSketch.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesCompactSketch.java deleted file mode 100644 index 8672014d4..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesCompactSketch.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.tuple.SerializerDeserializer; - -/** - * The on-heap implementation of CompactTupleSketch of type ArrayOfDoubles. - */ -final class HeapArrayOfDoublesCompactSketch extends ArrayOfDoublesCompactSketch { - - private final short seedHash_; - private long[] keys_; - private double[] values_; - - /** - * Converts the given UpdatableArrayOfDoublesSketch to this compact form. - * @param sketch the given UpdatableArrayOfDoublesSketch - */ - HeapArrayOfDoublesCompactSketch(final ArrayOfDoublesUpdatableSketch sketch) { - this(sketch, sketch.getThetaLong()); - } - - /** - * Converts the given UpdatableArrayOfDoublesSketch to this compact form - * trimming if necessary according to given thetaLong - * @param sketch the given UpdatableArrayOfDoublesSketch - * @param thetaLong new value of thetaLong - */ - HeapArrayOfDoublesCompactSketch(final ArrayOfDoublesUpdatableSketch sketch, final long thetaLong) { - super(sketch.getNumValues()); - isEmpty_ = sketch.isEmpty(); - thetaLong_ = Math.min(sketch.getThetaLong(), thetaLong); - seedHash_ = Util.computeSeedHash(sketch.getSeed()); - final int count = sketch.getRetainedEntries(); - if (count > 0) { - keys_ = new long[count]; - values_ = new double[count * numValues_]; - final ArrayOfDoublesSketchIterator it = sketch.iterator(); - int i = 0; - while (it.next()) { - final long key = it.getKey(); - if (key < thetaLong_) { - keys_[i] = key; - System.arraycopy(it.getValues(), 0, values_, i * numValues_, numValues_); - i++; - } - } - // trim if necessary - if (i < count) { - if (i == 0) { - keys_ = null; - values_ = null; - } else { - keys_ = Arrays.copyOf(keys_, i); - values_ = Arrays.copyOf(values_, i * numValues_); - } - } - } - } - - /* - * Creates an instance from components - */ - HeapArrayOfDoublesCompactSketch(final long[] keys, final double[] values, final long thetaLong, - final boolean isEmpty, final int numValues, final short seedHash) { - super(numValues); - keys_ = keys; - values_ = values; - thetaLong_ = thetaLong; - isEmpty_ = isEmpty; - seedHash_ = seedHash; - } - - /** - * This is to create an instance given a serialized form - * @param seg the destination segment - */ - HeapArrayOfDoublesCompactSketch(final MemorySegment seg) { - this(seg, Util.DEFAULT_UPDATE_SEED); - } - - /** - * This is to create an instance given a serialized form - * @param seg the source MemorySegment - * @param seed See seed - */ - HeapArrayOfDoublesCompactSketch(final MemorySegment seg, final long seed) { - super(seg.get(JAVA_BYTE, NUM_VALUES_BYTE)); - seedHash_ = seg.get(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT); - SerializerDeserializer.validateFamily(seg.get(JAVA_BYTE, FAMILY_ID_BYTE), - seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE)); - SerializerDeserializer.validateType(seg.get(JAVA_BYTE, SKETCH_TYPE_BYTE), - SerializerDeserializer.SketchType.ArrayOfDoublesCompactSketch); - final byte version = seg.get(JAVA_BYTE, SERIAL_VERSION_BYTE); - if (version != serialVersionUID) { - throw new SketchesArgumentException( - "Serial version mismatch. Expected: " + serialVersionUID + ", actual: " + version); - } - Util.checkSeedHashes(seedHash_, Util.computeSeedHash(seed)); - isEmpty_ = (seg.get(JAVA_BYTE, FLAGS_BYTE) & (1 << Flags.IS_EMPTY.ordinal())) != 0; - thetaLong_ = seg.get(JAVA_LONG_UNALIGNED, THETA_LONG); - final boolean hasEntries = - (seg.get(JAVA_BYTE, FLAGS_BYTE) & (1 << Flags.HAS_ENTRIES.ordinal())) != 0; - if (hasEntries) { - final int count = seg.get(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT); - keys_ = new long[count]; - values_ = new double[count * numValues_]; - MemorySegment.copy(seg, JAVA_LONG_UNALIGNED, ENTRIES_START, keys_, 0, count); - MemorySegment.copy(seg, JAVA_DOUBLE_UNALIGNED, ENTRIES_START + ((long) SIZE_OF_KEY_BYTES * count), values_, 0, values_.length); - } - } - - @Override - public ArrayOfDoublesCompactSketch compact(final MemorySegment dstSeg) { - if (dstSeg == null) { - return new - HeapArrayOfDoublesCompactSketch(keys_.clone(), values_.clone(), thetaLong_, isEmpty_, numValues_, seedHash_); - } else { - final byte[] byteArr = toByteArray(); - MemorySegment.copy(byteArr, 0, dstSeg, JAVA_BYTE, 0, byteArr.length); - return new DirectArrayOfDoublesCompactSketch(dstSeg); - } - } - - @Override - public int getRetainedEntries() { - return keys_ == null ? 0 : keys_.length; - } - - @Override - public byte[] toByteArray() { - final int count = getRetainedEntries(); - final int sizeBytes = getCurrentBytes(); - final byte[] bytes = new byte[sizeBytes]; - final MemorySegment seg = MemorySegment.ofArray(bytes); - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) 1); - seg.set(JAVA_BYTE, SERIAL_VERSION_BYTE, serialVersionUID); - seg.set(JAVA_BYTE, FAMILY_ID_BYTE, (byte) Family.TUPLE.getID()); - seg.set(JAVA_BYTE, SKETCH_TYPE_BYTE, (byte) SerializerDeserializer.SketchType.ArrayOfDoublesCompactSketch.ordinal()); - seg.set(JAVA_BYTE, FLAGS_BYTE, (byte) ( - ((isEmpty() ? 1 : 0) << Flags.IS_EMPTY.ordinal()) - | ((count > 0 ? 1 : 0) << Flags.HAS_ENTRIES.ordinal()) - )); - seg.set(JAVA_BYTE, NUM_VALUES_BYTE, (byte) numValues_); - seg.set(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT, seedHash_); - seg.set(JAVA_LONG_UNALIGNED, THETA_LONG, thetaLong_); - if (count > 0) { - seg.set(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT, count); - MemorySegment.copy(keys_, 0, seg, JAVA_LONG_UNALIGNED, ENTRIES_START, count); - MemorySegment.copy(values_, 0, seg, JAVA_DOUBLE_UNALIGNED, ENTRIES_START + ((long) SIZE_OF_KEY_BYTES * count), values_.length); - } - return bytes; - } - - @Override - //converts compact heap array of double[] to compact double[][] - public double[][] getValues() { - final int count = getRetainedEntries(); - final double[][] values = new double[count][]; - if (count > 0) { - int i = 0; - for (int j = 0; j < count; j++) { - values[i++] = Arrays.copyOfRange(values_, j * numValues_, (j + 1) * numValues_); - } - } - return values; - } - - @Override - double[] getValuesAsOneDimension() { - return values_.clone(); - } - - @Override - long[] getKeys() { - return keys_.clone(); - } - - @Override - public ArrayOfDoublesSketchIterator iterator() { - return new HeapArrayOfDoublesSketchIterator(keys_, values_, numValues_); - } - - @Override - short getSeedHash() { - return seedHash_; - } - - @Override - public boolean hasMemorySegment() { return false; } - - @Override - MemorySegment getMemorySegment() { return null; } -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesIntersection.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesIntersection.java deleted file mode 100644 index a87b349bb..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesIntersection.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -/** - * On-heap implementation of intersection set operation for tuple sketches of type - * ArrayOfDoubles. - */ -final class HeapArrayOfDoublesIntersection extends ArrayOfDoublesIntersection { - - /** - * Creates an instance of a HeapArrayOfDoublesIntersection with a custom update seed - * @param numValues number of double values associated with each key - * @param seed See seed - */ - HeapArrayOfDoublesIntersection(final int numValues, final long seed) { - super(numValues, seed); - } - - @Override - protected ArrayOfDoublesQuickSelectSketch createSketch(final int nomEntries, final int numValues, final long seed) { - return new HeapArrayOfDoublesQuickSelectSketch(nomEntries, 0, 1f, numValues, seed); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesQuickSelectSketch.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesQuickSelectSketch.java deleted file mode 100644 index 370d6cb44..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesQuickSelectSketch.java +++ /dev/null @@ -1,358 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.common.Util.checkSeedHashes; -import static org.apache.datasketches.common.Util.computeSeedHash; -import static org.apache.datasketches.common.Util.exactLog2OfLong; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.thetacommon.HashOperations; -import org.apache.datasketches.tuple.SerializerDeserializer; -import org.apache.datasketches.tuple.Util; - -/** - * The on-heap implementation of the tuple QuickSelect sketch of type ArrayOfDoubles. - */ - -final class HeapArrayOfDoublesQuickSelectSketch extends ArrayOfDoublesQuickSelectSketch { - - private final int lgNomEntries_; - private final int lgResizeFactor_; - private final float samplingProbability_; - - private int count_; - private long[] keys_; - private double[] values_; - - /** - * This is to create an instance of a QuickSelectSketch with custom resize factor and sampling - * probability - * @param nomEntries Nominal number of entries. Forced to the smallest power of 2 greater than - * or equal to the given value. - * @param lgResizeFactor log2(resize factor) - value from 0 to 3: - * 0 - no resizing (max size allocated), - * 1 - double internal hash table each time it reaches a threshold - * 2 - grow four times - * 3 - grow eight times (default) - * @param samplingProbability - * See Sampling Probability - * @param numValues number of double values to keep for each key - * @param seed See seed - */ - HeapArrayOfDoublesQuickSelectSketch(final int nomEntries, final int lgResizeFactor, - final float samplingProbability, final int numValues, final long seed) { - super(numValues, seed); - lgNomEntries_ = exactLog2OfLong(ceilingPowerOf2(nomEntries)); - lgResizeFactor_ = lgResizeFactor; - samplingProbability_ = samplingProbability; - thetaLong_ = (long) (Long.MAX_VALUE * (double) samplingProbability); - final int startingCapacity = Util.getStartingCapacity(nomEntries, lgResizeFactor); - keys_ = new long[startingCapacity]; - values_ = new double[startingCapacity * numValues]; - lgCurrentCapacity_ = Integer.numberOfTrailingZeros(startingCapacity); - setRebuildThreshold(); - } - - /** - * This is to create an instance given a serialized form - * @param seg the source MemorySegment - * @param seed See seed - */ - HeapArrayOfDoublesQuickSelectSketch(final MemorySegment seg, final long seed) { - super(seg.get(JAVA_BYTE, NUM_VALUES_BYTE), seed); - SerializerDeserializer.validateFamily(seg.get(JAVA_BYTE, FAMILY_ID_BYTE), - seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE)); - SerializerDeserializer.validateType(seg.get(JAVA_BYTE, SKETCH_TYPE_BYTE), - SerializerDeserializer.SketchType.ArrayOfDoublesQuickSelectSketch); - final byte version = seg.get(JAVA_BYTE, SERIAL_VERSION_BYTE); - if (version != serialVersionUID) { - throw new SketchesArgumentException("Serial version mismatch. Expected: " - + serialVersionUID + ", actual: " + version); - } - final byte flags = seg.get(JAVA_BYTE, FLAGS_BYTE); - checkSeedHashes(seg.get(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT), computeSeedHash(seed)); - isEmpty_ = (flags & (1 << Flags.IS_EMPTY.ordinal())) > 0; - lgNomEntries_ = seg.get(JAVA_BYTE, LG_NOM_ENTRIES_BYTE); - thetaLong_ = seg.get(JAVA_LONG_UNALIGNED, THETA_LONG); - final int currentCapacity = 1 << seg.get(JAVA_BYTE, LG_CUR_CAPACITY_BYTE); - lgResizeFactor_ = seg.get(JAVA_BYTE, LG_RESIZE_FACTOR_BYTE); - samplingProbability_ = seg.get(JAVA_FLOAT_UNALIGNED, SAMPLING_P_FLOAT); - keys_ = new long[currentCapacity]; - values_ = new double[currentCapacity * numValues_]; - final boolean hasEntries = (flags & (1 << Flags.HAS_ENTRIES.ordinal())) > 0; - count_ = hasEntries ? seg.get(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT) : 0; - if (count_ > 0) { - MemorySegment.copy(seg, JAVA_LONG_UNALIGNED, ENTRIES_START, keys_, 0, currentCapacity); - final long off = ENTRIES_START + ((long) SIZE_OF_KEY_BYTES * currentCapacity); - MemorySegment.copy(seg, JAVA_DOUBLE_UNALIGNED, off, values_, 0, currentCapacity * numValues_); - - } - setRebuildThreshold(); - lgCurrentCapacity_ = Integer.numberOfTrailingZeros(currentCapacity); - } - - @Override - //converts heap hashTable of double[] to compacted double[][] - public double[][] getValues() { - final int numVal = numValues_; - final int count = getRetainedEntries(); - final double[][] values = new double[count][]; - if (count > 0) { - int cnt = 0; - for (int j = 0; j < keys_.length; j++) { - if (keys_[j] == 0) { continue; } - values[cnt++] = Arrays.copyOfRange(values_, j * numVal, (j + 1) * numVal); - } - assert cnt == count; - } - return values; - } - - @Override - //converts heap hashTable of double[] to compacted double[] - double[] getValuesAsOneDimension() { - final int numVal = numValues_; - final int count = getRetainedEntries(); - final double[] values = new double[count * numVal]; - if (count > 0) { - int cnt = 0; - for (int j = 0; j < keys_.length; j++) { - if (keys_[j] == 0) { continue; } - System.arraycopy(values_, j * numVal, values, cnt++ * numVal, numVal); - } - assert cnt == count; - } - return values; - } - - @Override - //converts heap hashTable of long[] to compacted long[] - long[] getKeys() { - final int count = getRetainedEntries(); - final long[] keysArr = new long[count]; - if (count > 0) { - int cnt = 0; - for (int j = 0; j < keys_.length; j++) { - if (keys_[j] == 0) { continue; } - keysArr[cnt++] = keys_[j]; - } - assert cnt == count; - } - return keysArr; - } - - @Override - public int getRetainedEntries() { - return count_; - } - - @Override - public int getNominalEntries() { - return 1 << lgNomEntries_; - } - - @Override - public float getSamplingProbability() { - return samplingProbability_; - } - - @Override - public ResizeFactor getResizeFactor() { - return ResizeFactor.getRF(lgResizeFactor_); - } - - @Override - public byte[] toByteArray() { - final byte[] byteArray = new byte[getSerializedSizeBytes()]; - final MemorySegment seg = MemorySegment.ofArray(byteArray); - serializeInto(seg); - return byteArray; - } - - @Override - public ArrayOfDoublesSketchIterator iterator() { - return new HeapArrayOfDoublesSketchIterator(keys_, values_, numValues_); - } - - @Override - int getSerializedSizeBytes() { - return ENTRIES_START + ((SIZE_OF_KEY_BYTES + (SIZE_OF_VALUE_BYTES * numValues_)) * getCurrentCapacity()); - } - - // X/Y: X = Byte index for just AoDQuickSelectSketch - // Y = Byte index when combined with TupleUnion Preamble - // Long || Start Byte Adr: - // Adr: - // First 16 bytes are preamble from AoDUnion - // || 7/23 | 6/22 | 5/21 | 4/20 | 3/19 | 2/18 | 1/17 | 0/16 | - // 0/2 || Seed Hash | #Dbls | Flags | SkType2 | FamID | SerVer | Preamble_Longs | - // || 15/31 | 14/30 | 13/29 | 12/28 | 11/27 | 10/26 | 9/25 | 8/24 | - // 1/3 ||------------------------------Theta Long----------------------------------------------| - // || 23/39 | 22/38 | 21/37 | 20/36 | 19/35 | 18/34 | 17/33 | 16/32 | - // 2/4 || Sampling P Float | | LgRF |lgCapLongs| LgNomEntries | - // || 31/47 | 30/46 | 29/45 | 28/44 | 27/43 | 26/42 | 25/41 | 24/40 | - // 3/5 || | Retained Entries Int | - // || | 32/48 | - // 4/6 || Keys Array longs * keys[] Length | - // || Values Array doubles * values[] Length | - - @Override - void serializeInto(final MemorySegment seg) { - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) 1); - seg.set(JAVA_BYTE, SERIAL_VERSION_BYTE, serialVersionUID); - seg.set(JAVA_BYTE, FAMILY_ID_BYTE, (byte) Family.TUPLE.getID()); - seg.set(JAVA_BYTE, SKETCH_TYPE_BYTE, - (byte) SerializerDeserializer.SketchType.ArrayOfDoublesQuickSelectSketch.ordinal()); - seg.set(JAVA_BYTE, FLAGS_BYTE, (byte)( - (isInSamplingMode() ? 1 << Flags.IS_IN_SAMPLING_MODE.ordinal() : 0) - | (isEmpty_ ? 1 << Flags.IS_EMPTY.ordinal() : 0) - | (count_ > 0 ? 1 << Flags.HAS_ENTRIES.ordinal() : 0) - )); - seg.set(JAVA_BYTE, NUM_VALUES_BYTE, (byte) numValues_); - seg.set(JAVA_SHORT_UNALIGNED, SEED_HASH_SHORT, computeSeedHash(seed_)); - seg.set(JAVA_LONG_UNALIGNED, THETA_LONG, thetaLong_); - seg.set(JAVA_BYTE, LG_NOM_ENTRIES_BYTE, (byte) lgNomEntries_); - seg.set(JAVA_BYTE, LG_CUR_CAPACITY_BYTE, (byte) Integer.numberOfTrailingZeros(keys_.length)); - seg.set(JAVA_BYTE, LG_RESIZE_FACTOR_BYTE, (byte) lgResizeFactor_); - seg.set(JAVA_FLOAT_UNALIGNED, SAMPLING_P_FLOAT, samplingProbability_); - seg.set(JAVA_INT_UNALIGNED, RETAINED_ENTRIES_INT, count_); - if (count_ > 0) { - MemorySegment.copy(keys_, 0, seg, JAVA_LONG_UNALIGNED, ENTRIES_START, keys_.length); - final long off = ENTRIES_START + ((long) SIZE_OF_KEY_BYTES * keys_.length); - MemorySegment.copy(values_, 0, seg, JAVA_DOUBLE_UNALIGNED, off, values_.length); - } - } - - @Override - public boolean hasMemorySegment() { return false; } - - @Override - MemorySegment getMemorySegment() { return null; } - - @Override - public void reset() { - isEmpty_ = true; - count_ = 0; - thetaLong_ = (long) (Long.MAX_VALUE * (double) samplingProbability_); - final int startingCapacity = Util.getStartingCapacity(1 << lgNomEntries_, lgResizeFactor_); - keys_ = new long[startingCapacity]; - values_ = new double[startingCapacity * numValues_]; - lgCurrentCapacity_ = Integer.numberOfTrailingZeros(startingCapacity); - setRebuildThreshold(); - } - - @Override - protected long getKey(final int index) { - return keys_[index]; - } - - @Override - protected void incrementCount() { - count_++; - } - - @Override - protected void setValues(final int index, final double[] values) { - if (numValues_ == 1) { - values_[index] = values[0]; - } else { - System.arraycopy(values, 0, values_, index * numValues_, numValues_); - } - } - - @Override - protected void updateValues(final int index, final double[] values) { - if (numValues_ == 1) { - values_[index] += values[0]; - } else { - final int offset = index * numValues_; - for (int i = 0; i < numValues_; i++) { - values_[offset + i] += values[i]; - } - } - } - - @Override - protected void setNotEmpty() { - isEmpty_ = false; - } - - @Override - protected boolean isInSamplingMode() { - return samplingProbability_ < 1f; - } - - @Override - protected void setThetaLong(final long thetaLong) { - thetaLong_ = thetaLong; - } - - @Override - protected int getCurrentCapacity() { - return keys_.length; - } - - @Override - protected void rebuild(final int newCapacity) { - final long[] oldKeys = keys_; - final double[] oldValues = values_; - keys_ = new long[newCapacity]; - values_ = new double[newCapacity * numValues_]; - count_ = 0; - lgCurrentCapacity_ = Integer.numberOfTrailingZeros(newCapacity); - for (int i = 0; i < oldKeys.length; i++) { - if ((oldKeys[i] != 0) && (oldKeys[i] < thetaLong_)) { - insert(oldKeys[i], Arrays.copyOfRange(oldValues, i * numValues_, (i + 1) * numValues_)); - } - } - setRebuildThreshold(); - } - - @Override - protected int insertKey(final long key) { - return HashOperations.hashInsertOnly(keys_, lgCurrentCapacity_, key); - } - - @Override - protected int findOrInsertKey(final long key) { - return HashOperations.hashSearchOrInsert(keys_, lgCurrentCapacity_, key); - } - - @Override - protected double[] find(final long key) { - final int index = HashOperations.hashSearch(keys_, lgCurrentCapacity_, key); - if (index == -1) { return null; } - return Arrays.copyOfRange(values_, index * numValues_, (index + 1) * numValues_); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesSketchIterator.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesSketchIterator.java deleted file mode 100644 index a684d4f25..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesSketchIterator.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.util.Arrays; - -/** - * Iterator over the on-heap ArrayOfDoublesSketch (compact or hash table) - */ -final class HeapArrayOfDoublesSketchIterator implements ArrayOfDoublesSketchIterator { - - private long[] keys_; - private double[] values_; - private int numValues_; - private int i_; - - HeapArrayOfDoublesSketchIterator(final long[] keys, final double[] values, final int numValues) { - keys_ = keys; - values_ = values; - numValues_ = numValues; - i_ = -1; - } - - @Override - public boolean next() { - if (keys_ == null) { return false; } - i_++; - while (i_ < keys_.length) { - if (keys_[i_] != 0) { return true; } - i_++; - } - return false; - } - - @Override - public long getKey() { - return keys_[i_]; - } - - @Override - public double[] getValues() { - if (numValues_ == 1) { - return new double[] { values_[i_] }; - } - return Arrays.copyOfRange(values_, i_ * numValues_, (i_ + 1) * numValues_); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesUnion.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesUnion.java deleted file mode 100644 index b3f93c60e..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesUnion.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.SerializerDeserializer; - -/** - * The on-heap implementation of the TupleUnion set operation for tuple sketches of type - * ArrayOfDoubles. - */ -final class HeapArrayOfDoublesUnion extends ArrayOfDoublesUnion { - - /** - * Creates an instance of HeapArrayOfDoublesUnion with a custom seed - * @param nomEntries Nominal number of entries. Forced to the nearest power of 2 greater than - * given value. - * @param numValues Number of double values to keep for each key. - * @param seed See seed - */ - HeapArrayOfDoublesUnion(final int nomEntries, final int numValues, final long seed) { - super(new HeapArrayOfDoublesQuickSelectSketch(nomEntries, 3, 1f, numValues, seed)); - } - - HeapArrayOfDoublesUnion(final ArrayOfDoublesQuickSelectSketch gadget, final long unionThetaLong) { - super(gadget); - unionThetaLong_ = unionThetaLong; - } - - /** - * This is to create an instance given a serialized form and a custom seed - * @param seg the source MemorySegment - * @param seed See seed - * @return a ArrayOfDoublesUnion on the Java heap - */ - static ArrayOfDoublesUnion heapifyUnion(final MemorySegment seg, final long seed) { - final byte version = seg.get(JAVA_BYTE, SERIAL_VERSION_BYTE); - if (version != serialVersionUID) { - throw new SketchesArgumentException("Serial version mismatch. Expected: " - + serialVersionUID + ", actual: " + version); - } - SerializerDeserializer.validateFamily(seg.get(JAVA_BYTE, FAMILY_ID_BYTE), seg.get(JAVA_BYTE, PREAMBLE_LONGS_BYTE)); - SerializerDeserializer.validateType(seg.get(JAVA_BYTE, SKETCH_TYPE_BYTE), - SerializerDeserializer.SketchType.ArrayOfDoublesUnion); - - final MemorySegment sketchSeg = seg.asSlice(PREAMBLE_SIZE_BYTES, seg.byteSize() - PREAMBLE_SIZE_BYTES); - final ArrayOfDoublesQuickSelectSketch sketch = new HeapArrayOfDoublesQuickSelectSketch(sketchSeg, seed); - return new HeapArrayOfDoublesUnion(sketch, seg.get(JAVA_LONG_UNALIGNED, THETA_LONG)); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/package-info.java b/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/package-info.java deleted file mode 100644 index 42a34373a..000000000 --- a/src/main/java/org/apache/datasketches/tuple/arrayofdoubles/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package is for a concrete implementation of the Tuple sketch for an array of double values. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; diff --git a/src/main/java/org/apache/datasketches/tuple/package-info.java b/src/main/java/org/apache/datasketches/tuple/package-info.java deleted file mode 100644 index 4a6be9210..000000000 --- a/src/main/java/org/apache/datasketches/tuple/package-info.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * The tuple package contains a number of sketches based on the same - * fundamental algorithms of the Theta Sketch Framework and extend these - * concepts for whole new families of sketches. - */ -package org.apache.datasketches.tuple; diff --git a/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummary.java b/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummary.java deleted file mode 100644 index 5008fecd5..000000000 --- a/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummary.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.strings; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.datasketches.tuple.Util.stringArrHash; -import static org.apache.datasketches.tuple.Util.stringConcat; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.UpdatableSummary; - -/** - * Implements UpdatableSummary<String[]> - * @author Lee Rhodes - */ -public final class ArrayOfStringsSummary implements UpdatableSummary { - - private String[] stringArr = new String[] {}; //empty string array; - - /** - * No argument constructor. - */ - ArrayOfStringsSummary() {} //required for ArrayOfStringsSummaryFactory - - //Used by copy() and in test - ArrayOfStringsSummary(final String[] stringArr) { - update(stringArr); - } - - //used by fromMemorySegment and in test - /** - * This reads a MemorySegment that has a layout similar to the C struct: - * {@snippet : - * typedef struct { - * int totBytes; - * byte nodes; //number of Nodes. - * Node[nodes] = { Node[0], Node[1], ... } - * } - * } - * Where a Node has a layout similar to the C struct: - * {@snippet : - * typedef struct { - * int numBytes; - * byte[] byteArray; //UTF-8 byte array. Not null terminated. - * } - * } - * @param seg the MemorySegment containing the Summary data - */ - ArrayOfStringsSummary(final MemorySegment seg) { - int pos = 0; - final int totBytes = seg.get(JAVA_INT_UNALIGNED, pos); pos += Integer.BYTES; - checkInBytes(seg, totBytes); - final int nodes = seg.get(JAVA_BYTE, pos); pos += Byte.BYTES; - checkNumNodes(nodes); - final String[] stringArr = new String[nodes]; - for (int i = 0; i < nodes; i++) { - final int len = seg.get(JAVA_INT_UNALIGNED, pos); pos += Integer.BYTES; - final byte[] byteArr = new byte[len]; - MemorySegment.copy(seg, JAVA_BYTE, pos, byteArr, 0, len); pos += len; - stringArr[i] = new String(byteArr, UTF_8); - } - assert pos == totBytes; - this.stringArr = stringArr; - } - - //From UpdatableSummary - - @Override - public final ArrayOfStringsSummary update(final String[] value) { - if (value == null) { stringArr = new String[] {}; } - else { stringArr = value.clone(); } - return this; - } - - //From Summary - - @Override - public ArrayOfStringsSummary copy() { - return new ArrayOfStringsSummary(stringArr); - } - - @Override - public byte[] toByteArray() { - final ComputeBytes cb = new ComputeBytes(stringArr); - final int totBytes = cb.totBytes_; - final byte[] out = new byte[totBytes]; - final MemorySegment wseg = MemorySegment.ofArray(out); - int pos = 0; - wseg.set(JAVA_INT_UNALIGNED, pos, totBytes); pos += Integer.BYTES; - final int numNodes = cb.numNodes_; - wseg.set(JAVA_BYTE, pos, (byte)numNodes); pos += Byte.BYTES; - for (int i = 0; i < numNodes; i++) { - final int nodeLen = cb.nodeLengthsArr_[i]; - wseg.set(JAVA_INT_UNALIGNED, pos, nodeLen); pos += Integer.BYTES; - MemorySegment.copy(cb.nodeBytesArr_[i], 0, wseg, JAVA_BYTE, pos, nodeLen); pos += nodeLen; - } - assert pos == totBytes; - return out; - } - - //From Object - - @Override - public int hashCode() { - return (int) stringArrHash(stringArr); - } - - @Override - public boolean equals(final Object summary) { - if (summary == null || !(summary instanceof ArrayOfStringsSummary)) { - return false; - } - final String thatStr = stringConcat(((ArrayOfStringsSummary) summary).stringArr); - final String thisStr = stringConcat(stringArr); - return thisStr.equals(thatStr); - } - - //Local - - /** - * Returns the nodes array for this summary. - * @return the nodes array for this summary. - */ - public String[] getValue() { - return stringArr.clone(); - } - - //also used in test - static void checkNumNodes(final int numNodes) { - if (numNodes > 127 || numNodes < 0) { - throw new SketchesArgumentException("Number of nodes cannot exceed 127 or be negative."); - } - } - - //also used in test - static void checkInBytes(final MemorySegment seg, final int totBytes) { - if (seg.byteSize() < totBytes) { - throw new SketchesArgumentException("Incoming MemorySegment has insufficient capacity."); - } - } - - /** - * Computes total bytes and number of nodes from the given string array. - */ - private static class ComputeBytes { - final byte numNodes_; - final int[] nodeLengthsArr_; - final byte[][] nodeBytesArr_; - final int totBytes_; - - ComputeBytes(final String[] stringArr) { - numNodes_ = (byte) stringArr.length; - checkNumNodes(numNodes_); - nodeLengthsArr_ = new int[numNodes_]; - nodeBytesArr_ = new byte[numNodes_][]; - int sumNodeBytes = 0; - for (int i = 0; i < numNodes_; i++) { - nodeBytesArr_[i] = stringArr[i].getBytes(UTF_8); - nodeLengthsArr_[i] = nodeBytesArr_[i].length; - sumNodeBytes += nodeLengthsArr_[i]; - } - totBytes_ = sumNodeBytes + (numNodes_ + 1) * Integer.BYTES + 1; - } - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryDeserializer.java b/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryDeserializer.java deleted file mode 100644 index dffe91983..000000000 --- a/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryDeserializer.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.strings; - -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.tuple.DeserializeResult; -import org.apache.datasketches.tuple.SummaryDeserializer; - -/** - * Implements SummaryDeserializer<ArrayOfStringsSummary> - * @author Lee Rhodes - */ -public class ArrayOfStringsSummaryDeserializer implements SummaryDeserializer { - - /** - * No argument constructor. - */ - public ArrayOfStringsSummaryDeserializer() { } - - @Override - public DeserializeResult heapifySummary(final MemorySegment seg) { - return ArrayOfStringsSummaryDeserializer.fromMemorySegment(seg); - } - - /** - * Also used in test. - * @param seg the given MemorySegment - * @return the DeserializeResult - */ - static DeserializeResult fromMemorySegment(final MemorySegment seg) { - final ArrayOfStringsSummary nsum = new ArrayOfStringsSummary(seg); - final int totBytes = seg.get(JAVA_INT_UNALIGNED, 0); - return new DeserializeResult<>(nsum, totBytes); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryFactory.java b/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryFactory.java deleted file mode 100644 index 8ca2a6a1a..000000000 --- a/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.strings; - -import org.apache.datasketches.tuple.SummaryFactory; - -/** - * Implements SummaryFactory<ArrayOfStringsSummary> - * @author Lee Rhodes - */ -public class ArrayOfStringsSummaryFactory implements SummaryFactory { - - /** - * No argument constructor. - */ - public ArrayOfStringsSummaryFactory() { } - - @Override - public ArrayOfStringsSummary newSummary() { - return new ArrayOfStringsSummary(); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummarySetOperations.java b/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummarySetOperations.java deleted file mode 100644 index 270acbe3c..000000000 --- a/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummarySetOperations.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.strings; - -import org.apache.datasketches.tuple.SummarySetOperations; - -/** - * Implements SummarySetOperations<ArrayOfStringsSummary> - * @author Lee Rhodes - */ -public class ArrayOfStringsSummarySetOperations implements SummarySetOperations { - - /** - * No argument constructor. - */ - public ArrayOfStringsSummarySetOperations() { } - - @Override - public ArrayOfStringsSummary union(final ArrayOfStringsSummary a, final ArrayOfStringsSummary b) { - return a.copy(); - } - - @Override - public ArrayOfStringsSummary intersection(final ArrayOfStringsSummary a, final ArrayOfStringsSummary b) { - return a.copy(); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsTupleSketch.java b/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsTupleSketch.java deleted file mode 100644 index 6260f0df2..000000000 --- a/src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsTupleSketch.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.strings; - -import static org.apache.datasketches.tuple.Util.stringArrHash; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.tuple.UpdatableTupleSketch; - -/** - * Extends UpdatableTupleSketch<String[], ArrayOfStringsSummary> - * @author Lee Rhodes - */ -public class ArrayOfStringsTupleSketch extends UpdatableTupleSketch { - - /** - * Constructs new sketch with default K = 4096 (lgK = 12), default ResizeFactor=X8, - * and default p = 1.0. - */ - public ArrayOfStringsTupleSketch() { - this(12); - } - - /** - * Constructs new sketch with default ResizeFactor=X8, default p = 1.0 and given lgK. - * @param lgK Log_base2 of Nominal Entries. - * See Nominal Entries - */ - public ArrayOfStringsTupleSketch(final int lgK) { - this(lgK, ResizeFactor.X8, 1.0F); - } - - /** - * Constructs new sketch with given ResizeFactor, p and lgK. - * @param lgK Log_base2 of Nominal Entries. - * See Nominal Entries - * @param rf ResizeFactor - * See Resize Factor - * @param p sampling probability - * See Sampling Probability - */ - public ArrayOfStringsTupleSketch(final int lgK, final ResizeFactor rf, final float p) { - super(1 << lgK, rf.lg(), p, new ArrayOfStringsSummaryFactory()); - } - - /** - * Constructs this sketch from a MemorySegment image, which must be from an ArrayOfStringsTupleSketch, and - * usually with data. - * @param seg the given MemorySegment - * @deprecated As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. - * This capability will be removed in a future release. - * Heapifying a CompactTupleSketch is not deprecated. - */ - @Deprecated - public ArrayOfStringsTupleSketch(final MemorySegment seg) { - super(seg, new ArrayOfStringsSummaryDeserializer(), new ArrayOfStringsSummaryFactory()); - } - - /** - * Copy Constructor - * @param sketch the sketch to copy - */ - public ArrayOfStringsTupleSketch(final ArrayOfStringsTupleSketch sketch) { - super(sketch); - } - - /** - * @return a deep copy of this sketch - */ - @Override - public ArrayOfStringsTupleSketch copy() { - return new ArrayOfStringsTupleSketch(this); - } - - /** - * Updates the sketch with String arrays for both key and value. - * @param strArrKey the given String array key - * @param strArr the given String array value - */ - public void update(final String[] strArrKey, final String[] strArr) { - super.update(stringArrHash(strArrKey), strArr); - } - -} diff --git a/src/main/java/org/apache/datasketches/tuple/strings/package-info.java b/src/main/java/org/apache/datasketches/tuple/strings/package-info.java deleted file mode 100644 index 9085103da..000000000 --- a/src/main/java/org/apache/datasketches/tuple/strings/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * This package is for a generic implementation of the Tuple sketch for single String value. - */ - -package org.apache.datasketches.tuple.strings; diff --git a/src/main/javadoc/overview.html b/src/main/javadoc/overview.html deleted file mode 100644 index 9124aa98a..000000000 --- a/src/main/javadoc/overview.html +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - -

Sketching Core Library

-

Overview

- -

The Sketching Core Library provides a range of stochastic streaming algorithms and closely - related java technologies that are particularly useful when integrating this technology into - systems that must deal with massive data. -

- -

This library is divided into packages that constitute distinct groups of functionality:

- -Note: In general, if the requirements or promises of any method's contract are not fulfilled -(that is, if there is a bug in either the method or its caller), -then an unchecked exception will be thrown. -The precise type of such an unchecked exception does not form part of any method's contract. - - diff --git a/src/test/java/org/apache/datasketches/common/A_BeforeSuite.java b/src/test/java/org/apache/datasketches/common/A_BeforeSuite.java deleted file mode 100644 index 97fe267ff..000000000 --- a/src/test/java/org/apache/datasketches/common/A_BeforeSuite.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import org.testng.annotations.BeforeSuite; - -public class A_BeforeSuite { - - @BeforeSuite(alwaysRun = true) - public void printTestEnvironment() { - System.out.println("===================================================="); - System.out.println("TEST JDK: " + System.getProperty("java.version")); - System.out.println("TEST JDK HOME: " + System.getProperty("java.home")); - System.out.println("====================================================="); - } -} diff --git a/src/test/java/org/apache/datasketches/common/ArrayOfXSerDeTest.java b/src/test/java/org/apache/datasketches/common/ArrayOfXSerDeTest.java deleted file mode 100644 index efd33365b..000000000 --- a/src/test/java/org/apache/datasketches/common/ArrayOfXSerDeTest.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.testng.Assert.assertEquals; - -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -public class ArrayOfXSerDeTest { - - @Test - public void checkBooleanItems() { - int bytes; - byte[] byteArr; - final int offset = 10; - MemorySegment wseg; - final ArrayOfBooleansSerDe serDe = new ArrayOfBooleansSerDe(); - - final Boolean[] items = {true,false,true,false,true,false,true,false,true,false}; - bytes = serDe.sizeOf(items); - byteArr = serDe.serializeToByteArray(items); - assertEquals(byteArr.length, bytes); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final Boolean[] deSer = serDe.deserializeFromMemorySegment(wseg, offset, items.length); - assertEquals(deSer, items); - assertEquals(serDe.sizeOf(wseg, offset, items.length), bytes); - - final Boolean item = true; - bytes = serDe.sizeOf(item); - byteArr = serDe.serializeToByteArray(item); - assertEquals(byteArr.length, bytes); - assertEquals(serDe.toString(item), item.toString()); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final Boolean deItem = serDe.deserializeFromMemorySegment(wseg, offset, 1)[0]; - assertEquals(deItem, item); - assertEquals(serDe.sizeOf(wseg, offset, 1), bytes); - } - - @Test - public void checkDoubleItems() { - int bytes; - byte[] byteArr; - final int offset = 10; - MemorySegment wseg; - final ArrayOfDoublesSerDe serDe = new ArrayOfDoublesSerDe(); - - final Double[] items = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0}; - bytes = serDe.sizeOf(items); - byteArr = serDe.serializeToByteArray(items); - assertEquals(byteArr.length, bytes); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final Double[] deSer = serDe.deserializeFromMemorySegment(wseg, offset, items.length); - assertEquals(deSer,items); - assertEquals(serDe.sizeOf(wseg, offset, items.length), bytes); - - final Double item = 13.0; - bytes = serDe.sizeOf(item); - byteArr = serDe.serializeToByteArray(item); - assertEquals(byteArr.length, bytes); - assertEquals(serDe.sizeOf(item), bytes); - assertEquals(serDe.toString(item), item.toString()); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final Double deItem = serDe.deserializeFromMemorySegment(wseg, offset, 1)[0]; - assertEquals(deItem, item); - assertEquals(serDe.sizeOf(wseg, offset, 1), bytes); - } - - @Test - public void checkLongItems() { - int bytes; - byte[] byteArr; - final int offset = 10; - MemorySegment wseg; - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - - final Long[] items = {1L, 2L, 3L, 4L, 5L, 6L}; - bytes = serDe.sizeOf(items); - byteArr = serDe.serializeToByteArray(items); - assertEquals(byteArr.length, bytes); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final Long[] deSer = serDe.deserializeFromMemorySegment(wseg, offset, items.length); - assertEquals(deSer,items); - assertEquals(serDe.sizeOf(wseg, offset, items.length), bytes); - - final Long item = 13L; - bytes = serDe.sizeOf(item); - byteArr = serDe.serializeToByteArray(item); - assertEquals(byteArr.length, bytes); - assertEquals(serDe.sizeOf(item), bytes); - assertEquals(serDe.toString(item), item.toString()); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final Long deItem = serDe.deserializeFromMemorySegment(wseg, offset, 1)[0]; - assertEquals(deItem, item); - assertEquals(serDe.sizeOf(wseg, offset, 1), bytes); - } - - @Test - public void checkNumberItems() { - int bytes; - byte[] byteArr; - final int offset = 10; - MemorySegment wseg; - final ArrayOfNumbersSerDe serDe = new ArrayOfNumbersSerDe(); - - Number item = (double)5; - bytes = serDe.sizeOf(item); - byteArr = serDe.serializeToByteArray(item); - assertEquals(byteArr.length, bytes); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final Number deSer1 = serDe.deserializeFromMemorySegment(wseg, offset, 1)[0]; - assertEquals(deSer1,item); - assertEquals(serDe.sizeOf(wseg, offset, 1), bytes); - - final Number[] items = {(long)1, (int)2, (short)3, (byte)4, (double)5, (float)6}; - bytes = serDe.sizeOf(items); - byteArr = serDe.serializeToByteArray(items); - assertEquals(byteArr.length, bytes); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final Number[] deSer = serDe.deserializeFromMemorySegment(wseg, offset, items.length); - assertEquals(deSer,items); - assertEquals(serDe.sizeOf(wseg, offset, items.length), bytes); - - item = 13.0; - bytes = serDe.sizeOf(item); - byteArr = serDe.serializeToByteArray(new Number[] {item}); - assertEquals(byteArr.length, bytes); - assertEquals(serDe.sizeOf(item), bytes); - assertEquals(serDe.toString(item), item.toString()); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final Number[] deItem = serDe.deserializeFromMemorySegment(wseg, offset, 1); - assertEquals(deItem[0], item); - assertEquals(serDe.sizeOf(wseg, offset, 1), bytes); - } - - @Test - public void checkUTF8Items() { - int bytes; - byte[] byteArr; - final int offset = 10; - MemorySegment wseg; - final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - - String item = "abcdefghijklmnopqr"; - bytes = serDe.sizeOf(item); - byteArr = serDe.serializeToByteArray(item); - assertEquals(byteArr.length, bytes); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final String deSer1 = serDe.deserializeFromMemorySegment(wseg, offset, 1)[0]; - assertEquals(deSer1,item); - assertEquals(serDe.sizeOf(wseg, offset, 1), bytes); - - final String[] items = {"abc","def","ghi","jkl","mno","pqr"}; - bytes = serDe.sizeOf(items); - byteArr = serDe.serializeToByteArray(items); - assertEquals(byteArr.length, bytes); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final String[] deSer = serDe.deserializeFromMemorySegment(wseg, offset, items.length); - assertEquals(deSer,items); - assertEquals(serDe.sizeOf(wseg, offset, items.length), bytes); - - item = "13.0"; - bytes = serDe.sizeOf(item); - byteArr = serDe.serializeToByteArray(new String[] {item}); - assertEquals(byteArr.length, bytes); - assertEquals(serDe.sizeOf(item), bytes); - assertEquals(serDe.toString(item), item); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final String[] deItem = serDe.deserializeFromMemorySegment(wseg, offset, 1); - assertEquals(deItem[0], item); - assertEquals(serDe.sizeOf(wseg, offset, 1), bytes); - } - - @Test - public void checkUTF16Items() { - int bytes; - byte[] byteArr; - final int offset = 10; - MemorySegment wseg; - final ArrayOfUtf16StringsSerDe serDe = new ArrayOfUtf16StringsSerDe(); - - String item = "abcdefghijklmnopqr"; - bytes = serDe.sizeOf(item); - byteArr = serDe.serializeToByteArray(item); - assertEquals(byteArr.length, bytes); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final String deSer1 = serDe.deserializeFromMemorySegment(wseg, offset, 1)[0]; - assertEquals(deSer1,item); - assertEquals(serDe.sizeOf(wseg, offset, 1), bytes); - - final String[] items = {"abc","def","ghi","jkl","mno","pqr"}; - bytes = serDe.sizeOf(items); - byteArr = serDe.serializeToByteArray(items); - assertEquals(byteArr.length, bytes); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final String[] deSer = serDe.deserializeFromMemorySegment(wseg, offset, items.length); - assertEquals(deSer,items); - assertEquals(serDe.sizeOf(wseg, offset, items.length), bytes); // - - item = "13.0"; - bytes = serDe.sizeOf(item); - byteArr = serDe.serializeToByteArray(new String[] {item}); - assertEquals(byteArr.length, bytes); - assertEquals(serDe.sizeOf(item), bytes); - assertEquals(serDe.toString(item), item); - - wseg = MemorySegment.ofArray(new byte[offset + byteArr.length]); - MemorySegment.copy(byteArr, 0, wseg, JAVA_BYTE, offset, byteArr.length); - final String[] deItem = serDe.deserializeFromMemorySegment(wseg, offset, 1); - assertEquals(deItem[0], item); - assertEquals(serDe.sizeOf(wseg, offset, 1), bytes); - } - -} diff --git a/src/test/java/org/apache/datasketches/common/BoundsOnBinomialProportionsTest.java b/src/test/java/org/apache/datasketches/common/BoundsOnBinomialProportionsTest.java deleted file mode 100644 index 210e7b3cf..000000000 --- a/src/test/java/org/apache/datasketches/common/BoundsOnBinomialProportionsTest.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static org.apache.datasketches.common.BoundsOnBinomialProportions.approximateLowerBoundOnP; -import static org.apache.datasketches.common.BoundsOnBinomialProportions.approximateUpperBoundOnP; -import static org.apache.datasketches.common.BoundsOnBinomialProportions.erf; -import static org.apache.datasketches.common.BoundsOnBinomialProportions.estimateUnknownP; -import static org.apache.datasketches.common.BoundsOnBinomialProportions.normalCDF; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import org.testng.annotations.Test; - -/** - * @author Kevin Lang - */ -public class BoundsOnBinomialProportionsTest { - - @Test - public static void tinyLBTest() { - //these answers were computed using a different programming language and therefore might not - // match exactly. - final double[] answers = {0.0, 0.004592032688529923, 0.04725537386564205, - 0.1396230607626959, 0.2735831034867167, 0.4692424353373485}; - final double kappa = 2.0; - assertTrue( 0.0 == approximateLowerBoundOnP(0, 0, kappa) ); - final long n = 5; - for (long k = 0; k <= n; k++) { - final double lb = approximateLowerBoundOnP(n, k, kappa); - final double est = estimateUnknownP(n, k); - assertTrue(lb <= est); - assertTrue(Math.abs(lb - answers[(int) k]) < 1e-14); - // System.out.printf ("LB\t%d\t%d\t%.1f\t%.16g%n", n, k, kappa, lb); - } - } - - @Test - public static void tinyUBTest() { - //these answers were computed using a different programming language and therefore might not - // match exactly. - final double[] answers = {0.5307575646626514, 0.7264168965132833, 0.860376939237304, - 0.952744626134358, 0.9954079673114701, 1.0}; - final double kappa = 2.0; - assertTrue(1.0 == approximateUpperBoundOnP(0, 0, kappa)); - final long n = 5; - for (long k = 0; k <= n; k++) { - final double ub = approximateUpperBoundOnP(n, k, kappa); - final double est = estimateUnknownP(n, k); - assertTrue(ub >= est); - assertTrue(Math.abs(ub - answers[(int) k]) < 1e-14); - // System.out.printf ("UB\t%d\t%d\t%.1f\t%.16g%n", n, k, kappa, ub); - } - } - - // This is for Kevin's use only, and will not be one of the unit tests. - public static void lotsOfSpewage(final long maxN) { - for (long n = 0; n <= maxN; n++) { - for (long k = 0; k <= n; k++) { - for (double kappa = 0.5; kappa < 5.0; kappa += 0.5) { - final double lb = approximateLowerBoundOnP(n, k, kappa); - final double ub = approximateUpperBoundOnP(n, k, kappa); - final double est = estimateUnknownP(n, k); - assertTrue(lb <= est); - assertTrue(ub >= est); - final String slb = String.format("LB\t%d\t%d\t%.1f\t%.16g%n", n, k, kappa, lb); - final String sub = String.format("UB\t%d\t%d\t%.1f\t%.16g%n", n, k, kappa, ub); - println(slb); - println(sub); - } - } - } - } - - // This is for Kevin's use only, and will not be one of the unit tests. - public static void printSomeNormalCDF() { - final double[] someX = {-10.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 10.0}; - for (int i = 0; i < 11; i++) { - final String s = String.format("normalCDF(%.1f) = %.12f%n", someX[i], normalCDF(someX[i])); - println(s); - } - } - - // This is for Kevin's use only, and will not be one of the unit tests. - // public static void main (String[] args) { - // tinyLBTest (); - // tinyUBTest (); - // assertTrue (args.length == 1); - // long maxN = Long.parseLong(args[0]); - // lotsOfSpewage (maxN); - // } - - @Test - public static void checkNumStdDevZero() { - final double lb = BoundsOnBinomialProportions.approximateLowerBoundOnP( 1000, 100, 0.0); - final double ub = BoundsOnBinomialProportions.approximateUpperBoundOnP( 1000, 100, 0.0); - println("LB: " + lb); - println("UB: " + ub); - } - - @Test - public static void checkInputs() { - try { - estimateUnknownP(-1, 50); - fail("Should have thrown SketchesArgumentException."); - } - catch (final SketchesArgumentException e) { - //expected - } - try { - estimateUnknownP(500, -50); - fail("Should have thrown SketchesArgumentException."); - } - catch (final SketchesArgumentException e) { - //expected - } - try { - estimateUnknownP(500, 5000); - fail("Should have thrown SketchesArgumentException."); - } - catch (final SketchesArgumentException e) { - //expected - } - assertEquals(estimateUnknownP(0, 0), 0.5, 0.0); - } - - @Test - public static void checkErf() { - assertTrue(erf(-2.0) < 0.99); - assertTrue(erf(2.0) > 0.99); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - - -} diff --git a/src/test/java/org/apache/datasketches/common/BoundsOnRatiosInSampledSetsTest.java b/src/test/java/org/apache/datasketches/common/BoundsOnRatiosInSampledSetsTest.java deleted file mode 100644 index c0ef12455..000000000 --- a/src/test/java/org/apache/datasketches/common/BoundsOnRatiosInSampledSetsTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static org.apache.datasketches.common.BoundsOnRatiosInSampledSets.checkInputs; -import static org.apache.datasketches.common.BoundsOnRatiosInSampledSets.getEstimateOfA; -import static org.apache.datasketches.common.BoundsOnRatiosInSampledSets.getEstimateOfB; -import static org.apache.datasketches.common.BoundsOnRatiosInSampledSets.getEstimateOfBoverA; -import static org.apache.datasketches.common.BoundsOnRatiosInSampledSets.getLowerBoundForBoverA; -import static org.apache.datasketches.common.BoundsOnRatiosInSampledSets.getUpperBoundForBoverA; -import static org.testng.Assert.assertEquals; - -import org.testng.annotations.Test; - -public class BoundsOnRatiosInSampledSetsTest { - - @Test - public void checkNormalReturns() { - getLowerBoundForBoverA(500, 100, .1); - getLowerBoundForBoverA(500, 100, 0.75); - getLowerBoundForBoverA(500, 100, 1.0); - assertEquals(getLowerBoundForBoverA(0, 0, .1), 0.0, 0.0); - - getUpperBoundForBoverA(500, 100, .1); - getUpperBoundForBoverA(500, 100, 0.75); - getUpperBoundForBoverA(500, 100, 1.0); - assertEquals(getUpperBoundForBoverA(0, 0, .1), 1.0, 0.0); - - getEstimateOfBoverA(500,100); - getEstimateOfA(500, .1); - getEstimateOfB(100, .1); - assertEquals(getEstimateOfBoverA(0, 0), .5, 0.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInputA() { - checkInputs(-1, 0, .3); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInputB() { - checkInputs(500, -1, .3); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInputF() { - checkInputs(500, 100, -1); - } - -} diff --git a/src/test/java/org/apache/datasketches/common/ByteArrayUtilTest.java b/src/test/java/org/apache/datasketches/common/ByteArrayUtilTest.java deleted file mode 100644 index 31b990c40..000000000 --- a/src/test/java/org/apache/datasketches/common/ByteArrayUtilTest.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static org.apache.datasketches.common.ByteArrayUtil.getDoubleBE; -import static org.apache.datasketches.common.ByteArrayUtil.getDoubleLE; -import static org.apache.datasketches.common.ByteArrayUtil.getFloatBE; -import static org.apache.datasketches.common.ByteArrayUtil.getFloatLE; -import static org.apache.datasketches.common.ByteArrayUtil.getIntBE; -import static org.apache.datasketches.common.ByteArrayUtil.getIntLE; -import static org.apache.datasketches.common.ByteArrayUtil.getLongBE; -import static org.apache.datasketches.common.ByteArrayUtil.getLongLE; -import static org.apache.datasketches.common.ByteArrayUtil.getShortBE; -import static org.apache.datasketches.common.ByteArrayUtil.getShortLE; -import static org.apache.datasketches.common.ByteArrayUtil.putDoubleBE; -import static org.apache.datasketches.common.ByteArrayUtil.putDoubleLE; -import static org.apache.datasketches.common.ByteArrayUtil.putFloatBE; -import static org.apache.datasketches.common.ByteArrayUtil.putFloatLE; -import static org.apache.datasketches.common.ByteArrayUtil.putIntBE; -import static org.apache.datasketches.common.ByteArrayUtil.putIntLE; -import static org.apache.datasketches.common.ByteArrayUtil.putLongBE; -import static org.apache.datasketches.common.ByteArrayUtil.putLongLE; -import static org.apache.datasketches.common.ByteArrayUtil.putShortBE; -import static org.apache.datasketches.common.ByteArrayUtil.putShortLE; -import static org.testng.Assert.assertEquals; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class ByteArrayUtilTest { - - @Test - public void checkCopyBytes() { - final byte[] src = { 1, 2, 3, 4 }; - final byte[] tgt = new byte[8]; - ByteArrayUtil.copyBytes(src, 1, tgt, 4, 3); - System.out.println(""); - } - - @Test - public void checkGetPutShortLE() { - final byte[] arr = { 79, -93, 124, 117 }; - final short out1 = getShortLE(arr, 0); - final short out2 = getShortLE(arr, 2); - final byte[] arr2 = new byte[4]; - putShortLE(arr2, 0, out1); - putShortLE(arr2, 2, out2); - assertEquals(arr2, arr); - } - - @Test - public void checkGetPutShortBE() { - final byte[] arr = { 79, -93, 124, 117 }; - final short out1 = getShortBE(arr, 0); - final short out2 = getShortBE(arr, 2); - final byte[] arr2 = new byte[4]; - putShortBE(arr2, 0, out1); - putShortBE(arr2, 2, out2); - assertEquals(arr2, arr); - } - - @Test - public void checkGetPutIntLE() { - final byte[] arr = { 79, -93, 124, 117, -73, -100, -114, 77 }; - final int out1 = getIntLE(arr, 0); - final int out2 = getIntLE(arr, 4); - final byte[] arr2 = new byte[8]; - putIntLE(arr2, 0, out1); - putIntLE(arr2, 4, out2); - assertEquals(arr2, arr); - } - - @Test - public void checkGetPutIntBE() { - final byte[] arr = { 79, -93, 124, 117, -73, -100, -114, 77 }; - final int out1 = getIntBE(arr, 0); - final int out2 = getIntBE(arr, 4); - final byte[] arr2 = new byte[8]; - putIntBE(arr2, 0, out1); - putIntBE(arr2, 4, out2); - assertEquals(arr2, arr); - } - - - @Test - public void checkGetPutLongLE() { - final byte[] arr = { 79, -93, 124, 117, -73, -100, -114, 77, 5, -95, -15, 41, -89, -124, -26, -87 }; - final long out1 = getLongLE(arr, 0); - final long out2 = getLongLE(arr, 8); - final byte[] arr2 = new byte[16]; - putLongLE(arr2, 0, out1); - putLongLE(arr2, 8, out2); - assertEquals(arr2, arr); - } - - @Test - public void checkGetPutLongBE() { - final byte[] arr = { 79, -93, 124, 117, -73, -100, -114, 77, 5, -95, -15, 41, -89, -124, -26, -87 }; - final long out1 = getLongBE(arr, 0); - final long out2 = getLongBE(arr, 8); - final byte[] arr2 = new byte[16]; - putLongBE(arr2, 0, out1); - putLongBE(arr2, 8, out2); - assertEquals(arr2, arr); - } - - @Test - public void checkGetPutFloatLE() { - final byte[] arr = { -37, 15, 73, 64, 84, -8, 45, 64 }; //PI, E - final float out1 = getFloatLE(arr, 0); - final float out2 = getFloatLE(arr, 4); - final byte[] arr2 = new byte[8]; - putFloatLE(arr2, 0, out1); - putFloatLE(arr2, 4, out2); - assertEquals(arr2, arr); - assertEquals(out1, (float)Math.PI); - assertEquals(out2, (float)Math.E); - } - - @Test - public void checkGetPutFloatBE() { - final byte[] arr = { -37, 15, 73, 64, 84, -8, 45, 64 }; //PI, E - final float out1 = getFloatBE(arr, 0); - final float out2 = getFloatBE(arr, 4); - final byte[] arr2 = new byte[8]; - putFloatBE(arr2, 0, out1); - putFloatBE(arr2, 4, out2); - assertEquals(arr2, arr); - } - - @Test - public void checkGetPutDoubleLE() { - final byte[] arr = { 24, 45, 68, 84, -5, 33, 9, 64, 105, 87, 20, -117, 10, -65, 5, 64 }; //PI, E - final double out1 = getDoubleLE(arr, 0); - final double out2 = getDoubleLE(arr, 8); - final byte[] arr2 = new byte[16]; - putDoubleLE(arr2, 0, out1); - putDoubleLE(arr2, 8, out2); - assertEquals(arr2, arr); - assertEquals(out1, Math.PI); - assertEquals(out2, Math.E); - } - - @Test - public void checkGetPutDoubleBE() { - final byte[] arr = { 24, 45, 68, 84, -5, 33, 9, 64, 105, 87, 20, -117, 10, -65, 5, 64 }; //PI, E - final double out1 = getDoubleBE(arr, 0); - final double out2 = getDoubleBE(arr, 8); - final byte[] arr2 = new byte[16]; - putDoubleBE(arr2, 0, out1); - putDoubleBE(arr2, 8, out2); - assertEquals(arr2, arr); - } - -} diff --git a/src/test/java/org/apache/datasketches/common/FamilyTest.java b/src/test/java/org/apache/datasketches/common/FamilyTest.java deleted file mode 100644 index 1c7c1a71f..000000000 --- a/src/test/java/org/apache/datasketches/common/FamilyTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static org.apache.datasketches.common.Family.idToFamily; -import static org.apache.datasketches.common.Family.stringToFamily; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class FamilyTest { - - @Test - public void checkFamilyEnum() { - final Family[] families = Family.values(); - final int numFam = families.length; - - for (int i = 0; i < numFam; i++) { - final Family f = families[i]; - final int fid = f.getID(); - f.checkFamilyID(fid); - - final Family f2 = idToFamily(fid); - assertTrue(f.equals(f2)); - assertEquals(f.getFamilyName(), f2.getFamilyName()); - final int id2 = f2.getID(); - assertEquals(fid, id2); - } - checkStringToFamily("Alpha"); - checkStringToFamily("QuickSelect"); - checkStringToFamily("Union"); - checkStringToFamily("Intersection"); - checkStringToFamily("AnotB"); - checkStringToFamily("HLL"); - checkStringToFamily("Quantiles"); - } - - private static void checkStringToFamily(final String inStr) { - final String fName = stringToFamily(inStr).toString(); - assertEquals(fName, inStr.toUpperCase()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadFamilyName() { - stringToFamily("Test"); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadFamilyID() { - final Family famAlpha = Family.ALPHA; - final Family famQS = Family.QUICKSELECT; - famAlpha.checkFamilyID(famQS.getID()); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/common/Shuffle.java b/src/test/java/org/apache/datasketches/common/Shuffle.java deleted file mode 100644 index af6c4f8b7..000000000 --- a/src/test/java/org/apache/datasketches/common/Shuffle.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import java.util.Random; - -/** - * @author Lee Rhodes - */ -public final class Shuffle { - private static final Random rand = new Random(); - - /** - * Shuffle the given input array using a default source of randomness. - * @param array the array to be shuffled. - */ - public static void shuffle(final float[] array) { - shuffle(array, rand); - } - - /** - * Shuffle the given input array using the given source of randomness. - * @param array the array to be shuffled. - * @param rand the source of randomness used to shuffle the list. - */ - public static void shuffle(final float[] array, final Random rand) { - final int arrLen = array.length; - for (int i = 0; i < arrLen; i++) { - final int r = rand.nextInt(i + 1); - swap(array, i, r); - } - } - - private static void swap(final float[] array, final int i1, final int i2) { - final float value = array[i1]; - array[i1] = array[i2]; - array[i2] = value; - } - - /** - * Shuffle the given input array using a default source of randomness. - * @param array the array to be shuffled. - */ - public static void shuffle(final double[] array) { - shuffle(array, rand); - } - - /** - * Shuffle the given input array using the given source of randomness. - * @param array the array to be shuffled. - * @param rand the source of randomness used to shuffle the list. - */ - public static void shuffle(final double[] array, final Random rand) { - final int arrLen = array.length; - for (int i = 0; i < arrLen; i++) { - final int r = rand.nextInt(i + 1); - swap(array, i, r); - } - } - - private static void swap(final double[] array, final int i1, final int i2) { - final double value = array[i1]; - array[i1] = array[i2]; - array[i2] = value; - } - - /** - * Shuffle the given input array using a default source of randomness. - * @param array the array to be shuffled. - */ - public static void shuffle(final long[] array) { - shuffle(array, rand); - } - - /** - * Shuffle the given input array using the given source of randomness. - * @param array the array to be shuffled. - * @param rand the source of randomness used to shuffle the list. - */ - public static void shuffle(final long[] array, final Random rand) { - final int arrLen = array.length; - for (int i = 0; i < arrLen; i++) { - final int r = rand.nextInt(i + 1); - swap(array, i, r); - } - } - - private static void swap(final long[] array, final int i1, final int i2) { - final long value = array[i1]; - array[i1] = array[i2]; - array[i2] = value; - } - - /** - * Shuffle the given input array using a default source of randomness. - * @param array the array to be shuffled. - */ - public static void shuffle(final int[] array) { - shuffle(array, rand); - } - - /** - * Shuffle the given input array using the given source of randomness. - * @param array the array to be shuffled. - * @param rand the source of randomness used to shuffle the list. - */ - public static void shuffle(final int[] array, final Random rand) { - final int arrLen = array.length; - for (int i = 0; i < arrLen; i++) { - final int r = rand.nextInt(i + 1); - swap(array, i, r); - } - } - - private static void swap(final int[] array, final int i1, final int i2) { - final int value = array[i1]; - array[i1] = array[i2]; - array[i2] = value; - } - - /** - * Shuffle the given input array using a default source of randomness. - * @param array the array to be shuffled. - * @param the component type of the given array. - */ - public static void shuffle(final T[] array) { - shuffle(array, rand); - } - - /** - * Shuffle the given input array using the given source of randomness. - * @param array the array to be shuffled. - * @param rand the source of randomness used to shuffle the list. - * @param the component type of the given array. - */ - public static void shuffle(final T[] array, final Random rand) { - final int arrLen = array.length; - for (int i = 0; i < arrLen; i++) { - final int r = rand.nextInt(i + 1); - swap(array, i, r); - } - } - - private static void swap(final T[] array, final int i1, final int i2) { - final T value = array[i1]; - array[i1] = array[i2]; - array[i2] = value; - } - -} diff --git a/src/test/java/org/apache/datasketches/common/ShuffleTest.java b/src/test/java/org/apache/datasketches/common/ShuffleTest.java deleted file mode 100644 index 2b133a5ab..000000000 --- a/src/test/java/org/apache/datasketches/common/ShuffleTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static org.testng.Assert.fail; - -import org.testng.annotations.Test; - -public class ShuffleTest { - - @Test - public void checkFloat() { - float[] array = new float[10]; - for (int i = 0; i < array.length; i++) { array[i] = i; } - Shuffle.shuffle(array); - int neCount = 0; - for (int i = 0; i < array.length; i++) { - if (array[i] != i) { neCount++; } - } - //System.out.println(neCount); - if (neCount == 0) { fail(); } - } - - @Test - public void checkDouble() { - double[] array = new double[10]; - for (int i = 0; i < array.length; i++) { array[i] = i; } - Shuffle.shuffle(array); - int neCount = 0; - for (int i = 0; i < array.length; i++) { - if (array[i] != i) { neCount++; } - } - //System.out.println(neCount); - if (neCount == 0) { fail(); } - } - - @Test - public void checkLong() { - long[] array = new long[10]; - for (int i = 0; i < array.length; i++) { array[i] = i; } - Shuffle.shuffle(array); - int neCount = 0; - for (int i = 0; i < array.length; i++) { - if (array[i] != i) { neCount++; } - } - //System.out.println(neCount); - if (neCount == 0) { fail(); } - } - - @Test - public void checkInt() { - int[] array = new int[10]; - for (int i = 0; i < array.length; i++) { array[i] = i; } - Shuffle.shuffle(array); - int neCount = 0; - for (int i = 0; i < array.length; i++) { - if (array[i] != i) { neCount++; } - } - //System.out.println(neCount); - if (neCount == 0) { fail(); } - } -} - diff --git a/src/test/java/org/apache/datasketches/common/SketchesExceptionTest.java b/src/test/java/org/apache/datasketches/common/SketchesExceptionTest.java deleted file mode 100644 index a7bc84166..000000000 --- a/src/test/java/org/apache/datasketches/common/SketchesExceptionTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import org.testng.annotations.Test; - -public class SketchesExceptionTest { - - @Test(expectedExceptions = SketchesException.class) - public void checkSketchesException() { - throw new SketchesException("This is a test."); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkSketchesArgumentException() { - throw new SketchesArgumentException("This is a test."); - } - - @Test(expectedExceptions = SketchesStateException.class) - public void checkSketchesStateException() { - throw new SketchesStateException("This is a test."); - } - - @Test - public void checkSketchesExceptionWithThrowable() { - try { - throw new SketchesException("First Exception."); - } catch (final SketchesException se) { - try { - throw new SketchesException("Second Exception. ", se); - } catch (final SketchesException se2) { - //success - } - } - } - -} diff --git a/src/test/java/org/apache/datasketches/common/TestUtil.java b/src/test/java/org/apache/datasketches/common/TestUtil.java deleted file mode 100644 index fbe39a856..000000000 --- a/src/test/java/org/apache/datasketches/common/TestUtil.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Objects; - -/** - * Utilities common to testing - */ -public final class TestUtil { - - private static final String userDir = System.getProperty("user.dir"); - - /** - * TestNG group constants - */ - public static final String GENERATE_JAVA_FILES = "generate_java_files"; - public static final String CHECK_CPP_FILES = "check_cpp_files"; - public static final String CHECK_GO_FILES = "check_go_files"; - public static final String CHECK_RUST_FILES = "check_rust_files"; - public static final String CHECK_CPP_HISTORICAL_FILES = "check_cpp_historical_files"; - - /** - * The project relative Path for Java serialized sketches to be tested by other languages. - */ - public static final Path javaPath = Path.of(userDir, "serialization_test_data", "java_generated_files").normalize(); - - /** - * The project relative Path for C++ serialized sketches to be tested by Java. - */ - public static final Path cppPath = Path.of(userDir, "serialization_test_data", "cpp_generated_files").normalize(); - - /** - * The project relative Path for Go serialized sketches to be tested by Java. - */ - public static final Path goPath = Path.of(userDir, "serialization_test_data", "go_generated_files").normalize(); - - /** - * The project relative Path for Rust serialized sketches to be tested by Java. - */ - public static final Path rustPath = Path.of(userDir, "serialization_test_data", "rust_generated_files").normalize(); - - /** - * The project relative Path for /src/test/resources - */ - public static final Path resPath = Path.of(userDir,"src","test","resources").normalize(); - - public enum Existence { MUST_EXIST, WARNING } - - /** - * Gets all the bytes of a file as a byte array. - * If the file is missing, this either throws an exception or writes a warning message to the console - * based on the state of the optional {@link #Existence Existence}. - * @param basePath the base directory path where the file is located - * @param fileName the simple file name of the file - * @param option an optional parameter. If option == Existence.MUST_EXIST and the file does not exist an exception will be thrown. - * If option == Existence.WARNING, or not given, and the file does not exist, it writes a warning message - * to {@link System.err System.err}. - * If option has more than one argument an exception will be thrown. - * @return a byte array. It may be empty. - * @throws RuntimeException for IO errors, or if resolved path is not a file or not readable or optionally not found. - */ - public static byte[] getFileBytes(final Path basePath, final String fileName, Existence... option) { - Objects.requireNonNull(basePath, "input parameter 'Path basePath' cannot be null."); - Objects.requireNonNull(fileName, "input parameter 'String fileName' cannot be null."); - if (option.length > 1) { throw new IllegalArgumentException("Existence option has a maximum of one argument"); } - Existence status = (option.length == 1) ? option[0] : Existence.WARNING; - - Path path = Path.of(basePath.toString(), fileName); - Path absPath = path.toAbsolutePath(); //for error output - if (Files.notExists(path)) { - if (status == Existence.MUST_EXIST) { - throw new RuntimeException("File disappeared or not found: " + absPath); - } else { - System.err.println("WARNING: File disappeared or not found: " + absPath); - return new byte[0]; - } - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new RuntimeException("Path is not a regular file or not readable: " + absPath); - } - try { - byte[] bytes = Files.readAllBytes(path); - return bytes; - } catch (IOException e) { - throw new RuntimeException("System IO Error reading file: " + absPath + " " + e); - } - } - - /** - * Puts all the bytes of the given byte array to a file with the given fileName. - * This assumes that the base directory path is {@link #javaPath javaPath}. - * @param fileName the name of the target file - * @param bytes the given byte array - */ - public static void putBytesToJavaPath(final String fileName, final byte[] bytes) { - putBytesToFile(javaPath, fileName, bytes); - } - - /** - * Puts all the bytes of the given byte array to a basePath file with the given fileName. - * If the file exists it will be overwritten. - * @param basePath the directory path for the given fileName - * @param fileName the name of the target file - * @param bytes the given byte array - * @throws RuntimeException for IO errors, - */ - public static void putBytesToFile(final Path basePath, final String fileName, final byte[] bytes) { - Objects.requireNonNull(basePath, "input parameter 'Path basePath' cannot be null."); - Objects.requireNonNull(fileName, "input parameter 'String fileName' cannot be null."); - Objects.requireNonNull(bytes, "input parameter 'byte[] bytes' cannot be null."); - Path filePath = null; - try { - Files.createDirectories(basePath); //create the directory if it doesn't exist. - filePath = basePath.resolve(fileName); - Files.write(filePath, bytes); - } catch (IOException e) { - final String filePathDesc = String.valueOf(filePath); - throw new RuntimeException("System IO Error writing file: " + filePathDesc + " " + e); - } - } -} diff --git a/src/test/java/org/apache/datasketches/common/TestUtilTest.java b/src/test/java/org/apache/datasketches/common/TestUtilTest.java deleted file mode 100644 index e8051fe88..000000000 --- a/src/test/java/org/apache/datasketches/common/TestUtilTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.datasketches.common.TestUtil.getFileBytes; -import static org.apache.datasketches.common.TestUtil.putBytesToFile; -import static org.apache.datasketches.common.TestUtil.resPath; -import static org.apache.datasketches.common.TestUtil.Existence.MUST_EXIST; -import static org.apache.datasketches.common.TestUtil.Existence.WARNING; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.nio.file.Path; - -import org.testng.annotations.Test; - -public class TestUtilTest { - - @Test - public void testGetFileBytes_Success() {// throws IOException { - byte[] resultBytes = getFileBytes(resPath, "GettysburgAddress.txt"); - assertNotNull(resultBytes); - String resultString = new String(resultBytes, UTF_8); - assertTrue(resultString.startsWith("Abraham Lincoln's Gettysburg Address:")); - } - - @Test - public void testGetFileBytes_MissingFile_Warning() { - byte[] resultBytes = getFileBytes(resPath, "Test_NonExistentFile_OK", WARNING); //WARNING is the default - assertNotNull(resultBytes); - assertEquals(resultBytes.length, 0, "Should return empty array for missing file."); - } - - @Test(expectedExceptions = RuntimeException.class) - public void testGetFileBytes_MissingFile_MustExist() { - getFileBytes(resPath, "Test_NonExistentFile_OK", MUST_EXIST); - } - - @Test(expectedExceptions = RuntimeException.class) - public void testGetFileBytes_NotRegular_NotReadable() throws IOException { - getFileBytes(resPath, ""); - } - - private static final Path testPath = Path.of(".", "target", "testDir"); - - @Test - public void testPutBytesToFile() { - byte[] gettysBytes = getFileBytes(resPath, "GettysburgAddress.txt"); - putBytesToFile(testPath, "GettysburgAddressCopy.txt", gettysBytes); - byte[] gettysBytes2 = getFileBytes(testPath, "GettysburgAddressCopy.txt"); - assertEquals(gettysBytes, gettysBytes2); - } - -} diff --git a/src/test/java/org/apache/datasketches/common/UtilTest.java b/src/test/java/org/apache/datasketches/common/UtilTest.java deleted file mode 100644 index da8858ca7..000000000 --- a/src/test/java/org/apache/datasketches/common/UtilTest.java +++ /dev/null @@ -1,468 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common; - -import static java.lang.Math.pow; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.javaPath; -import static org.apache.datasketches.common.Util.bytesToInt; -import static org.apache.datasketches.common.Util.bytesToLong; -import static org.apache.datasketches.common.Util.bytesToString; -import static org.apache.datasketches.common.Util.ceilingMultiple2expK; -import static org.apache.datasketches.common.Util.ceilingPowerBaseOfDouble; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.common.Util.characterPad; -import static org.apache.datasketches.common.Util.checkBounds; -import static org.apache.datasketches.common.Util.checkIfMultipleOf8AndGT0; -import static org.apache.datasketches.common.Util.checkIfPowerOf2; -import static org.apache.datasketches.common.Util.checkProbability; -import static org.apache.datasketches.common.Util.convertToLongArray; -import static org.apache.datasketches.common.Util.exactLog2OfInt; -import static org.apache.datasketches.common.Util.exactLog2OfLong; -import static org.apache.datasketches.common.Util.floorPowerBaseOfDouble; -import static org.apache.datasketches.common.Util.floorPowerOf2; -import static org.apache.datasketches.common.Util.intToBytes; -import static org.apache.datasketches.common.Util.invPow2; -import static org.apache.datasketches.common.Util.isEven; -import static org.apache.datasketches.common.Util.isLessThanUnsigned; -import static org.apache.datasketches.common.Util.isMultipleOf8AndGT0; -import static org.apache.datasketches.common.Util.isOdd; -import static org.apache.datasketches.common.Util.isPowerOf2; -import static org.apache.datasketches.common.Util.longToBytes; -import static org.apache.datasketches.common.Util.milliSecToString; -import static org.apache.datasketches.common.Util.nanoSecToString; -import static org.apache.datasketches.common.Util.numberOfLeadingOnes; -import static org.apache.datasketches.common.Util.numberOfTrailingOnes; -import static org.apache.datasketches.common.Util.powerSeriesNextDouble; -import static org.apache.datasketches.common.Util.pwr2SeriesNext; -import static org.apache.datasketches.common.Util.pwr2SeriesPrev; -import static org.apache.datasketches.common.Util.zeroPad; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import org.testng.Assert; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class UtilTest { - private static final String LS = System.getProperty("line.separator"); - - @Test - public void numTrailingOnes() { - long mask = 1L; - for (int i = 0; i <= 64; i++) { - final long v = ~mask & -1L; - mask <<= 1; - final int numT1s = numberOfTrailingOnes(v); - final int numL1s = numberOfLeadingOnes(v); - assertEquals(Long.numberOfTrailingZeros(~v), numT1s); - assertEquals(Long.numberOfLeadingZeros(~v), numL1s); - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBoundsTest() { - checkBounds(999L, 2L, 1000L); - } - - @Test - public void checkIsPowerOf2() { - Assert.assertEquals(isPowerOf2(0), false); - Assert.assertEquals(isPowerOf2(1), true); - Assert.assertEquals(isPowerOf2(2), true); - Assert.assertEquals(isPowerOf2(4), true); - Assert.assertEquals(isPowerOf2(8), true); - Assert.assertEquals(isPowerOf2(1L << 62), true); - Assert.assertEquals(isPowerOf2(3), false); - Assert.assertEquals(isPowerOf2(5), false); - Assert.assertEquals(isPowerOf2( -1), false); - } - - @Test - public void checkCheckIfPowerOf2() { - checkIfPowerOf2(8L, "Test 8"); - try { - checkIfPowerOf2(7L, "Test 7"); - Assert.fail("Expected SketchesArgumentException"); - } - catch (final SketchesArgumentException e) { - //pass - } - } - - @Test - public void checkCeilingIntPowerOf2() { - Assert.assertEquals(ceilingPowerOf2(Integer.MAX_VALUE), 1 << 30); - Assert.assertEquals(ceilingPowerOf2(1 << 30), 1 << 30); - Assert.assertEquals(ceilingPowerOf2(64), 64); - Assert.assertEquals(ceilingPowerOf2(65), 128); - Assert.assertEquals(ceilingPowerOf2(0), 1); - Assert.assertEquals(ceilingPowerOf2( -1), 1); - } - - @Test - public void checkCeilingLongPowerOf2() { - Assert.assertEquals(ceilingPowerOf2(Long.MAX_VALUE), 1L << 62); - Assert.assertEquals(ceilingPowerOf2(1L << 62), 1L << 62); - Assert.assertEquals(ceilingPowerOf2(64L), 64L); - Assert.assertEquals(ceilingPowerOf2(65L), 128L); - Assert.assertEquals(ceilingPowerOf2(0L), 1L); - Assert.assertEquals(ceilingPowerOf2( -1L), 1L); - } - - - @Test - public void checkCeilingPowerOf2double() { - Assert.assertEquals(ceilingPowerBaseOfDouble(2.0, Integer.MAX_VALUE), pow(2.0, 31)); - Assert.assertEquals(ceilingPowerBaseOfDouble(2.0, 1 << 30), pow(2.0, 30)); - Assert.assertEquals(ceilingPowerBaseOfDouble(2.0, 64.0), 64.0); - Assert.assertEquals(ceilingPowerBaseOfDouble(2.0, 65.0), 128.0); - Assert.assertEquals(ceilingPowerBaseOfDouble(2.0, 0.0), 1.0); - Assert.assertEquals(ceilingPowerBaseOfDouble(2.0, -1.0), 1.0); - } - - @Test - public void checkFloorPowerOf2Int() { - Assert.assertEquals(floorPowerOf2( -1), 1); - Assert.assertEquals(floorPowerOf2(0), 1); - Assert.assertEquals(floorPowerOf2(1), 1); - Assert.assertEquals(floorPowerOf2(2), 2); - Assert.assertEquals(floorPowerOf2(3), 2); - Assert.assertEquals(floorPowerOf2(4), 4); - - Assert.assertEquals(floorPowerOf2((1 << 30) - 1), 1 << 29); - Assert.assertEquals(floorPowerOf2(1 << 30), 1 << 30); - Assert.assertEquals(floorPowerOf2((1 << 30) + 1), 1 << 30); - } - @Test - public void checkFloorPowerOf2Long() { - Assert.assertEquals(floorPowerOf2( -1L), 1L); - Assert.assertEquals(floorPowerOf2(0L), 1L); - Assert.assertEquals(floorPowerOf2(1L), 1L); - Assert.assertEquals(floorPowerOf2(2L), 2L); - Assert.assertEquals(floorPowerOf2(3L), 2L); - Assert.assertEquals(floorPowerOf2(4L), 4L); - - Assert.assertEquals(floorPowerOf2((1L << 63) - 1L), 1L << 62); - Assert.assertEquals(floorPowerOf2(1L << 62), 1L << 62); - Assert.assertEquals(floorPowerOf2((1L << 62) + 1L), 1L << 62); - } - @Test - public void checkFloorPowerOf2double() { - Assert.assertEquals(floorPowerBaseOfDouble(2.0, -1.0), 1.0); - Assert.assertEquals(floorPowerBaseOfDouble(2.0, 0.0), 1.0); - Assert.assertEquals(floorPowerBaseOfDouble(2.0, 1.0), 1.0); - Assert.assertEquals(floorPowerBaseOfDouble(2.0, 2.0), 2.0); - Assert.assertEquals(floorPowerBaseOfDouble(2.0, 3.0), 2.0); - Assert.assertEquals(floorPowerBaseOfDouble(2.0, 4.0), 4.0); - - Assert.assertEquals(floorPowerBaseOfDouble(2.0, (1 << 30) - 1.0), 1 << 29); - Assert.assertEquals(floorPowerBaseOfDouble(2.0, 1 << 30), 1 << 30); - Assert.assertEquals(floorPowerBaseOfDouble(2.0, (1 << 30) + 1.0), 1L << 30); - } - - @Test - public void checkCheckIfMultipleOf8AndGT0() { - checkIfMultipleOf8AndGT0(8, "test 8"); - try { checkIfMultipleOf8AndGT0( 7, "test 7"); fail(); } catch (final SketchesArgumentException e) { } - try { checkIfMultipleOf8AndGT0(-8, "test -8"); fail(); } catch (final SketchesArgumentException e) { } - try { checkIfMultipleOf8AndGT0(-1, "test -1"); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkIsMultipleOf8AndGT0() { - Assert.assertTrue(isMultipleOf8AndGT0(8)); - Assert.assertFalse(isMultipleOf8AndGT0(7)); - Assert.assertFalse(isMultipleOf8AndGT0(-8)); - Assert.assertFalse(isMultipleOf8AndGT0(-1)); - } - - @Test - public void checkInvPow2() { - Assert.assertEquals(invPow2(1), 0.5); - Assert.assertEquals(invPow2(0), 1.0); - try {invPow2(-1); failIAE(); } catch (final SketchesArgumentException e) {} - try {invPow2(1024); failIAE(); } catch (final SketchesArgumentException e) {} - try {invPow2(Integer.MIN_VALUE); failIAE(); } catch (final SketchesArgumentException e) {} - } - - private static void failIAE() { throw new IllegalArgumentException("Test should have failed!"); } - - @Test - public void checkIsLessThanUnsigned() { - final long n1 = 1; - final long n2 = 3; - final long n3 = -3; - final long n4 = -1; - Assert.assertTrue(isLessThanUnsigned(n1, n2)); - Assert.assertTrue(isLessThanUnsigned(n2, n3)); - Assert.assertTrue(isLessThanUnsigned(n3, n4)); - Assert.assertFalse(isLessThanUnsigned(n2, n1)); - Assert.assertFalse(isLessThanUnsigned(n3, n2)); - Assert.assertFalse(isLessThanUnsigned(n4, n3)); - } - - @Test - public void checkZeroPad() { - final long v = 123456789; - final String vHex = Long.toHexString(v); - final String out = zeroPad(vHex, 16); - println("Pad 16, prepend 0: " + out); - } - - @Test - public void checkCharacterPad() { - String s = "Pad 30, postpend z:"; - String out = characterPad(s, 30, 'z', true); - println(out); - assertEquals(out, "Pad 30, postpend z:zzzzzzzzzzz"); - s = "Pad 30, prepend z:"; - out = characterPad(s, 30, 'z', false); - println(out); - assertEquals(out,"zzzzzzzzzzzzPad 30, prepend z:"); - } - - @Test - public void checkProbabilityFn1() { - checkProbability(.5, "Good"); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkProbabilityFn2() { - checkProbability(-.5, "Too Low"); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkProbabilityFn3() { - checkProbability(1.5, "Too High"); - } - - @Test - public void checkEvenOdd() { - assertTrue(isEven(0)); - assertFalse(isOdd(0)); - assertTrue(isOdd(-1)); - assertFalse(isEven(-1)); - } - - @Test - public void checkBytesToInt() { - final byte[] arr = {4, 3, 2, 1}; - final int result = 4 + (3 << 8) + (2 << 16) + (1 << 24); - Assert.assertEquals(bytesToInt(arr), result); - final byte[] arr2 = intToBytes(result, new byte[4]); - Assert.assertEquals(arr, arr2); - } - - @Test - public void checkBytesToLong() { - final byte[] arr = {8, 7, 6, 5, 4, 3, 2, 1}; - final long result = 8L + (7L << 8) + (6L << 16) + (5L << 24) - + (4L << 32) + (3L << 40) + (2L << 48) + (1L << 56); - Assert.assertEquals(bytesToLong(arr), result); - } - - @Test - public void checkBytesToString() { - final long lng = 0XF8F7F6F504030201L; - //println(Long.toHexString(lng)); - byte[] bytes = new byte[8]; - bytes = longToBytes(lng, bytes); - final String sep = "."; - final String unsignLE = bytesToString(bytes, false, true, sep); - final String signedLE = bytesToString(bytes, true, true, sep); - final String unsignBE = bytesToString(bytes, false, false, sep); - final String signedBE = bytesToString(bytes, true, false, sep); - Assert.assertEquals(unsignLE, "1.2.3.4.245.246.247.248"); - Assert.assertEquals(signedLE, "1.2.3.4.-11.-10.-9.-8"); - Assert.assertEquals(unsignBE, "248.247.246.245.4.3.2.1"); - Assert.assertEquals(signedBE, "-8.-9.-10.-11.4.3.2.1"); - } - - @Test - public void checkNsecToString() { - final long nS = 1000000000L + 1000000L + 1000L + 1L; - final String result = nanoSecToString(nS); - final String expected = "1.001_001_001"; - Assert.assertEquals(result, expected); - } - - @Test - public void checkMsecToString() { - final long nS = (60L * 60L * 1000L) + (60L * 1000L) + 1000L + 1L; - final String result = milliSecToString(nS); - final String expected = "1:01:01.001"; - Assert.assertEquals(result, expected); - } - - @Test - public void checkPwr2LawNext() { - int next = (int)pwr2SeriesNext(2, 1); - Assert.assertEquals(next, 2); - next = (int)pwr2SeriesNext(2, 2); - Assert.assertEquals(next, 3); - next = (int)pwr2SeriesNext(2, 3); - Assert.assertEquals(next, 4); - - next = (int)pwr2SeriesNext(2, 0); - Assert.assertEquals(next, 1); - } - - @Test - public void checkPwr2LawNextDouble() { - double next = powerSeriesNextDouble(2, 1.0, true, 2.0); - Assert.assertEquals(next, 2.0, 0.0); - next = powerSeriesNextDouble(2, 2.0, true, 2.0); - Assert.assertEquals(next, 3.0, 0.0); - next = powerSeriesNextDouble(2, 3, true, 2.0); - Assert.assertEquals(next, 4.0, 0.0); - - next = powerSeriesNextDouble(2, 1, false, 2.0); - Assert.assertEquals(next, Math.sqrt(2), 0.0); - next = powerSeriesNextDouble(2, 0.5, true, 2.0); - Assert.assertEquals(next, 2.0, 0.0); - next = powerSeriesNextDouble(2, 0.5, false, 2.0); - Assert.assertEquals(next, Math.sqrt(2), 0.0); - next = powerSeriesNextDouble(2, next, false, 2.0); - Assert.assertEquals(next, 2.0, 0.0); - } - - @Test - public void checkPwr2SeriesExamples() { - final int maxP = 32; - final int minP = 1; - final int ppo = 4; - - for (int p = minP; p <= maxP; p = (int)pwr2SeriesNext(ppo, p)) { - print(p + " "); - } - println(""); - - for (int p = maxP; p >= minP; p = pwr2SeriesPrev(ppo, p)) { - print(p + " "); - } - println(""); - } - - @Test - public void checkExactLog2OfLong() { - Assert.assertEquals(exactLog2OfLong(2), 1); - Assert.assertEquals(exactLog2OfLong(1), 0); - Assert.assertEquals(exactLog2OfLong(1L << 62), 62); - try { - exactLog2OfLong(0); - fail(); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkExactLog2OfInt() { - Assert.assertEquals(exactLog2OfInt(2), 1); - Assert.assertEquals(exactLog2OfInt(1), 0); - Assert.assertEquals(exactLog2OfInt(1 << 30), 30); - try { - exactLog2OfInt(0); - fail(); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkExactLog2OfLongWithArg() { - Assert.assertEquals(exactLog2OfLong(2, "2"), 1); - Assert.assertEquals(exactLog2OfLong(1, "1"), 0); - Assert.assertEquals(exactLog2OfLong(1L << 62,"1L<<62"), 62); - try { - exactLog2OfLong(0,"0"); - fail(); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkExactLog2OfIntWithArg() { - Assert.assertEquals(exactLog2OfInt(2,"2"), 1); - Assert.assertEquals(exactLog2OfInt(1,"1"), 0); - Assert.assertEquals(exactLog2OfInt(1 << 30,"1<<30"), 30); - try { - exactLog2OfInt(0,"0"); - fail(); - } catch (final SketchesArgumentException e) { } - } - - @Test - static void checkConvertToLongArray() { - final byte[] arr = {1,2,3,4,5,6,7,8,9,10,11,12}; - - long[] out = convertToLongArray(arr, false); - String s = zeroPad(Long.toHexString(out[0]), 16); - assertEquals(s, "0807060504030201"); - s = zeroPad(Long.toHexString(out[1]), 16); - assertEquals(s, "000000000c0b0a09"); - - out = convertToLongArray(arr, true); - s = zeroPad(Long.toHexString(out[0]), 16); - assertEquals(s, "0102030405060708"); - s = zeroPad(Long.toHexString(out[1]), 16); - assertEquals(s, "00000000090a0b0c"); - } - - @Test - static void checkCeilingMultiple2expK() { - final long n = (1 << 36) - 1L; - final int k = 6; - final long v = ceilingMultiple2expK(n, k); - final long v2 = (long)Math.ceil(n / (double)(1 << k)); - assertEquals(v, v2); - } - - @Test - public void checkDirCreation() { - assertNotNull(javaPath); - assertNotNull(cppPath); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - private static boolean enablePrinting = true; - - static void println(final Object o) { - if (enablePrinting) { - if (o == null) { print(LS); } - else { print(o.toString() + LS); } - } - } - - /** - * @param o value to print - */ - static void print(final Object o) { - if (enablePrinting && (o != null)) { - //System.out.print(o.toString()); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/common/positional/PositionalSegmentTest.java b/src/test/java/org/apache/datasketches/common/positional/PositionalSegmentTest.java deleted file mode 100644 index 86de3540d..000000000 --- a/src/test/java/org/apache/datasketches/common/positional/PositionalSegmentTest.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common.positional; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_CHAR_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.testng.Assert.assertEquals; - -import java.lang.foreign.MemorySegment; -import java.util.List; - -import org.testng.annotations.Test; -import org.testng.collections.Lists; - -public class PositionalSegmentTest { - - @Test - public void checkBytes() { - final int n = 100; //elements - final MemorySegment seg = MemorySegment.ofArray(new byte[n * Byte.BYTES]); - final PositionalSegment posSeg = PositionalSegment.wrap(seg); - for (int i = 0; i < (n/2); i++) { posSeg.setByte((byte)i); } - for (int i = n/2; i < n; i++) { posSeg.setByte(i * Byte.BYTES, (byte)i); } - posSeg.resetPosition(); - for (int i = 0; i < n; i++) { - final byte v1 = posSeg.getByte(i * Byte.BYTES); - final byte v2 = posSeg.getByte(); - assertEquals(v1, v2); - assertEquals(v2, i); - } - posSeg.resetPosition(); - final byte[] arr = new byte[n]; - posSeg.getByteArray(arr, 0, n); - - posSeg.resetPosition(); - posSeg.setByteArray(arr, 0, n); - - final MemorySegment seg2 = posSeg.getMemorySegment(); - for (int i = 0; i < n; i++) { - assertEquals(seg2.get(JAVA_BYTE, i * Byte.BYTES), (byte)i); - } - } - - @Test - public void checkChars() { - final int n = 128; //elements - final MemorySegment seg = MemorySegment.ofArray(new byte[n * Character.BYTES]); - final PositionalSegment posSeg = PositionalSegment.wrap(seg); - for (int i = 0; i < (n/2); i++) { posSeg.setChar((char)i); } - for (int i = n/2; i < n; i++) { posSeg.setChar(i * Character.BYTES, (char)i); } - posSeg.resetPosition(); - for (int i = 0; i < n; i++) { - final int v1 = posSeg.getChar(i *Character.BYTES); - final int v2 = posSeg.getChar(); - assertEquals(v1, v2); - assertEquals(v2, i); - } - posSeg.resetPosition(); - final char[] arr = new char[n]; - posSeg.getCharArray(arr, 0, n); - - posSeg.resetPosition(); - posSeg.setCharArray(arr, 0, n); - - final MemorySegment seg2 = posSeg.getMemorySegment(); - for (int i = 0; i < n; i++) { - assertEquals(seg2.get(JAVA_CHAR_UNALIGNED, i * Character.BYTES), (char)i); - } - } - - @Test - public void checkShorts() { - final int n = 128; //elements - final MemorySegment seg = MemorySegment.ofArray(new byte[n * Short.BYTES]); - final PositionalSegment posSeg = PositionalSegment.wrap(seg); - for (int i = 0; i < (n/2); i++) { posSeg.setShort((short)i); } - for (int i = n/2; i < n; i++) { posSeg.setShort(i * Short.BYTES, (short)i); } - posSeg.resetPosition(); - for (int i = 0; i < n; i++) { - final int v1 = posSeg.getShort(i *Short.BYTES); - final int v2 = posSeg.getShort(); - assertEquals(v1, v2); - assertEquals(v2, i); - } - posSeg.resetPosition(); - final short[] arr = new short[n]; - posSeg.getShortArray(arr, 0, n); - - posSeg.resetPosition(); - posSeg.setShortArray(arr, 0, n); - - final MemorySegment seg2 = posSeg.getMemorySegment(); - for (int i = 0; i < n; i++) { - assertEquals(seg2.get(JAVA_SHORT_UNALIGNED, i * Short.BYTES), (short)i); - } - } - - @Test - public void checkInts() { - final int n = 128; //elements - final MemorySegment seg = MemorySegment.ofArray(new byte[n * Integer.BYTES]); - final PositionalSegment posSeg = PositionalSegment.wrap(seg); - for (int i = 0; i < (n/2); i++) { posSeg.setInt((int)i); } - for (int i = n/2; i < n; i++) { posSeg.setInt(i * Integer.BYTES, (int)i); } - posSeg.resetPosition(); - for (int i = 0; i < n; i++) { - final int v1 = posSeg.getInt(i * Integer.BYTES); - final int v2 = posSeg.getInt(); - assertEquals(v1, v2); - assertEquals(v2, i); - } - posSeg.resetPosition(); - final int[] arr = new int[n]; - posSeg.getIntArray(arr, 0, n); - - posSeg.resetPosition(); - posSeg.setIntArray(arr, 0, n); - - final MemorySegment seg2 = posSeg.getMemorySegment(); - for (int i = 0; i < n; i++) { - assertEquals(seg2.get(JAVA_INT_UNALIGNED, i * Integer.BYTES), (int)i); - } - } - - - @Test - public void checkLongs() { - final int n = 128; //elements - final MemorySegment seg = MemorySegment.ofArray(new byte[n * Long.BYTES]); - final PositionalSegment posSeg = PositionalSegment.wrap(seg); - for (int i = 0; i < (n/2); i++) { posSeg.setLong(i); } - for (int i = n/2; i < n; i++) { posSeg.setLong(i * Long.BYTES, i); } - posSeg.resetPosition(); - for (int i = 0; i < n; i++) { - final long v1 = posSeg.getLong(i * Long.BYTES); - final long v2 = posSeg.getLong(); - assertEquals(v1, v2); - assertEquals(v2, i); - } - posSeg.resetPosition(); - final long[] arr = new long[n]; - posSeg.getLongArray(arr, 0, n); - - posSeg.resetPosition(); - posSeg.setLongArray(arr, 0, n); - - final MemorySegment seg2 = posSeg.getMemorySegment(); - for (int i = 0; i < n; i++) { - assertEquals(seg2.get(JAVA_LONG_UNALIGNED, i * Long.BYTES), i); - } - } - - @Test - public void checkFloats() { - final int n = 128; //elements - final MemorySegment seg = MemorySegment.ofArray(new byte[n * Float.BYTES]); - final PositionalSegment posSeg = PositionalSegment.wrap(seg); - for (int i = 0; i < (n/2); i++) { posSeg.setFloat(i); } - for (int i = n/2; i < n; i++) { posSeg.setFloat(i * Float.BYTES, i); } - posSeg.resetPosition(); - for (int i = 0; i < n; i++) { - final float v1 = posSeg.getFloat(i * Float.BYTES); - final float v2 = posSeg.getFloat(); - assertEquals(v1, v2); - assertEquals(v2, i); - } - posSeg.resetPosition(); - final float[] arr = new float[n]; - posSeg.getFloatArray(arr, 0, n); - - posSeg.resetPosition(); - posSeg.setFloatArray(arr, 0, n); - - final MemorySegment seg2 = posSeg.getMemorySegment(); - for (int i = 0; i < n; i++) { - assertEquals(seg2.get(JAVA_FLOAT_UNALIGNED, i * Float.BYTES), i); - } - } - - @Test - public void checkDoubles() { - final int n = 128; //elements - final MemorySegment seg = MemorySegment.ofArray(new byte[n * Double.BYTES]); - final PositionalSegment posSeg = PositionalSegment.wrap(seg); - for (int i = 0; i < (n/2); i++) { posSeg.setDouble(i); } - for (int i = n/2; i < n; i++) { posSeg.setDouble(i * Double.BYTES, i); } - posSeg.resetPosition(); - for (int i = 0; i < n; i++) { - final double v1 = posSeg.getDouble(i * Double.BYTES); - final double v2 = posSeg.getDouble(); - assertEquals(v1, v2); - assertEquals(v2, i); - } - posSeg.resetPosition(); - final double[] arr = new double[n]; - posSeg.getDoubleArray(arr, 0, n); - - posSeg.resetPosition(); - posSeg.setDoubleArray(arr, 0, n); - - final MemorySegment seg2 = posSeg.getMemorySegment(); - for (int i = 0; i < n; i++) { - assertEquals(seg2.get(JAVA_DOUBLE_UNALIGNED, i * Double.BYTES), i); - } - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s String to print - */ - static void println(final String s) { - //System.out.println(s); - } - -} diff --git a/src/test/java/org/apache/datasketches/common/positional/PositionalTest.java b/src/test/java/org/apache/datasketches/common/positional/PositionalTest.java deleted file mode 100644 index 63cf640f2..000000000 --- a/src/test/java/org/apache/datasketches/common/positional/PositionalTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.common.positional; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class PositionalTest { - - @Test - public void checkInvariants() { - final Positional posit = Positional.getInstance(100); - posit.setStartPositionEnd(40, 45, 50); - posit.setStartPositionEnd(0, 0, 100); - try { - posit.setStartPositionEnd(0, 0, 101); fail(); - } catch (final PositionInvariantsException e) { } //OK - try { - posit.setPosition(101); fail(); - } catch (final PositionInvariantsException e) { } //OK - try { - posit.setStartPositionEnd(50, 45, 40); fail(); //out of order - } catch (final PositionInvariantsException e) { } //OK - } - - @Test - public void checkGetSets() { - final Positional posit = Positional.getInstance(100); - posit.setStartPositionEnd(40, 45, 50); - assertEquals(posit.getStart(), 40); - assertEquals(posit.getPosition(), 45); - assertEquals(posit.getEnd(), 50); - assertEquals(posit.getRemaining(), 5); - assertTrue(posit.hasRemaining()); - posit.resetPosition(); - assertEquals(posit.getPosition(), 40); - posit.setPosition(45); - assertEquals(posit.getPosition(), 45); - posit.incrementPosition(1); - assertEquals(posit.getPosition(), 46); - } - -} diff --git a/src/test/java/org/apache/datasketches/count/CountMinSketchTest.java b/src/test/java/org/apache/datasketches/count/CountMinSketchTest.java deleted file mode 100644 index bb0bef806..000000000 --- a/src/test/java/org/apache/datasketches/count/CountMinSketchTest.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.count; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesException; -import org.testng.annotations.Test; - -import java.io.ByteArrayOutputStream; -import java.lang.annotation.Repeatable; -import java.nio.ByteBuffer; - -import static org.testng.Assert.*; - -public class CountMinSketchTest { - - @Test - public void createNewCountMinSketchTest() throws Exception { - assertThrows(SketchesArgumentException.class, () -> new CountMinSketch((byte) 5, 1, 123)); - assertThrows(SketchesArgumentException.class, () -> new CountMinSketch((byte) 4, (1 << 28), 123)); - final byte numHashes = 3; - final int numBuckets = 5; - final long seed = 1234567; - final CountMinSketch c = new CountMinSketch(numHashes, numBuckets, seed); - - assertEquals(c.getNumHashes_(), numHashes); - assertEquals(c.getNumBuckets_(), numBuckets); - assertEquals(c.getSeed_(), seed); - assertTrue(c.isEmpty()); - } - - @Test - public void parameterSuggestionsTest() { - // Bucket suggestions - assertThrows("Relative error must be at least 0.", SketchesException.class, () -> CountMinSketch.suggestNumBuckets(-1.0)); - assertEquals(CountMinSketch.suggestNumBuckets(0.2), 14); - assertEquals(CountMinSketch.suggestNumBuckets(0.1), 28); - assertEquals(CountMinSketch.suggestNumBuckets(0.05), 55); - assertEquals(CountMinSketch.suggestNumBuckets(0.01), 272); - - // Check that the sketch get_epsilon acts inversely to suggest_num_buckets - final byte numHashes = 3; - final long seed = 1234567; - assertTrue(new CountMinSketch(numHashes, 14, seed).getRelativeError() <= 0.2); - assertTrue(new CountMinSketch(numHashes, 28, seed).getRelativeError() <= 0.1); - assertTrue(new CountMinSketch(numHashes, 55, seed).getRelativeError() <= 0.05); - assertTrue(new CountMinSketch(numHashes, 272, seed).getRelativeError() <= 0.01); - - // Hash suggestions - assertThrows("Confidence must be between 0 and 1.0 (inclusive).", SketchesException.class, () -> CountMinSketch.suggestNumHashes(10)); - assertThrows("Confidence must be between 0 and 1.0 (inclusive).", SketchesException.class, () -> CountMinSketch.suggestNumHashes(-1.0)); - assertEquals(CountMinSketch.suggestNumHashes(0.682689492), 2); - assertEquals(CountMinSketch.suggestNumHashes(0.954499736), 4); - assertEquals(CountMinSketch.suggestNumHashes(0.997300204), 6); - } - - @Test - public void countMinSketchOneUpdateTest() { - final byte numHashes = 3; - final int numBuckets = 5; - final long seed = 1234567; - long insertedWeights = 0; - final CountMinSketch c = new CountMinSketch(numHashes, numBuckets, seed); - final String x = "x"; - - assertTrue(c.isEmpty()); - assertEquals(c.getEstimate(x), 0); - c.update(x, 1); - assertFalse(c.isEmpty()); - assertEquals(c.getEstimate(x), 1); - insertedWeights++; - - final long w = 9; - insertedWeights += w; - c.update(x, w); - assertEquals(c.getEstimate(x), insertedWeights); - - final double w1 = 10.0; - insertedWeights += (long) w1; - c.update(x, (long) w1); - assertEquals(c.getEstimate(x), insertedWeights); - assertEquals(c.getTotalWeight_(), insertedWeights); - assertTrue(c.getEstimate(x) <= c.getUpperBound(x)); - assertTrue(c.getEstimate(x) >= c.getLowerBound(x)); - } - - @Test - public void frequencyCancellationTest() { - final CountMinSketch c = new CountMinSketch((byte) 1, 5, 123456); - c.update("x", 1); - c.update("y", -1); - assertEquals(c.getTotalWeight_(), 2); - assertEquals(c.getEstimate("x"), 1); - assertEquals(c.getEstimate("y"), -1); - } - - @Test - public void frequencyEstimates() { - final int numItems = 10; - final long[] data = new long[numItems]; - final long[] frequencies = new long[numItems]; - - for (int i = 0; i < numItems; i++) { - data[i] = i; - frequencies[i] = (long) 1 << (numItems - i); - } - - final double relativeError = 0.1; - final double confidence = 0.99; - final int numBuckets = CountMinSketch.suggestNumBuckets(relativeError); - final byte numHashes = CountMinSketch.suggestNumHashes(confidence); - - final CountMinSketch c = new CountMinSketch(numHashes, numBuckets, 1234567); - for (int i = 0; i < numItems; i++) { - final long value = data[i]; - final long freq = frequencies[i]; - c.update(value, freq); - } - - for (final long i : data) { - final long est = c.getEstimate(i); - final long upp = c.getUpperBound(i); - final long low = c.getLowerBound(i); - assertTrue(est <= upp); - assertTrue(est >= low); - } - } - - @Test - public void mergeFailTest() { - final double relativeError = 0.25; - final double confidence = 0.9; - final long seed = 1234567; - final int numBuckets = CountMinSketch.suggestNumBuckets(relativeError); - final byte numHashes = CountMinSketch.suggestNumHashes(confidence); - final CountMinSketch s = new CountMinSketch(numHashes, numBuckets, seed); - - assertThrows("Cannot merge a sketch with itself.", SketchesException.class, () -> s.merge(s)); - - final CountMinSketch s1 = new CountMinSketch((byte) (numHashes + 1), numBuckets, seed); - final CountMinSketch s2 = new CountMinSketch(numHashes, numBuckets + 1, seed); - final CountMinSketch s3 = new CountMinSketch(numHashes, numBuckets, seed + 1); - - final CountMinSketch[] sketches = {s1, s2, s3}; - for (final CountMinSketch sk : sketches) { - assertThrows("Incompatible sketch configuration.", SketchesException.class, () -> s.merge(sk)); - } - } - - @Test - public void mergeTest() { - final double relativeError = 0.25; - final double confidence = 0.9; - final long seed = 123456; - final int numBuckets = CountMinSketch.suggestNumBuckets(relativeError); - final byte numHashes = CountMinSketch.suggestNumHashes(confidence); - final CountMinSketch c = new CountMinSketch(numHashes, numBuckets, seed); - - final byte sHashes = c.getNumHashes_(); - final int sBuckets = c.getNumBuckets_(); - final long sSeed = c.getSeed_(); - final CountMinSketch s = new CountMinSketch(sHashes, sBuckets, sSeed); - - c.merge(s); - assertEquals(c.getTotalWeight_(), 0); - - final long[] data = {2, 3, 5, 7}; - for (final long d : data) { - c.update(d, 1); - s.update(d, 1); - } - c.merge(s); - - assertEquals(c.getTotalWeight_(), 2 * s.getTotalWeight_()); - - for (final long d : data) { - assertTrue(c.getEstimate(d) <= c.getUpperBound(d)); - assertTrue(s.getEstimate(d) <= 2); - } - } - - @Test - public void serializeDeserializeEmptyTest() { - final byte numHashes = 3; - final int numBuckets = 32; - final long seed = 123456; - final CountMinSketch c = new CountMinSketch(numHashes, numBuckets, seed); - - final byte[] b = c.toByteArray(); - assertThrows(SketchesArgumentException.class, () -> CountMinSketch.deserialize(b, seed - 1)); - - final CountMinSketch d = CountMinSketch.deserialize(b, seed); - assertEquals(d.getNumHashes_(), c.getNumHashes_()); - assertEquals(d.getNumBuckets_(), c.getNumBuckets_()); - assertEquals(d.getSeed_(), c.getSeed_()); - final long zero = 0; - assertEquals(d.getEstimate(zero), c.getEstimate(zero)); - assertEquals(d.getTotalWeight_(), c.getTotalWeight_()); - } - - @Test - public void serializeDeserializeTest() { - final byte numHashes = 5; - final int numBuckets = 64; - final long seed = 1234456; - final CountMinSketch c = new CountMinSketch(numHashes, numBuckets, seed); - for (long i = 0; i < 10; i++) { - c.update(i, 10*i*i); - } - - final byte[] b = c.toByteArray(); - - assertThrows(SketchesArgumentException.class, () -> CountMinSketch.deserialize(b, seed - 1)); - final CountMinSketch d = CountMinSketch.deserialize(b, seed); - - assertEquals(d.getNumHashes_(), c.getNumHashes_()); - assertEquals(d.getNumBuckets_(), c.getNumBuckets_()); - assertEquals(d.getSeed_(), c.getSeed_()); - assertEquals(d.getTotalWeight_(), c.getTotalWeight_()); - - for (long i = 0; i < 10; i++) { - assertEquals(d.getEstimate(i), c.getEstimate(i)); - } - } -} diff --git a/src/test/java/org/apache/datasketches/cpc/CompressedStateTest.java b/src/test/java/org/apache/datasketches/cpc/CompressedStateTest.java deleted file mode 100644 index f9b85cef0..000000000 --- a/src/test/java/org/apache/datasketches/cpc/CompressedStateTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.io.PrintStream; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class CompressedStateTest { - static PrintStream ps = System.out; - long vIn = 0; - int lgK = 10; - - private void updateStateUnion(final CpcSketch sk) { - Format skFmt = sk.getFormat(); - CompressedState state = CompressedState.compress(sk); - Flavor f = state.getFlavor(); - Format fmt = state.getFormat(); - assertEquals(fmt, skFmt); - long c = state.numCoupons; - MemorySegment wseg = MemorySegment.ofArray(new byte[(int)state.getRequiredSerializedBytes()]); - state.exportToSegment(wseg); - printf("%8d %8d %10s %35s\n", vIn, c, f.toString(), fmt.toString()); - CompressedState state2 = CompressedState.importFromSegment(wseg); - - final CpcUnion union = new CpcUnion(lgK); - union.update(sk); - final CpcSketch sk2 = union.getResult(); - skFmt = sk2.getFormat(); - state = CompressedState.compress(sk2); - f = state.getFlavor(); - fmt = state.getFormat(); - assertEquals(fmt, skFmt); - c = state.numCoupons; - wseg = MemorySegment.ofArray(new byte[(int)state.getRequiredSerializedBytes()]); - state.exportToSegment(wseg); - printf("%8d %8d %10s %35s\n", vIn, c, f.toString(), fmt.toString()); - state2 = CompressedState.importFromSegment(wseg); - fmt = state2.getFormat(); - assertEquals(fmt, skFmt); - } - - @Test - public void checkLoadMemorySegment() { - printf("%8s %8s %10s %35s\n", "vIn", "c", "Flavor", "Format"); - final CpcSketch sk = new CpcSketch(lgK); - final int k = 1 << lgK; - - //EMPTY_MERGED - updateStateUnion(sk); - - //SPARSE - sk.update(++vIn); - updateStateUnion(sk); - - //HYBRID - - while ((sk.numCoupons << 5) < (3L * k)) { sk.update(++vIn); } - updateStateUnion(sk); - - //PINNED - while ((sk.numCoupons << 1) < k) { sk.update(++vIn); } - updateStateUnion(sk); //here - - //SLIDING - while ((sk.numCoupons << 3) < (27L * k)) { sk.update(++vIn); } - updateStateUnion(sk); - } - - @Test - public void checkToString() { - final CpcSketch sketch = new CpcSketch(10); - CompressedState state = CompressedState.compress(sketch); - println(state.toString()); - sketch.update(0); - state = CompressedState.compress(sketch); - println(CompressedState.toString(state, true)); - for (int i = 1; i < 600; i++) { sketch.update(i); } - state = CompressedState.compress(sketch); - println(CompressedState.toString(state, true)); - } - - @Test - public void checkIsCompressed() { - final CpcSketch sk = new CpcSketch(10); - final byte[] byteArr = sk.toByteArray(); - byteArr[5] &= (byte) -3; - try { - CompressedState.importFromSegment(MemorySegment.ofArray(byteArr)); - fail(); - } catch (final AssertionError e) { } - } - - /** - * @param format the string to print - * @param args the arguments - */ - private static void printf(final String format, final Object... args) { - //ps.printf(format, args); - } - - /** - * @param s the string to print - */ - private static void println(final String s) { - //ps.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/cpc/CompressionDataTest.java b/src/test/java/org/apache/datasketches/cpc/CompressionDataTest.java deleted file mode 100644 index ae706e7e8..000000000 --- a/src/test/java/org/apache/datasketches/cpc/CompressionDataTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.cpc.CompressionData.decodingTablesForHighEntropyByte; -import static org.apache.datasketches.cpc.CompressionData.encodingTablesForHighEntropyByte; -import static org.apache.datasketches.cpc.CompressionData.lengthLimitedUnaryDecodingTable65; -import static org.apache.datasketches.cpc.CompressionData.lengthLimitedUnaryEncodingTable65; -import static org.apache.datasketches.cpc.CompressionData.validateDecodingTable; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class CompressionDataTest { - - @Test - public static void checkTables() { - validateDecodingTable(lengthLimitedUnaryDecodingTable65, lengthLimitedUnaryEncodingTable65); - - for (int i = 0; i < (16 + 6); i++) { - validateDecodingTable(decodingTablesForHighEntropyByte[i], encodingTablesForHighEntropyByte[i]); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/cpc/CpcCompressionTest.java b/src/test/java/org/apache/datasketches/cpc/CpcCompressionTest.java deleted file mode 100644 index c5ec12399..000000000 --- a/src/test/java/org/apache/datasketches/cpc/CpcCompressionTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.cpc.CompressionData.decodingTablesForHighEntropyByte; -import static org.apache.datasketches.cpc.CompressionData.encodingTablesForHighEntropyByte; -import static org.apache.datasketches.cpc.CompressionData.lengthLimitedUnaryDecodingTable65; -import static org.apache.datasketches.cpc.CompressionData.lengthLimitedUnaryEncodingTable65; -import static org.apache.datasketches.cpc.CpcCompression.BIT_BUF; -import static org.apache.datasketches.cpc.CpcCompression.BUF_BITS; -import static org.apache.datasketches.cpc.CpcCompression.NEXT_WORD_IDX; -import static org.apache.datasketches.cpc.CpcCompression.lowLevelCompressBytes; -import static org.apache.datasketches.cpc.CpcCompression.lowLevelCompressPairs; -import static org.apache.datasketches.cpc.CpcCompression.lowLevelUncompressBytes; -import static org.apache.datasketches.cpc.CpcCompression.lowLevelUncompressPairs; -import static org.apache.datasketches.cpc.CpcCompression.readUnary; -import static org.apache.datasketches.cpc.CpcCompression.writeUnary; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Random; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class CpcCompressionTest { - - @Test - public void checkWriteReadUnary() { - final int[] compressedWords = new int[256]; - - final long[] ptrArr = new long[3]; - int nextWordIndex = 0; //must be int - long bitBuf = 0; //must be long - int bufBits = 0; //could be byte - - for (int i = 0; i < 100; i++) { - - // Inline WriteUnary - ptrArr[NEXT_WORD_IDX] = nextWordIndex; - ptrArr[BIT_BUF] = bitBuf; - ptrArr[BUF_BITS] = bufBits; - assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; //catch sign extension error - writeUnary(compressedWords, ptrArr, i); - nextWordIndex = (int) ptrArr[NEXT_WORD_IDX]; - bitBuf = ptrArr[BIT_BUF]; - bufBits = (int) ptrArr[BUF_BITS]; - assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; //catch truncation error - //END Inline WriteUnary - - } - - // Pad the bitstream so that the decompressor's 12-bit peek can't overrun its input. - final long padding = 7; - bufBits += (int)padding; - //MAYBE_FLUSH_BITBUF(compressedWords, nextWordIndex); - if (bufBits >= 32) { - compressedWords[nextWordIndex++] = (int) bitBuf; - bitBuf >>>= 32; - bufBits -= 32; - } - - if (bufBits > 0) { // We are done encoding now, so we flush the bit buffer. - assert (bufBits < 32); - compressedWords[nextWordIndex++] = (int) bitBuf; - } - final int numWordsUsed = nextWordIndex; - println("Words used: " + numWordsUsed); - nextWordIndex = 0; //must be int - bitBuf = 0; //must be long - bufBits = 0; //could be byte - - for (int i = 0; i < 100; i++) { - - // Inline ReadUnary - ptrArr[NEXT_WORD_IDX] = nextWordIndex; - ptrArr[BIT_BUF] = bitBuf; - ptrArr[BUF_BITS] = bufBits; - assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; - final long result = readUnary(compressedWords, ptrArr); - println("Result: " + result + ", expected: " + i); - - assertEquals(result, i); - nextWordIndex = (int) ptrArr[NEXT_WORD_IDX]; - bitBuf = ptrArr[BIT_BUF]; - bufBits = (int) ptrArr[BUF_BITS]; - assert nextWordIndex == ptrArr[NEXT_WORD_IDX]; - //END Inline ReadUnary - - } - assertTrue(nextWordIndex <= numWordsUsed); - } - - @Test - public void checkWriteReadBytes() { - final int[] compressedWords = new int[128]; - final byte[] byteArray = new byte[256]; - final byte[] byteArray2 = new byte[256]; //output - for (int i = 0; i < 256; i++) { byteArray[i] = (byte) i; } - - for (int j = 0; j < 22; j++) { - final long numWordsWritten = lowLevelCompressBytes( - byteArray, 256, encodingTablesForHighEntropyByte[j], compressedWords); - - lowLevelUncompressBytes(byteArray2, 256, decodingTablesForHighEntropyByte[j], - compressedWords, numWordsWritten); - - println("Words used: " + numWordsWritten); - assertEquals(byteArray2, byteArray); - } - } - - @Test - public void checkWriteReadBytes65() { - final int size = 65; - final int[] compressedWords = new int[128]; - final byte[] byteArray = new byte[size]; - final byte[] byteArray2 = new byte[size]; //output - for (int i = 0; i < size; i++) { byteArray[i] = (byte) i; } - - final long numWordsWritten = lowLevelCompressBytes( - byteArray, size, lengthLimitedUnaryEncodingTable65, compressedWords); - - lowLevelUncompressBytes(byteArray2, size, lengthLimitedUnaryDecodingTable65, - compressedWords, numWordsWritten); - - println("Words used: " + numWordsWritten); - assertEquals(byteArray2, byteArray); - } - - - @Test - public void checkWriteReadPairs() { - final Random rgen = new Random(1); - final int lgK = 14; - final int N = 3000; - final int MAX_WORDS = 4000; - final int[] pairArray = new int[N]; - final int[] pairArray2 = new int[N]; - int i; - for (i = 0; i < N; i++) { - final int rand = rgen.nextInt(1 << (lgK + 6)); - pairArray[i] = rand; - } - Arrays.sort(pairArray); //must be unsigned sort! So keep lgK < 26 - int prev = -1; - int nxt = 0; - for (i = 0; i < N; i++) { // uniquify - if (pairArray[i] != prev) { - prev = pairArray[i]; - pairArray[nxt++] = pairArray[i]; - } - } - final int numPairs = nxt; - println("numCsv = " + numPairs); - - final int[] compressedWords = new int[MAX_WORDS]; - int bb; // numBaseBits - - for (bb = 0; bb <= 11; bb++) { - final long numWordsWritten = - lowLevelCompressPairs(pairArray, numPairs, bb, compressedWords); - println("numWordsWritten = " + numWordsWritten + ", bb = " + bb); - - lowLevelUncompressPairs(pairArray2, numPairs, bb, compressedWords, numWordsWritten); - - for (i = 0; i < numPairs; i++) { - assert (pairArray[i] == pairArray2[i]); - } - } - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/cpc/CpcSketchCrossLanguageTest.java b/src/test/java/org/apache/datasketches/cpc/CpcSketchCrossLanguageTest.java deleted file mode 100644 index b0f3ef77f..000000000 --- a/src/test/java/org/apache/datasketches/cpc/CpcSketchCrossLanguageTest.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES; -import static org.apache.datasketches.common.TestUtil.CHECK_GO_FILES; -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.getFileBytes; -import static org.apache.datasketches.common.TestUtil.goPath; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -/** - * Serialize binary sketches to be tested by C++ code. - * Test deserialization of binary sketches serialized by C++ code. - */ -public class CpcSketchCrossLanguageTest { - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTesting() throws IOException { - final int[] nArr = {0, 100, 200, 2000, 20_000}; - final Flavor[] flavorArr = {Flavor.EMPTY, Flavor.SPARSE, Flavor.HYBRID, Flavor.PINNED, Flavor.SLIDING}; - int flavorIdx = 0; - for (final int n: nArr) { - final CpcSketch sk = new CpcSketch(11); - for (int i = 0; i < n; i++) { - sk.update(i); - } - assertEquals(sk.getFlavor(), flavorArr[flavorIdx++]); - putBytesToJavaPath("cpc_n" + n + "_java.sk", sk.toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - void negativeIntEquivalence() throws Exception { - final CpcSketch sk = new CpcSketch(); - final byte v1 = (byte) -1; - sk.update(v1); - final short v2 = -1; - sk.update(v2); - final int v3 = -1; - sk.update(v3); - final long v4 = -1; - sk.update(v4); - assertEquals(sk.getEstimate(), 1, 0.01); - putBytesToJavaPath("cpc_negative_one_java.sk", sk.toByteArray()); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void allFlavors() throws IOException { - final int[] nArr = {0, 100, 200, 2000, 20000}; - final Flavor[] flavorArr = {Flavor.EMPTY, Flavor.SPARSE, Flavor.HYBRID, Flavor.PINNED, Flavor.SLIDING}; - int flavorIdx = 0; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "cpc_n" + n + "_cpp.sk"); - final CpcSketch sketch = CpcSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(sketch.getFlavor(), flavorArr[flavorIdx++]); - assertEquals(sketch.getEstimate(), n, n * 0.02); - } - } - - @Test(groups = {CHECK_GO_FILES}) - public void checkAllFlavorsGo() throws IOException { - final int[] nArr = {0, 100, 200, 2000, 20000}; - final Flavor[] flavorArr = {Flavor.EMPTY, Flavor.SPARSE, Flavor.HYBRID, Flavor.PINNED, Flavor.SLIDING}; - int flavorIdx = 0; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(goPath, "cpc_n" + n + "_go.sk"); - final CpcSketch sketch = CpcSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(sketch.getFlavor(), flavorArr[flavorIdx++]); - assertEquals(sketch.getEstimate(), n, n * 0.02); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/cpc/CpcSketchTest.java b/src/test/java/org/apache/datasketches/cpc/CpcSketchTest.java deleted file mode 100644 index 1f8ae715f..000000000 --- a/src/test/java/org/apache/datasketches/cpc/CpcSketchTest.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.cpc.TestUtil.specialEquals; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.io.PrintStream; -import java.nio.ByteBuffer; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class CpcSketchTest { - static PrintStream ps = System.out; - - @Test - public void checkUpdatesEstimate() { - final CpcSketch sk = new CpcSketch(10, 0); - println(sk.toString(true)); - assertEquals(sk.getFormat(), Format.EMPTY_HIP); - sk.update(1L); - sk.update(2.0); - sk.update("3"); - final byte[] bytes = { 4, 4 }; - sk.update(bytes); - sk.update(ByteBuffer.wrap(bytes)); // same as previous - sk.update(ByteBuffer.wrap(bytes, 0, 1)); - sk.update(new char[] { 5 }); - sk.update(new int[] { 6 }); - sk.update(new long[] { 7 }); - final double est = sk.getEstimate(); - final double lb = sk.getLowerBound(2); - final double ub = sk.getUpperBound(2); - assertTrue(lb >= 0); - assertTrue(lb <= est); - assertTrue(est <= ub); - assertEquals(sk.getFlavor(), Flavor.SPARSE); - assertEquals(sk.getFormat(), Format.SPARSE_HYBRID_HIP); - println(sk.toString()); - println(sk.toString(true)); - } - - @Test - public void checkEstimatesWithMerge() { - final int lgK = 4; - final CpcSketch sk1 = new CpcSketch(lgK); - final CpcSketch sk2 = new CpcSketch(lgK); - final int n = 1 << lgK; - for (int i = 0; i < n; i++ ) { - sk1.update(i); - sk2.update(i + n); - } - final CpcUnion union = new CpcUnion(lgK); - union.update(sk1); - union.update(sk2); - final CpcSketch result = union.getResult(); - final double est = result.getEstimate(); - final double lb = result.getLowerBound(2); - final double ub = result.getUpperBound(2); - assertTrue(lb >= 0); - assertTrue(lb <= est); - assertTrue(est <= ub); - assertTrue(result.validate()); - println(result.toString(true)); - } - - @Test - public void checkCornerCaseUpdates() { - final int lgK = 4; - final CpcSketch sk = new CpcSketch(lgK); - sk.update(0.0); - sk.update(-0.0); - int est = (int) Math.round(sk.getEstimate()); - assertEquals(est, 1); - String s = null; - sk.update(s); - s = ""; - sk.update(s); - est = (int) Math.round(sk.getEstimate()); - assertEquals(est, 1); - - byte[] barr = null; - sk.update(barr); - est = (int) Math.round(sk.getEstimate()); - assertEquals(est, 1); - barr = new byte[0]; - sk.update(barr); - est = (int) Math.round(sk.getEstimate()); - assertEquals(est, 1); - - char[] carr = null; - sk.update(carr); - est = (int) Math.round(sk.getEstimate()); - assertEquals(est, 1); - carr = new char[0]; - est = (int) Math.round(sk.getEstimate()); - assertEquals(est, 1); - - int[] iarr = null; - sk.update(iarr); - est = (int) Math.round(sk.getEstimate()); - assertEquals(est, 1); - iarr = new int[0]; - est = (int) Math.round(sk.getEstimate()); - assertEquals(est, 1); - - long[] larr = null; - sk.update(larr); - est = (int) Math.round(sk.getEstimate()); - assertEquals(est, 1); - larr = new long[0]; - est = (int) Math.round(sk.getEstimate()); - assertEquals(est, 1); - } - - @Test - public void checkCornerHashUpdates() { - final CpcSketch sk = new CpcSketch(26); - final long hash1 = 0; - final long hash0 = -1L; - sk.hashUpdate(hash0, hash1); - final PairTable table = sk.pairTable; - println(table.toString(true)); - } - - @SuppressWarnings("unused") - @Test - public void checkCopyWithWindow() { - final int lgK = 4; - final CpcSketch sk = new CpcSketch(lgK); - CpcSketch sk2 = sk.copy(); - for (int i = 0; i < (1 << lgK); i++) { //pinned - sk.update(i); - } - sk2 = sk.copy(); - final long[] bitMatrix = CpcUtil.bitMatrixOfSketch(sk); - CpcSketch.refreshKXP(sk, bitMatrix); - } - - @Test - public void checkFamily() { - assertEquals(CpcSketch.getFamily(), Family.CPC); - } - - @Test - public void checkLgK() { - CpcSketch sk = new CpcSketch(10); - assertEquals(sk.getLgK(), 10); - try { - sk = new CpcSketch(3); - fail(); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkIconHipUBLBLg15() { - CpcConfidence.getIconConfidenceUB(15, 1, 2); - CpcConfidence.getIconConfidenceLB(15, 1, 2); - CpcConfidence.getHipConfidenceUB(15, 1, 1.0, 2); - CpcConfidence.getHipConfidenceLB(15, 1, 1.0, 2); - } - - @Test - public void checkHeapify() { - final int lgK = 10; - final CpcSketch sk = new CpcSketch(lgK, Util.DEFAULT_UPDATE_SEED); - assertTrue(sk.isEmpty()); - final byte[] byteArray = sk.toByteArray(); - final CpcSketch sk2 = CpcSketch.heapify(byteArray, Util.DEFAULT_UPDATE_SEED); - assertTrue(specialEquals(sk2, sk, false, false)); - } - - @Test - public void checkHeapify2() { - final int lgK = 10; - final CpcSketch sk = new CpcSketch(lgK); - assertTrue(sk.isEmpty()); - final byte[] byteArray = sk.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArray); - final CpcSketch sk2 = CpcSketch.heapify(seg); - assertTrue(specialEquals(sk2, sk, false, false)); - } - - @Test - public void checkRowColUpdate() { - final int lgK = 10; - final CpcSketch sk = new CpcSketch(lgK, Util.DEFAULT_UPDATE_SEED); - sk.rowColUpdate(0); - assertEquals(sk.getFlavor(), Flavor.SPARSE); - } - - @Test - public void checkGetMaxSize() { - final int size4 = CpcSketch.getMaxSerializedBytes(4); - final int size26 = CpcSketch.getMaxSerializedBytes(26); - assertEquals(size4, 24 + 40); - assertEquals(size26, (int) ((0.6 * (1 << 26)) + 40)); - } - - /** - * @param s the string to print - */ - private static void println(final String s) { - //ps.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/cpc/CpcUnionTest.java b/src/test/java/org/apache/datasketches/cpc/CpcUnionTest.java deleted file mode 100644 index f3a87d68f..000000000 --- a/src/test/java/org/apache/datasketches/cpc/CpcUnionTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import org.testng.annotations.Test; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; - -/** - * @author Lee Rhodes - */ -public class CpcUnionTest { - - @Test - public void checkExceptions() { - CpcSketch sk = new CpcSketch(10, 1); - CpcUnion union = new CpcUnion(); - try { - union.update(sk); - fail(); - } catch (SketchesArgumentException e) {} - sk = null; - union.update(sk); - union = null; - try { - CpcUnion.getBitMatrix(union); - fail(); - } catch (SketchesStateException e) {} - } - - @Test - public void checkGetters() { - int lgK = 10; - CpcUnion union = new CpcUnion(lgK); - assertEquals(union.getLgK(), lgK); - assertEquals(union.getNumCoupons(), 0L); - CpcSketch sk = new CpcSketch(lgK); - for (int i = 0; i <= (4 << lgK); i++) { sk.update(i); } - union.update(sk); - assertTrue(union.getNumCoupons() > 0); - assertTrue(CpcUnion.getBitMatrix(union) != null); - assertEquals(Family.CPC, CpcUnion.getFamily()); - - } - - @Test - public void checkReduceK() { - CpcUnion union = new CpcUnion(12); - CpcSketch sk = new CpcSketch(11); - int u = 1; - sk.update(u); - union.update(sk); - CpcUnion.getBitMatrix(union); - CpcSketch sk2 = new CpcSketch(10); - int shTrans = ((3 * 512) / 32); //sparse-hybrid transition for lgK=9 - while (sk2.numCoupons < shTrans) { sk2.update(++u); } - union.update(sk2); - CpcSketch sk3 = new CpcSketch(9); - sk3.update(++u); - union.update(sk3); - CpcSketch sk4 = new CpcSketch(8); - sk4.update(++u); - union.update(sk4); - } - -} diff --git a/src/test/java/org/apache/datasketches/cpc/CpcWrapperTest.java b/src/test/java/org/apache/datasketches/cpc/CpcWrapperTest.java deleted file mode 100644 index 81f35f63c..000000000 --- a/src/test/java/org/apache/datasketches/cpc/CpcWrapperTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.io.PrintStream; - -import org.testng.annotations.Test; -import org.apache.datasketches.common.Family; - -/** - * @author Lee Rhodes - */ -public class CpcWrapperTest { - static PrintStream ps = System.out; - - @SuppressWarnings("unused") - @Test - public void check() { - final int lgK = 10; - final CpcSketch sk1 = new CpcSketch(lgK); - final CpcSketch sk2 = new CpcSketch(lgK); - final CpcSketch skD = new CpcSketch(lgK); - final double dEst = skD.getEstimate(); - final double dlb = skD.getLowerBound(2); - final double dub = skD.getUpperBound(2); - - final int n = 100000; - for (int i = 0; i < n; i++) { - sk1.update(i); - sk2.update(i + n); - skD.update(i); - skD.update(i + n); - } - final byte[] concatArr = skD.toByteArray(); - - final CpcUnion union = new CpcUnion(lgK); - final CpcSketch result = union.getResult(); - final double uEst = result.getEstimate(); - final double ulb = result.getLowerBound(2); - final double uub = result.getUpperBound(2); - union.update(sk1); - union.update(sk2); - final CpcSketch merged = union.getResult(); - final byte[] mergedArr = merged.toByteArray(); - - final MemorySegment concatSeg = MemorySegment.ofArray(concatArr); - final CpcWrapper concatSk = new CpcWrapper(concatSeg); - assertEquals(concatSk.getLgK(), lgK); - - printf(" %12s %12s %12s\n", "Lb", "Est", "Ub"); - final double ccEst = concatSk.getEstimate(); - final double ccLb = concatSk.getLowerBound(2); - final double ccUb = concatSk.getUpperBound(2); - printf("Concatenated: %12.0f %12.0f %12.0f\n", ccLb, ccEst, ccUb); - - //MemorySegment mergedSeg = MemorySegment.ofArray(mergedArr); - final CpcWrapper mergedSk = new CpcWrapper(mergedArr); - final double mEst = mergedSk.getEstimate(); - final double mLb = mergedSk.getLowerBound(2); - final double mUb = mergedSk.getUpperBound(2); - printf("Merged: %12.0f %12.0f %12.0f\n", mLb, mEst, mUb); - assertEquals(Family.CPC, CpcWrapper.getFamily()); - } - - @SuppressWarnings("unused") - @Test - public void checkIsCompressed() { - final CpcSketch sk = new CpcSketch(10); - final byte[] byteArr = sk.toByteArray(); - byteArr[5] &= (byte) -3; - try { - final CpcWrapper wrapper = new CpcWrapper(MemorySegment.ofArray(byteArr)); - fail(); - } catch (final AssertionError e) {} - } - - /** - * @param format the string to print - * @param args the arguments - */ - static void printf(final String format, final Object... args) { - //ps.printf(format, args); //disable here - } - - /** - * @param s the string to print - */ - static void println(final String s) { - //ps.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/cpc/IconEstimatorTest.java b/src/test/java/org/apache/datasketches/cpc/IconEstimatorTest.java deleted file mode 100644 index 9c5a7aaa8..000000000 --- a/src/test/java/org/apache/datasketches/cpc/IconEstimatorTest.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.cpc.IconEstimator.getIconEstimate; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import org.apache.datasketches.common.SketchesStateException; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class IconEstimatorTest { - - //SLOW EXACT VERSION, Eventually move to characterization - - /** - * Important note: do not change anything in the following function. - * It has been carefully designed and tested for numerical accuracy. - * In particular, the use of log1p and expm1 is critically important. - * @param kf the value of k as a double - * @param nf the value of n as a double - * @param col the given column - * @return the quantity qnj - */ - static double qnj(final double kf, final double nf, final int col) { - final double tmp1 = -1.0 / (kf * (Math.pow(2.0, col))); - final double tmp2 = Math.log1p(tmp1); - return (-1.0 * (Math.expm1(nf * tmp2))); - } - - static double exactCofN(final double kf, final double nf) { - double total = 0.0; - for (int col = 128; col >= 1; col--) { - total += qnj(kf, nf, col); - } - return kf * total; - } - - static final double iconInversionTolerance = 1.0e-15; - - static double exactIconEstimatorBinarySearch(final double kf, final double targetC, - final double nLoIn, final double nHiIn) { - int depth = 0; - double nLo = nLoIn; - double nHi = nHiIn; - - while (true) { // manual tail recursion optimization - if (depth > 100) { - throw new SketchesStateException("Excessive recursion in binary search\n"); - } - assert nHi > nLo; - final double nMid = nLo + (0.5 * (nHi - nLo)); - assert ((nMid > nLo) && (nMid < nHi)); - if (((nHi - nLo) / nMid) < iconInversionTolerance) { - return (nMid); - } - final double midC = exactCofN(kf, nMid); - if (midC == targetC) { - return nMid; - } - if (midC < targetC) { - nLo = nMid; - depth++; - continue; - } - if (midC > targetC) { - nHi = nMid; - depth++; - continue; - } - throw new SketchesStateException("bad value in binary search\n"); - } - } - - static double exactIconEstimatorBracketHi(final double kf, final double targetC, final double nLo) { - int depth = 0; - double curN = 2.0 * nLo; - double curC = exactCofN(kf, curN); - while (curC <= targetC) { - if (depth > 100) { - throw new SketchesStateException("Excessive looping in exactIconEstimatorBracketHi\n"); - } - depth++; - curN *= 2.0; - curC = exactCofN(kf, curN); - } - assert (curC > targetC); - return (curN); - } - - static double exactIconEstimator(final int lgK, final long c) { - final double targetC = c; - if ((c == 0L) || (c == 1L)) { - return targetC; - } - final double kf = (1L << lgK); - final double nLo = targetC; - assert exactCofN(kf, nLo) < targetC; // bracket lo - final double nHi = exactIconEstimatorBracketHi(kf, targetC, nLo); // bracket hi - return exactIconEstimatorBinarySearch(kf, targetC, nLo, nHi); - } - - //@Test //used for characterization - public static void testIconEstimator() { - final int lgK = 12; - final int k = 1 << lgK; - long c = 1; - while (c < (k * 64)) { // was K * 15 - final double exact = exactIconEstimator(lgK, c); - final double approx = getIconEstimate(lgK, c); - final double relDiff = (approx - exact) / exact; - printf("%d\t%.19g\t%.19g\t%.19g\n", c, relDiff, exact, approx); - final long a = c + 1; - final long b = (1001 * c) / 1000; - c = ((a > b) ? a : b); - } - } - - @Test //used for unit test - public static void quickIconEstimatorTest() { - for (int lgK = 4; lgK <= 26; lgK++) { - final long k = 1L << lgK; - long[] cArr = {2, 5 * k, 6 * k, 60L * k}; - assertEquals(getIconEstimate(lgK, 0L), 0.0, 0.0); - assertEquals(getIconEstimate(lgK, 1L), 1.0, 0.0); - for (long c : cArr) { - final double exact = exactIconEstimator(lgK, c); - final double approx = getIconEstimate(lgK, c); - final double relDiff = Math.abs((approx - exact) / exact); - printf("%d\t %d\t %.19g\t %.19g\t %.19g\n", lgK, c, relDiff, exact, approx); - assertTrue(relDiff < Math.max(2E-6, 1.0/(80 * k))); - } - } - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * Print with format - * @param format the given format - * @param args the args - */ - static void printf(String format, Object ... args) { - String out = String.format(format, args); - print(out); - } - - /** - * @param s value to print - */ - static void println(String s) { - print(s + "\n"); - } - - /** - * @param s value to print - */ - static void print(String s) { - //System.out.print(s); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/cpc/PairTableTest.java b/src/test/java/org/apache/datasketches/cpc/PairTableTest.java deleted file mode 100644 index 404f9b1c9..000000000 --- a/src/test/java/org/apache/datasketches/cpc/PairTableTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.cpc.PairTable.introspectiveInsertionSort; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - -import java.util.Random; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class PairTableTest { - Random rand = new Random(); - - @Test - public void checkSort() { - int len = 10; - int[] arr1 = new int[len]; - for (int i = 0; i < len; i++) { - int r1 = rand.nextInt(10000); - arr1[i] = r1; - } - introspectiveInsertionSort(arr1, 0, len-1); - println(""); - for (int i : arr1) { println(""+i); } - } - - @Test - public void checkSort2() { - int len = 10; - int[] arr2 = new int[len]; - for (int i = 0; i < len; i++) { - int r1 = rand.nextInt(10000); - long r2 = 3_000_000_000L; - arr2[i] = (int) (r2 + r1); - } - println(""); - introspectiveInsertionSort(arr2, 0, len-1); - for (int i : arr2) { println("" + (i & 0XFFFF_FFFFL)); } - } - - @Test - public void checkSort3() { - int len = 20; - int[] arr3 = new int[len]; - for (int i = 0; i < len; i++) { - arr3[i] = (len - i) + 1; - } - println(""); - introspectiveInsertionSort(arr3, 0, len-1); - for (int i : arr3) { println(""+i); } - } - - @Test - public void checkMerge() { - int[] arrA = new int[] { 1, 3, 5 }; - int[] arrB = new int[] { 2, 4, 6 }; - int[] arrC = new int[6]; - PairTable.merge(arrA, 0, 3, arrB, 0, 3, arrC, 0); - for (int i : arrC) { println(""+i); } - } - - @Test - public void checkMerge2() { - int[] arrA = new int[] { 1, 3, 5 }; - int[] arrB = new int[] { 2, 4, 6 }; - int[] arrC = new int[6]; - for (int i = 0; i < 3; i++) { - arrA[i] = (int) (arrA[i] + 3_000_000_000L); - arrB[i] = (int) (arrB[i] + 3_000_000_000L); - } - PairTable.merge(arrA, 0, 3, arrB, 0, 3, arrC, 0); - for (int i : arrC) { println("" + (i & 0XFFFF_FFFFL)); } - } - - @SuppressWarnings("unused") - @Test - public void checkException() { - int lgK = 10; - PairTable a = new PairTable(2, lgK + 6); - assertEquals(a.getValidBits(), lgK + 6); - println(a.toString()); - PairTable b = null; - try { - PairTable.equals(a, b); - fail(); - } catch (SketchesArgumentException e) { } - try { - PairTable.equals(b, a); - fail(); - } catch (SketchesArgumentException e) { } - try { - PairTable c = new PairTable(1, 16); - fail(); - } catch (SketchesArgumentException e) { } - } - - - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/cpc/PreambleUtilTest.java b/src/test/java/org/apache/datasketches/cpc/PreambleUtilTest.java deleted file mode 100644 index c8891d2ca..000000000 --- a/src/test/java/org/apache/datasketches/cpc/PreambleUtilTest.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.cpc.PreambleUtil.COMPRESSED_FLAG_MASK; -import static org.apache.datasketches.cpc.PreambleUtil.SER_VER; -import static org.apache.datasketches.cpc.PreambleUtil.getDefinedPreInts; -import static org.apache.datasketches.cpc.PreambleUtil.getFamily; -import static org.apache.datasketches.cpc.PreambleUtil.getFiCol; -import static org.apache.datasketches.cpc.PreambleUtil.getFlags; -import static org.apache.datasketches.cpc.PreambleUtil.getFormat; -import static org.apache.datasketches.cpc.PreambleUtil.getHipAccum; -import static org.apache.datasketches.cpc.PreambleUtil.getKxP; -import static org.apache.datasketches.cpc.PreambleUtil.getLgK; -import static org.apache.datasketches.cpc.PreambleUtil.getNumCoupons; -import static org.apache.datasketches.cpc.PreambleUtil.getNumSv; -import static org.apache.datasketches.cpc.PreambleUtil.getPreInts; -import static org.apache.datasketches.cpc.PreambleUtil.getSeedHash; -import static org.apache.datasketches.cpc.PreambleUtil.getSerVer; -import static org.apache.datasketches.cpc.PreambleUtil.getSvLengthInts; -import static org.apache.datasketches.cpc.PreambleUtil.getSvStreamOffset; -import static org.apache.datasketches.cpc.PreambleUtil.getWLengthInts; -import static org.apache.datasketches.cpc.PreambleUtil.getWStreamOffset; -import static org.apache.datasketches.cpc.PreambleUtil.hasHip; -import static org.apache.datasketches.cpc.PreambleUtil.putEmptyMerged; -import static org.apache.datasketches.cpc.PreambleUtil.putPinnedSlidingHip; -import static org.apache.datasketches.cpc.PreambleUtil.putPinnedSlidingHipNoSv; -import static org.apache.datasketches.cpc.PreambleUtil.putPinnedSlidingMerged; -import static org.apache.datasketches.cpc.PreambleUtil.putPinnedSlidingMergedNoSv; -import static org.apache.datasketches.cpc.PreambleUtil.putSparseHybridHip; -import static org.apache.datasketches.cpc.PreambleUtil.putSparseHybridMerged; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import org.testng.annotations.Test; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.cpc.PreambleUtil.HiField; - -/** - * @author Lee Rhodes - */ -public class PreambleUtilTest { - static final short defaultSeedHash = Util.computeSeedHash(Util.DEFAULT_UPDATE_SEED) ; - - private static void checkFirst8(final MemorySegment wseg, final Format format, final int lgK, final int fiCol) { - assertEquals(getFormat(wseg), format); - assertEquals(getPreInts(wseg), getDefinedPreInts(format)); - assertEquals(getSerVer(wseg), SER_VER); - assertEquals(getFamily(wseg), Family.CPC); - assertEquals(getLgK(wseg), lgK); - assertEquals(getFiCol(wseg), fiCol); - assertEquals(getFlags(wseg), (format.ordinal() << 2) | COMPRESSED_FLAG_MASK); - assertEquals(getSeedHash(wseg), defaultSeedHash); - } - - @Test - public void checkNormalPutSegment() { - final int lgK = 12; - final double kxp = lgK; - final double hipAccum = 1005; - final int fiCol = 1; - final int[] csvStream = {1, 2, 3}; - final int numCoupons = csvStream.length; - final int csvLength = csvStream.length; - final short seedHash = defaultSeedHash; - final int[] cwStream = {4, 5, 6}; - final int cwLength = cwStream.length; - final int numSv = cwStream.length; - final int maxInts = 10 + csvLength + cwLength; - final MemorySegment wseg = MemorySegment.ofArray(new byte[4 * maxInts]); - - Format format; - - format = Format.EMPTY_MERGED; - putEmptyMerged(wseg, lgK, seedHash); - println(CpcSketch.toString((byte[])wseg.toArray(JAVA_BYTE), true)); - checkFirst8(wseg, format, lgK, (byte) 0); - assertFalse(hasHip(wseg)); - - format = Format.SPARSE_HYBRID_MERGED; - putSparseHybridMerged(wseg, lgK, numCoupons, csvLength, seedHash, csvStream); - println(CpcSketch.toString(wseg, true)); - println(CpcSketch.toString(wseg, false)); - checkFirst8(wseg, format, lgK, (byte) 0); - assertEquals(getNumCoupons(wseg), numCoupons); - assertEquals(getSvLengthInts(wseg), csvLength); - - format = Format.SPARSE_HYBRID_HIP; - putSparseHybridHip(wseg, lgK, numCoupons, csvLength, kxp, hipAccum, seedHash, csvStream); - println(CpcSketch.toString(wseg, true)); - println(CpcSketch.toString(wseg, false)); - checkFirst8(wseg, format, lgK, (byte) 0); - assertEquals(getNumCoupons(wseg), numCoupons); - assertEquals(getSvLengthInts(wseg), csvLength); - assertEquals(getKxP(wseg), kxp); - assertEquals(getHipAccum(wseg), hipAccum); - assertTrue(hasHip(wseg)); - - format = Format.PINNED_SLIDING_MERGED_NOSV; - putPinnedSlidingMergedNoSv(wseg, lgK, fiCol, numCoupons, cwLength, seedHash, cwStream); - println(CpcSketch.toString(wseg, true)); - println(CpcSketch.toString(wseg, false)); - checkFirst8(wseg, format, lgK, fiCol); - assertEquals(getNumCoupons(wseg), numCoupons); - assertEquals(getWLengthInts(wseg), cwLength); - - format = Format.PINNED_SLIDING_HIP_NOSV; - putPinnedSlidingHipNoSv(wseg, lgK, fiCol, numCoupons, cwLength, kxp, hipAccum, seedHash, - cwStream); - println(CpcSketch.toString(wseg, true)); - println(CpcSketch.toString(wseg, false)); - checkFirst8(wseg, format, lgK, fiCol); - assertEquals(getNumCoupons(wseg), numCoupons); - assertEquals(getWLengthInts(wseg), cwLength); - assertEquals(getKxP(wseg), kxp); - assertEquals(getHipAccum(wseg), hipAccum); - - format = Format.PINNED_SLIDING_MERGED; - putPinnedSlidingMerged(wseg, lgK, fiCol, numCoupons, numSv, csvLength, cwLength, seedHash, - csvStream, cwStream); - println(CpcSketch.toString(wseg, true)); - println(CpcSketch.toString(wseg, false)); - checkFirst8(wseg, format, lgK, fiCol); - assertEquals(getNumCoupons(wseg), numCoupons); - assertEquals(getNumSv(wseg), numSv); - assertEquals(getSvLengthInts(wseg), csvLength); - assertEquals(getWLengthInts(wseg), cwLength); - - format = Format.PINNED_SLIDING_HIP; - putPinnedSlidingHip(wseg, lgK, fiCol, numCoupons, numSv, kxp, hipAccum, csvLength, cwLength, - seedHash, csvStream, cwStream); - println(CpcSketch.toString(wseg, true)); - println(CpcSketch.toString(wseg, false)); - checkFirst8(wseg, format, lgK, fiCol); - assertEquals(getNumCoupons(wseg), numCoupons); - assertEquals(getNumSv(wseg), numSv); - assertEquals(getSvLengthInts(wseg), csvLength); - assertEquals(getWLengthInts(wseg), cwLength); - assertEquals(getKxP(wseg), kxp); - assertEquals(getHipAccum(wseg), hipAccum); - } - - @Test - public void checkStreamErrors() { - final MemorySegment wseg = MemorySegment.ofArray(new byte[4 * 10]); - putEmptyMerged(wseg, (byte) 12, defaultSeedHash); - try { getSvStreamOffset(wseg); fail(); } catch (final SketchesArgumentException e) { } - wseg.set(JAVA_BYTE, 5, (byte) (7 << 2)); - try { getSvStreamOffset(wseg); fail(); } catch (final SketchesStateException e) { } - wseg.set(JAVA_BYTE, 5, (byte) 0); - try { getWStreamOffset(wseg); fail(); } catch (final SketchesArgumentException e) { } - wseg.set(JAVA_BYTE, 5, (byte) (7 << 2)); - try { getWStreamOffset(wseg); fail(); } catch (final SketchesStateException e) { } - } - - @Test - public void checkStreamErrors2() { - final MemorySegment wseg = MemorySegment.ofArray(new byte[4 * 10]); - final int[] svStream = { 1 }; - final int[] wStream = { 2 }; - try { - putPinnedSlidingMerged(wseg, 4, 0, 1, 1, 1, 0, (short) 0, svStream, wStream); - fail(); - } catch (final SketchesStateException e) { } - assertTrue(PreambleUtil.isCompressed(wseg)); - } - - @Test - public void checkEmptySegment() { - final MemorySegment wseg = MemorySegment.ofArray(new byte[4 * 10]); - wseg.set(JAVA_BYTE, 2, (byte) 16); //legal Family - wseg.set(JAVA_BYTE, 5, (byte) (1 << 2)); //select NONE - println(CpcSketch.toString(wseg, false)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkFieldError() { - PreambleUtil.fieldError(Format.EMPTY_MERGED, HiField.NUM_COUPONS); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkCapacity() { - PreambleUtil.checkCapacity(100, 101); - } - - @Test(expectedExceptions = SketchesStateException.class) - public void checkHiFieldError() { - PreambleUtil.getHiFieldOffset(Format.EMPTY_MERGED, HiField.NUM_COUPONS); - } - - @Test - public void checkWindowOffset() { - final long offset = CpcUtil.determineCorrectOffset(4, 54); - assertEquals(offset, 1L); - } - - @Test - public void checkFormatEnum() { - assertEquals(Format.EMPTY_MERGED, Format.ordinalToFormat(0)); - assertEquals(Format.EMPTY_HIP, Format.ordinalToFormat(1)); - assertEquals(Format.SPARSE_HYBRID_MERGED, Format.ordinalToFormat(2)); - assertEquals(Format.SPARSE_HYBRID_HIP, Format.ordinalToFormat(3)); - assertEquals(Format.PINNED_SLIDING_MERGED_NOSV, Format.ordinalToFormat(4)); - assertEquals(Format.PINNED_SLIDING_HIP_NOSV, Format.ordinalToFormat(5)); - assertEquals(Format.PINNED_SLIDING_MERGED, Format.ordinalToFormat(6)); - assertEquals(Format.PINNED_SLIDING_HIP, Format.ordinalToFormat(7)); - } - - @Test - public void checkFlavorEnum() { - assertEquals(Flavor.EMPTY, Flavor.ordinalToFlavor(0)); - assertEquals(Flavor.SPARSE, Flavor.ordinalToFlavor(1)); - assertEquals(Flavor.HYBRID, Flavor.ordinalToFlavor(2)); - assertEquals(Flavor.PINNED, Flavor.ordinalToFlavor(3)); - assertEquals(Flavor.SLIDING, Flavor.ordinalToFlavor(4)); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/cpc/RuntimeAssertsTest.java b/src/test/java/org/apache/datasketches/cpc/RuntimeAssertsTest.java deleted file mode 100644 index 1c0068891..000000000 --- a/src/test/java/org/apache/datasketches/cpc/RuntimeAssertsTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals; -import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertFalse; -import static org.testng.Assert.fail; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class RuntimeAssertsTest { - - @Test - public void checkPositives() { - rtAssertFalse(false); - - short[] shortArr1 = new short[] { 1, 2, 3 }; - short[] shortArr2 = shortArr1.clone(); - rtAssertEquals(shortArr1, shortArr2); - shortArr1 = null; - shortArr2 = null; - rtAssertEquals(shortArr1, shortArr2); - - float[] floatArr1 = new float[] { 1, 2, 3 }; - float[] floatArr2 = floatArr1.clone(); - rtAssertEquals(floatArr1, floatArr2, 0); - floatArr1 = null; - floatArr2 = null; - rtAssertEquals(floatArr1, floatArr2, 0); - - double[] doubleArr1 = new double[] { 1, 2, 3 }; - double[] doubleArr2 = doubleArr1.clone(); - rtAssertEquals(doubleArr1, doubleArr2, 0); - doubleArr1 = null; - doubleArr2 = null; - rtAssertEquals(doubleArr1, doubleArr2, 0); - } - - @Test - public void checkSimpleExceptions() { - try { rtAssert(false); fail(); } catch (AssertionError e) { } - try { rtAssertFalse(true); fail(); } catch (AssertionError e) { } - try { rtAssertEquals(1L, 2L); fail(); } catch (AssertionError e) { } - try { rtAssertEquals(1.0, 2.0, 0); fail(); } catch (AssertionError e) { } - try { rtAssertEquals(true, false); fail(); } catch (AssertionError e) { } - } - - @Test - public void checkByteArr() { - byte[] arr1 = {1, 2}; - byte[] arr2 = {1}; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = new byte[] {1, 3}; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = null; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = arr1; - arr1 = null; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = null; - rtAssertEquals(arr1, arr2); - } - - @Test - public void checkShortArr() { - short[] arr1 = {1, 2}; - short[] arr2 = {1}; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = new short[] {1, 3}; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = null; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = arr1; - arr1 = null; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = null; - rtAssertEquals(arr1, arr2); - } - - @Test - public void checkIntArr() { - int[] arr1 = {1, 2}; - int[] arr2 = {1}; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = new int[] {1, 3}; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = null; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = arr1; - arr1 = null; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = null; - rtAssertEquals(arr1, arr2); - } - - @Test - public void checkLongArr() { - long[] arr1 = {1, 2}; - long[] arr2 = {1}; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = new long[] {1, 3}; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = null; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = arr1; - arr1 = null; - try { rtAssertEquals(arr1, arr2); fail(); } catch (AssertionError e) { } - arr2 = null; - rtAssertEquals(arr1, arr2); - } - - @Test - public void checkFloatArr() { - float[] arr1 = {1, 2}; - float[] arr2 = {1}; - try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { } - arr2 = new float[] {1, 3}; - try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { } - arr2 = null; - try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { } - arr2 = arr1; - arr1 = null; - try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { } - arr2 = null; - rtAssertEquals(arr1, arr2, 0); - } - - @Test - public void checkDoubleArr() { - double[] arr1 = {1, 2}; - double[] arr2 = {1}; - try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { } - arr2 = new double[] {1, 3}; - try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { } - arr2 = null; - try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { } - arr2 = arr1; - arr1 = null; - try { rtAssertEquals(arr1, arr2, 0); fail(); } catch (AssertionError e) { } - arr2 = null; - rtAssertEquals(arr1, arr2, 0); - } - -} diff --git a/src/test/java/org/apache/datasketches/cpc/TestAllTest.java b/src/test/java/org/apache/datasketches/cpc/TestAllTest.java deleted file mode 100644 index 4f94fce47..000000000 --- a/src/test/java/org/apache/datasketches/cpc/TestAllTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.cpc; - -import static org.testng.Assert.assertEquals; - -import java.io.PrintStream; -import java.io.PrintWriter; -import java.util.Arrays; - -import org.apache.datasketches.common.Util; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class TestAllTest { - // Enable these as desired for all tests. - private PrintStream ps = null; //System.out; //prints to console - private PrintWriter pw = null; //prints to file (optional) - - //STREAMING - - @Test //scope = Test - public void streamingCheck() { - int lgMinK = 10; - int lgMaxK = 10; - int trials = 10; - int ppoN = 1; - - StreamingValidation sVal = new StreamingValidation( - lgMinK, lgMaxK, trials, ppoN, ps, pw); - sVal.start(); - } - - //Matrix - @Test - public void matrixCouponCountCheck() { - long pat = 0xA5A5A5A5_5A5A5A5AL; - int len = 16; - long[] arr = new long[len]; - Arrays.fill(arr, pat); - long trueCount = (long)len * Long.bitCount(pat); - long testCount = BitMatrix.countCoupons(arr); - assertEquals(testCount, trueCount); - } - - //COMPRESSION - - @Test //scope = Test - public void compressionCharacterizationCheck() { - int lgMinK = 10; - int lgMaxK = 10; - int lgMaxT = 5; //Trials at start - int lgMinT = 2; //Trials at end - int lgMulK = 7; - int uPPO = 1; - int incLgK = 1; - - CompressionCharacterization cc = new CompressionCharacterization( - lgMinK, lgMaxK, lgMinT, lgMaxT, lgMulK, uPPO, incLgK, ps, pw); - cc.start(); - } - - //@Test //used for troubleshooting a specific rowCol problems - public void singleRowColCheck() { - int lgK = 20; - CpcSketch srcSketch = new CpcSketch(lgK); - int rowCol = 54746379; - srcSketch.rowColUpdate(rowCol); - ps.println(srcSketch.toString(true)); - - CompressedState state = CompressedState.compress(srcSketch); - ps.println(CompressedState.toString(state, true)); - CpcSketch uncSketch = CpcSketch.uncompress(state, Util.DEFAULT_UPDATE_SEED); - ps.println(uncSketch.toString(true)); - } - - //MERGING - - @Test //longer test. use for characterization - public void mergingValidationCheck() { - int lgMinK = 10; - int lgMaxK = 10; //inclusive - int lgMulK = 5; //5 - int uPPO = 1; //16 - int incLgK = 1; - - MergingValidation mv = new MergingValidation( - lgMinK, lgMaxK, lgMulK, uPPO, incLgK, ps, pw); - mv.start(); - } - - @Test //scope = Test - public void quickMergingValidationCheck() { - int lgMinK = 10; - int lgMaxK = 10; - int incLgK = 1; - - QuickMergingValidation qmv = new QuickMergingValidation( - lgMinK, lgMaxK, incLgK, ps, pw); - qmv.start(); - } - - @Test - public void checkPwrLaw10NextDouble() { - double next = TestUtil.pwrLaw10NextDouble(1, 10.0); - assertEquals(next, 100.0); - } - -} diff --git a/src/test/java/org/apache/datasketches/fdt/FdtSketchTest.java b/src/test/java/org/apache/datasketches/fdt/FdtSketchTest.java deleted file mode 100644 index 4c1527b7a..000000000 --- a/src/test/java/org/apache/datasketches/fdt/FdtSketchTest.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.fdt; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.List; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.fdt.FdtSketch; -import org.apache.datasketches.fdt.Group; -import org.apache.datasketches.fdt.PostProcessor; -import org.apache.datasketches.tuple.TupleSketchIterator; -import org.apache.datasketches.tuple.strings.ArrayOfStringsSummary; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class FdtSketchTest { - private static final String LS = System.getProperty("line.separator"); - private static final char sep = '|'; //string separator - - @SuppressWarnings("deprecation") - @Test - public void checkFdtSketch() { - final int lgK = 14; - final FdtSketch sketch = new FdtSketch(lgK); - - final String[] nodesArr = {"abc", "def" }; - sketch.update(nodesArr); - - final TupleSketchIterator it = sketch.iterator(); - int count = 0; - while (it.next()) { - final String[] nodesArr2 = it.getSummary().getValue(); - assertEquals(nodesArr2, nodesArr); - count++; - } - assertEquals(count, 1); - - //serialize - final byte[] byteArr = sketch.toByteArray(); - //deserialize - MemorySegment seg = MemorySegment.ofArray(byteArr); - FdtSketch sketch2 = new FdtSketch(seg); - - //check output - final TupleSketchIterator it2 = sketch2.iterator(); - int count2 = 0; - while (it2.next()) { - final String[] nodesArr2 = it2.getSummary().getValue(); - assertEquals(nodesArr2, nodesArr); - count2++; - } - assertEquals(count, count2); - assertEquals(sketch2.getEstimate(), sketch.getEstimate()); - assertEquals(sketch2.getLowerBound(2), sketch.getLowerBound(2)); - assertEquals(sketch2.getUpperBound(2), sketch.getUpperBound(2)); - } - - @Test - public void checkAlternateLgK() { - int lgK = FdtSketch.computeLgK(.01, .01); - assertEquals(lgK, 20); - lgK = FdtSketch.computeLgK(.02, .05); - assertEquals(lgK, 15); - try { - lgK = FdtSketch.computeLgK(.01, .001); - fail(); - } catch (SketchesArgumentException e) { - //ok - } - } - - @Test - public void checkFdtSketchWithThreshold() { - FdtSketch sk = new FdtSketch(.02, .05); //thresh, RSE - assertEquals(sk.getLgK(), 15); - println("LgK: " + sk.getLgK()); - } - - @Test - public void simpleCheckPostProcessing() { - FdtSketch sk = new FdtSketch(8); - int[] priKeyIndices = {0,2}; - String[] arr1 = {"a", "1", "c"}; - String[] arr2 = {"a", "2", "c"}; - String[] arr3 = {"a", "3", "c"}; - String[] arr4 = {"a", "4", "c"}; - String[] arr5 = {"a", "1", "d"}; - String[] arr6 = {"a", "2", "d"}; - sk.update(arr1); - sk.update(arr2); - sk.update(arr3); - sk.update(arr4); - sk.update(arr5); - sk.update(arr6); - //get results from PostProcessor directly - Group gp = new Group(); //uninitialized - PostProcessor post = new PostProcessor(sk, gp, sep); - post = sk.getPostProcessor(gp, sep); - post = sk.getPostProcessor(); //equivalent - List list = post.getGroupList(priKeyIndices, 2, 0); - assertEquals(list.size(), 2); - assertEquals(post.getGroupCount(), 2); - println(gp.getHeader()); - for (int i = 0; i < list.size(); i++) { - println(list.get(i).toString()); - } - list = post.getGroupList(priKeyIndices, 2, 1); - assertEquals(list.size(), 1); - - //get results from sketch directly - list = sk.getResult(priKeyIndices, 0, 2, sep); - assertEquals(list.size(), 2); - } - - @Test - public void checkEstimatingPostProcessing() { - FdtSketch sk = new FdtSketch(4); - int[] priKeyIndices = {0}; - for (int i = 0; i < 32; i++) { - String[] arr = {"a", Integer.toHexString(i)}; - sk.update(arr); - } - assertTrue(sk.isEstimationMode()); - List list = sk.getResult(priKeyIndices, 0, 2, sep); - assertEquals(list.size(), 1); - println(new Group().getHeader()); - for (int i = 0; i < list.size(); i++) { - println(list.get(i).toString()); - } - } - - @Test - public void checkCopyCtor() { - final int lgK = 14; - final FdtSketch sk = new FdtSketch(lgK); - - final String[] nodesArr = {"abc", "def" }; - sk.update(nodesArr); - assertEquals(sk.getRetainedEntries(), 1); - final FdtSketch sk2 = sk.copy(); - assertEquals(sk2.getRetainedEntries(), 1); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(String s) { - print(s + LS); - } - - /** - * @param s value to print - */ - static void print(String s) { - //System.out.print(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/fdt/GroupTest.java b/src/test/java/org/apache/datasketches/fdt/GroupTest.java deleted file mode 100644 index 2d84a0d1d..000000000 --- a/src/test/java/org/apache/datasketches/fdt/GroupTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.fdt; - -import static org.testng.Assert.assertEquals; - -import org.apache.datasketches.fdt.Group; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class GroupTest { - private static final String LS = System.getProperty("line.separator"); - - @Test - public void checkToString() { //check visually - Group gp = new Group(); - gp.init("AAAAAAAA,BBBBBBBBBB", 100_000_000, 1E8, 1.2E8, 8E7, 0.1, 0.01); - assertEquals(gp.getPrimaryKey(), "AAAAAAAA,BBBBBBBBBB"); - assertEquals(gp.getCount(), 100_000_000); - assertEquals(gp.getEstimate(), 1E8); - assertEquals(gp.getUpperBound(), 1.2E8); - assertEquals(gp.getLowerBound(), 8E7); - assertEquals(gp.getFraction(), 0.1); - assertEquals(gp.getRse(), 0.01); - - println(gp.getHeader()); - println(gp.toString()); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(String s) { - print(s + LS); - } - - /** - * @param s value to print - */ - static void print(String s) { - //System.out.print(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/filters/bloomfilter/BloomFilterBuilderTest.java b/src/test/java/org/apache/datasketches/filters/bloomfilter/BloomFilterBuilderTest.java deleted file mode 100644 index b4dd9119d..000000000 --- a/src/test/java/org/apache/datasketches/filters/bloomfilter/BloomFilterBuilderTest.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.filters.bloomfilter; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertThrows; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.filters.bloomfilter.BloomFilter; -import org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder; -import org.testng.annotations.Test; - -public class BloomFilterBuilderTest { - - @Test - public void testSuggestHashesFromSizes() { - // invalid distinct items - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.suggestNumHashes(0, 32768)); - - // invalid filter size - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.suggestNumHashes(10_000, -1)); - - // manually computed values based on formula - assertEquals(BloomFilterBuilder.suggestNumHashes(100, 1L << 16), 455); - assertEquals(BloomFilterBuilder.suggestNumHashes(10_000, 1L << 12), 1); - assertEquals(BloomFilterBuilder.suggestNumHashes(1_000_000_000, Integer.MAX_VALUE * 4L), 6); - assertEquals(BloomFilterBuilder.suggestNumHashes(1_500_000, 1L << 24), 8); - } - - @Test - public void testSuggestHashesFromProbability() { - // negative probability - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.suggestNumHashes(-0.5)); - - // probability > 1 - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.suggestNumHashes(2.5)); - - // manually computed values based on formula - assertEquals(BloomFilterBuilder.suggestNumHashes(0.333), 2); - assertEquals(BloomFilterBuilder.suggestNumHashes(0.01), 7); - assertEquals(BloomFilterBuilder.suggestNumHashes(1e-12), 40); - } - - @Test - public void testCreateFromSize() { - // invalid number of hashes - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.createBySize(1000, -1, 123)); - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.createBySize(1000, 65536, 123)); - - // invalid number of bits - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.createBySize(0, 3, 456)); - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.createBySize(BloomFilter.MAX_SIZE_BITS + 1, 3, 456)); - - final BloomFilter bf = BloomFilterBuilder.createBySize(1L << 21, 3); - assertEquals(bf.getCapacity(), 1 << 21L); - assertEquals(bf.getNumHashes(), 3); - assertEquals(bf.getBitsUsed(), 0); - } - - @Test - public void testCreateFromAccuracy() { - // invalid number of distinct items - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.createByAccuracy(-1, 0.01)); - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.createByAccuracy(1L << 40, 0.01)); - - // invalid probabilities - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.createByAccuracy(20000, -0.5)); - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.createByAccuracy(20000, 2.0)); - - final long numDistinct = 30000; - final double fpp = 0.001; - final BloomFilter bf = BloomFilterBuilder.createByAccuracy(numDistinct, fpp); - // filter rounds size up to nearest multiple of 64 - assertEquals(bf.getCapacity(), (long) Math.ceil(BloomFilterBuilder.suggestNumFilterBits(numDistinct, fpp) / 64.0) * 64); - assertEquals(bf.getNumHashes(), BloomFilterBuilder.suggestNumHashes(fpp)); - } - - @Test - public void testInitializeFromSize() { - final long numBits = 50000; - final short numHashes = 7; - final long numBytes = BloomFilterBuilder.getSerializedFilterSize(numBits); - final MemorySegment wseg = MemorySegment.ofArray(new byte[(int) numBytes]); - - // invalid number of bits - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.initializeBySize(-1, numHashes, wseg)); - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.initializeBySize(1L << 40, numHashes, wseg)); - - // invalid number of hashes - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.initializeBySize(numBits, -3, wseg)); - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.initializeBySize(numBits, 100_000, wseg)); - - // MemorySegment too small - assertThrows(SketchesArgumentException.class, () - -> BloomFilterBuilder.initializeBySize(numBits, numHashes, MemorySegment.ofArray(new byte[32]))); - - final BloomFilter bf = BloomFilterBuilder.initializeBySize(numBits, numHashes, wseg); - // filter rounds size up to nearest multiple of 64 - assertEquals(bf.getCapacity(), (long) Math.ceil(numBits / 64.0) * 64); - assertEquals(bf.getNumHashes(), numHashes); - } - - @Test - public void testInitializeFromAccuracy() { - final long numDistinct = 30000; - final double fpp = 0.001; - final long numBytes = BloomFilterBuilder.getSerializedFilterSizeByAccuracy(numDistinct, fpp); - final MemorySegment wseg = MemorySegment.ofArray(new byte[(int) numBytes]); - - // invalid number of distinct items - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.initializeByAccuracy(-1, fpp, wseg)); - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.initializeByAccuracy(1L << 40, fpp, wseg)); - - // invalid probabilities - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.initializeByAccuracy(numDistinct, -0.5, wseg)); - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.initializeByAccuracy(numDistinct, 2.0, wseg)); - - // MemorySegment too small - assertThrows(SketchesArgumentException.class, () - -> BloomFilterBuilder.initializeByAccuracy(numDistinct, fpp, MemorySegment.ofArray(new byte[32]))); - - final BloomFilter bf = BloomFilterBuilder.initializeByAccuracy(numDistinct, fpp, wseg); - // filter rounds size up to nearest multiple of 64 - assertEquals(bf.getCapacity(), (long) Math.ceil(BloomFilterBuilder.suggestNumFilterBits(numDistinct, fpp) / 64.0) * 64); - assertEquals(bf.getNumHashes(), BloomFilterBuilder.suggestNumHashes(fpp)); - } - - @Test - public void testSuggestNumFilterBits() { - // non-positive number distincts - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.suggestNumFilterBits(0, 0.01)); - - // non-positive probability - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.suggestNumFilterBits(2500, 0.0)); - - // probability > 1 - assertThrows(SketchesArgumentException.class, () -> BloomFilterBuilder.suggestNumFilterBits(1000, 2.5)); - - // manually computed values based on formula - assertEquals(BloomFilterBuilder.suggestNumFilterBits(250_000, 0.01), 2396265); - BloomFilter bf = BloomFilterBuilder.createByAccuracy(250_000, 0.01); - assertEquals(bf.getCapacity(), 2396288); // next smallest multiple of 64 - assertEquals(bf.getNumHashes(), BloomFilterBuilder.suggestNumHashes(250_000, 2396288)); - - assertEquals(BloomFilterBuilder.suggestNumFilterBits(5_000_000, 1e-4), 95850584); - final long seed = 19805243; - bf = BloomFilterBuilder.createByAccuracy(5_000_000, 1e-4, seed); - assertEquals(bf.getCapacity(), 95850624); // next smallest multiple of 64 - assertEquals(bf.getNumHashes(), BloomFilterBuilder.suggestNumHashes(5_000_000, 95850624)); - assertEquals(bf.getSeed(), seed); - } -} diff --git a/src/test/java/org/apache/datasketches/filters/bloomfilter/BloomFilterCrossLanguageTest.java b/src/test/java/org/apache/datasketches/filters/bloomfilter/BloomFilterCrossLanguageTest.java deleted file mode 100644 index 4decdb91c..000000000 --- a/src/test/java/org/apache/datasketches/filters/bloomfilter/BloomFilterCrossLanguageTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.filters.bloomfilter; - -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES; -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.getFileBytes; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -/** - * Serialize binary sketches to be tested by C++ code. - * Test deserialization of binary sketches serialized by C++ code. - */ -public class BloomFilterCrossLanguageTest { - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBloomFilterBinariesForCompatibilityTesting() throws IOException { - final int[] nArr = {0, 10_000, 2_000_000, 300_000_00}; - final short[] hArr = {3, 5}; - for (final int n : nArr) { - for (final short numHashes : hArr) { - final long configBits = Math.max(n, 1000L); // so empty still has valid bit size - final BloomFilter bf = BloomFilterBuilder.createBySize(configBits, numHashes); - for (int i = 0; i < (n / 10); ++i) { - bf.update(i); - } - if (n > 0) { bf.update(Float.NaN); } - assertEquals(bf.isEmpty(), n == 0); - assertTrue(bf.isEmpty() || (bf.getBitsUsed() > (n / 10))); - putBytesToJavaPath("bf_n" + n + "_h" + numHashes + "_java.sk", bf.toByteArray()); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void readBloomFilterBinariesForCompatibilityTesting() throws IOException { - final int[] nArr = {0, 10_000, 2_000_000, 300_000_00}; - final short[] hArr = {3, 5}; - for (final int n : nArr) { - for (final short numHashes : hArr) { - final byte[] bytes = getFileBytes(cppPath,"bf_n" + n + "_h" + numHashes + "_cpp.sk"); - final BloomFilter bf = BloomFilter.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bf.isEmpty(), n == 0); - assertTrue(bf.isEmpty() || (bf.getBitsUsed() > (n / 10))); - - for (int i = 0; i < (n / 10); ++i) { - assertTrue(bf.query(i)); - } - if (n > 0) { - assert(bf.query(Double.NaN)); - } - } - } - } -} diff --git a/src/test/java/org/apache/datasketches/filters/bloomfilter/BloomFilterTest.java b/src/test/java/org/apache/datasketches/filters/bloomfilter/BloomFilterTest.java deleted file mode 100644 index 6bf67ab31..000000000 --- a/src/test/java/org/apache/datasketches/filters/bloomfilter/BloomFilterTest.java +++ /dev/null @@ -1,522 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.filters.bloomfilter; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_CHAR_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesReadOnlyException; -import org.apache.datasketches.filters.bloomfilter.BloomFilter; -import org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder; -import org.testng.annotations.Test; - -import java.lang.foreign.Arena; - -public class BloomFilterTest { - - @Test - public void createNewFilterTest() throws Exception { - // construct the same filter multiple ways - final long numItems = 4000; - final double targetFpp = 0.01; - - final long numBits = BloomFilterBuilder.suggestNumFilterBits(numItems, targetFpp); - final short numHashes = BloomFilterBuilder.suggestNumHashes(numItems, numBits); - final int sizeBytes = (int) BloomFilterBuilder.getSerializedFilterSize(numBits); - final long seed = 89023L; - - final BloomFilter bf1 = new BloomFilter(numBits, numHashes, seed); - assertTrue(bf1.isEmpty()); - assertFalse(bf1.hasMemorySegment()); - assertFalse(bf1.isOffHeap()); - assertFalse(bf1.isReadOnly()); - - - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = arena.allocate(sizeBytes); - final BloomFilter bf2 = new BloomFilter(numBits, numHashes, seed, wseg); - assertTrue(bf2.isEmpty()); - assertTrue(bf2.hasMemorySegment()); - assertTrue(bf2.isOffHeap()); - assertFalse(bf2.isReadOnly()); - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void tooSmallMemorySegmentTest() { - new BloomFilter(65536, 4, 1L, MemorySegment.ofArray(new byte[32])); - } - - @Test - public void wrapEmptyFilterTest() { - final long numBits = 8192; - final int numHashes = 4; - final BloomFilter bf = BloomFilterBuilder.createBySize(numBits, numHashes); - assertTrue(bf.isEmpty()); - assertEquals(bf.getBitsUsed(), 0); - assertEquals(bf.getCapacity(), numBits); - assertEquals(bf.getNumHashes(), numHashes); - - final MemorySegment seg = MemorySegment.ofArray(bf.toByteArray()); - assertEquals(bf.getSerializedSizeBytes(), seg.byteSize()); - - final MemorySegment wseg = MemorySegment.ofArray(bf.toByteArray()); - assertEquals(bf.getSerializedSizeBytes(), wseg.byteSize()); - - // read-only - final BloomFilter bfReadOnly = BloomFilter.wrap(seg); - assertTrue(bfReadOnly.isEmpty()); - assertEquals(bfReadOnly.getBitsUsed(), 0); - assertEquals(bfReadOnly.getCapacity(), numBits); - assertEquals(bfReadOnly.getNumHashes(), numHashes); - assertTrue(bfReadOnly.isReadOnly()); - - // writable should fail - assertThrows(SketchesArgumentException.class, () -> BloomFilter.writableWrap(wseg)); - } - - @Test - public void wrapNonEmptyFilterTest() { - final long numBits = 8192; - final int numHashes = 4; - final long seed = 52483905L; - final BloomFilter bf = BloomFilterBuilder.createBySize(numBits, numHashes, seed); - - final long valStart = 1024; - final long valEnd = 2048; - for (long i = valStart; i < valEnd; ++i) { - bf.update(i); - } - - final MemorySegment wseg = MemorySegment.ofArray(bf.toByteArray()); - assertEquals(bf.getSerializedSizeBytes(), wseg.byteSize()); - - // writable - final BloomFilter bfWritable = BloomFilter.writableWrap(wseg); - assertFalse(bfWritable.isEmpty()); - assertEquals(bfWritable.getBitsUsed(), bf.getBitsUsed()); - assertEquals(bfWritable.getCapacity(), bf.getCapacity()); - assertEquals(bfWritable.getNumHashes(), bf.getNumHashes()); - assertFalse(bfWritable.isReadOnly()); - - // read-only, wrapping the same writable MemorySegment - final BloomFilter bfReadOnly = BloomFilter.wrap(wseg); - assertFalse(bfReadOnly.isEmpty()); - assertEquals(bfReadOnly.getBitsUsed(), bf.getBitsUsed()); - assertEquals(bfReadOnly.getCapacity(), bf.getCapacity()); - assertEquals(bfReadOnly.getNumHashes(), bf.getNumHashes()); - assertTrue(bfReadOnly.isReadOnly()); - - // update writable, should be reflected in read-only because - // they use the same underling MemorySegment - assertFalse(bfWritable.queryAndUpdate(32768)); - assertTrue(bfReadOnly.query(32768)); - - assertThrows(SketchesReadOnlyException.class, () -> bfReadOnly.update(99999)); - } - - @Test - public void basicFilterOperationsTest() { - final long numBits = 8192; - final int numHashes = 3; - - final BloomFilter bf = BloomFilterBuilder.createBySize(numBits, numHashes); - assertTrue(bf.isEmpty()); - assertEquals(bf.getCapacity(), numBits); // n is multiple of 64 so should be exact - assertEquals(bf.getNumHashes(), numHashes); - assertEquals(bf.getBitsUsed(), 0); - - final long n = 1000; - for (long i = 0; i < n; ++i) { - bf.queryAndUpdate(i); - } - - assertFalse(bf.isEmpty()); - // these next tests assume the filter isn't too close to capacity - assertTrue(bf.getBitsUsed() <= (n * numHashes)); - assertTrue(bf.getBitsUsed() >= (n * (numHashes - 1))); - - int numFound = 0; - for (long i = 0; i < (2 * n); ++i) { - if (bf.query(i)) { - ++numFound; - } - } - assertTrue(numFound >= n); - assertTrue(numFound < (1.1 * n)); - - assert(String.valueOf(bf).length() > 0); - - bf.reset(); - assertTrue(bf.isEmpty()); - assertEquals(bf.getCapacity(), numBits); // n is multiple of 64 so should be exact - assertEquals(bf.getNumHashes(), numHashes); - assertEquals(bf.getBitsUsed(), 0); - } - - @Test - public void inversionTest() { - final long numBits = 8192; - final int numHashes = 3; - - final BloomFilter bf = BloomFilterBuilder.createBySize(numBits, numHashes); - - final int n = 500; - for (int i = 0; i < n; ++i) { - bf.queryAndUpdate(Integer.toString(i)); - } - - final long numBitsSet = bf.getBitsUsed(); - bf.invert(); - assertEquals(bf.getBitsUsed(), numBits - numBitsSet); - - // original items should be mostly not-present - int count = 0; - for (int i = 0; i < n; ++i) { - count += bf.query(Integer.toString(i)) ? 1 : 0; - } - assertTrue(count < (numBits / 10)); - - // many other items should be present - count = 0; - for (int i = n; i < numBits; ++i) { - count += bf.query(Integer.toString(i)) ? 1 : 0; - } - assertTrue(count > n); - } - - @Test - public void incompatibleSetOperationsTest() { - final int numBits = 128; - final int numHashes = 4; - final BloomFilter bf1 = BloomFilterBuilder.createBySize(numBits, numHashes); - - // mismatched num bits - final BloomFilter bf2 = BloomFilterBuilder.createBySize(numBits * 2, numHashes, bf1.getSeed()); - assertThrows(SketchesArgumentException.class, () -> bf1.union(bf2)); - - // mismatched num hashes - final BloomFilter bf3 = BloomFilterBuilder.createBySize(numBits, numHashes * 2, bf1.getSeed()); - assertThrows(SketchesArgumentException.class, () -> bf1.intersect(bf3)); - - // mismatched seed - final BloomFilter bf4 = BloomFilterBuilder.createBySize(numBits, numHashes, bf1.getSeed() - 1); - assertThrows(SketchesArgumentException.class, () -> bf1.union(bf4)); - } - - @Test - public void basicUnionTest() { - final long numBits = 12288; - final int numHashes = 4; - - final BloomFilter bf1 = BloomFilterBuilder.createBySize(numBits, numHashes); - final BloomFilter bf2 = BloomFilterBuilder.createBySize(numBits, numHashes, bf1.getSeed()); - - final int n = 1000; - final int maxItem = ((3 * n) / 2) - 1; - for (int i = 0; i < n; ++i) { - bf1.queryAndUpdate(i); - bf2.queryAndUpdate((n / 2) + i); - } - - bf1.union(null); // no-op - bf1.union(bf2); - for (int i = 0; i < maxItem; ++i) { - assertTrue(bf1.query(i)); - } - - int count = 0; - for (int i = maxItem; i < numBits; ++i) { - count += bf1.query(i) ? 1 : 0; - } - - assertTrue(count < (numBits / 10)); // not being super strict - } - - @Test - public void basicIntersectionTest() { - final long numBits = 8192; - final int numHashes = 5; - - final BloomFilter bf1 = BloomFilterBuilder.createBySize(numBits, numHashes); - final BloomFilter bf2 = BloomFilterBuilder.createBySize(numBits, numHashes, bf1.getSeed()); - - final int n = 1024; - final int maxItem = ((3 * n) / 2) - 1; - for (int i = 0; i < n; ++i) { - bf1.queryAndUpdate(i); - bf2.queryAndUpdate((n / 2) + i); - } - - bf1.intersect(null); // no-op - bf1.intersect(bf2); - for (int i = n / 2; i < n; ++i) { - assertTrue(bf1.query(i)); - } - - int count = 0; - for (int i = 0; i < (n / 2); ++i) { - count += bf1.query(i) ? 1 : 0; - } - for (int i = maxItem; i < numBits; ++i) { - count += bf1.query(i) ? 1 : 0; - } - - assertTrue(count < (numBits / 10)); // not being super strict - } - - @Test - public void emptySerializationTest() { - final long numBits = 32768; - final int numHashes = 7; - final BloomFilter bf = BloomFilterBuilder.createBySize(numBits, numHashes); - - final byte[] bytes = bf.toByteArray(); - final MemorySegment segBytes = MemorySegment.ofArray(bytes); - final BloomFilter fromBytes = BloomFilter.heapify(segBytes); - assertTrue(fromBytes.isEmpty()); - assertEquals(fromBytes.getCapacity(), numBits); - assertEquals(fromBytes.getNumHashes(), numHashes); - - final long[] longs = bf.toLongArray(); - final MemorySegment segLongs = MemorySegment.ofArray(longs); - final BloomFilter fromLongs = BloomFilter.heapify(segLongs); - assertTrue(fromLongs.isEmpty()); - assertEquals(fromLongs.getCapacity(), numBits); - assertEquals(fromLongs.getNumHashes(), numHashes); - - // compare segments - assertEquals(segBytes.byteSize(), segLongs.byteSize()); - for (long i = 0; i < segBytes.byteSize(); ++i) { - assertEquals(segBytes.get(JAVA_BYTE, i), segLongs.get(JAVA_BYTE, i)); - } - } - - @Test - public void nonEmptySerializationTest() { - final long numBits = 32768; - final int numHashes = 5; - final BloomFilter bf = BloomFilterBuilder.createBySize(numBits, numHashes); - - final int n = 2500; - for (int i = 0; i < n; ++i) { - bf.queryAndUpdate(0.5 + i); - } - final long numBitsSet = bf.getBitsUsed(); - - // test a bunch more items w/o updating - int count = 0; - for (int i = n; i < numBits; ++i) { - count += bf.query(0.5 + i) ? 1 : 0; - } - - final byte[] bytes = bf.toByteArray(); - final MemorySegment segBytes = MemorySegment.ofArray(bytes); - final BloomFilter fromBytes = BloomFilter.heapify(segBytes); - assertFalse(fromBytes.isEmpty()); - assertEquals(fromBytes.getCapacity(), numBits); - assertEquals(fromBytes.getBitsUsed(), numBitsSet); - assertEquals(fromBytes.getNumHashes(), numHashes); - int fromBytesCount = 0; - for (int i = 0; i < numBits; ++i) { - final boolean val = fromBytes.query(0.5 + i); - if (val) { - ++fromBytesCount; - } - if (i < n) { - assertTrue(val); - } - } - assertEquals(fromBytesCount, n + count); // same numbers of items should match - - final long[] longs = bf.toLongArray(); - final MemorySegment segLongs = MemorySegment.ofArray(longs); - final BloomFilter fromLongs = BloomFilter.heapify(segLongs); - assertFalse(fromLongs.isEmpty()); - assertEquals(fromLongs.getCapacity(), numBits); - assertEquals(fromLongs.getBitsUsed(), numBitsSet); - assertEquals(fromLongs.getNumHashes(), numHashes); - int fromLongsCount = 0; - for (int i = 0; i < numBits; ++i) { - final boolean val = fromLongs.query(0.5 + i); - if (val) { - ++fromLongsCount; - } - if (i < n) { - assertTrue(val); - } - } - assertEquals(fromLongsCount, n + count); // same numbers of items should match - - assertEquals(segBytes.byteSize(), segLongs.byteSize()); - for (long i = 0; i < segBytes.byteSize(); ++i) { - assertEquals(segBytes.get(JAVA_BYTE, i), segLongs.get(JAVA_BYTE, i)); - } - } - - @Test - public void heapifyFromDirectTest() { - final long numDistinct = 10000; - final double targetFpp = 0.001; - final int numBytes = (int) BloomFilterBuilder.getSerializedFilterSizeByAccuracy(numDistinct, targetFpp); - final MemorySegment wseg = MemorySegment.ofArray(new byte[numBytes]); - final BloomFilter bf = BloomFilterBuilder.initializeByAccuracy(numDistinct, targetFpp, 89540235L, wseg); - - byte[] bytes = bf.toByteArray(); - assertEquals(bytes.length, Family.BLOOMFILTER.getMinPreLongs() * Long.BYTES); - BloomFilter bfBytes = BloomFilter.heapify(MemorySegment.ofArray(bytes)); - assertTrue(bfBytes.isEmpty()); - assertEquals(bfBytes.getNumHashes(), bf.getNumHashes()); - assertEquals(bfBytes.getBitsUsed(), 0); - assertEquals(bfBytes.getCapacity(), bf.getCapacity()); // even though empty - - long[] longs = bf.toLongArray(); - assertEquals(longs.length, Family.BLOOMFILTER.getMinPreLongs()); - BloomFilter bfLongs = BloomFilter.heapify(MemorySegment.ofArray(longs)); - assertTrue(bfLongs.isEmpty()); - assertEquals(bfLongs.getNumHashes(), bf.getNumHashes()); - assertEquals(bfLongs.getBitsUsed(), 0); - assertEquals(bfLongs.getCapacity(), bf.getCapacity()); - - // add some items now - for (int i = 0; i < 10000; ++i) { - bf.queryAndUpdate(Integer.toString(i)); - } - - bytes = bf.toByteArray(); - assertEquals(bytes.length, bf.getSerializedSizeBytes()); - bfBytes = BloomFilter.heapify(MemorySegment.ofArray(bytes)); - assertFalse(bfBytes.isEmpty()); - assertEquals(bfBytes.getNumHashes(), bf.getNumHashes()); - assertEquals(bfBytes.getBitsUsed(), bf.getBitsUsed()); - assertEquals(bfBytes.getCapacity(), bf.getCapacity()); - assertTrue(bfBytes.query(Integer.toString(5000))); - assertFalse(bfBytes.query(Integer.toString(50000))); - - longs = bf.toLongArray(); - assertEquals(longs.length, bf.getSerializedSizeBytes() / Long.BYTES); - bfLongs = BloomFilter.heapify(MemorySegment.ofArray(longs)); - assertFalse(bfLongs.isEmpty()); - assertEquals(bfLongs.getNumHashes(), bf.getNumHashes()); - assertEquals(bfLongs.getBitsUsed(), bf.getBitsUsed()); - assertEquals(bfLongs.getCapacity(), bf.getCapacity()); - assertTrue(bfBytes.query(Integer.toString(7500))); - assertFalse(bfBytes.query(Integer.toString(75000))); - } - - @Test - public void testBasicUpdateMethods() { - final int numDistinct = 100; - final double fpp = 1e-6; - final BloomFilter bf = BloomFilterBuilder.createByAccuracy(numDistinct, fpp); - - // empty/null String should do nothing - bf.update(""); - bf.update((String) null); - assertFalse(bf.queryAndUpdate("")); - assertFalse(bf.queryAndUpdate((String) null)); - assertEquals(bf.getBitsUsed(), 0); - - bf.update("abc"); - assertFalse(bf.queryAndUpdate("def")); - bf.update(932); - assertFalse(bf.queryAndUpdate(543)); - bf.update(Double.NaN); - assertFalse(bf.queryAndUpdate(Double.POSITIVE_INFINITY)); - assertTrue(bf.getBitsUsed() <= (bf.getNumHashes() * 6)); - assertFalse(bf.isEmpty()); - } - - @Test - public void testArrayUpdateMethods() { - // 3 doubles = 24 bytes - final double rawData[] = { 1.414, 2.71, 3.1415926538 }; - final MemorySegment seg = MemorySegment.ofArray(rawData); - - final int numDistinct = 100; - final double fpp = 1e-6; - - // for each BloomFilter update type, call update() then queryAndUpdate(), where - // the latter should return true. query() should likewise return true. - // A final intersection should have the same number of bits set as the raw input. - final BloomFilter bfSeg = BloomFilterBuilder.createByAccuracy(numDistinct, fpp); - bfSeg.update(seg); - assertTrue(bfSeg.queryAndUpdate(seg)); - assertTrue(bfSeg.query(seg)); - final long numBitsSet = bfSeg.getBitsUsed(); - final long seed = bfSeg.getSeed(); - - final BloomFilter bfBytes = BloomFilterBuilder.createByAccuracy(numDistinct, fpp, seed); - final byte[] bytes = seg.toArray(JAVA_BYTE); - bfBytes.update(bytes); - assertTrue(bfBytes.queryAndUpdate(bytes)); - assertTrue(bfBytes.query(bytes)); - assertEquals(bfBytes.getBitsUsed(), numBitsSet); - - final BloomFilter bfChars = BloomFilterBuilder.createByAccuracy(numDistinct, fpp, seed); - final char[] chars = seg.toArray(JAVA_CHAR_UNALIGNED); - bfChars.update(chars); - assertTrue(bfChars.queryAndUpdate(chars)); - assertTrue(bfChars.query(chars)); - assertEquals(bfChars.getBitsUsed(), numBitsSet); - - final BloomFilter bfShorts = BloomFilterBuilder.createByAccuracy(numDistinct, fpp, seed); - final short[] shorts = seg.toArray(JAVA_SHORT_UNALIGNED); - bfShorts.update(shorts); - assertTrue(bfShorts.queryAndUpdate(shorts)); - assertTrue(bfShorts.query(shorts)); - assertEquals(bfShorts.getBitsUsed(), numBitsSet); - - final BloomFilter bfInts = BloomFilterBuilder.createByAccuracy(numDistinct, fpp, seed); - final int[] ints = seg.toArray(JAVA_INT_UNALIGNED); - bfInts.update(ints); - assertTrue(bfInts.queryAndUpdate(ints)); - assertTrue(bfInts.query(ints)); - assertEquals(bfInts.getBitsUsed(), numBitsSet); - - final BloomFilter bfLongs = BloomFilterBuilder.createByAccuracy(numDistinct, fpp, seed); - final long[] longs = seg.toArray(JAVA_LONG_UNALIGNED); - bfLongs.update(longs); - assertTrue(bfLongs.queryAndUpdate(longs)); - assertTrue(bfLongs.query(longs)); - assertEquals(bfLongs.getBitsUsed(), numBitsSet); - - // intersect all the sketches into a new one - final BloomFilter bf = BloomFilterBuilder.createByAccuracy(numDistinct, fpp, seed); - bf.intersect(bfSeg); - bf.intersect(bfBytes); - bf.intersect(bfChars); - bf.intersect(bfShorts); - bf.intersect(bfInts); - bf.intersect(bfLongs); - assertEquals(bfLongs.getBitsUsed(), numBitsSet); - } -} diff --git a/src/test/java/org/apache/datasketches/filters/bloomfilter/DirectBitArrayRTest.java b/src/test/java/org/apache/datasketches/filters/bloomfilter/DirectBitArrayRTest.java deleted file mode 100644 index 0d08f9ae5..000000000 --- a/src/test/java/org/apache/datasketches/filters/bloomfilter/DirectBitArrayRTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.filters.bloomfilter; - -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.positional.PositionalSegment; -import org.apache.datasketches.filters.bloomfilter.DirectBitArrayR; -import org.apache.datasketches.filters.bloomfilter.HeapBitArray; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesReadOnlyException; -import org.testng.annotations.Test; - -public class DirectBitArrayRTest { - - private static MemorySegment bitArrayToMemorySegment(final HeapBitArray ba) { - // assumes we're using small enough an array to test that - // size can be measured with an int - final int numBytes = (int) ba.getSerializedSizeBytes(); - final byte[] bytes = new byte[numBytes]; - final MemorySegment wseg = MemorySegment.ofArray(bytes); - ba.writeToSegmentAsStream(PositionalSegment.wrap(wseg)); - - return wseg; - } - - @Test - public void createBitArrayTest() { - final HeapBitArray hba = new HeapBitArray(119); - assertTrue(hba.isEmpty()); - - final MemorySegment seg = bitArrayToMemorySegment(hba); - final DirectBitArrayR dba = DirectBitArrayR.wrap(seg, hba.isEmpty()); - assertTrue(dba.isEmpty()); - assertEquals(dba.getCapacity(), 128); // nearest multiple of 64 - assertEquals(dba.getArrayLength(), 2); - assertEquals(dba.getNumBitsSet(), 0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void createNegativeSizeBitArrayTest() { - final byte[] bytes = new byte[32]; - final MemorySegment wseg = MemorySegment.ofArray(bytes); - wseg.set(JAVA_INT_UNALIGNED, 0, -1); // negative length - DirectBitArrayR.wrap(wseg, true); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void tooSmallCapacityTest() { - final byte[] bytes = new byte[32]; - final MemorySegment wseg = MemorySegment.ofArray(bytes); - wseg.set(JAVA_INT_UNALIGNED, 0, 1024); // array length in longs - wseg.set(JAVA_LONG_UNALIGNED, 8, 201); // number of bits seg (non-empty) - DirectBitArrayR.wrap(wseg, false); - } - - // no text of max size because the BitArray allows up to Integer.MAX_VALUE - - @Test - public void basicOperationTest() { - final HeapBitArray hba = new HeapBitArray(128); - assertFalse(hba.getAndSetBit(1)); - assertFalse(hba.getAndSetBit(2)); - for (int i = 4; i < 64; i <<= 1) { - hba.getAndSetBit(64 + i); - } - assertEquals(hba.getNumBitsSet(), 6); - assertTrue(hba.getBit(68)); - assertFalse(hba.isEmpty()); - - final MemorySegment seg = bitArrayToMemorySegment(hba); - final DirectBitArrayR dba = DirectBitArrayR.wrap(seg, hba.isEmpty()); - assertEquals(dba.getNumBitsSet(), 6); - assertTrue(dba.getBit(68)); - assertFalse(dba.isEmpty()); - assertFalse(dba.isDirty()); - - assertTrue(dba.hasMemorySegment()); - assertFalse(dba.isOffHeap()); - assertTrue(dba.isReadOnly()); - } - - @Test - public void countBitsWhenDirty() { - // like basicOperationTest but with segBit which does - // not necessarily track numBitsSet_ - final HeapBitArray hba = new HeapBitArray(128); - assertFalse(hba.getAndSetBit(1)); - assertFalse(hba.getAndSetBit(2)); - for (int i = 4; i < 64; i <<= 1) { - hba.setBit(64 + i); - } - assertEquals(hba.getNumBitsSet(), 6); - assertTrue(hba.getBit(68)); - assertFalse(hba.isEmpty()); - - final MemorySegment seg = bitArrayToMemorySegment(hba); - final DirectBitArrayR dba = DirectBitArrayR.wrap(seg, hba.isEmpty()); - assertEquals(dba.getNumBitsSet(), 6); - assertTrue(dba.getBit(68)); - assertFalse(dba.isEmpty()); - assertFalse(dba.isDirty()); - } - - @Test - public void bitAddressOutOfBoundsEmptyTest() { - final int numBits = 256; - final HeapBitArray hba = new HeapBitArray(numBits); - final MemorySegment seg = bitArrayToMemorySegment(hba); - final DirectBitArrayR dba = DirectBitArrayR.wrap(seg, hba.isEmpty()); - assertFalse(dba.getBit(19)); // in range - assertFalse(dba.getBit(-10)); // out of bounds - assertFalse(dba.getBit(2048)); // out of bounds - } - - @Test - public void bitAddressOutOfBoundsNonEmptyTest() { - final int numBits = 1024; - final HeapBitArray hba = new HeapBitArray(numBits); - for (int i = 0; i < numBits; i += numBits / 8) { - hba.getAndSetBit(i); - } - - final MemorySegment seg = bitArrayToMemorySegment(hba); - final DirectBitArrayR dba = DirectBitArrayR.wrap(seg, hba.isEmpty()); - assertThrows(IndexOutOfBoundsException.class, () -> dba.getBit(-10)); - assertThrows(IndexOutOfBoundsException.class, () -> dba.getBit(2048)); - } - - @Test - public void checkInvalidMethods() { - final int numBits = 1024; - final HeapBitArray hba = new HeapBitArray(numBits); - for (int i = 0; i < numBits; i += numBits / 8) { - hba.getAndSetBit(i); - } - - final MemorySegment seg = bitArrayToMemorySegment(hba); - final DirectBitArrayR dba = DirectBitArrayR.wrap(seg, hba.isEmpty()); - - // all of these try to modify a read-only MemorySegment - assertThrows(SketchesReadOnlyException.class, () -> dba.setBit(14)); - assertThrows(SketchesReadOnlyException.class, () -> dba.getAndSetBit(100)); - assertThrows(SketchesReadOnlyException.class, () -> dba.reset()); - assertThrows(SketchesReadOnlyException.class, () -> dba.invert()); - assertThrows(SketchesReadOnlyException.class, () -> dba.intersect(hba)); - assertThrows(SketchesReadOnlyException.class, () -> dba.union(hba)); - } -} diff --git a/src/test/java/org/apache/datasketches/filters/bloomfilter/DirectBitArrayTest.java b/src/test/java/org/apache/datasketches/filters/bloomfilter/DirectBitArrayTest.java deleted file mode 100644 index 88f7ffae6..000000000 --- a/src/test/java/org/apache/datasketches/filters/bloomfilter/DirectBitArrayTest.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.filters.bloomfilter; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_CHAR_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.positional.PositionalSegment; -import org.apache.datasketches.filters.bloomfilter.BitArray; -import org.apache.datasketches.filters.bloomfilter.DirectBitArray; -import org.apache.datasketches.filters.bloomfilter.HeapBitArray; -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.Test; - -public class DirectBitArrayTest { - - private static MemorySegment bitArrayToMemorySegment(final HeapBitArray ba) { - // assumes we're using small enough an array to test that - // size can be measured with an int - final int numBytes = (int) ba.getSerializedSizeBytes(); - final byte[] bytes = new byte[numBytes]; - final MemorySegment wseg = MemorySegment.ofArray(bytes); - ba.writeToSegmentAsStream(PositionalSegment.wrap(wseg)); - - return wseg; - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void writableWrapEmptyBitArrayTest() { - final HeapBitArray hba = new HeapBitArray(119); - assertTrue(hba.isEmpty()); - - final MemorySegment seg = bitArrayToMemorySegment(hba); - DirectBitArray.writableWrap(seg, hba.isEmpty()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void createNegativeSizeBitArrayTest() { - final byte[] bytes = new byte[32]; - final MemorySegment wseg = MemorySegment.ofArray(bytes); - wseg.set(JAVA_INT_UNALIGNED, 0, -1); // negative length - DirectBitArray.writableWrap(wseg, true); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void tooSmallCapacityTest() { - final byte[] bytes = new byte[32]; - final MemorySegment wseg = MemorySegment.ofArray(bytes); - wseg.set(JAVA_INT_UNALIGNED, 0, 1024); // array length in longs - wseg.set(JAVA_LONG_UNALIGNED, 8, 201); // number of bits set (non-empty) - DirectBitArray.writableWrap(wseg, false); - } - - // no text of max size because the BitArray allows up to Integer.MAX_VALUE - - @Test - public void initializeTooSmallTest() { - final byte[] bytes = new byte[128]; - final MemorySegment wseg = MemorySegment.ofArray(bytes); - assertThrows(SketchesArgumentException.class, () -> DirectBitArray.initialize(128 * 65, wseg)); - assertThrows(SketchesArgumentException.class, () -> DirectBitArray.initialize(-5, wseg)); - } - - @Test - public void basicInitializeOperationsTest() { - final byte[] bytes = new byte[56]; - final MemorySegment wseg = MemorySegment.ofArray(bytes); - - final DirectBitArray dba = DirectBitArray.initialize(192, wseg); - assertTrue(dba.isEmpty()); - assertTrue(dba.hasMemorySegment()); - assertFalse(dba.isReadOnly()); - assertEquals(dba.getNumBitsSet(), 0); - - assertFalse(dba.getAndSetBit(13)); - assertTrue(dba.getBit(13)); - dba.setBit(17); - assertTrue(dba.getAndSetBit(17)); - assertEquals(dba.getArrayLength(), 3); - assertFalse(dba.isEmpty()); - assertFalse(dba.getBit(183)); - - assertTrue(dba.isDirty()); - assertEquals(dba.getNumBitsSet(), 2); - assertFalse(dba.isDirty()); - - dba.reset(); - assertTrue(dba.isEmpty()); - assertTrue(dba.hasMemorySegment()); - assertFalse(dba.isReadOnly()); - assertEquals(dba.getNumBitsSet(), 0); - } - - @Test - public void basicWritableWrapTest() { - final HeapBitArray hba = new HeapBitArray(128); - assertFalse(hba.getAndSetBit(1)); - assertFalse(hba.getAndSetBit(2)); - for (int i = 4; i < 64; i <<= 1) { - hba.getAndSetBit(64 + i); - } - assertEquals(hba.getNumBitsSet(), 6); - assertTrue(hba.getBit(68)); - assertFalse(hba.isEmpty()); - - final MemorySegment seg = bitArrayToMemorySegment(hba); - final DirectBitArray dba = DirectBitArray.writableWrap(seg, hba.isEmpty()); - assertEquals(dba.getNumBitsSet(), 6); - assertTrue(dba.getBit(68)); - assertFalse(dba.isEmpty()); - assertFalse(dba.isDirty()); - - assertTrue(dba.hasMemorySegment()); - assertFalse(dba.isOffHeap()); - assertFalse(dba.isReadOnly()); - - assertFalse(dba.getAndSetBit(75)); - dba.setBit(100); - assertTrue(dba.getAndSetBit(100)); - assertEquals(dba.getNumBitsSet(), 8); - } - - @Test - public void countWritableWrappedBitsWhenDirty() { - // like basicOperationTest but with setBit which does - // not necessarily track numBitsSet_ - final HeapBitArray hba = new HeapBitArray(128); - assertFalse(hba.getAndSetBit(1)); - assertFalse(hba.getAndSetBit(2)); - for (int i = 4; i < 64; i <<= 1) { - hba.setBit(64 + i); - } - assertEquals(hba.getNumBitsSet(), 6); - assertTrue(hba.getBit(68)); - assertFalse(hba.isEmpty()); - - final MemorySegment seg = bitArrayToMemorySegment(hba); - final DirectBitArray dba = DirectBitArray.writableWrap(seg, hba.isEmpty()); - assertEquals(dba.getNumBitsSet(), 6); - assertTrue(dba.getBit(68)); - assertFalse(dba.isEmpty()); - assertFalse(dba.isDirty()); - - dba.setBit(102); - assertTrue(dba.isDirty()); - } - - @Test - public void bitAddresOutOfBoundsNonEmptyTest() { - final int numBits = 1024; - final byte[] bytes = new byte[((numBits / 64) + 2) * Long.BYTES]; - final MemorySegment wseg = MemorySegment.ofArray(bytes); - final DirectBitArray dba = DirectBitArray.initialize(numBits, wseg); - - for (int i = 0; i < numBits; i += numBits / 8) { - dba.getAndSetBit(i); - } - - assertThrows(IndexOutOfBoundsException.class, () -> dba.getBit(-10)); - assertThrows(IndexOutOfBoundsException.class, () -> dba.getBit(2048)); - assertThrows(IndexOutOfBoundsException.class, () -> dba.setBit(-20)); - assertThrows(IndexOutOfBoundsException.class, () -> dba.setBit(4096)); - assertThrows(IndexOutOfBoundsException.class, () -> dba.getAndSetBit(-30)); - assertThrows(IndexOutOfBoundsException.class, () -> dba.getAndSetBit(8192)); - } - - @Test - public void inversionTest() { - final int numBits = 1024; - final byte[] bytes = new byte[((numBits / 64) + 2) * Long.SIZE]; - final MemorySegment wseg = MemorySegment.ofArray(bytes); - final DirectBitArray dba = DirectBitArray.initialize(numBits, wseg); - - for (int i = 0; i < numBits; i += numBits / 8) { - dba.getAndSetBit(i); - } - assertTrue(dba.getBit(0)); - - final long numSet = dba.getNumBitsSet(); - dba.invert(); - - assertEquals(dba.getNumBitsSet(), numBits - numSet); - assertFalse(dba.getBit(0)); - - // update to make dirty and invert again - dba.setBit(0); - dba.invert(); - assertEquals(dba.getNumBitsSet(), numSet - 1); - assertFalse(dba.getBit(0)); - } - - @Test - public void invalidUnionIntersectionTest() { - final HeapBitArray hba = new HeapBitArray(128); - hba.setBit(0); - final MemorySegment wseg = bitArrayToMemorySegment(hba); - final DirectBitArray dba = DirectBitArray.writableWrap(wseg, false); - assertThrows(SketchesArgumentException.class, () -> dba.union(new HeapBitArray(64))); - assertThrows(SketchesArgumentException.class, () -> dba.intersect(new HeapBitArray(512))); - } - - @Test - public void validUnionAndIntersectionTest() { - final long numBits = 64; - final int sizeBytes = (int) BitArray.getSerializedSizeBytes(64); - final DirectBitArray ba1 = DirectBitArray.initialize(numBits, MemorySegment.ofArray(new byte[sizeBytes])); - final DirectBitArray ba2 = DirectBitArray.initialize(numBits, MemorySegment.ofArray(new byte[sizeBytes])); - final DirectBitArray ba3 = DirectBitArray.initialize(numBits, MemorySegment.ofArray(new byte[sizeBytes])); - - final int n = 10; - for (int i = 0; i < n; ++i) { - ba1.getAndSetBit(i); - ba2.getAndSetBit(i + (n / 2)); - ba3.getAndSetBit(2 * i); - } - assertEquals(ba1.getNumBitsSet(), n); - assertEquals(ba2.getNumBitsSet(), n); - assertEquals(ba3.getNumBitsSet(), n); - - ba1.intersect(ba2); - assertEquals(ba1.getNumBitsSet(), n / 2); - - ba3.union(ba2); - assertEquals(ba3.getNumBitsSet(), (3 * n) / 2); - } -} diff --git a/src/test/java/org/apache/datasketches/filters/bloomfilter/HeapBitArrayTest.java b/src/test/java/org/apache/datasketches/filters/bloomfilter/HeapBitArrayTest.java deleted file mode 100644 index 6e8556442..000000000 --- a/src/test/java/org/apache/datasketches/filters/bloomfilter/HeapBitArrayTest.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.filters.bloomfilter; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.positional.PositionalSegment; -import org.apache.datasketches.filters.bloomfilter.HeapBitArray; -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.Test; - -public class HeapBitArrayTest { - - @Test - public void createBitArrayTest() { - final HeapBitArray ba = new HeapBitArray(119); - assertEquals(ba.getCapacity(), 128); // nearest multiple of 64 - assertEquals(ba.getArrayLength(), 2); - assertEquals(ba.getNumBitsSet(), 0); - assertTrue(ba.isEmpty()); - - assertFalse(ba.hasMemorySegment()); - assertFalse(ba.isOffHeap()); - assertFalse(ba.isReadOnly()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void createNegativeSizeBitArrayTest() { - new HeapBitArray(-64); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void createTooLargeBitArrayTest() { - new HeapBitArray(1L + ((long) Integer.MAX_VALUE * Long.SIZE)); - } - - @Test - public void basicOperationTest() { - final HeapBitArray ba = new HeapBitArray(128); - assertEquals(ba.getAndSetBit(1), false); - assertEquals(ba.getAndSetBit(2), false); - for (int i = 4; i < 64; i <<= 1) { - ba.getAndSetBit(64 + i); - } - assertEquals(ba.getNumBitsSet(), 6); - assertEquals(ba.getBit(68), true); - assertFalse(ba.isEmpty()); - - assertFalse(ba.getBit(5)); - ba.setBit(5); - assertTrue(ba.getAndSetBit(5)); - assertEquals(ba.getNumBitsSet(), 7); - - ba.reset(); - assertTrue(ba.isEmpty()); - assertEquals(ba.getNumBitsSet(), 0); - - assertTrue(String.valueOf(ba).length() > 0); - } - - @Test - public void bitAddresOutOfBoundsTest() { - final HeapBitArray ba = new HeapBitArray(1024); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> ba.getBit(-10)); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> ba.getBit(2048)); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> ba.setBit(-20)); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> ba.setBit(4096)); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> ba.getAndSetBit(-30)); - assertThrows(ArrayIndexOutOfBoundsException.class, () -> ba.getAndSetBit(8192)); - } - - @Test - public void inversionTest() { - final int numBits = 1024; - final HeapBitArray ba = new HeapBitArray(numBits); - for (int i = 0; i < numBits; i += numBits / 8) { - ba.getAndSetBit(i); - } - assertTrue(ba.getBit(0)); - - final long numSet = ba.getNumBitsSet(); - ba.invert(); - - assertEquals(ba.getNumBitsSet(), numBits - numSet); - assertFalse(ba.getBit(0)); - - // update to make dirty and invert again - ba.setBit(0); - ba.invert(); - assertEquals(ba.getNumBitsSet(), numSet - 1); - assertFalse(ba.getBit(0)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void invalidUnionTest() { - final HeapBitArray ba = new HeapBitArray(128); - ba.union(new HeapBitArray(64)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void invalidIntersectionTest() { - final HeapBitArray ba = new HeapBitArray(128); - ba.intersect(new HeapBitArray(64)); - } - - @Test - public void validUnionAndIntersectionTest() { - final HeapBitArray ba1 = new HeapBitArray(64); - final HeapBitArray ba2 = new HeapBitArray(64); - final HeapBitArray ba3 = new HeapBitArray(64); - - final int n = 10; - for (int i = 0; i < n; ++i) { - ba1.getAndSetBit(i); - ba2.getAndSetBit(i + (n / 2)); - ba3.getAndSetBit(2 * i); - } - assertEquals(ba1.getNumBitsSet(), n); - assertEquals(ba2.getNumBitsSet(), n); - assertEquals(ba3.getNumBitsSet(), n); - - ba1.intersect(ba2); - assertEquals(ba1.getNumBitsSet(), n / 2); - - ba3.union(ba2); - assertEquals(ba3.getNumBitsSet(), (3 * n) / 2); - } - - @Test - public void serializeEmptyTest() { - final HeapBitArray ba = new HeapBitArray(64); - final byte[] arr = new byte[(int) ba.getSerializedSizeBytes()]; - final PositionalSegment posSeg = PositionalSegment.wrap(MemorySegment.ofArray(arr)); - ba.writeToSegmentAsStream(posSeg); - posSeg.resetPosition(); - final HeapBitArray newBA = HeapBitArray.heapify(posSeg, true); - assertEquals(newBA.getArrayLength(), ba.getArrayLength()); - assertEquals(newBA.getCapacity(), ba.getCapacity()); - assertEquals(newBA.getNumBitsSet(), ba.getNumBitsSet()); - assertTrue(newBA.isEmpty()); - } - - @Test - public void serializeNonEmptyTest() { - final long n = 8192; - final HeapBitArray ba = new HeapBitArray(n); - for (int i = 0; i < n; i += 3) { - ba.getAndSetBit(i); - } - final byte[] arr = new byte[(int) ba.getSerializedSizeBytes()]; - final PositionalSegment posSeg = PositionalSegment.wrap(MemorySegment.ofArray(arr)); - ba.writeToSegmentAsStream(posSeg); - posSeg.resetPosition(); - final HeapBitArray newBA = HeapBitArray.heapify(posSeg, false); - assertEquals(newBA.getArrayLength(), ba.getArrayLength()); - assertEquals(newBA.getCapacity(), ba.getCapacity()); - assertEquals(newBA.getNumBitsSet(), ba.getNumBitsSet()); - assertFalse(newBA.isEmpty()); - } -} diff --git a/src/test/java/org/apache/datasketches/frequencies/DistTest.java b/src/test/java/org/apache/datasketches/frequencies/DistTest.java deleted file mode 100644 index d6d56da1a..000000000 --- a/src/test/java/org/apache/datasketches/frequencies/DistTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -import org.testng.Assert; -//import org.testng.annotations.Test; - -public class DistTest { - - /** - * @param prob the probability of success for the geometric distribution. - * @return a random number generated from the geometric distribution. - */ - public static long randomGeometricDist(double prob) { - assert ((prob > 0.0) && (prob < 1.0)); - return 1 + (long) (Math.log(Math.random()) / Math.log(1.0 - prob)); - } - - public static double zeta(long n, double theta) { - // the zeta function, used by the below zipf function - // (this is not often called from outside this library) - // ... but have made it public now to speed things up - long i; - double ans = 0.0; - - for (i = 1; i <= n; i++) { - ans += Math.pow(1.0 / i, theta); - } - return (ans); - } - - // This draws values from the zipf distribution - // n is range, theta is skewness parameter - // theta = 0 gives uniform distribution, - // theta > 1 gives highly skewed distribution. - public static long zipf(double theta, long n, double zetan) { - double alpha; - double eta; - double u; - double uz; - double val; - - // randinit must be called before entering this procedure for - // the first time since it uses the random generators - - alpha = 1. / (1. - theta); - eta = (1. - Math.pow(2. / n, 1. - theta)) / (1. - (zeta(2, theta) / zetan)); - - u = 0.0; - while (u == 0.0) { - u = Math.random(); - } - uz = u * zetan; - if (uz < 1.) { - val = 1; - } else if (uz < (1. + Math.pow(0.5, theta))) { - val = 2; - } else { - val = 1 + (n * Math.pow(((eta * u) - eta) + 1., alpha)); - } - - return (long) val; - } - - //@Test - public static void testRandomGeometricDist() { - long maxItem = 0L; - double prob = .1; - for (int i = 0; i < 100; i++) { - long item = randomGeometricDist(prob); - if (item > maxItem) { - maxItem = item; - } - // If you succeed with probability p the probability - // of failing 20/p times is smaller than 1/2^20. - Assert.assertTrue(maxItem < (20.0 / prob)); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/frequencies/FrequentItemsSketchCrossLanguageTest.java b/src/test/java/org/apache/datasketches/frequencies/FrequentItemsSketchCrossLanguageTest.java deleted file mode 100644 index 49a735df7..000000000 --- a/src/test/java/org/apache/datasketches/frequencies/FrequentItemsSketchCrossLanguageTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES; -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.getFileBytes; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.testng.annotations.Test; - -/** - * Serialize binary sketches to be tested by C++ code. - * Test deserialization of binary sketches serialized by C++ code. - */ -public class FrequentItemsSketchCrossLanguageTest { - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingLongsSketch() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (final int n: nArr) { - final FrequentLongsSketch sk = new FrequentLongsSketch(64); - for (int i = 1; i <= n; i++) { - sk.update(i); - } - assertTrue(n == 0 ? sk.isEmpty() : !sk.isEmpty()); - if (n > 10) { assertTrue(sk.getMaximumError() > 0); } - else { assertEquals(sk.getMaximumError(), 0); } - putBytesToJavaPath("frequent_long_n" + n + "_java.sk", sk.toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingStringsSketch() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (final int n: nArr) { - final FrequentItemsSketch sk = new FrequentItemsSketch<>(64); - for (int i = 1; i <= n; i++) { - sk.update(Integer.toString(i)); - } - assertTrue(n == 0 ? sk.isEmpty() : !sk.isEmpty()); - if (n > 10) { assertTrue(sk.getMaximumError() > 0); } - else { assertEquals(sk.getMaximumError(), 0); } - putBytesToJavaPath("frequent_string_n" + n + "_java.sk", sk.toByteArray(new ArrayOfStringsSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingStringsSketchAscii() throws IOException { - final FrequentItemsSketch sk = new FrequentItemsSketch<>(64); - sk.update("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 1); - sk.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 2); - sk.update("ccccccccccccccccccccccccccccc", 3); - sk.update("ddddddddddddddddddddddddddddd", 4); - putBytesToJavaPath("frequent_string_ascii_java.sk", sk.toByteArray(new ArrayOfStringsSerDe())); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingStringsSketchUtf8() throws IOException { - final FrequentItemsSketch sk = new FrequentItemsSketch<>(64); - sk.update("абвгд", 1); - sk.update("еёжзи", 2); - sk.update("йклмн", 3); - sk.update("опрст", 4); - sk.update("уфхцч", 5); - sk.update("шщъыь", 6); - sk.update("эюя", 7); - putBytesToJavaPath("frequent_string_utf8_java.sk", sk.toByteArray(new ArrayOfStringsSerDe())); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void longs() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "frequent_long_n" + n + "_cpp.sk"); - final FrequentLongsSketch sketch = FrequentLongsSketch.getInstance(MemorySegment.ofArray(bytes)); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - if (n > 10) { - assertTrue(sketch.getMaximumError() > 0); - } else { - assertEquals(sketch.getMaximumError(), 0); - } - assertEquals(sketch.getStreamLength(), n); - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void strings() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "frequent_string_n" + n + "_cpp.sk"); - final FrequentItemsSketch sketch = FrequentItemsSketch.getInstance(MemorySegment.ofArray(bytes), new ArrayOfStringsSerDe()); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - if (n > 10) { - assertTrue(sketch.getMaximumError() > 0); - } else { - assertEquals(sketch.getMaximumError(), 0); - } - assertEquals(sketch.getStreamLength(), n); - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void stringsAscii() throws IOException { - final byte[] bytes = getFileBytes(cppPath, "frequent_string_ascii_cpp.sk"); - final FrequentItemsSketch sketch = FrequentItemsSketch.getInstance(MemorySegment.ofArray(bytes), new ArrayOfStringsSerDe()); - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getMaximumError(), 0); - assertEquals(sketch.getStreamLength(), 10); - assertEquals(sketch.getEstimate("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), 1); - assertEquals(sketch.getEstimate("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), 2); - assertEquals(sketch.getEstimate("ccccccccccccccccccccccccccccc"), 3); - assertEquals(sketch.getEstimate("ddddddddddddddddddddddddddddd"), 4); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void stringsUtf8() throws IOException { - final byte[] bytes = getFileBytes(cppPath, "frequent_string_utf8_cpp.sk"); - final FrequentItemsSketch sketch = FrequentItemsSketch.getInstance(MemorySegment.ofArray(bytes), new ArrayOfStringsSerDe()); - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getMaximumError(), 0); - assertEquals(sketch.getStreamLength(), 28); - assertEquals(sketch.getEstimate("абвгд"), 1); - assertEquals(sketch.getEstimate("еёжзи"), 2); - assertEquals(sketch.getEstimate("йклмн"), 3); - assertEquals(sketch.getEstimate("опрст"), 4); - assertEquals(sketch.getEstimate("уфхцч"), 5); - assertEquals(sketch.getEstimate("шщъыь"), 6); - assertEquals(sketch.getEstimate("эюя"), 7); - } - -} diff --git a/src/test/java/org/apache/datasketches/frequencies/HashMapStressTest.java b/src/test/java/org/apache/datasketches/frequencies/HashMapStressTest.java deleted file mode 100644 index 6a123839c..000000000 --- a/src/test/java/org/apache/datasketches/frequencies/HashMapStressTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -import org.apache.datasketches.frequencies.ReversePurgeLongHashMap; -import org.apache.datasketches.hash.MurmurHash3; -//import org.testng.annotations.Test; - -public class HashMapStressTest { - - //@Test - public static void stress() { - println("ReversePurgeLongHashMap Stress Test"); - printf("%12s%15s%n", "Capacity", "TimePerAdjust"); - for (int capacity = 2 << 5; capacity < (2 << 24); capacity *= 2) { - int n = 10000000; - - long[] keys = new long[n]; - long[] values = new long[n]; - - for (int i = 0; i < n; i++) { - keys[i] = murmur(i); - values[i] = (i < (capacity / 2)) ? n : 1; - } - - ReversePurgeLongHashMap hashmap = new ReversePurgeLongHashMap(capacity); - long timePerAdjust = timeOneHashMap(hashmap, keys, values, (int) (.75 * capacity)); - printf("%12d%15d%n", capacity, timePerAdjust); - } - } - - private static long timeOneHashMap(ReversePurgeLongHashMap hashMap, long[] keys, long[] values, - int sizeToShift) { - final long startTime = System.nanoTime(); - int n = keys.length; - assert (n == values.length); - for (int i = 0; i < n; i++) { - hashMap.adjustOrPutValue(keys[i], values[i]); - if (hashMap.getNumActive() == sizeToShift) { - hashMap.adjustAllValuesBy(-1); - hashMap.keepOnlyPositiveCounts(); - } - } - final long endTime = System.nanoTime(); - return (endTime - startTime) / n; - } - - private static long murmur(long key) { - long[] keyArr = { key }; - return MurmurHash3.hash(keyArr, 0)[0]; - } - - private static void println(Object obj) { System.out.println(obj.toString()); } - - private static void printf(String fmt, Object ... args) { System.out.printf(fmt, args); } - -} \ No newline at end of file diff --git a/src/test/java/org/apache/datasketches/frequencies/ItemsSketchTest.java b/src/test/java/org/apache/datasketches/frequencies/ItemsSketchTest.java deleted file mode 100644 index d77933444..000000000 --- a/src/test/java/org/apache/datasketches/frequencies/ItemsSketchTest.java +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.frequencies.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.frequencies.PreambleUtil.FLAGS_BYTE; -import static org.apache.datasketches.frequencies.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.frequencies.PreambleUtil.SER_VER_BYTE; -import static org.apache.datasketches.frequencies.Util.LG_MIN_MAP_SIZE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import org.testng.Assert; -import org.testng.annotations.Test; - -import org.apache.datasketches.common.ArrayOfLongsSerDe; -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.ArrayOfUtf16StringsSerDe; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.frequencies.ErrorType; -import org.apache.datasketches.frequencies.FrequentItemsSketch; -import org.apache.datasketches.frequencies.ReversePurgeItemHashMap; -import org.apache.datasketches.frequencies.FrequentItemsSketch.Row; - -public class ItemsSketchTest { - - @Test - public void empty() { - final FrequentItemsSketch sketch = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertEquals(sketch.getNumActiveItems(), 0); - Assert.assertEquals(sketch.getStreamLength(), 0); - Assert.assertEquals(sketch.getLowerBound("a"), 0); - Assert.assertEquals(sketch.getUpperBound("a"), 0); - } - - @Test - public void nullInput() { - final FrequentItemsSketch sketch = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sketch.update(null); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertEquals(sketch.getNumActiveItems(), 0); - Assert.assertEquals(sketch.getStreamLength(), 0); - Assert.assertEquals(sketch.getLowerBound(null), 0); - Assert.assertEquals(sketch.getUpperBound(null), 0); - } - - @Test - public void oneItem() { - final FrequentItemsSketch sketch = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sketch.update("a"); - Assert.assertFalse(sketch.isEmpty()); - Assert.assertEquals(sketch.getNumActiveItems(), 1); - Assert.assertEquals(sketch.getStreamLength(), 1); - Assert.assertEquals(sketch.getEstimate("a"), 1); - Assert.assertEquals(sketch.getLowerBound("a"), 1); - } - - @Test - public void severalItems() { - final FrequentItemsSketch sketch = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sketch.update("a"); - sketch.update("b"); - sketch.update("c"); - sketch.update("d"); - sketch.update("b"); - sketch.update("c"); - sketch.update("b"); - Assert.assertFalse(sketch.isEmpty()); - Assert.assertEquals(sketch.getNumActiveItems(), 4); - Assert.assertEquals(sketch.getStreamLength(), 7); - Assert.assertEquals(sketch.getEstimate("a"), 1); - Assert.assertEquals(sketch.getEstimate("b"), 3); - Assert.assertEquals(sketch.getEstimate("c"), 2); - Assert.assertEquals(sketch.getEstimate("d"), 1); - - FrequentItemsSketch.Row[] items = sketch.getFrequentItems(ErrorType.NO_FALSE_POSITIVES); - Assert.assertEquals(items.length, 4); - - items = sketch.getFrequentItems(3, ErrorType.NO_FALSE_POSITIVES); - Assert.assertEquals(items.length, 1); - Assert.assertEquals(items[0].getItem(), "b"); - - sketch.reset(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertEquals(sketch.getNumActiveItems(), 0); - Assert.assertEquals(sketch.getStreamLength(), 0); - } - - @Test - public void estimationMode() { - final FrequentItemsSketch sketch = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sketch.update(1, 10); - sketch.update(2); - sketch.update(3); - sketch.update(4); - sketch.update(5); - sketch.update(6); - sketch.update(7, 15); - sketch.update(8); - sketch.update(9); - sketch.update(10); - sketch.update(11); - sketch.update(12); - - Assert.assertFalse(sketch.isEmpty()); - Assert.assertEquals(sketch.getStreamLength(), 35); - - { - final FrequentItemsSketch.Row[] items = - sketch.getFrequentItems(ErrorType.NO_FALSE_POSITIVES); - Assert.assertEquals(items.length, 2); - // only 2 items (1 and 7) should have counts more than 1 - int count = 0; - for (final FrequentItemsSketch.Row item: items) { - if (item.getLowerBound() > 1) { - count++; - } - } - Assert.assertEquals(count, 2); - } - - { - final FrequentItemsSketch.Row[] items = - sketch.getFrequentItems(ErrorType.NO_FALSE_NEGATIVES); - Assert.assertTrue(items.length >= 2); - // only 2 items (1 and 7) should have counts more than 1 - int count = 0; - for (final FrequentItemsSketch.Row item: items) { - if (item.getLowerBound() > 5) { - count++; - } - } - Assert.assertEquals(count, 2); - } - } - - @Test - public void serializeStringDeserializeEmpty() { - final FrequentItemsSketch sketch1 = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - final byte[] bytes = sketch1.toByteArray(new ArrayOfStringsSerDe()); - final FrequentItemsSketch sketch2 = - FrequentItemsSketch.getInstance(MemorySegment.ofArray(bytes), new ArrayOfStringsSerDe()); - Assert.assertTrue(sketch2.isEmpty()); - Assert.assertEquals(sketch2.getNumActiveItems(), 0); - Assert.assertEquals(sketch2.getStreamLength(), 0); - } - - @Test - public void serializeDeserializeUft8Strings() { - final FrequentItemsSketch sketch1 = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sketch1.update("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); - sketch1.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); - sketch1.update("ccccccccccccccccccccccccccccc"); - sketch1.update("ddddddddddddddddddddddddddddd"); - - final byte[] bytes = sketch1.toByteArray(new ArrayOfStringsSerDe()); - final FrequentItemsSketch sketch2 = - FrequentItemsSketch.getInstance(MemorySegment.ofArray(bytes), new ArrayOfStringsSerDe()); - sketch2.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); - sketch2.update("ccccccccccccccccccccccccccccc"); - sketch2.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); - - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertEquals(sketch2.getNumActiveItems(), 4); - Assert.assertEquals(sketch2.getStreamLength(), 7); - Assert.assertEquals(sketch2.getEstimate("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), 1); - Assert.assertEquals(sketch2.getEstimate("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), 3); - Assert.assertEquals(sketch2.getEstimate("ccccccccccccccccccccccccccccc"), 2); - Assert.assertEquals(sketch2.getEstimate("ddddddddddddddddddddddddddddd"), 1); - } - - @Test - public void serializeDeserializeUtf16Strings() { - final FrequentItemsSketch sketch1 = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sketch1.update("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); - sketch1.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); - sketch1.update("ccccccccccccccccccccccccccccc"); - sketch1.update("ddddddddddddddddddddddddddddd"); - - final byte[] bytes = sketch1.toByteArray(new ArrayOfUtf16StringsSerDe()); - final FrequentItemsSketch sketch2 = - FrequentItemsSketch.getInstance(MemorySegment.ofArray(bytes), new ArrayOfUtf16StringsSerDe()); - sketch2.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); - sketch2.update("ccccccccccccccccccccccccccccc"); - sketch2.update("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); - - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertEquals(sketch2.getNumActiveItems(), 4); - Assert.assertEquals(sketch2.getStreamLength(), 7); - Assert.assertEquals(sketch2.getEstimate("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), 1); - Assert.assertEquals(sketch2.getEstimate("bbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), 3); - Assert.assertEquals(sketch2.getEstimate("ccccccccccccccccccccccccccccc"), 2); - Assert.assertEquals(sketch2.getEstimate("ddddddddddddddddddddddddddddd"), 1); - } - - @Test - public void forceResize() { - final FrequentItemsSketch sketch1 = new FrequentItemsSketch<>(2 << LG_MIN_MAP_SIZE); - for (int i=0; i<32; i++) { - sketch1.update(Integer.toString(i), i*i); - } - } - - @Test - public void getRowHeader() { - final String header = FrequentItemsSketch.Row.getRowHeader(); - Assert.assertNotNull(header); - Assert.assertTrue(header.length() > 0); - } - - @Test - public void serializeLongDeserialize() { - final FrequentItemsSketch sketch1 = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sketch1.update(1L); - sketch1.update(2L); - sketch1.update(3L); - sketch1.update(4L); - - final String s = sketch1.toString(); - println(s); - - final byte[] bytes = sketch1.toByteArray(new ArrayOfLongsSerDe()); - final FrequentItemsSketch sketch2 = - FrequentItemsSketch.getInstance(MemorySegment.ofArray(bytes), new ArrayOfLongsSerDe()); - sketch2.update(2L); - sketch2.update(3L); - sketch2.update(2L); - - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertEquals(sketch2.getNumActiveItems(), 4); - Assert.assertEquals(sketch2.getStreamLength(), 7); - Assert.assertEquals(sketch2.getEstimate(1L), 1); - Assert.assertEquals(sketch2.getEstimate(2L), 3); - Assert.assertEquals(sketch2.getEstimate(3L), 2); - Assert.assertEquals(sketch2.getEstimate(4L), 1); - } - - @Test - public void mergeExact() { - final FrequentItemsSketch sketch1 = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sketch1.update("a"); - sketch1.update("b"); - sketch1.update("c"); - sketch1.update("d"); - - final FrequentItemsSketch sketch2 = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sketch2.update("b"); - sketch2.update("c"); - sketch2.update("b"); - - sketch1.merge(sketch2); - Assert.assertFalse(sketch1.isEmpty()); - Assert.assertEquals(sketch1.getNumActiveItems(), 4); - Assert.assertEquals(sketch1.getStreamLength(), 7); - Assert.assertEquals(sketch1.getEstimate("a"), 1); - Assert.assertEquals(sketch1.getEstimate("b"), 3); - Assert.assertEquals(sketch1.getEstimate("c"), 2); - Assert.assertEquals(sketch1.getEstimate("d"), 1); - } - - @Test - public void checkNullMapReturns() { - final ReversePurgeItemHashMap map = new ReversePurgeItemHashMap<>(1 << LG_MIN_MAP_SIZE); - Assert.assertNull(map.getActiveKeys()); - Assert.assertNull(map.getActiveValues()); - } - - @SuppressWarnings("unlikely-arg-type") - @Test - public void checkMisc() { - final FrequentItemsSketch sk1 = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - Assert.assertEquals(sk1.getCurrentMapCapacity(), 6); - Assert.assertEquals(sk1.getEstimate(Long.valueOf(1)), 0); - final FrequentItemsSketch sk2 = new FrequentItemsSketch<>(8); - Assert.assertEquals(sk1.merge(sk2), sk1 ); - Assert.assertEquals(sk1.merge(null), sk1); - sk1.update(Long.valueOf(1)); - final FrequentItemsSketch.Row[] rows = sk1.getFrequentItems(ErrorType.NO_FALSE_NEGATIVES); - final FrequentItemsSketch.Row row = rows[0]; - Assert.assertTrue(row.hashCode() != 0); - Assert.assertTrue(row.equals(row)); - Assert.assertFalse(row.equals(sk1)); - Assert.assertEquals((long)row.getItem(), 1L); - Assert.assertEquals(row.getEstimate(), 1); - Assert.assertEquals(row.getUpperBound(), 1); - final String s = row.toString(); - println(s); - final FrequentItemsSketch.Row nullRow = null; //check equals(null) - Assert.assertFalse(row.equals(nullRow)); - } - - @Test - public void checkToString() { - final FrequentItemsSketch sk = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sk.update(Long.valueOf(1)); - println(FrequentItemsSketch.toString(sk.toByteArray(new ArrayOfLongsSerDe()))); - } - - @Test - public void checkGetFrequentItems1() { - final FrequentItemsSketch fis = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - fis.update(1L); - final Row[] rowArr = fis.getFrequentItems(ErrorType.NO_FALSE_POSITIVES); - final Row row = rowArr[0]; - assertNotNull(row); - assertEquals(row.est, 1L); - assertEquals(row.item, Long.valueOf(1L)); - assertEquals(row.lb, 1L); - assertEquals(row.ub, 1L); - Row newRow = new Row<>(row.item, row.est+1, row.ub, row.lb); - assertFalse(row.equals(newRow)); - newRow = new Row<>(row.item, row.est, row.ub, row.lb); - assertTrue(row.equals(newRow)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkUpdateException() { - final FrequentItemsSketch sk1 = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sk1.update(Long.valueOf(1), -1); - } - - @Test - public void checkMemorySegmentExceptions() { - final FrequentItemsSketch sk1 = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sk1.update(Long.valueOf(1), 1); - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - final byte[] byteArr = sk1.toByteArray(serDe); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - //FrequentItemsSketch sk2 = FrequentItemsSketch.getInstance(seg, serDe); - //println(sk2.toString()); - final long pre0 = seg.get(JAVA_LONG_UNALIGNED, 0); //The correct first 8 bytes. - //Now start corrupting - tryBadSeg(seg, PREAMBLE_LONGS_BYTE, 2); //Corrupt - seg.set(JAVA_LONG_UNALIGNED, 0, pre0); //restore - - tryBadSeg(seg, SER_VER_BYTE, 2); //Corrupt - seg.set(JAVA_LONG_UNALIGNED, 0, pre0); //restore - - tryBadSeg(seg, FAMILY_BYTE, 2); //Corrupt - seg.set(JAVA_LONG_UNALIGNED, 0, pre0); //restore - - tryBadSeg(seg, FLAGS_BYTE, 4); //Corrupt to true - seg.set(JAVA_LONG_UNALIGNED, 0, pre0); //restore - } - - @Test - public void oneItemUtf8() { - final FrequentItemsSketch sketch1 = new FrequentItemsSketch<>(1 << LG_MIN_MAP_SIZE); - sketch1.update("\u5fb5"); - Assert.assertFalse(sketch1.isEmpty()); - Assert.assertEquals(sketch1.getNumActiveItems(), 1); - Assert.assertEquals(sketch1.getStreamLength(), 1); - Assert.assertEquals(sketch1.getEstimate("\u5fb5"), 1); - - final byte[] bytes = sketch1.toByteArray(new ArrayOfStringsSerDe()); - final FrequentItemsSketch sketch2 = - FrequentItemsSketch.getInstance(MemorySegment.ofArray(bytes), new ArrayOfStringsSerDe()); - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertEquals(sketch2.getNumActiveItems(), 1); - Assert.assertEquals(sketch2.getStreamLength(), 1); - Assert.assertEquals(sketch2.getEstimate("\u5fb5"), 1); - } - - @Test - public void checkGetEpsilon() { - assertEquals(FrequentItemsSketch.getEpsilon(1024), 3.5 / 1024, 0.0); - try { - FrequentItemsSketch.getEpsilon(1000); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkGetAprioriError() { - final double eps = 3.5 / 1024; - assertEquals(FrequentItemsSketch.getAprioriError(1024, 10_000), eps * 10_000); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - //Restricted methods - - private static void tryBadSeg(final MemorySegment seg, final int byteOffset, final int byteValue) { - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - try { - seg.set(JAVA_BYTE, byteOffset, (byte) byteValue); //Corrupt - FrequentItemsSketch.getInstance(seg, serDe); - fail(); - } catch (final SketchesArgumentException e) { - //expected - } - } - - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/frequencies/LongsSketchTest.java b/src/test/java/org/apache/datasketches/frequencies/LongsSketchTest.java deleted file mode 100644 index 109ad8cd5..000000000 --- a/src/test/java/org/apache/datasketches/frequencies/LongsSketchTest.java +++ /dev/null @@ -1,620 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.frequencies.DistTest.randomGeometricDist; -import static org.apache.datasketches.frequencies.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.frequencies.PreambleUtil.FLAGS_BYTE; -import static org.apache.datasketches.frequencies.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.frequencies.PreambleUtil.SER_VER_BYTE; -import static org.apache.datasketches.frequencies.Util.LG_MIN_MAP_SIZE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import org.testng.Assert; -import org.testng.annotations.Test; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.frequencies.ErrorType; -import org.apache.datasketches.frequencies.FrequentLongsSketch; -import org.apache.datasketches.frequencies.PreambleUtil; -import org.apache.datasketches.frequencies.ReversePurgeLongHashMap; -import org.apache.datasketches.frequencies.FrequentLongsSketch.Row; - -public class LongsSketchTest { - - @Test - public void hashMapSerialTest() { - final ReversePurgeLongHashMap map = new ReversePurgeLongHashMap(8); - map.adjustOrPutValue(10, 15); - map.adjustOrPutValue(10, 5); - map.adjustOrPutValue(1, 1); - map.adjustOrPutValue(2, 3); - final String string = map.serializeToString(); - //println(string); - //println(map.toString()); - final ReversePurgeLongHashMap new_map = - ReversePurgeLongHashMap.getInstance(string); - final String new_string = new_map.serializeToString(); - Assert.assertTrue(string.equals(new_string)); - } - - @Test - public void frequentItemsStringSerialTest() { - final FrequentLongsSketch sketch = new FrequentLongsSketch(8); - final FrequentLongsSketch sketch2 = new FrequentLongsSketch(128); - sketch.update(10, 100); - sketch.update(10, 100); - sketch.update(15, 3443); - sketch.update(1000001, 1010230); - sketch.update(1000002, 1010230); - - final String string0 = sketch.serializeToString(); - final FrequentLongsSketch new_sketch0 = FrequentLongsSketch.getInstance(string0); - final String new_string0 = new_sketch0.serializeToString(); - Assert.assertTrue(string0.equals(new_string0)); - Assert.assertTrue(new_sketch0.getMaximumMapCapacity() == sketch.getMaximumMapCapacity()); - Assert.assertTrue(new_sketch0.getCurrentMapCapacity() == sketch.getCurrentMapCapacity()); - - sketch2.update(190, 12902390); - sketch2.update(191, 12902390); - sketch2.update(192, 12902390); - sketch2.update(193, 12902390); - sketch2.update(194, 12902390); - sketch2.update(195, 12902390); - sketch2.update(196, 12902390); - sketch2.update(197, 12902390); - sketch2.update(198, 12902390); - sketch2.update(199, 12902390); - sketch2.update(200, 12902390); - sketch2.update(201, 12902390); - sketch2.update(202, 12902390); - sketch2.update(203, 12902390); - sketch2.update(204, 12902390); - sketch2.update(205, 12902390); - sketch2.update(206, 12902390); - sketch2.update(207, 12902390); - sketch2.update(208, 12902390); - - final String string2 = sketch2.serializeToString(); - final FrequentLongsSketch new_sketch2 = FrequentLongsSketch.getInstance(string2); - final String new_string2 = new_sketch2.serializeToString(); - Assert.assertTrue(string2.equals(new_string2)); - Assert.assertTrue(new_sketch2.getMaximumMapCapacity() == sketch2.getMaximumMapCapacity()); - Assert.assertTrue(new_sketch2.getCurrentMapCapacity() == sketch2.getCurrentMapCapacity()); - Assert.assertTrue(new_sketch2.getStreamLength() == sketch2.getStreamLength()); - - final FrequentLongsSketch merged_sketch = sketch.merge(sketch2); - - final String string = merged_sketch.serializeToString(); - final FrequentLongsSketch new_sketch = FrequentLongsSketch.getInstance(string); - final String new_string = new_sketch.serializeToString(); - Assert.assertTrue(string.equals(new_string)); - Assert.assertTrue(new_sketch.getMaximumMapCapacity() == merged_sketch.getMaximumMapCapacity()); - Assert.assertTrue(new_sketch.getCurrentMapCapacity() == merged_sketch.getCurrentMapCapacity()); - Assert.assertTrue(new_sketch.getStreamLength() == merged_sketch.getStreamLength()); - } - - @Test - public void frequentItemsByteSerialTest() { - //Empty Sketch - final FrequentLongsSketch sketch = new FrequentLongsSketch(16); - final byte[] bytearray0 = sketch.toByteArray(); - final MemorySegment seg0 = MemorySegment.ofArray(bytearray0); - final FrequentLongsSketch new_sketch0 = FrequentLongsSketch.getInstance(seg0); - final String str0 = FrequentLongsSketch.toString(seg0); - println(str0); - final String string0 = sketch.serializeToString(); - final String new_string0 = new_sketch0.serializeToString(); - Assert.assertTrue(string0.equals(new_string0)); - - final FrequentLongsSketch sketch2 = new FrequentLongsSketch(128); - sketch.update(10, 100); - sketch.update(10, 100); - sketch.update(15, 3443); - sketch.update(1000001, 1010230); - sketch.update(1000002, 1010230); - - final byte[] bytearray1 = sketch.toByteArray(); - final MemorySegment seg1 = MemorySegment.ofArray(bytearray1); - final FrequentLongsSketch new_sketch1 = FrequentLongsSketch.getInstance(seg1); - final String str1 = FrequentLongsSketch.toString(bytearray1); - println(str1); - final String string1 = sketch.serializeToString(); - final String new_string1 = new_sketch1.serializeToString(); - Assert.assertTrue(string1.equals(new_string1)); - Assert.assertTrue(new_sketch1.getMaximumMapCapacity() == sketch.getMaximumMapCapacity()); - Assert.assertTrue(new_sketch1.getCurrentMapCapacity() == sketch.getCurrentMapCapacity()); - - sketch2.update(190, 12902390); - sketch2.update(191, 12902390); - sketch2.update(192, 12902390); - sketch2.update(193, 12902390); - sketch2.update(194, 12902390); - sketch2.update(195, 12902390); - sketch2.update(196, 12902390); - sketch2.update(197, 12902390); - sketch2.update(198, 12902390); - sketch2.update(199, 12902390); - sketch2.update(200, 12902390); - sketch2.update(201, 12902390); - sketch2.update(202, 12902390); - sketch2.update(203, 12902390); - sketch2.update(204, 12902390); - sketch2.update(205, 12902390); - sketch2.update(206, 12902390); - sketch2.update(207, 12902390); - sketch2.update(208, 12902390); - - final byte[] bytearray2 = sketch2.toByteArray(); - final MemorySegment seg2 = MemorySegment.ofArray(bytearray2); - final FrequentLongsSketch new_sketch2 = FrequentLongsSketch.getInstance(seg2); - - final String string2 = sketch2.serializeToString(); - final String new_string2 = new_sketch2.serializeToString(); - - Assert.assertTrue(string2.equals(new_string2)); - Assert.assertTrue(new_sketch2.getMaximumMapCapacity() == sketch2.getMaximumMapCapacity()); - Assert.assertTrue(new_sketch2.getCurrentMapCapacity() == sketch2.getCurrentMapCapacity()); - Assert.assertTrue(new_sketch2.getStreamLength() == sketch2.getStreamLength()); - - final FrequentLongsSketch merged_sketch = sketch.merge(sketch2); - - final byte[] bytearray = sketch.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(bytearray); - final FrequentLongsSketch new_sketch = FrequentLongsSketch.getInstance(seg); - - final String string = sketch.serializeToString(); - final String new_string = new_sketch.serializeToString(); - - Assert.assertTrue(string.equals(new_string)); - Assert.assertTrue(new_sketch.getMaximumMapCapacity() == merged_sketch.getMaximumMapCapacity()); - Assert.assertTrue(new_sketch.getCurrentMapCapacity() == merged_sketch.getCurrentMapCapacity()); - Assert.assertTrue(new_sketch.getStreamLength() == merged_sketch.getStreamLength()); - } - - @Test - public void frequentItemsByteResetAndEmptySerialTest() { - final FrequentLongsSketch sketch = new FrequentLongsSketch(16); - sketch.update(10, 100); - sketch.update(10, 100); - sketch.update(15, 3443); - sketch.update(1000001, 1010230); - sketch.update(1000002, 1010230); - sketch.reset(); - - final byte[] bytearray0 = sketch.toByteArray(); - final MemorySegment seg0 = MemorySegment.ofArray(bytearray0); - final FrequentLongsSketch new_sketch0 = FrequentLongsSketch.getInstance(seg0); - - final String string0 = sketch.serializeToString(); - final String new_string0 = new_sketch0.serializeToString(); - Assert.assertTrue(string0.equals(new_string0)); - Assert.assertTrue(new_sketch0.getMaximumMapCapacity() == sketch.getMaximumMapCapacity()); - Assert.assertTrue(new_sketch0.getCurrentMapCapacity() == sketch.getCurrentMapCapacity()); - } - - @Test - public void checkFreqLongsSegSerDe() { - final int minSize = 1 << LG_MIN_MAP_SIZE; - final FrequentLongsSketch sk1 = new FrequentLongsSketch(minSize); - sk1.update(10, 100); - sk1.update(10, 100); - sk1.update(15, 3443); println(sk1.toString()); - sk1.update(1000001, 1010230); println(sk1.toString()); - sk1.update(1000002, 1010230); println(sk1.toString()); - - final byte[] bytearray0 = sk1.toByteArray(); - final MemorySegment seg0 = MemorySegment.ofArray(bytearray0); - final FrequentLongsSketch sk2 = FrequentLongsSketch.getInstance(seg0); - - checkEquality(sk1, sk2); - } - - @Test - public void checkFreqLongsStringSerDe() { - final int minSize = 1 << LG_MIN_MAP_SIZE; - final FrequentLongsSketch sk1 = new FrequentLongsSketch(minSize); - sk1.update(10, 100); - sk1.update(10, 100); - sk1.update(15, 3443); - sk1.update(1000001, 1010230); - sk1.update(1000002, 1010230); - - final String string1 = sk1.serializeToString(); - final FrequentLongsSketch sk2 = FrequentLongsSketch.getInstance(string1); - - checkEquality(sk1, sk2); - } - - private static void checkEquality(final FrequentLongsSketch sk1, final FrequentLongsSketch sk2) { - assertEquals(sk1.getNumActiveItems(), sk2.getNumActiveItems()); - assertEquals(sk1.getCurrentMapCapacity(), sk2.getCurrentMapCapacity()); - assertEquals(sk1.getMaximumError(), sk2.getMaximumError()); - assertEquals(sk1.getMaximumMapCapacity(), sk2.getMaximumMapCapacity()); - assertEquals(sk1.getStorageBytes(), sk2.getStorageBytes()); - assertEquals(sk1.getStreamLength(), sk2.getStreamLength()); - assertEquals(sk1.isEmpty(), sk2.isEmpty()); - - final ErrorType NFN = ErrorType.NO_FALSE_NEGATIVES; - final ErrorType NFP = ErrorType.NO_FALSE_POSITIVES; - Row[] rowArr1 = sk1.getFrequentItems(NFN); - Row[] rowArr2 = sk2.getFrequentItems(NFN); - assertEquals(sk1.getFrequentItems(NFN).length, sk2.getFrequentItems(NFN).length); - for (int i=0; i threshold); - } - - rows = sketches[h].getFrequentItems(ErrorType.NO_FALSE_POSITIVES); - for (int i = 0; i < rows.length; i++) { - Assert.assertTrue(rows[i].getLowerBound() > threshold); - } - - rows = sketches[h].getFrequentItems(Long.MAX_VALUE, ErrorType.NO_FALSE_POSITIVES); - Assert.assertEquals(rows.length, 0); - } - } - - @Test - public void updateOneTime() { - final int size = 100; - final double error_tolerance = 1.0 / size; - //double delta = .01; - final int numSketches = 1; - for (int h = 0; h < numSketches; h++) { - final FrequentLongsSketch sketch = newFrequencySketch(error_tolerance); - Assert.assertEquals(sketch.getUpperBound(13L), 0); - Assert.assertEquals(sketch.getLowerBound(13L), 0); - Assert.assertEquals(sketch.getMaximumError(), 0); - Assert.assertEquals(sketch.getEstimate(13L), 0); - sketch.update(13L); - // Assert.assertEquals(sketch.getEstimate(13L), 1); - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkGetInstanceMemorySegment() { - final MemorySegment seg = MemorySegment.ofArray(new byte[4]); - FrequentLongsSketch.getInstance(seg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkGetInstanceString() { - final String s = ""; - FrequentLongsSketch.getInstance(s); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkUpdateNegative() { - final int minSize = 1 << LG_MIN_MAP_SIZE; - final FrequentLongsSketch fls = new FrequentLongsSketch(minSize); - fls.update(1, 0); - fls.update(1, -1); - } - - @SuppressWarnings("unlikely-arg-type") - @Test - public void checkGetFrequentItems1() { - final int minSize = 1 << LG_MIN_MAP_SIZE; - final FrequentLongsSketch fis = new FrequentLongsSketch(minSize); - fis.update(1); - final Row[] rowArr = fis.getFrequentItems(ErrorType.NO_FALSE_POSITIVES); - final Row row = rowArr[0]; - assertTrue(row.hashCode() != 0); - assertTrue(row.equals(row)); - assertFalse(row.equals(fis)); - assertNotNull(row); - assertEquals(row.est, 1L); - assertEquals(row.item, 1L); - assertEquals(row.lb, 1L); - assertEquals(row.ub, 1L); - Row newRow = new Row(row.item, row.est+1, row.ub, row.lb); - assertFalse(row.equals(newRow)); - newRow = new Row(row.item, row.est, row.ub, row.lb); - assertTrue(row.equals(newRow)); - - } - - @Test - public void checkGetStorageBytes() { - final int minSize = 1 << LG_MIN_MAP_SIZE; - final FrequentLongsSketch fls = new FrequentLongsSketch(minSize); - assertEquals(fls.toByteArray().length, fls.getStorageBytes()); - fls.update(1); - assertEquals(fls.toByteArray().length, fls.getStorageBytes()); - } - - @Test - public void checkDeSerFromStringArray() { - final int minSize = 1 << LG_MIN_MAP_SIZE; - final FrequentLongsSketch fls = new FrequentLongsSketch(minSize); - String ser = fls.serializeToString(); - println(ser); - fls.update(1); - ser = fls.serializeToString(); - println(ser); - } - - @Test - public void checkMerge() { - final int minSize = 1 << LG_MIN_MAP_SIZE; - final FrequentLongsSketch fls1 = new FrequentLongsSketch(minSize); - FrequentLongsSketch fls2 = null; - FrequentLongsSketch fle = fls1.merge(fls2); - assertTrue(fle.isEmpty()); - - fls2 = new FrequentLongsSketch(minSize); - fle = fls1.merge(fls2); - assertTrue(fle.isEmpty()); - } - - @Test - public void checkSortItems() { - final int numSketches = 1; - final int n = 2222; - final double error_tolerance = 1.0/100; - final int sketchSize = Util.ceilingPowerOf2((int) (1.0 /(error_tolerance*ReversePurgeLongHashMap.getLoadFactor()))); - //println("sketchSize: "+sketchSize); - - final FrequentLongsSketch[] sketches = new FrequentLongsSketch[numSketches]; - for (int h = 0; h < numSketches; h++) { - sketches[h] = new FrequentLongsSketch(sketchSize); - } - - long item; - final double prob = .001; - for (int i = 0; i < n; i++) { - item = randomGeometricDist(prob) + 1; - for (int h = 0; h < numSketches; h++) { - sketches[h].update(item); - } - } - - for(int h=0; h threshold); - } - final Row first = rows[0]; - final long anItem = first.getItem(); - final long anEst = first.getEstimate(); - final long aLB = first.getLowerBound(); - final String s = first.toString(); - println(s); - assertTrue(anEst >= 0); - assertTrue(aLB >= 0); - assertEquals(anItem, anItem); //dummy test - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkGetAndCheckPreLongs() { - final byte[] byteArr = new byte[8]; - byteArr[0] = (byte) 2; - PreambleUtil.checkPreambleSize(MemorySegment.ofArray(byteArr)); - } - - @Test - public void checkToString1() { - final int size = 1 << LG_MIN_MAP_SIZE; - printSketch(size, new long[] {1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5}); - printSketch(size, new long[] {5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1}); - } - - @Test - public void checkStringDeserEmptyNotCorrupt() { - final int size = 1 << LG_MIN_MAP_SIZE; - final int thresh = (size * 3) / 4; - final String fmt = "%6d%10s%s"; - final FrequentLongsSketch fls = new FrequentLongsSketch(size); - println("Sketch Size: " + size); - String s = null; - int i = 0; - for ( ; i <= thresh; i++) { - fls.update(i+1, 1); - s = fls.serializeToString(); - println(String.format("SER " + fmt, (i + 1), fls.isEmpty() + " : ", s )); - final FrequentLongsSketch fls2 = FrequentLongsSketch.getInstance(s); - println(String.format("DESER " + fmt, (i + 1), fls2.isEmpty() + " : ", s )); - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkStringDeserEmptyCorrupt() { - final String s = "1," //serVer - + "10," //FamID - + "3," //lgMaxMapSz - + "0," //Empty Flag = false ... corrupted, should be true - + "7," //stream Len so far - + "1," //error offset - + "0," //numActive ...conflict with empty - + "8,"; //curMapLen - FrequentLongsSketch.getInstance(s); - } - - @Test - public void checkGetEpsilon() { - assertEquals(FrequentLongsSketch.getEpsilon(1024), 3.5 / 1024, 0.0); - try { - FrequentLongsSketch.getEpsilon(1000); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkGetAprioriError() { - final double eps = 3.5 / 1024; - assertEquals(FrequentLongsSketch.getAprioriError(1024, 10_000), eps * 10_000); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - //Restricted methods - - public void printSketch(final int size, final long[] freqArr) { - final FrequentLongsSketch fls = new FrequentLongsSketch(size); - final StringBuilder sb = new StringBuilder(); - for (int i = 0; i 0) { //check equals null case - final Row nullRow = null; - assertFalse(rows[0].equals(nullRow)); - } - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.err.println(s); //disable here - } - - private static FrequentLongsSketch newFrequencySketch(final double eps) { - final double loadFactor = ReversePurgeLongHashMap.getLoadFactor(); - final int maxMapSize = Util.ceilingPowerOf2((int) (1.0 /(eps*loadFactor))); - return new FrequentLongsSketch(maxMapSize); - } - -} diff --git a/src/test/java/org/apache/datasketches/frequencies/ReversePurgeLongHashMapTest.java b/src/test/java/org/apache/datasketches/frequencies/ReversePurgeLongHashMapTest.java deleted file mode 100644 index b4524a25a..000000000 --- a/src/test/java/org/apache/datasketches/frequencies/ReversePurgeLongHashMapTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -import static org.testng.Assert.assertNull; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.frequencies.ReversePurgeLongHashMap; -import org.testng.annotations.Test; - -public class ReversePurgeLongHashMapTest { - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkgetInstanceString() { - ReversePurgeLongHashMap.getInstance(""); - } - - @Test - public void checkActiveNull() { - ReversePurgeLongHashMap map = new ReversePurgeLongHashMap(4); - assertNull(map.getActiveKeys()); - assertNull(map.getActiveValues()); - } - -} diff --git a/src/test/java/org/apache/datasketches/frequencies/SerDeCompatibilityTest.java b/src/test/java/org/apache/datasketches/frequencies/SerDeCompatibilityTest.java deleted file mode 100644 index c314a51e6..000000000 --- a/src/test/java/org/apache/datasketches/frequencies/SerDeCompatibilityTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.frequencies; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.ArrayOfLongsSerDe; -import org.apache.datasketches.frequencies.FrequentItemsSketch; -import org.apache.datasketches.frequencies.FrequentLongsSketch; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class SerDeCompatibilityTest { - - static final ArrayOfItemsSerDe serDe = new ArrayOfLongsSerDe(); - - @Test - public void itemsToLongs() { - final FrequentItemsSketch sketch1 = new FrequentItemsSketch<>(8); - sketch1.update(1L); - sketch1.update(2L); - sketch1.update(3L); - sketch1.update(4L); - - final byte[] bytes = sketch1.toByteArray(serDe); - final FrequentLongsSketch sketch2 = FrequentLongsSketch.getInstance(MemorySegment.ofArray(bytes)); - sketch2.update(2L); - sketch2.update(3L); - sketch2.update(2L); - - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertEquals(sketch2.getNumActiveItems(), 4); - Assert.assertEquals(sketch2.getStreamLength(), 7); - Assert.assertEquals(sketch2.getEstimate(1L), 1); - Assert.assertEquals(sketch2.getEstimate(2L), 3); - Assert.assertEquals(sketch2.getEstimate(3L), 2); - Assert.assertEquals(sketch2.getEstimate(4L), 1); - } - - @Test - public void longsToItems() { - final FrequentLongsSketch sketch1 = new FrequentLongsSketch(8); - sketch1.update(1L); - sketch1.update(2L); - sketch1.update(3L); - sketch1.update(4L); - - final byte[] bytes = sketch1.toByteArray(); - final FrequentItemsSketch sketch2 = FrequentItemsSketch.getInstance(MemorySegment.ofArray(bytes), serDe); - sketch2.update(2L); - sketch2.update(3L); - sketch2.update(2L); - - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertEquals(sketch2.getNumActiveItems(), 4); - Assert.assertEquals(sketch2.getStreamLength(), 7); - Assert.assertEquals(sketch2.getEstimate(1L), 1); - Assert.assertEquals(sketch2.getEstimate(2L), 3); - Assert.assertEquals(sketch2.getEstimate(3L), 2); - Assert.assertEquals(sketch2.getEstimate(4L), 1); - } - -} diff --git a/src/test/java/org/apache/datasketches/hash/MurmurHash3FFMTest.java b/src/test/java/org/apache/datasketches/hash/MurmurHash3FFMTest.java deleted file mode 100644 index 4e2bb00e7..000000000 --- a/src/test/java/org/apache/datasketches/hash/MurmurHash3FFMTest.java +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hash; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_CHAR_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.Random; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class MurmurHash3FFMTest { - private final Random rand = new Random(); - private static final int trials = 1 << 20; - - @Test - public void compareLongArrLong() { //long[] - final int arrLen = 3; - final int iPer = 8 / Long.BYTES; - final long[] key = new long[arrLen]; - for (int i = 0; i < trials; i++) { //trials - for (int j = 0; j < (arrLen / iPer); j++) { //longs - final long r = rand.nextLong(); - key[j] = r; - } - final long[] res1 = hashV1(key, 0); - final long[] res2 = hashV2(key, 0); - assertEquals(res2, res1); - } - } - - @Test - public void compareIntArr() { //int[] - final int bytes = Integer.BYTES; - final int arrLen = 6; - final int[] key = new int[arrLen]; - final int iPer = 8 / bytes; - final int nLongs = arrLen / iPer; - final int shift = 64 / iPer; - - for (int i = 0; i < trials; i++) { //trials - for (int j = 0; j < nLongs; j++) { //longs - final long r = rand.nextLong(); - for (int k = 0; k < iPer; k++) { //ints - final int shft = k * shift; - key[k] = (int) (r >>> shft); - } - } - final long[] res1 = hashV1(key, 0); - final long[] res2 = hashV2(key, 0); - assertEquals(res2, res1); - } - } - - @Test - public void compareCharArr() { //char[] - final int bytes = Character.BYTES; - final int arrLen = 12; - final char[] key = new char[arrLen]; - final int iPer = 8 / bytes; - final int nLongs = arrLen / iPer; - final int shift = 64 / iPer; - - for (int i = 0; i < trials; i++) { //trials - for (int j = 0; j < nLongs; j++) { //longs - final long r = rand.nextLong(); - for (int k = 0; k < iPer; k++) { //char - final int shft = k * shift; - key[k] = (char) (r >>> shft); - } - } - final long[] res1 = hashV1(key, 0); - final long[] res2 = hashV2(key, 0); - assertEquals(res2, res1); - } - } - - @Test - public void compareByteArr() { //byte[] - final int bytes = Byte.BYTES; - final int arrLen = 12; - final byte[] key = new byte[arrLen]; - final int iPer = 8 / bytes; - final int nLongs = arrLen / iPer; - final int shift = 64 / iPer; - - for (int i = 0; i < trials; i++) { //trials - for (int j = 0; j < nLongs; j++) { //longs - final long r = rand.nextLong(); - for (int k = 0; k < iPer; k++) { //bytes - final int shft = k * shift; - key[k] = (byte) (r >>> shft); - } - } - final long[] res1 = hashV1(key, 0); - final long[] res2 = hashV2(key, 0); - assertEquals(res2, res1); - } - } - - @Test - public void compareLongVsLongArr() { - final int arrLen = 1; - final long[] key = new long[arrLen]; - final long[] out = new long[2]; - for (int i = 0; i < trials; i++) { //trials - final long r = rand.nextLong(); - key[0] = r; - final long[] res1 = hashV1(key, 0); - final long[] res2 = hashV2(r, 0, out); - assertEquals(res2, res1); - } - } - - private static final long[] hashV1(final long[] key, final long seed) { - return MurmurHash3.hash(key, seed); - } - - private static final long[] hashV1(final int[] key, final long seed) { - return MurmurHash3.hash(key, seed); - } - - private static final long[] hashV1(final char[] key, final long seed) { - return MurmurHash3.hash(key, seed); - } - - private static final long[] hashV1(final byte[] key, final long seed) { - return MurmurHash3.hash(key, seed); - } - - private static final long[] hashV2(final long[] key, final long seed) { - return MurmurHash3FFM.hash(key, seed); - } - - private static final long[] hashV2(final int[] key2, final long seed) { - return MurmurHash3FFM.hash(key2, seed); - } - - private static final long[] hashV2(final char[] key, final long seed) { - return MurmurHash3FFM.hash(key, seed); - } - - private static final long[] hashV2(final byte[] key, final long seed) { - return MurmurHash3FFM.hash(key, seed); - } - - //V2 single primitives - - private static final long[] hashV2(final long key, final long seed, final long[] out) { - return MurmurHash3FFM.hash(key, seed, out); - } - -// private static final long[] hashV2(double key, long seed, long[] out) { -// return MurmurHash3v4.hash(key, seed, out); -// } - -// private static final long[] hashV2(String key, long seed, long[] out) { -// return MurmurHash3v4.hash(key, seed, out); -// } - - @Test - public void offsetChecks() { - final long seed = 12345; - final int blocks = 6; - final int cap = blocks * 16; - - long[] hash1 = new long[2]; - long[] hash2; - - final MemorySegment wseg = MemorySegment.ofArray(new byte[cap]); - for (int i = 0; i < cap; i++) { wseg.set(JAVA_BYTE, i, (byte)(-128 + i)); } - - for (int offset = 0; offset < 16; offset++) { - final int arrLen = cap - offset; - hash1 = MurmurHash3FFM.hash(wseg, offset, arrLen, seed, hash1); - final byte[] byteArr2 = new byte[arrLen]; - MemorySegment.copy(wseg, JAVA_BYTE, offset, byteArr2, 0, arrLen); - hash2 = MurmurHash3.hash(byteArr2, seed); - assertEquals(hash1, hash2); - } - } - - @Test - public void byteArrChecks() { - final long seed = 0; - final int offset = 0; - final int bytes = 1024; - - long[] hash2 = new long[2]; - - for (int j = 1; j < bytes; j++) { - final byte[] in = new byte[bytes]; - - final MemorySegment wseg = MemorySegment.ofArray(in); - for (int i = 0; i < j; i++) { wseg.set(JAVA_BYTE, i, (byte) (-128 + i)); } - - final long[] hash1 = MurmurHash3.hash(in, seed); - hash2 = MurmurHash3FFM.hash(wseg, offset, bytes, seed, hash2); - final long[] hash3 = MurmurHash3FFM.hash(in, seed); - - assertEquals(hash1, hash2); - assertEquals(hash1, hash3); - } - } - - @Test - public void charArrChecks() { - final long seed = 0; - final int offset = 0; - final int chars = 16; - final int bytes = chars << 1; - - long[] hash2 = new long[2]; - - for (int j = 1; j < chars; j++) { - final char[] in = new char[chars]; - - final MemorySegment wseg = MemorySegment.ofArray(in); - for (int i = 0; i < j; i++) { wseg.set(JAVA_INT_UNALIGNED, i, i); } - - final long[] hash1 = MurmurHash3.hash(in, 0); - hash2 = MurmurHash3FFM.hash(wseg, offset, bytes, seed, hash2); - final long[] hash3 = MurmurHash3FFM.hash(in, seed); - - assertEquals(hash1, hash2); - assertEquals(hash1, hash3); - } - } - - @Test - public void intArrChecks() { - final long seed = 0; - final int offset = 0; - final int ints = 16; - final int bytes = ints << 2; - - long[] hash2 = new long[2]; - - for (int j = 1; j < ints; j++) { - final int[] in = new int[ints]; - - final MemorySegment wseg = MemorySegment.ofArray(in); - for (int i = 0; i < j; i++) { wseg.set(JAVA_INT_UNALIGNED, i, i); } - - final long[] hash1 = MurmurHash3.hash(in, 0); - hash2 = MurmurHash3FFM.hash(wseg, offset, bytes, seed, hash2); - final long[] hash3 = MurmurHash3FFM.hash(in, seed); - - assertEquals(hash1, hash2); - assertEquals(hash1, hash3); - } - } - - @Test - public void longArrChecks() { - final long seed = 0; - final int offset = 0; - final int longs = 16; - final int bytes = longs << 3; - - long[] hash2 = new long[2]; - - for (int j = 1; j < longs; j++) { - final long[] in = new long[longs]; - - final MemorySegment wseg = MemorySegment.ofArray(in); - for (int i = 0; i < j; i++) { wseg.set(JAVA_LONG_UNALIGNED, i, i); } - - final long[] hash1 = MurmurHash3.hash(in, 0); - hash2 = MurmurHash3FFM.hash(wseg, offset, bytes, seed, hash2); - final long[] hash3 = MurmurHash3FFM.hash(in, seed); - - assertEquals(hash1, hash2); - assertEquals(hash1, hash3); - } - } - - @Test - public void longCheck() { - final long seed = 0; - final int offset = 0; - final int bytes = 8; - - long[] hash2 = new long[2]; - final long[] in = { 1 }; - final MemorySegment wseg = MemorySegment.ofArray(in); - - final long[] hash1 = MurmurHash3.hash(in, 0); - hash2 = MurmurHash3FFM.hash(wseg, offset, bytes, seed, hash2); - final long[] hash3 = MurmurHash3FFM.hash(in, seed); - - assertEquals(hash1, hash2); - assertEquals(hash1, hash3); - } - - @Test - public void checkEmptiesNulls() { - final long seed = 123; - final long[] hashOut = new long[2]; - try { - MurmurHash3FFM.hash(MemorySegment.ofArray(new long[0]), 0, 0, seed, hashOut); //seg empty - fail(); - } catch (final IllegalArgumentException e) { } //OK - try { - final String s = ""; - MurmurHash3FFM.hash(s, seed, hashOut); //string empty - fail(); - } catch (final IllegalArgumentException e) { } //OK - try { - final String s = null; - MurmurHash3FFM.hash(s, seed, hashOut); //string null - fail(); - } catch (final IllegalArgumentException e) { } //OK - try { - final byte[] barr = {}; - MurmurHash3FFM.hash(barr, seed); //byte[] empty - fail(); - } catch (final IllegalArgumentException e) { } //OK - try { - final byte[] barr = null; - MurmurHash3FFM.hash(barr, seed); //byte[] null - fail(); - } catch (final IllegalArgumentException e) { } //OK - try { - final char[] carr = {}; - MurmurHash3FFM.hash(carr, seed); //char[] empty - fail(); - } catch (final IllegalArgumentException e) { } //OK - try { - final char[] carr = null; - MurmurHash3FFM.hash(carr, seed); //char[] null - fail(); - } catch (final IllegalArgumentException e) { } //OK - try { - final int[] iarr = {}; - MurmurHash3FFM.hash(iarr, seed); //int[] empty - fail(); - } catch (final IllegalArgumentException e) { } //OK - try { - final int[] iarr = null; - MurmurHash3FFM.hash(iarr, seed); //int[] null - fail(); - } catch (final IllegalArgumentException e) { } //OK - try { - final long[] larr = {}; - MurmurHash3FFM.hash(larr, seed); //long[] empty - fail(); - } catch (final IllegalArgumentException e) { } //OK - try { - final long[] larr = null; - MurmurHash3FFM.hash(larr, seed); //long[] null - fail(); - } catch (final IllegalArgumentException e) { } //OK - } - - @Test - public void checkStringLong() { - final long seed = 123; - final long[] hashOut = new long[2]; - final String s = "123"; - assertTrue(MurmurHash3FFM.hash(s, seed, hashOut)[0] != 0); - final long v = 123; - assertTrue(MurmurHash3FFM.hash(v, seed, hashOut)[0] != 0); - } - - @Test - public void doubleCheck() { - long[] hash1 = checkDouble(-0.0); - long[] hash2 = checkDouble(0.0); - assertEquals(hash1, hash2); - hash1 = checkDouble(Double.NaN); - final long nan = (0x7FFL << 52) + 1L; - hash2 = checkDouble(Double.longBitsToDouble(nan)); - assertEquals(hash1, hash2); - checkDouble(1.0); - } - - private static long[] checkDouble(final double dbl) { - final long seed = 0; - final int offset = 0; - final int bytes = 8; - - long[] hash2 = new long[2]; - - final double d = (dbl == 0.0) ? 0.0 : dbl; // canonicalize -0.0, 0.0 - final long data = Double.doubleToLongBits(d);// canonicalize all NaN forms - final long[] dataArr = { data }; - - final MemorySegment wseg = MemorySegment.ofArray(dataArr); - final long[] hash1 = MurmurHash3.hash(dataArr, 0); - hash2 = MurmurHash3FFM.hash(wseg, offset, bytes, seed, hash2); - final long[] hash3 = MurmurHash3FFM.hash(dbl, seed, hash2); - - assertEquals(hash1, hash2); - assertEquals(hash1, hash3); - return hash1; - } - -} diff --git a/src/test/java/org/apache/datasketches/hash/MurmurHash3FFMbTest.java b/src/test/java/org/apache/datasketches/hash/MurmurHash3FFMbTest.java deleted file mode 100644 index ab61a33a2..000000000 --- a/src/test/java/org/apache/datasketches/hash/MurmurHash3FFMbTest.java +++ /dev/null @@ -1,413 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hash; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.datasketches.hash.MurmurHash3FFM.hash; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; - -import org.testng.Assert; -import org.testng.annotations.Test; - -/** - * Tests the MurmurHash3 against specific, known hash results given known - * inputs obtained from the public domain C++ version 150. - * - * @author Lee Rhodes - */ -public class MurmurHash3FFMbTest { - - @Test - public void checkByteArrRemainderGT8() { //byte[], remainder > 8 - final String keyStr = "The quick brown fox jumps over the lazy dog"; - final byte[] key = keyStr.getBytes(UTF_8); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0xe34bbc7bbc071b6cL; - final long h2 = 0x7a433ca9c49a9347L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkByteArrRemainderGT8withSegment() { //byte[], remainder > 8 - final String keyStr = "The quick brown fox jumps over the lazy dog"; - final byte[] key = keyStr.getBytes(UTF_8); - final long[] out = new long[2]; - final MemorySegment seg = MemorySegment.ofArray(key); - final long[] result = hash(seg, 0, seg.byteSize(), 0, out); - //Should be: - final long h1 = 0xe34bbc7bbc071b6cL; - final long h2 = 0x7a433ca9c49a9347L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkByteArrChange1bit() { //byte[], change one bit - final String keyStr = "The quick brown fox jumps over the lazy eog"; - final byte[] key = keyStr.getBytes(UTF_8); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0x362108102c62d1c9L; - final long h2 = 0x3285cd100292b305L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkByteArrRemainderLt8() { //byte[], test a remainder < 8 - final String keyStr = "The quick brown fox jumps over the lazy dogdogdog"; - final byte[] key = keyStr.getBytes(UTF_8); - final long[] result = hash(key, 0); - //Should be; - final long h1 = 0x9c8205300e612fc4L; - final long h2 = 0xcbc0af6136aa3df9L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkByteArrReaminderEQ8() { //byte[], test a remainder = 8 - final String keyStr = "The quick brown fox jumps over the lazy1"; - final byte[] key = keyStr.getBytes(UTF_8); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0xe3301a827e5cdfe3L; - final long h2 = 0xbdbf05f8da0f0392L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - /** - * This test should have the exact same output as Test4 - */ - @Test - public void checkLongArrRemainderEQ8() { //long[], test a remainder = 8 - final String keyStr = "The quick brown fox jumps over the lazy1"; - final long[] key = stringToLongs(keyStr); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0xe3301a827e5cdfe3L; - final long h2 = 0xbdbf05f8da0f0392L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - /** - * This test should have the exact same output as Test4 - */ - @Test - public void checkIntArrRemainderEQ8() { //int[], test a remainder = 8 - final String keyStr = "The quick brown fox jumps over the lazy1"; //40B - final int[] key = stringToInts(keyStr); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0xe3301a827e5cdfe3L; - final long h2 = 0xbdbf05f8da0f0392L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkIntArrRemainderEQ0() { //int[], test a remainder = 0 - final String keyStr = "The quick brown fox jumps over t"; //32B - final int[] key = stringToInts(keyStr); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0xdf6af91bb29bdacfL; - final long h2 = 0x91a341c58df1f3a6L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - /** - * Tests an odd remainder of int[]. - */ - @Test - public void checkIntArrOddRemainder() { //int[], odd remainder - final String keyStr = "The quick brown fox jumps over the lazy dog"; //43B - final int[] key = stringToInts(keyStr); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0x1eb232b0087543f5L; - final long h2 = 0xfc4c1383c3ace40fL; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - /** - * Tests an odd remainder of int[]. - */ - @Test - public void checkCharArrOddRemainder() { //char[], odd remainder - final String keyStr = "The quick brown fox jumps over the lazy dog.."; //45B - final char[] key = keyStr.toCharArray(); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0xca77b498ea9ed953L; - final long h2 = 0x8b8f8ec3a8f4657eL; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - /** - * Tests an odd remainder of int[]. - */ - @Test - public void checkCharArrRemainderEQ0() { //char[], remainder of 0 - final String keyStr = "The quick brown fox jumps over the lazy "; //40B - final char[] key = keyStr.toCharArray(); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0x51b15e9d0887f9f1L; - final long h2 = 0x8106d226786511ebL; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkByteArrAllOnesZeros() { //byte[], test a ones byte and a zeros byte - final byte[] key = { - 0x54, 0x68, 0x65, 0x20, 0x71, 0x75, 0x69, 0x63, 0x6b, 0x20, 0x62, 0x72, 0x6f, 0x77, 0x6e, - 0x20, 0x66, 0x6f, 0x78, 0x20, 0x6a, 0x75, 0x6d, 0x70, 0x73, 0x20, 0x6f, 0x76, 0x65, - 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6c, 0x61, 0x7a, 0x79, 0x20, 0x64, 0x6f, 0x67, - (byte) 0xff, 0x64, 0x6f, 0x67, 0x00 - }; - final long[] result = MurmurHash3FFM.hash(key, 0); - //Should be: - final long h1 = 0xe88abda785929c9eL; - final long h2 = 0x96b98587cacc83d6L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - /** - * This test demonstrates that the hash of byte[], char[], int[], or long[] will produce the - * same hash result if, and only if, all the arrays have the same exact length in bytes, and if - * the contents of the values in the arrays have the same byte endianness and overall order. - */ - @Test - public void checkCrossTypeHashConsistency() { - long[] out; - println("Bytes"); - final byte[] bArr = {1,2,3,4,5,6,7,8, 9,10,11,12,13,14,15,16, 17,18,19,20,21,22,23,24}; - final long[] out1 = hash(bArr, 0L); - println(longToHexBytes(out1[0])); - println(longToHexBytes(out1[1])); - - println("Chars"); - final char[] cArr = {0X0201, 0X0403, 0X0605, 0X0807, 0X0a09, 0X0c0b, 0X0e0d, 0X100f, - 0X1211, 0X1413, 0X1615, 0X1817}; - out = hash(cArr, 0L); - Assert.assertEquals(out, out1); - println(longToHexBytes(out[0])); - println(longToHexBytes(out[1])); - - println("Ints"); - final int[] iArr = {0X04030201, 0X08070605, 0X0c0b0a09, 0X100f0e0d, 0X14131211, 0X18171615}; - out = hash(iArr, 0L); - Assert.assertEquals(out, out1); - println(longToHexBytes(out[0])); - println(longToHexBytes(out[1])); - - println("Longs"); - final long[] lArr = {0X0807060504030201L, 0X100f0e0d0c0b0a09L, 0X1817161514131211L}; - out = hash(lArr, 0L); - Assert.assertEquals(out, out1); - println(longToHexBytes(out[0])); - println(longToHexBytes(out[1])); - } - - @Test - public void checkEmptyOrNullExceptions() { - try { - final long[] arr = null; - hash(arr, 1L); - fail(); - } - catch (final IllegalArgumentException e) { } - try { - final int[] arr = null; hash(arr, 1L); fail(); - } catch (final IllegalArgumentException e) { } - try { - final char[] arr = null; hash(arr, 1L); fail(); - } catch (final IllegalArgumentException e) { } - try { - final byte[] arr = null; hash(arr, 1L); fail(); - } catch (final IllegalArgumentException e) { } - - long[] out = new long[2]; - try { - final String in = null; hash(in, 1L, out); fail(); - } catch (final IllegalArgumentException e) { } - try { - final MemorySegment seg = MemorySegment.ofArray(new byte[0]); - hash(seg, 0L, 4L, 1L, out); - } catch (final IllegalArgumentException e) { } - try (Arena arena = Arena.ofConfined()) { - final MemorySegment seg = arena.allocate(8); - out = hash(seg, 0L, 4L, 1L, out); - } - assertTrue((out[0] != 0) && (out[1] != 0)); - } - - @Test - public void checkHashTails() { - long[] out = new long[2]; - final MemorySegment seg = MemorySegment.ofArray(new byte[32]); - seg.fill((byte)85); - - for (int i = 16; i <= 32; i++) { - out = hash(seg, 0, i, 1L, out); - } - } - - @Test - public void checkSinglePrimitives() { - long[] out = new long[2]; - out = hash(1L, 1L, out); - out = hash(0.0, 1L, out); - out = hash("123", 1L, out); - } - - //Helper methods - - private static long[] stringToLongs(final String in) { - final byte[] bArr = in.getBytes(UTF_8); - final int inLen = bArr.length; - final int outLen = (inLen / 8) + (((inLen % 8) != 0) ? 1 : 0); - final long[] out = new long[outLen]; - - for (int i = 0; i < (outLen - 1); i++ ) { - for (int j = 0; j < 8; j++ ) { - out[i] |= ((bArr[(i * 8) + j] & 0xFFL) << (j * 8)); - } - } - final int inTail = 8 * (outLen - 1); - final int rem = inLen - inTail; - for (int j = 0; j < rem; j++ ) { - out[outLen - 1] |= ((bArr[inTail + j] & 0xFFL) << (j * 8)); - } - return out; - } - - private static int[] stringToInts(final String in) { - final byte[] bArr = in.getBytes(UTF_8); - final int inLen = bArr.length; - final int outLen = (inLen / 4) + (((inLen % 4) != 0) ? 1 : 0); - final int[] out = new int[outLen]; - - for (int i = 0; i < (outLen - 1); i++ ) { - for (int j = 0; j < 4; j++ ) { - out[i] |= ((bArr[(i * 4) + j] & 0xFFL) << (j * 8)); - } - } - final int inTail = 4 * (outLen - 1); - final int rem = inLen - inTail; - for (int j = 0; j < rem; j++ ) { - out[outLen - 1] |= ((bArr[inTail + j] & 0xFFL) << (j * 8)); - } - return out; - } - - /** - * Returns a string of spaced hex bytes in Big-Endian order. - * @param v the given long - * @return string of spaced hex bytes in Big-Endian order. - */ - private static String longToHexBytes(final long v) { - final long mask = 0XFFL; - final StringBuilder sb = new StringBuilder(); - for (int i = 8; i-- > 0; ) { - final String s = Long.toHexString((v >>> (i * 8)) & mask); - sb.append(zeroPad(s, 2)).append(" "); - } - return sb.toString(); - } - - /** - * Prepend the given string with zeros. If the given string is equal or greater than the given - * field length, it will be returned without modification. - * @param s the given string - * @param fieldLength desired total field length including the given string - * @return the given string prepended with zeros. - */ - private static final String zeroPad(final String s, final int fieldLength) { - return characterPad(s, fieldLength, '0', false); - } - - /** - * Prepend or postpend the given string with the given character to fill the given field length. - * If the given string is equal or greater than the given field length, it will be returned - * without modification. - * @param s the given string - * @param fieldLength the desired field length - * @param padChar the desired pad character - * @param postpend if true append the padCharacters to the end of the string. - * @return prepended or postpended given string with the given character to fill the given field - * length. - */ - private static final String characterPad(final String s, final int fieldLength, final char padChar, - final boolean postpend) { - final char[] chArr = s.toCharArray(); - final int sLen = chArr.length; - if (sLen < fieldLength) { - final char[] out = new char[fieldLength]; - final int blanks = fieldLength - sLen; - - if (postpend) { - for (int i = 0; i < sLen; i++) { - out[i] = chArr[i]; - } - for (int i = sLen; i < fieldLength; i++) { - out[i] = padChar; - } - } else { //prepend - for (int i = 0; i < blanks; i++) { - out[i] = padChar; - } - for (int i = blanks; i < fieldLength; i++) { - out[i] = chArr[i - blanks]; - } - } - - return String.valueOf(out); - } - return s; - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hash/MurmurHash3Test.java b/src/test/java/org/apache/datasketches/hash/MurmurHash3Test.java deleted file mode 100644 index b16b34629..000000000 --- a/src/test/java/org/apache/datasketches/hash/MurmurHash3Test.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hash; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.datasketches.common.Util.longToHexBytes; -import static org.apache.datasketches.hash.MurmurHash3.hash; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import org.testng.Assert; -import org.testng.annotations.Test; - -/** - * Tests the MurmurHash3 against specific, known hash results given known - * inputs obtained from the public domain C++ version 150. - * - * @author Lee Rhodes - */ -public class MurmurHash3Test { - - @Test - public void checkByteArrRemainderGT8() { //byte[], remainder > 8 - final String keyStr = "The quick brown fox jumps over the lazy dog"; - final byte[] key = keyStr.getBytes(UTF_8); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0xe34bbc7bbc071b6cL; - final long h2 = 0x7a433ca9c49a9347L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkByteBufRemainderGT8() { //byte buffer, remainder > 8 - final String keyStr = "The quick brown fox jumps over the lazy dog"; - final byte[] key = keyStr.getBytes(UTF_8); - - //Should be: - final long h1 = 0xe34bbc7bbc071b6cL; - final long h2 = 0x7a433ca9c49a9347L; - - checkHashByteBuf(key, h1, h2); - } - - @Test - public void checkByteArrChange1bit() { //byte[], change one bit - final String keyStr = "The quick brown fox jumps over the lazy eog"; - final byte[] key = keyStr.getBytes(UTF_8); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0x362108102c62d1c9L; - final long h2 = 0x3285cd100292b305L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkByteBufChange1bit() { //byte buffer, change one bit - final String keyStr = "The quick brown fox jumps over the lazy eog"; - final byte[] key = keyStr.getBytes(UTF_8); - - //Should be: - final long h1 = 0x362108102c62d1c9L; - final long h2 = 0x3285cd100292b305L; - - checkHashByteBuf(key, h1, h2); - } - - @Test - public void checkByteArrRemainderLt8() { //byte[], test a remainder < 8 - final String keyStr = "The quick brown fox jumps over the lazy dogdogdog"; - final byte[] key = keyStr.getBytes(UTF_8); - final long[] result = hash(key, 0); - //Should be; - final long h1 = 0x9c8205300e612fc4L; - final long h2 = 0xcbc0af6136aa3df9L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkByteBufRemainderLt8() { //byte buffer, test a remainder < 8 - final String keyStr = "The quick brown fox jumps over the lazy dogdogdog"; - final byte[] key = keyStr.getBytes(UTF_8); - - //Should be; - final long h1 = 0x9c8205300e612fc4L; - final long h2 = 0xcbc0af6136aa3df9L; - - checkHashByteBuf(key, h1, h2); - } - - @Test - public void checkByteArrReaminderEQ8() { //byte[], test a remainder = 8 - final String keyStr = "The quick brown fox jumps over the lazy1"; - final byte[] key = keyStr.getBytes(UTF_8); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0xe3301a827e5cdfe3L; - final long h2 = 0xbdbf05f8da0f0392L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkByteBufReaminderEQ8() { //byte buffer, test a remainder = 8 - final String keyStr = "The quick brown fox jumps over the lazy1"; - final byte[] key = keyStr.getBytes(UTF_8); - - //Should be: - final long h1 = 0xe3301a827e5cdfe3L; - final long h2 = 0xbdbf05f8da0f0392L; - - checkHashByteBuf(key, h1, h2); - } - - /** - * This test should have the exact same output as Test4 - */ - @Test - public void checkLongArrRemainderEQ8() { //long[], test a remainder = 8 - final String keyStr = "The quick brown fox jumps over the lazy1"; - final long[] key = stringToLongs(keyStr); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0xe3301a827e5cdfe3L; - final long h2 = 0xbdbf05f8da0f0392L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - - } - - /** - * This test should have the exact same output as Test4 - */ - @Test - public void checkIntArrRemainderEQ8() { //int[], test a remainder = 8 - final String keyStr = "The quick brown fox jumps over the lazy1"; //40B - final int[] key = stringToInts(keyStr); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0xe3301a827e5cdfe3L; - final long h2 = 0xbdbf05f8da0f0392L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkIntArrRemainderEQ0() { //int[], test a remainder = 0 - final String keyStr = "The quick brown fox jumps over t"; //32B - final int[] key = stringToInts(keyStr); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0xdf6af91bb29bdacfL; - final long h2 = 0x91a341c58df1f3a6L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - - /** - * Tests an odd remainder of int[]. - */ - @Test - public void checkIntArrOddRemainder() { //int[], odd remainder - final String keyStr = "The quick brown fox jumps over the lazy dog"; //43B - final int[] key = stringToInts(keyStr); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0x1eb232b0087543f5L; - final long h2 = 0xfc4c1383c3ace40fL; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - - /** - * Tests an odd remainder of int[]. - */ - @Test - public void checkCharArrOddRemainder() { //char[], odd remainder - final String keyStr = "The quick brown fox jumps over the lazy dog.."; //45B - final char[] key = keyStr.toCharArray(); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0xca77b498ea9ed953L; - final long h2 = 0x8b8f8ec3a8f4657eL; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - /** - * Tests an odd remainder of int[]. - */ - @Test - public void checkCharArrRemainderEQ0() { //char[], remainder of 0 - final String keyStr = "The quick brown fox jumps over the lazy "; //40B - final char[] key = keyStr.toCharArray(); - final long[] result = hash(key, 0); - //Should be: - final long h1 = 0x51b15e9d0887f9f1L; - final long h2 = 0x8106d226786511ebL; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkByteArrAllOnesZeros() { //byte[], test a ones byte and a zeros byte - final byte[] key = { - 0x54, 0x68, 0x65, 0x20, 0x71, 0x75, 0x69, 0x63, 0x6b, 0x20, 0x62, 0x72, 0x6f, 0x77, 0x6e, - 0x20, 0x66, 0x6f, 0x78, 0x20, 0x6a, 0x75, 0x6d, 0x70, 0x73, 0x20, 0x6f, 0x76, 0x65, - 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6c, 0x61, 0x7a, 0x79, 0x20, 0x64, 0x6f, 0x67, - (byte) 0xff, 0x64, 0x6f, 0x67, 0x00 - }; - final long[] result = MurmurHash3.hash(key, 0); - - //Should be: - final long h1 = 0xe88abda785929c9eL; - final long h2 = 0x96b98587cacc83d6L; - Assert.assertEquals(result[0], h1); - Assert.assertEquals(result[1], h2); - } - - @Test - public void checkByteBufAllOnesZeros() { //byte[], test a ones byte and a zeros byte - final byte[] key = { - 0x54, 0x68, 0x65, 0x20, 0x71, 0x75, 0x69, 0x63, 0x6b, 0x20, 0x62, 0x72, 0x6f, 0x77, 0x6e, - 0x20, 0x66, 0x6f, 0x78, 0x20, 0x6a, 0x75, 0x6d, 0x70, 0x73, 0x20, 0x6f, 0x76, 0x65, - 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6c, 0x61, 0x7a, 0x79, 0x20, 0x64, 0x6f, 0x67, - (byte) 0xff, 0x64, 0x6f, 0x67, 0x00 - }; - - final long h1 = 0xe88abda785929c9eL; - final long h2 = 0x96b98587cacc83d6L; - - checkHashByteBuf(key, h1, h2); - } - - /** - * This test demonstrates that the hash of byte[], char[], int[], or long[] will produce the - * same hash result if, and only if, all the arrays have the same exact length in bytes, and if - * the contents of the values in the arrays have the same byte endianness and overall order. - */ - @Test - public void checkCrossTypeHashConsistency() { - long[] out; - println("Bytes"); - final byte[] bArr = {1,2,3,4,5,6,7,8, 9,10,11,12,13,14,15,16, 17,18,19,20,21,22,23,24}; - final long[] out1 = hash(bArr, 0L); - println(longToHexBytes(out1[0])); - println(longToHexBytes(out1[1])); - - println("ByteBuffer"); - final ByteBuffer bBuf = ByteBuffer.wrap(bArr); - out = hash(bBuf, 0L); - Assert.assertEquals(out, out1); - println(longToHexBytes(out1[0])); - println(longToHexBytes(out1[1])); - - println("Chars"); - final char[] cArr = {0X0201, 0X0403, 0X0605, 0X0807, 0X0a09, 0X0c0b, 0X0e0d, 0X100f, - 0X1211, 0X1413, 0X1615, 0X1817}; - out = hash(cArr, 0L); - Assert.assertEquals(out, out1); - println(longToHexBytes(out[0])); - println(longToHexBytes(out[1])); - - println("Ints"); - final int[] iArr = {0X04030201, 0X08070605, 0X0c0b0a09, 0X100f0e0d, 0X14131211, 0X18171615}; - out = hash(iArr, 0L); - Assert.assertEquals(out, out1); - println(longToHexBytes(out[0])); - println(longToHexBytes(out[1])); - - println("Longs"); - final long[] lArr = {0X0807060504030201L, 0X100f0e0d0c0b0a09L, 0X1817161514131211L}; - out = hash(lArr, 0L); - Assert.assertEquals(out, out1); - println(longToHexBytes(out[0])); - println(longToHexBytes(out[1])); - } - - - //Helper methods - private static long[] stringToLongs(final String in) { - final byte[] bArr = in.getBytes(UTF_8); - final int inLen = bArr.length; - final int outLen = (inLen / 8) + ((inLen % 8) != 0 ? 1 : 0); - final long[] out = new long[outLen]; - - for (int i = 0; i < (outLen - 1); i++ ) { - for (int j = 0; j < 8; j++ ) { - out[i] |= (bArr[(i * 8) + j] & 0xFFL) << (j * 8); - } - } - final int inTail = 8 * (outLen - 1); - final int rem = inLen - inTail; - for (int j = 0; j < rem; j++ ) { - out[outLen - 1] |= (bArr[inTail + j] & 0xFFL) << (j * 8); - } - return out; - } - - private static int[] stringToInts(final String in) { - final byte[] bArr = in.getBytes(UTF_8); - final int inLen = bArr.length; - final int outLen = (inLen / 4) + ((inLen % 4) != 0 ? 1 : 0); - final int[] out = new int[outLen]; - - for (int i = 0; i < (outLen - 1); i++ ) { - for (int j = 0; j < 4; j++ ) { - out[i] |= (bArr[(i * 4) + j] & 0xFFL) << (j * 8); - } - } - final int inTail = 4 * (outLen - 1); - final int rem = inLen - inTail; - for (int j = 0; j < rem; j++ ) { - out[outLen - 1] |= (bArr[inTail + j] & 0xFFL) << (j * 8); - } - return out; - } - - /** - * Tests {@link MurmurHash3#hash(ByteBuffer, long)} on the provided key. - * - * @param key byte array to hash - * @param h1 first half of expected hash - * @param h2 second half of expected hash - */ - private static void checkHashByteBuf(final byte[] key, final long h1, final long h2) { - // Include dummy byte at start, end to make sure position, limit are respected. - final ByteBuffer buf = ByteBuffer.allocate(key.length + 2).order(ByteOrder.LITTLE_ENDIAN); - buf.position(1); - buf.put(key); - buf.limit(1 + key.length); - buf.position(1); - - final long[] result1 = MurmurHash3.hash(buf, 0); - - // Position, limit, order should not be changed. - Assert.assertEquals(1, buf.position()); - Assert.assertEquals(1 + key.length, buf.limit()); - Assert.assertEquals(ByteOrder.LITTLE_ENDIAN, buf.order()); - - // Check the actual hashes. - Assert.assertEquals(result1[0], h1); - Assert.assertEquals(result1[1], h2); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hash/XxHash64LoopingTest.java b/src/test/java/org/apache/datasketches/hash/XxHash64LoopingTest.java deleted file mode 100644 index d0998e0c2..000000000 --- a/src/test/java/org/apache/datasketches/hash/XxHash64LoopingTest.java +++ /dev/null @@ -1,1084 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hash; - -import static org.apache.datasketches.hash.XxHash64.hash; -import static org.testng.Assert.assertEquals; - -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class XxHash64LoopingTest { - - /* - * This test is adapted from - * - * OpenHFT/Zero-Allocation-Hashing to test hash compatibility with that implementation. - * See LICENSE. - */ - @Test - public void testWithSeed() { - final long seed = 42L; - for (int i = 0; i < 1025; i++) { - final byte[] byteArr = new byte[i]; - for (int j = 0; j < byteArr.length; j++) { byteArr[j] = (byte) j; } - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - final long hash = hash(wseg, 0, byteArr.length, seed); - assertEquals(hash, HASHES_OF_LOOPING_BYTES_WITH_SEED_42[i]); - } - } - - /*This data is from - * - * OpenHFT/Zero-Allocation-Hashing to test hash compatibility with that implementation. - * See LICENSE. - */ - private static final long[] HASHES_OF_LOOPING_BYTES_WITH_SEED_42 = { - -7444071767201028348L, - -8959994473701255385L, - 7116559933691734543L, - 6019482000716350659L, - -6625277557348586272L, - -5507563483608914162L, - 1540412690865189709L, - 4522324563441226749L, - -7143238906056518746L, - -7989831429045113014L, - -7103973673268129917L, - -2319060423616348937L, - -7576144055863289344L, - -8903544572546912743L, - 6376815151655939880L, - 5913754614426879871L, - 6466567997237536608L, - -869838547529805462L, - -2416009472486582019L, - -3059673981515537339L, - 4211239092494362041L, - 1414635639471257331L, - 166863084165354636L, - -3761330575439628223L, - 3524931906845391329L, - 6070229753198168844L, - -3740381894759773016L, - -1268276809699008557L, - 1518581707938531581L, - 7988048690914090770L, - -4510281763783422346L, - -8988936099728967847L, - -8644129751861931918L, - 2046936095001747419L, - 339737284852751748L, - -8493525091666023417L, - -3962890767051635164L, - -5799948707353228709L, - -6503577434416464161L, - 7718729912902936653L, - 191197390694726650L, - -2677870679247057207L, - 20411540801847004L, - 2738354376741059902L, - -3754251900675510347L, - -3208495075154651980L, - 5505877218642938179L, - 6710910171520780908L, - -9060809096139575515L, - 6936438027860748388L, - -6675099569841255629L, - -5358120966884144380L, - -4970515091611332076L, - -1810965683604454696L, - -516197887510505242L, - 1240864593087756274L, - 6033499571835033332L, - 7223146028771530185L, - 909128106589125206L, - 1567720774747329341L, - -1867353301780159863L, - 4655107429511759333L, - 5356891185236995950L, - 182631115370802890L, - -3582744155969569138L, - 595148673029792797L, - 495183136068540256L, - 5536689004903505647L, - -8472683670935785889L, - -4335021702965928166L, - 7306662983232020244L, - 4285260837125010956L, - 8288813008819191181L, - -3442351913745287612L, - 4883297703151707194L, - 9135546183059994964L, - 123663780425483012L, - 509606241253238381L, - 5940344208569311369L, - -2650142344608291176L, - 3232776678942440459L, - -922581627593772181L, - 7617977317085633049L, - 7154902266379028518L, - -5806388675416795571L, - 4368003766009575737L, - -2922716024457242064L, - 4771160713173250118L, - 3275897444752647349L, - -297220751499763878L, - 5095659287766176401L, - 1181843887132908826L, - 9058283605301070357L, - 3984713963471276643L, - 6050484112980480005L, - 1551535065359244224L, - 565337293533335618L, - 7412521035272884309L, - -4735469481351389369L, - 6998597101178745656L, - -9107075101236275961L, - 5879828914430779796L, - 6034964979406620806L, - 5666406915264701514L, - -4666218379625258428L, - 2749972203764815656L, - -782986256139071446L, - 6830581400521008570L, - 2588852022632995043L, - -5484725487363818922L, - -3319556935687817112L, - 6481961252981840893L, - 2204492445852963006L, - -5301091763401031066L, - -2615065677047206256L, - -6769817545131782460L, - -8421640685322953142L, - -3669062629317949176L, - -9167016978640750490L, - 2783671191687959562L, - -7599469568522039782L, - -7589134103255480011L, - -5932706841188717592L, - -8689756354284562694L, - -3934347391198581249L, - -1344748563236040701L, - 2172701592984478834L, - -5322052340624064417L, - -8493945390573620511L, - 3349021988137788403L, - -1806262525300459538L, - -8091524448239736618L, - 4022306289903960690L, - -8346915997379834224L, - -2106001381993805461L, - -5784123934724688161L, - 6775158099649720388L, - -3869682756870293568L, - 4356490186652082006L, - 8469371446702290916L, - -2972961082318458602L, - -7188106622222784561L, - -4961006366631572412L, - 3199991182014172900L, - 2917435868590434179L, - 8385845305547872127L, - 7706824402560674655L, - -1587379863634865277L, - -4212156212298809650L, - -1305209322000720233L, - -7866728337506665880L, - 8195089740529247049L, - -4876930125798534239L, - 798222697981617129L, - -2441020897729372845L, - -3926158482651178666L, - -1254795122048514130L, - 5192463866522217407L, - -5426289318796042964L, - -3267454004443530826L, - 471043133625225785L, - -660956397365869974L, - -6149209189144999161L, - -2630977660039166559L, - 8512219789663151219L, - -3309844068134074620L, - -6211275327487847132L, - -2130171729366885995L, - 6569302074205462321L, - 4855778342281619706L, - 3867211421508653033L, - -3002480002418725542L, - -8297543107467502696L, - 8049642289208775831L, - -5439825716055425635L, - 7251760070798756432L, - -4774526021749797528L, - -3892389575184442548L, - 5162451061244344424L, - 6000530226398686578L, - -5713092252241819676L, - 8740913206879606081L, - -8693282419677309723L, - 1576205127972543824L, - 5760354502610401246L, - 3173225529903529385L, - 1785166236732849743L, - -1024443476832068882L, - -7389053248306187459L, - 1171021620017782166L, - 1471572212217428724L, - 7720766400407679932L, - -8844781213239282804L, - -7030159830170200877L, - 2195066352895261150L, - 1343620937208608634L, - 9178233160016731645L, - -757883447602665223L, - 3303032934975960867L, - -3685775162104101116L, - -4454903657585596656L, - -5721532367620482629L, - 8453227136542829644L, - 5397498317904798888L, - 7820279586106842836L, - -2369852356421022546L, - 3910437403657116169L, - 6072677490463894877L, - -2651044781586183960L, - 5173762670440434510L, - -2970017317595590978L, - -1024698859439768763L, - -3098335260967738522L, - -1983156467650050768L, - -8132353894276010246L, - -1088647368768943835L, - -3942884234250555927L, - 7169967005748210436L, - 2870913702735953746L, - -2207022373847083021L, - 1104181306093040609L, - 5026420573696578749L, - -5874879996794598513L, - -4777071762424874671L, - -7506667858329720470L, - -2926679936584725232L, - -5530649174168373609L, - 5282408526788020384L, - 3589529249264153135L, - -6220724706210580398L, - -7141769650716479812L, - 5142537361821482047L, - -7029808662366864423L, - -6593520217660744466L, - 1454581737122410695L, - -139542971769349865L, - 1727752089112067235L, - -775001449688420017L, - -5011311035350652032L, - -8671171179275033159L, - -2850915129917664667L, - -5258897903906998781L, - -6954153088230718761L, - -4070351752166223959L, - -6902592976462171099L, - -7850366369290661391L, - -4562443925864904705L, - 3186922928616271015L, - 2208521081203400591L, - -2727824999830592777L, - -3817861137262331295L, - 2236720618756809066L, - -4888946967413746075L, - -446884183491477687L, - -43021963625359034L, - -5857689226703189898L, - -2156533592262354883L, - -2027655907961967077L, - 7151844076490292500L, - -5029149124756905464L, - 526404452686156976L, - 8741076980297445408L, - 7962851518384256467L, - -105985852299572102L, - -2614605270539434398L, - -8265006689379110448L, - 8158561071761524496L, - -6923530157382047308L, - 5551949335037580397L, - 565709346370307061L, - -4780869469938333359L, - 6931895917517004830L, - 565234767538051407L, - -8663136372880869656L, - 1427340323685448983L, - 6492705666640232290L, - 1481585578088475369L, - -1712711110946325531L, - 3281685342714380741L, - 6441384790483098576L, - -1073539554682358394L, - 5704050067194788964L, - -5495724689443043319L, - -5425043165837577535L, - 8349736730194941321L, - -4123620508872850061L, - 4687874980541143573L, - -468891940172550975L, - -3212254545038049829L, - -6830802881920725628L, - 9033050533972480988L, - 4204031879107709260L, - -677513987701096310L, - -3286978557209370155L, - 1644111582609113135L, - 2040089403280131741L, - 3323690950628902653L, - -7686964480987925756L, - -4664519769497402737L, - 3358384147145476542L, - -4699919744264452277L, - -4795197464927839170L, - 5051607253379734527L, - -8987703459734976898L, - 8993686795574431834L, - -2688919474688811047L, - 375938183536293311L, - 1049459889197081920L, - -1213022037395838295L, - 4932989235110984138L, - -6647247877090282452L, - -7698817539128166242L, - -3264029336002462659L, - 6487828018122309795L, - -2660821091484592878L, - 7104391069028909121L, - -1765840012354703384L, - 85428166783788931L, - -6732726318028261938L, - 7566202549055682933L, - 229664898114413280L, - -1474237851782211353L, - -1571058880058007603L, - -7926453582850712144L, - 2487148368914275243L, - 8740031015380673473L, - 1908345726881363169L, - -2510061320536523178L, - 7854780026906019630L, - -6023415596650016493L, - -6264841978089051107L, - 4024998278016087488L, - -4266288992025826072L, - -3222176619422665563L, - -1999258726038299316L, - 1715270077442385636L, - 6764658837948099754L, - -8646962299105812577L, - -51484064212171546L, - -1482515279051057493L, - -8663965522608868414L, - -256555202123523670L, - 1973279596140303801L, - -7280796173024508575L, - -5691760367231354704L, - -5915786562256300861L, - -3697715074906156565L, - 3710290115318541949L, - 6796151623958134374L, - -935299482515386356L, - -7078378973978660385L, - 5379481350768846927L, - -9011221735308556302L, - 5936568631579608418L, - -6060732654964511813L, - -4243141607840017809L, - 3198488845875349355L, - -7809288876010447646L, - 4371587872421472389L, - -1304197371105522943L, - 7389861473143460103L, - -1892352887992004024L, - 2214828764044713398L, - 6347546952883613388L, - 1275694314105480954L, - -5262663163358903733L, - 1524757505892047607L, - 1474285098416162746L, - -7976447341881911786L, - 4014100291977623265L, - 8994982266451461043L, - -7737118961020539453L, - -2303955536994331092L, - 1383016539349937136L, - 1771516393548245271L, - -5441914919967503849L, - 5449813464890411403L, - -3321280356474552496L, - 4084073849712624363L, - 4290039323210935932L, - 2449523715173349652L, - 7494827882138362156L, - 9035007221503623051L, - 5722056230130603177L, - -5443061851556843748L, - -7554957764207092109L, - 447883090204372074L, - 533916651576859197L, - -3104765246501904165L, - -4002281505194601516L, - -8402008431255610992L, - -408273018037005304L, - 214196458752109430L, - 6458513309998070914L, - 2665048360156607904L, - 96698248584467992L, - -3238403026096269033L, - 6759639479763272920L, - -4231971627796170796L, - -2149574977639731179L, - -1437035755788460036L, - -6000005629185669767L, - 145244292800946348L, - -3056352941404947199L, - 3748284277779018970L, - 7328354565489106580L, - -2176895260373660284L, - 3077983936372755601L, - 1215485830019410079L, - 683050801367331140L, - -3173237622987755212L, - -1951990779107873701L, - -4714366021269652421L, - 4934690664256059008L, - 1674823104333774474L, - -3974408282362828040L, - 2001478896492417760L, - -4115105568354384199L, - -2039694725495941666L, - -587763432329933431L, - -391276713546911316L, - -5543400904809469053L, - 1882564440421402418L, - -4991793588968693036L, - 3454088185914578321L, - 2290855447126188424L, - 3027910585026909453L, - 2136873580213167431L, - -6243562989966916730L, - 5887939953208193029L, - -3491821629467655741L, - -3138303216306660662L, - 8572629205737718669L, - 4154439973110146459L, - 5542921963475106759L, - -2025215496720103521L, - -4047933760493641640L, - -169455456138383823L, - -1164572689128024473L, - -8551078127234162906L, - -7247713218016599028L, - 8725299775220778242L, - 6263466461599623132L, - 7931568057263751768L, - 7365493014712655238L, - -7343740914722477108L, - 8294118602089088477L, - 7677867223984211483L, - -7052188421655969232L, - -3739992520633991431L, - 772835781531324307L, - 881441588914692737L, - 6321450879891466401L, - 5682516032668315027L, - 8493068269270840662L, - -3895212467022280567L, - -3241911302335746277L, - -7199586338775635848L, - -4606922569968527974L, - -806850906331637768L, - 2433670352784844513L, - -5787982146811444512L, - 7852193425348711165L, - 8669396209073850051L, - -6898875695148963118L, - 6523939610287206782L, - -8084962379210153174L, - 8159432443823995836L, - -2631068535470883494L, - -338649779993793113L, - 6514650029997052016L, - 3926259678521802094L, - 5443275905907218528L, - 7312187582713433551L, - -2993773587362997676L, - -1068335949405953411L, - 4499730398606216151L, - 8538015793827433712L, - -4057209365270423575L, - -1504284818438273559L, - -6460688570035010846L, - 1765077117408991117L, - 8278320303525164177L, - 8510128922449361533L, - 1305722765578569816L, - 7250861238779078656L, - -576624504295396147L, - -4363714566147521011L, - -5932111494795524073L, - 1837387625936544674L, - -4186755953373944712L, - -7657073597826358867L, - 140408487263951108L, - 5578463635002659628L, - 3400326044813475885L, - -6092804808386714986L, - -2410324417287268694L, - 3222007930183458970L, - 4932471983280850419L, - 3554114546976144528L, - -7216067928362857082L, - -6115289896923351748L, - -6769646077108881947L, - 4263895947722578066L, - 2939136721007694271L, - 1426030606447416658L, - -1316192446807442076L, - 5366182640480055129L, - 6527003877470258527L, - 5849680119000207603L, - 5263993237214222328L, - -6936533648789185663L, - -9063642143790846605L, - 3795892210758087672L, - 4987213125282940176L, - 2505500970421590750L, - -1014022559552365387L, - -3574736245968367770L, - 1180676507127340259L, - -2261908445207512503L, - -8416682633172243509L, - 1114990703652673283L, - 7753746660364401380L, - 1874908722469707905L, - 2033421444403047677L, - 21412168602505589L, - 385957952615286205L, - 2053171460074727107L, - 1915131899400103774L, - 6680879515029368390L, - 568807208929724162L, - -6211541450459087674L, - -5026690733412145448L, - 1384781941404886235L, - -98027820852587266L, - 1806580495924249669L, - 6322077317403503963L, - 9078162931419569939L, - -2809061215428363978L, - 7697867577577415733L, - -5270063855897737274L, - 5649864555290587388L, - -6970990547695444247L, - 579684606137331754L, - 3871931565451195154L, - 2030008578322050218L, - -5012357307111799829L, - -2271365921756144065L, - 4551962665158074190L, - -3385474923040271312L, - -7647625164191633577L, - 6634635380316963029L, - -5201190933687061585L, - 8864818738548593973L, - 2855828214210882907L, - 9154512990734024165L, - -6945306719789457786L, - 1200243352799481087L, - 875998327415853787L, - 1275313054449881011L, - -6105772045375948736L, - -2926927684328291437L, - 9200050852144954779L, - 5188726645765880663L, - 5197037323312705176L, - 3434926231010121611L, - -5054013669361906544L, - 2582959199749224670L, - -6053757512723474059L, - -5016308176846054473L, - -2509827316698626133L, - 7700343644503853204L, - -1997627249894596731L, - 3993168688325352290L, - -8181743677541277704L, - 3719056119682565597L, - -7264411659282947790L, - 7177028972346484464L, - -5460831176884283278L, - 1799904662416293978L, - -6549616005092764514L, - 5472403994001122052L, - 8683463751708388502L, - -7873363037838316398L, - 689134758256487260L, - -1287443614028696450L, - 4452712919702709507L, - 762909374167538893L, - 6594302592326281411L, - 1183786629674781984L, - 5021847859620133476L, - -2490098069181538915L, - 5105145136026716679L, - 4437836948098585718L, - 1987270426215858862L, - 6170312798826946249L, - 634297557126003407L, - -1672811625495999581L, - 6282971595586218191L, - 4549149305727581687L, - -5652165370435317782L, - 1064501550023753890L, - -5334885527127139723L, - -6904378001629481237L, - -1807576691784201230L, - -205688432992053911L, - 7621619053293393289L, - 6258649161313982470L, - -1111634238359342096L, - -8044260779481691987L, - 400270655839010807L, - -7806833581382890725L, - -2970563349459508036L, - -7392591524816802798L, - 2918924613160219805L, - -6444161627929149002L, - 6096497501321778876L, - -1477975665655830038L, - 1690651307597306138L, - -2364076888826085362L, - -6521987420014905821L, - -4419193480146960582L, - 3538587780233092477L, - 8374665961716940404L, - 7492412312405424500L, - 6311662249091276767L, - -1240235198282023566L, - 5478559631401166447L, - 3476714419313462133L, - 377427285984503784L, - 2570472638778991109L, - -2741381313777447835L, - -7123472905503039596L, - 2493658686946955193L, - 1024677789035847585L, - -2916713904339582981L, - -4532003852004642304L, - -2202143560366234111L, - 5832267856442755135L, - -261740607772957384L, - 239435959690278014L, - 5755548341947719409L, - 6138795458221887696L, - -7709506987360146385L, - -6657487758065140444L, - -7006376793203657499L, - 6544409861846502033L, - 3171929352014159247L, - 1051041925048792869L, - 2617300158375649749L, - 952652799620095175L, - -576661730162168147L, - -1634191369221345988L, - 4833656816115993519L, - 647566759700005786L, - 2473810683785291822L, - 3005977181064745326L, - -3321881966853149523L, - 7595337666427588699L, - 6004093624251057224L, - -563917505657690279L, - 6117428527147449302L, - -6287297509522976113L, - -4527219334756214406L, - 742626429298092489L, - 3057351806086972041L, - 645967551210272605L, - -4428701157828864227L, - 3236379103879435414L, - -8477089892132066300L, - -6127365537275859058L, - -4052490484706946358L, - -8004854976625046469L, - -3679456917426613424L, - -8212793762082595299L, - -818288739465424130L, - 1358812099481667095L, - 7835987612195254310L, - -3663247409614323059L, - -2931105150130396604L, - 7296136776835614792L, - -2014557408985889628L, - 7267662411237959788L, - 3699280615819277743L, - -212010675469091396L, - -6518374332458360120L, - 145026010541628849L, - 1879297324213501001L, - -7146296067751816833L, - -5002958800391379931L, - 6060682439924517608L, - -432234782921170964L, - -6669688947353256956L, - 7728943532792041267L, - 830911367341171721L, - 3396934884314289432L, - -779464156662780749L, - 2330041851883352285L, - -4783350380736276693L, - -5758476056890049254L, - -7551552301614791791L, - 1253334187723911710L, - -2685018208308798978L, - 5379636036360946454L, - 6154668487114681217L, - -8641287462255458898L, - 4676087643800649558L, - -2405142641398691475L, - 1088685126864246881L, - 6431149082338374041L, - -607357695335069155L, - -720970692129524140L, - 2648766932394044468L, - 8408344790179354573L, - -6193808387735667350L, - 7722524628524697419L, - -6975433852560238120L, - -2925851029234475295L, - -4274458387165211028L, - -8355836377702147319L, - 5278146397877332061L, - 8502098812383680707L, - 2292836642336580326L, - -6127608082651070062L, - 2222301962240611208L, - -1930887695854799378L, - 7640503480494894592L, - 1162652186586436094L, - -1918002592943761683L, - 7648998601717261840L, - -8472603250832757057L, - -988877663117552456L, - 2368458128168026494L, - -6480813811998475245L, - -5896967824416018967L, - -2593783161701820446L, - 6950098417530252598L, - 6362589545555771236L, - 7981389665448567125L, - 3954017080198558850L, - 1626078615050230622L, - 6650159066527969109L, - 697345338922935394L, - -1226816215461768626L, - 8740408765973837440L, - -4194155864629568323L, - 7016680023232424746L, - 6043281358142429469L, - -4201005667174376809L, - 1216727117859013155L, - 6367202436544203935L, - 35414869396444636L, - 3715622794033998412L, - 488654435687670554L, - -2503747297224687460L, - 3147101919441470388L, - -8248611218693190922L, - 970697264481229955L, - 3411465763826851418L, - 9117405004661599969L, - -5204346498331519734L, - -19637460819385174L, - -5039124225167977219L, - 2990108874601696668L, - -2623857460235459202L, - 4256291692861397446L, - 6724147860870760443L, - 3558616688507246537L, - 6487680097936412800L, - -6470792832935928161L, - 4314814550912237614L, - -1292878983006062345L, - 6791915152630414174L, - 5971652079925815310L, - 2557529546662864312L, - 466175054322801580L, - -585216717310746872L, - -2486640422147349036L, - 7212029603994220134L, - 3958995069888972500L, - 4950471855791412790L, - -3721948842035712763L, - -6184503487488243051L, - 4079570444585775332L, - -3952156172546996872L, - 4543894231118208322L, - -1739995588466209963L, - 9155948355455935530L, - 5821980345462207860L, - -2431287667309520417L, - -3890108130519441316L, - -558124689277030490L, - 6079823537335801717L, - 5409742395192364262L, - -2329885777717160453L, - -7332804342513677651L, - 1466490574975950555L, - -420549419907427929L, - -5249909814389692516L, - -5145692168206210661L, - 5934113980649113921L, - 3241618428555359661L, - -6622110266160980250L, - 5048250878669516223L, - 5747219637359976174L, - 2975906212588223728L, - 5730216838646273215L, - -176713127129024690L, - 6734624279336671146L, - 5127866734316017180L, - 7111761230887705595L, - 3457811808274317235L, - 3362961434604932375L, - -1877869936854991246L, - 7171428594877765665L, - -8252167178400462374L, - -6306888185035821047L, - -6684702191247683887L, - -7754928454824190529L, - -1902605599135704386L, - -4037319846689421239L, - 8493746058123583457L, - -8156648963857047193L, - 2051510355149839497L, - -1256416624177218909L, - -3344927996254072010L, - -1838853051925943568L, - 316927471680974556L, - -1502257066700798003L, - -5836095610125837606L, - -1594125583615895424L, - 1442211486559637962L, - -144295071206619569L, - 5159850900959273410L, - 4589139881166423678L, - -7038726987463097509L, - 2886082400772974595L, - 2780759114707171916L, - 5694649587906297495L, - 1260349041268169667L, - 4921517488271434890L, - 644696475796073018L, - 6262811963753436289L, - -6128198676595868773L, - -3625352083004760261L, - -8751453332943236675L, - 8749249479868749221L, - -2450808199545048250L, - -6517435817046180917L, - -3433321727429234998L, - -2591586258908763451L, - 3847750870868804507L, - 6603614438546398643L, - -7598682191291031287L, - 8710261565627204971L, - 4753389483755344355L, - -4645333069458786881L, - -6742695046613492214L, - 643070478568866643L, - -7543096104151965610L, - 7171495384655926161L, - 595063872610714431L, - 3292310150781130424L, - 4326847806055440904L, - -4580020566072794152L, - 3142286571820373678L, - 5530356537440155930L, - 546372639737516181L, - 7401214477400367500L, - 7406531960402873109L, - 3287639667219172570L, - 4977301681213633671L, - 5253257820925174498L, - 2906216636104297878L, - 6142955758238347523L, - -3498651268741727235L, - -5875053958265588593L, - 3896719087169993883L, - -910904726885775073L, - 380107493197368177L, - -4993591912695447004L, - 2970487257212582761L, - 2551762717569548774L, - 953061649962736812L, - 8949739538606589463L, - -2962839167079475801L, - -1375673191272573835L, - 3761793818361866390L, - -389577789190726878L, - 5661262051502180269L, - -6558556411143987683L, - -702798336372315031L, - -336662820551371779L, - 998576401126580155L, - -5945021269112582755L, - 6108533925730179871L, - 2207095297001999618L, - -9042779159998880435L, - -6177868444342118372L, - 6775965402605895077L, - -3788428885163306576L, - 7790055010527190387L, - 3581587652196995358L, - -6176354155561607694L, - -5859381340906321207L, - 395898765763528395L, - 8132967590863909348L, - -3329092504090544483L, - -6785855381158040247L, - 1497218517051796750L, - -5352392845588925911L, - -6271364901230559194L, - 2314830370653350118L, - -7617588269001325450L, - 1423166885758213795L, - 8538612578307869519L, - -61918791718295474L, - -8177103503192338593L, - -4740086042584326695L, - 3677931948215558698L, - 6558856291580149558L, - 2674975452453336335L, - 5133796555646930522L, - 5139252693299337100L, - 7949476871295347205L, - 4407815324662880678L, - -3758305875280581215L, - 6066309507576587415L, - -7368508486398350973L, - -3181640264332856492L, - 6905100869343314145L, - 3677177673848733417L, - 8862933624870506941L, - -8575223195813810568L, - 9178470351355678144L, - 4677809017145408358L, - -1194833416287894989L, - 3436364743255571183L, - -5204770725795363579L, - 560599448536335263L, - -3192077522964776200L, - -751575299648803575L, - 6334581746534596579L, - -8358187891202563300L, - -1462480609823525055L, - 5605961062646987941L, - 4968399805931440889L, - 7968693270782626653L, - -5868205923557518188L, - 1830234928743560617L, - -8435261076693154407L, - 2138416970728681332L, - 8088740745199685138L, - 806532400344230520L, - 1800590379902909333L, - -8909128842071238901L, - -7357495566969170860L, - 3679766664126940553L, - 2060050474865839094L, - 2363972840121763414L, - 525695004292982714L, - -1224842191746529593L, - 7011317848855545003L, - -6337167558180299938L, - -5184688833363785939L, - -8426673387248359061L, - -5035438815930785229L, - 3521810320608058994L, - 4803742557254962242L, - 6623527039545786598L, - -1221475882122634738L, - -3344794405518401087L, - 6510298498414053658L, - 2844753907937720338L, - 90502309714994895L, - -750403235344282494L, - -4825474181021465833L, - -3405519947983849510L, - 3503875590944089793L, - 7286294700691822468L, - 7828126881500292486L, - 8437899353709338096L, - 136052254470293480L, - 1113259077339995086L, - -8244887265606191121L, - 8089569503800461649L, - -1429698194850157567L, - 1575595674002364989L, - 3576095286627428675L, - -7653655285807569222L, - -6053506977362539111L, - -3923855345805787169L, - -8001149080454232377L, - -4382867706931832271L, - 4212860258835896297L, - 4207674254247034014L, - 5519424058779519159L, - -754483042161434654L, - 1434113479814210082L, - -6416645032698336896L, - 5624329676066514819L, - -8229557208322175959L, - 3922640911653270376L, - 7826932478782081910L, - -4862787164488635842L, - 1449234668827944573L, - -1781657689570106327L, - 5442827552725289699L, - 3589862161007644641L, - 4787115581650652778L, - -3512152721942525726L, - -6750103117958685206L, - 5012970446659949261L, - 6797752795961689017L, - 5086454597639943700L, - -7616068364979994076L, - 1492846825433110217L, - 2967476304433704510L, - -8413824338284112078L, - -1319049442043273974L, - -1756090916806844109L, - -9061091728950139525L, - -6864767830358160810L, - 4879532090226251157L, - 5528644708740739488L - }; -} diff --git a/src/test/java/org/apache/datasketches/hash/XxHash64Test.java b/src/test/java/org/apache/datasketches/hash/XxHash64Test.java deleted file mode 100644 index b005aaf6c..000000000 --- a/src/test/java/org/apache/datasketches/hash/XxHash64Test.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hash; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_CHAR_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.hash.XxHash.hashByteArr; -import static org.apache.datasketches.hash.XxHash.hashCharArr; -import static org.apache.datasketches.hash.XxHash.hashDoubleArr; -import static org.apache.datasketches.hash.XxHash.hashFloatArr; -import static org.apache.datasketches.hash.XxHash.hashIntArr; -import static org.apache.datasketches.hash.XxHash.hashLong; -import static org.apache.datasketches.hash.XxHash.hashLongArr; -import static org.apache.datasketches.hash.XxHash.hashShortArr; -import static org.apache.datasketches.hash.XxHash.hashString; -import static org.apache.datasketches.hash.XxHash64.hash; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class XxHash64Test { - - @Test - public void offsetChecks() { - final long seed = 12345; - final int blocks = 6; - final int cap = blocks * 16; - - long hash; - - final MemorySegment wseg = MemorySegment.ofArray(new byte[cap]); - for (int i = 0; i < cap; i++) { wseg.set(JAVA_BYTE, i, (byte)(-128 + i)); } - - for (int offset = 0; offset < 16; offset++) { - final int arrLen = cap - offset; - hash = hash(wseg, offset, arrLen, seed); - assertTrue(hash != 0); - } - } - - @Test - public void byteArrChecks() { - final long seed = 0; - final int offset = 0; - final int bytes = 16; - - for (int j = 1; j < bytes; j++) { - final byte[] in = new byte[bytes]; - - final MemorySegment wseg = MemorySegment.ofArray(in); - for (int i = 0; i < j; i++) { wseg.set(JAVA_BYTE, i, (byte) (-128 + i)); } - - final long hash = hash(wseg, offset, bytes, seed); - assertTrue(hash != 0); - } - } - - /* - * This test is adapted from - * - * OpenHFT/Zero-Allocation-Hashing to test hash compatibility with that implementation. - * It is licensed under Apache License, version 2.0. See LICENSE. - */ - @Test - public void collisionTest() { - final MemorySegment wseg = MemorySegment.ofArray(new byte[128]); - wseg.set(JAVA_LONG_UNALIGNED, 0, 1); - wseg.set(JAVA_LONG_UNALIGNED, 16, 42); - wseg.set(JAVA_LONG_UNALIGNED, 32, 2); - final long h1 = hash(wseg, 0, wseg.byteSize(), 0); - - wseg.set(JAVA_LONG_UNALIGNED, 0, 1L + 0xBA79078168D4BAFL); - wseg.set(JAVA_LONG_UNALIGNED, 32, 2L + 0x9C90005B80000000L); - final long h2 = hash(wseg, 0, wseg.byteSize(), 0); - assertEquals(h1, h2); - - wseg.set(JAVA_LONG_UNALIGNED, 0, 1L + (0xBA79078168D4BAFL * 2)); - wseg.set(JAVA_LONG_UNALIGNED, 32, 2L + (0x392000b700000000L)); //= (0x9C90005B80000000L * 2) fix overflow false pos - - final long h3 = hash(wseg, 0, wseg.byteSize(), 0); - assertEquals(h2, h3); - } - - private static final byte[] barr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; - - @Test - public void testArrHashes() { - final MemorySegment wseg = MemorySegment.ofArray(barr); - final long hash0 = hash(wseg, 8, 8, 0); - long hash1 = hashByteArr(barr, 8, 8, 0); - assertEquals(hash1, hash0); - - final char[] carr = new char[8]; - MemorySegment.copy(wseg, JAVA_CHAR_UNALIGNED, 0, carr, 0, 8); - hash1 = hashCharArr(carr, 4, 4, 0); - assertEquals(hash1, hash0); - - final short[] sarr = new short[8]; - MemorySegment.copy(wseg, JAVA_SHORT_UNALIGNED, 0, sarr, 0, 8); - hash1 = hashShortArr(sarr, 4, 4, 0); - assertEquals(hash1, hash0); - - final int[] iarr = new int[4]; - MemorySegment.copy(wseg, JAVA_INT_UNALIGNED, 0, iarr, 0, 4); - hash1 = hashIntArr(iarr, 2, 2, 0); - assertEquals(hash1, hash0); - - final float[] farr = new float[4]; - MemorySegment.copy(wseg, JAVA_FLOAT_UNALIGNED, 0, farr, 0, 4); - hash1 = hashFloatArr(farr, 2, 2, 0); - assertEquals(hash1, hash0); - - final long[] larr = new long[2]; - MemorySegment.copy(wseg, JAVA_LONG_UNALIGNED, 0, larr, 0, 2); - hash1 = hashLongArr(larr, 1, 1, 0); - final long in = wseg.get(JAVA_LONG_UNALIGNED, 8); - final long hash2 = hashLong(in, 00); //tests the single long hash - assertEquals(hash1, hash0); - assertEquals(hash2, hash0); - - final double[] darr = new double[2]; - MemorySegment.copy(wseg, JAVA_DOUBLE_UNALIGNED, 0, darr, 0, 2); - hash1 = hashDoubleArr(darr, 1, 1, 0); - assertEquals(hash1, hash0); - } - - @Test - public void testString() { - final String s = "Now is the time for all good men to come to the aid of their country."; - final char[] arr = s.toCharArray(); - final long hash0 = hashString(s, 0, s.length(), 0); - final long hash1 = hashCharArr(arr, 0, arr.length, 0); - assertEquals(hash1, hash0); - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/AuxHashMapTest.java b/src/test/java/org/apache/datasketches/hll/AuxHashMapTest.java deleted file mode 100644 index 3f6a80fd4..000000000 --- a/src/test/java/org/apache/datasketches/hll/AuxHashMapTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.fail; - -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.hll.HeapAuxHashMap; -import org.apache.datasketches.hll.PairIterator; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class AuxHashMapTest { - static final String LS = System.getProperty("line.separator"); - - @Test - public void checkMustReplace() { - HeapAuxHashMap map = new HeapAuxHashMap(3, 7); - map.mustAdd(100, 5); - int val = map.mustFindValueFor(100); - assertEquals(val, 5); - - map.mustReplace(100, 10); - val = map.mustFindValueFor(100); - assertEquals(val, 10); - - try { - map.mustReplace(101, 5); - fail(); - } catch (SketchesStateException e) { - //expected - } - } - - @Test - public void checkGrowSpace() { - HeapAuxHashMap map = new HeapAuxHashMap(3, 7); - assertFalse(map.hasMemorySegment()); - assertFalse(map.isOffHeap()); - assertEquals(map.getLgAuxArrInts(), 3); - for (int i = 1; i <= 7; i++) { - map.mustAdd(i, i); - } - assertEquals(map.getLgAuxArrInts(), 4); - PairIterator itr = map.getIterator(); - int count1 = 0; - int count2 = 0; - while (itr.nextAll()) { - count2++; - int pair = itr.getPair(); - if (pair != 0) { count1++; } - } - assertEquals(count1, 7); - assertEquals(count2, 16); - } - - @Test(expectedExceptions = SketchesStateException.class) - public void checkExceptions1() { - HeapAuxHashMap map = new HeapAuxHashMap(3, 7); - map.mustAdd(100, 5); - map.mustFindValueFor(101); - } - - @Test(expectedExceptions = SketchesStateException.class) - public void checkExceptions2() { - HeapAuxHashMap map = new HeapAuxHashMap(3, 7); - map.mustAdd(100, 5); - map.mustAdd(100, 6); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/BaseHllSketchTest.java b/src/test/java/org/apache/datasketches/hll/BaseHllSketchTest.java deleted file mode 100644 index 0ba429b0e..000000000 --- a/src/test/java/org/apache/datasketches/hll/BaseHllSketchTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import org.apache.datasketches.hll.BaseHllSketch; -import org.apache.datasketches.hll.HllSketch; -import org.apache.datasketches.hll.PreambleUtil; -import org.apache.datasketches.hll.TgtHllType; -import org.apache.datasketches.hll.HllUnion; -import org.testng.annotations.Test; - -import java.lang.foreign.MemorySegment; - -import java.nio.ByteBuffer; - -/** - * @author Lee Rhodes - * - */ -public class BaseHllSketchTest { - - @Test - public void checkUpdateTypes() { - final HllSketch sk = new HllSketch(10); - final byte[] byteArr = null; - sk.update(byteArr); - sk.update(new byte[] {}); - sk.update(new byte[] {0, 1, 2, 3}); - final ByteBuffer byteBuf = null; - sk.update(byteBuf); - sk.update(ByteBuffer.wrap(new byte[] {})); - sk.update(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})); - final char[] charArr = null; - sk.update(charArr); - sk.update(new char[] {}); - sk.update(new char[] {0, 1, 2, 3}); - sk.update(1.0); - sk.update(-0.0); - final int[] intArr = null; - sk.update(intArr); - sk.update(new int[] {}); - sk.update(new int[] {0, 1, 2, 3}); - sk.update(1234L); - final long[] longArr = null; - sk.update(longArr); - sk.update(new long[] {}); - sk.update(new long[] {0, 1, 2, 3}); - String s = null; - sk.update(s); - s = ""; - sk.update(s); - sk.update("1234"); - - final HllUnion u = new HllUnion(10); - final byte[] byteArr1 = null; - u.update(byteArr1); - u.update(new byte[] {}); - u.update(new byte[] {0, 1, 2, 3}); - final ByteBuffer byteBuf1 = null; - u.update(byteBuf1); - u.update(ByteBuffer.wrap(new byte[] {})); - u.update(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})); - final char[] charArr1 = null; - u.update(charArr1); - u.update(new char[] {}); - u.update(new char[] {0, 1, 2, 3}); - u.update(1.0); - u.update(-0.0); - final int[] intArr1 = null; - u.update(intArr1); - u.update(new int[] {}); - u.update(new int[] {0, 1, 2, 3}); - u.update(1234L); - final long[] longArr1 = null; - u.update(longArr1); - u.update(new long[] {}); - u.update(new long[] {0, 1, 2, 3}); - String s1 = null; - u.update(s1); - s1 = ""; - u.update(s); - u.update("1234"); - } - - @Test - public void misc() { - final HllSketch sk = new HllSketch(10, TgtHllType.HLL_4); - assertTrue(sk.isEstimationMode()); - sk.reset(); - assertEquals(BaseHllSketch.getSerializationVersion(), PreambleUtil.SER_VER); - final MemorySegment wseg = MemorySegment.ofArray(sk.toCompactByteArray()); - assertEquals(BaseHllSketch.getSerializationVersion(wseg), PreambleUtil.SER_VER); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/hll/CouponListTest.java b/src/test/java/org/apache/datasketches/hll/CouponListTest.java deleted file mode 100644 index df7c07cb2..000000000 --- a/src/test/java/org/apache/datasketches/hll/CouponListTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.hll.AbstractCoupons; -import org.apache.datasketches.hll.CurMode; -import org.apache.datasketches.hll.HllSketch; -import org.apache.datasketches.hll.PairIterator; -import org.apache.datasketches.hll.TgtHllType; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class CouponListTest { - - @Test //visual check - public void checkIterator() { - checkIterator(false, 4, 7); - checkIterator(true, 4, 7); - } - - private static void checkIterator(final boolean direct, final int lgK, final int n) { - final TgtHllType tgtHllType = TgtHllType.HLL_4; - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, tgtHllType); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = (direct) ? new HllSketch(lgK, tgtHllType, wseg) : new HllSketch(lgK, tgtHllType); - for (int i = 0; i < n; i++) { sk.update(i); } - final String store = direct ? "MemorySegment" : "Heap"; - println("CurMode: " + sk.getCurMode().toString() + "; Store: " + store); - final PairIterator itr = sk.iterator(); - println(itr.getHeader()); - while (itr.nextAll()) { - assertTrue(itr.getSlot() < (1 << lgK)); - println(itr.getString()); - } - } - - @Test - public void checkDuplicatesAndMisc() { - checkDuplicatesAndMisc(false); - checkDuplicatesAndMisc(true); - } - - private static void checkDuplicatesAndMisc(final boolean direct) { - final int lgConfigK = 8; - final TgtHllType tgtHllType = TgtHllType.HLL_4; - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = (direct) ? new HllSketch(lgConfigK, tgtHllType, wseg) : new HllSketch(8); - - for (int i = 1; i <= 7; i++) { - sk.update(i); - sk.update(i); - } - assertEquals(sk.getCurMode(), CurMode.LIST); - assertEquals(sk.getCompositeEstimate(), 7.0, 7 * .01); - assertEquals(sk.getHipEstimate(), 7.0, 7 * .01); - sk.hllSketchImpl.putEmptyFlag(false); //dummy - sk.hllSketchImpl.putRebuildCurMinNumKxQFlag(false); //dummy - if (direct) { - assertNotNull(sk.getMemorySegment()); - } else { - assertNull(sk.getMemorySegment()); - } - - sk.update(8); - sk.update(8); - assertEquals(sk.getCurMode(), CurMode.SET); - assertEquals(sk.getCompositeEstimate(), 8.0, 8 * .01); - assertEquals(sk.getHipEstimate(), 8.0, 8 * .01); - if (direct) { - assertNotNull(sk.getMemorySegment()); - } else { - assertNull(sk.getMemorySegment()); - } - - for (int i = 9; i <= 25; i++) { - sk.update(i); - sk.update(i); - } - assertEquals(sk.getCurMode(), CurMode.HLL); - assertEquals(sk.getCompositeEstimate(), 25.0, 25 * .1); - if (direct) { - assertNotNull(sk.getMemorySegment()); - } else { - assertNull(sk.getMemorySegment()); - - } - } - - @Test - public void toByteArray_Heapify() { - toByteArrayHeapify(7); - toByteArrayHeapify(21); - } - - private static void toByteArrayHeapify(final int lgK) { - final HllSketch sk1 = new HllSketch(lgK); - - final int u = (lgK < 8) ? 7 : ((1 << (lgK - 3))/4) * 3; - for (int i = 0; i < u; i++) { - sk1.update(i); - } - final double est1 = sk1.getEstimate(); - assertEquals(est1, u, u * 100.0E-6); - //println("Original\n" + sk1.toString()); - - byte[] byteArray = sk1.toCompactByteArray(); - //println("Preamble: " + PreambleUtil.toString(byteArray)); - HllSketch sk2 = HllSketch.heapify(byteArray); - double est2 = sk2.getEstimate(); - //println("Heapify Compact\n" + sk2.toString(true, true, true, true)); - assertEquals(est2, est1, 0.0); - - byteArray = sk1.toUpdatableByteArray(); - sk2 = HllSketch.heapify(byteArray); - est2 = sk2.getEstimate(); - //println("Heapify Updatable\n" + sk2.toString()); - assertEquals(est2, est1, 0.0); - } - - @Test - public void checkGetMemorySegment() { - final HllSketch sk1 = new HllSketch(4); - final AbstractCoupons absCoup = (AbstractCoupons) sk1.hllSketchImpl; - assertNull(absCoup.getMemorySegment()); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/hll/CrossCountingTest.java b/src/test/java/org/apache/datasketches/hll/CrossCountingTest.java deleted file mode 100644 index 7bad7e18e..000000000 --- a/src/test/java/org/apache/datasketches/hll/CrossCountingTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.TgtHllType.HLL_4; -import static org.apache.datasketches.hll.TgtHllType.HLL_6; -import static org.apache.datasketches.hll.TgtHllType.HLL_8; -import static org.testng.Assert.assertEquals; - -import org.apache.datasketches.hll.HllSketch; -import org.apache.datasketches.hll.PairIterator; -import org.apache.datasketches.hll.TgtHllType; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -@SuppressWarnings("unused") -public class CrossCountingTest { - static final String LS = System.getProperty("line.separator"); - - @Test - public void crossCountingChecks() { - crossCountingCheck(4, 100); - crossCountingCheck(4, 10000); - crossCountingCheck(12, 7); - crossCountingCheck(12, 384); - crossCountingCheck(12, 10000); - } - - void crossCountingCheck(final int lgK, final int n) { - final HllSketch sk4 = buildSketch(n, lgK, HLL_4); - final int s4csum = computeChecksum(sk4); - //println(sk4.toString(true, true, true, true)); - int csum; - - final HllSketch sk6 = buildSketch(n, lgK, HLL_6); - csum = computeChecksum(sk6); - assertEquals(csum, s4csum); - //println(sk6.toString(true, true, true, true)); - - final HllSketch sk8 = buildSketch(n, lgK, HLL_8); - csum = computeChecksum(sk8); - assertEquals(csum, s4csum); - //println(sk8.toString(true, true, true, true)); - - //Conversions -// println("\nConverted HLL_6 to HLL_4:"); - final HllSketch sk6to4 = sk6.copyAs(HLL_4); - csum = computeChecksum(sk6to4); - assertEquals(csum, s4csum); -// println(sk6to4.toString(true, true, true, true)); - -// println("\nConverted HLL_8 to HLL_4:"); - final HllSketch sk8to4 = sk8.copyAs(HLL_4); - csum = computeChecksum(sk8to4); - assertEquals(csum, s4csum); -// println(sk8to4.toString(true, true, true, true)); - -// println("\nConverted HLL_4 to HLL_6:"); - final HllSketch sk4to6 = sk4.copyAs(HLL_6); - csum = computeChecksum(sk4to6); - //println(sk4to6.toString(true, true, true, true)); - assertEquals(csum, s4csum); - -// println("\nConverted HLL_8 to HLL_6:"); - final HllSketch sk8to6 = sk8.copyAs(HLL_6); - csum = computeChecksum(sk8to6); - assertEquals(csum, s4csum); -// println(sk8to6.toString(true, true, true, true)); - -// println("\nConverted HLL_4 to HLL_8:"); - final HllSketch sk4to8 = sk4.copyAs(HLL_8); - csum = computeChecksum(sk4to8); - assertEquals(csum, s4csum); -// println(sk4to8.toString(true, true, true, true)); - -// println("\nConverted HLL_6 to HLL_8:"); - final HllSketch sk6to8 = sk6.copyAs(HLL_8); - csum = computeChecksum(sk6to8); - assertEquals(csum, s4csum); -// println(sk6to8.toString(true, true, true, true)); - } - - private static HllSketch buildSketch(final int n, final int lgK, final TgtHllType tgtHllType) { - final HllSketch sketch = new HllSketch(lgK, tgtHllType); - for (int i = 0; i < n; i++) { - sketch.update(i); - } - return sketch; - } - - private static int computeChecksum(final HllSketch sketch) { - final PairIterator itr = sketch.iterator(); - int checksum = 0; - int key = 0; - while (itr.nextAll()) { - checksum += itr.getPair(); - key = itr.getKey(); //dummy - } - return checksum; - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - print(s + LS); - } - - /** - * @param s value to print - */ - static void print(final String s) { - //System.out.print(s); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/hll/DirectAuxHashMapTest.java b/src/test/java/org/apache/datasketches/hll/DirectAuxHashMapTest.java deleted file mode 100644 index 6a2b54217..000000000 --- a/src/test/java/org/apache/datasketches/hll/DirectAuxHashMapTest.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.hll.HllUtil.LG_AUX_ARR_INTS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; -import java.util.HashMap; - -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.hll.AbstractHllArray; -import org.apache.datasketches.hll.AuxHashMap; -import org.apache.datasketches.hll.DirectAuxHashMap; -import org.apache.datasketches.hll.DirectHllArray; -import org.apache.datasketches.hll.HeapAuxHashMap; -import org.apache.datasketches.hll.HllArray; -import org.apache.datasketches.hll.HllSketch; -import org.apache.datasketches.hll.HllUtil; -import org.apache.datasketches.hll.PairIterator; -import org.apache.datasketches.hll.TgtHllType; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class DirectAuxHashMapTest { - - @Test - public void checkGrow() { - final int lgConfigK = 4; - final TgtHllType tgtHllType = TgtHllType.HLL_4; - final int n = 8; //put lgConfigK == 4 into HLL mode - final long bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType); - HllSketch hllSketch; - final Arena arena = Arena.ofConfined(); - final MemorySegment wseg = arena.allocate(bytes); - - hllSketch = new HllSketch(lgConfigK, tgtHllType, wseg); - for (int i = 0; i < n; i++) { - hllSketch.update(i); - } - hllSketch.couponUpdate(HllUtil.pair(7, 15)); //mock extreme values - hllSketch.couponUpdate(HllUtil.pair(8, 15)); - hllSketch.couponUpdate(HllUtil.pair(9, 15)); - println(hllSketch.toString(true, true, true, true)); - DirectHllArray dha = (DirectHllArray) hllSketch.hllSketchImpl; - assertEquals(dha.getAuxHashMap().getLgAuxArrInts(), 2); - assertTrue(hllSketch.hasMemorySegment()); - assertTrue(hllSketch.isOffHeap()); - assertTrue(hllSketch.isSameResource(wseg)); - - //Check heapify - byte[] byteArray = hllSketch.toCompactByteArray(); - HllSketch hllSketch2 = HllSketch.heapify(byteArray); - final HllArray ha = (HllArray) hllSketch2.hllSketchImpl; - assertEquals(ha.getAuxHashMap().getLgAuxArrInts(), 2); - assertEquals(ha.getAuxHashMap().getAuxCount(), 3); - - //Check wrap - byteArray = hllSketch.toUpdatableByteArray(); - final MemorySegment wseg2 = MemorySegment.ofArray(byteArray); - hllSketch2 = HllSketch.writableWrap(wseg2); - println(hllSketch2.toString(true, true, true, true)); - final DirectHllArray dha2 = (DirectHllArray) hllSketch2.hllSketchImpl; - assertEquals(dha2.getAuxHashMap().getLgAuxArrInts(), 2); - assertEquals(dha2.getAuxHashMap().getAuxCount(), 3); - - //Check grow to on-heap - hllSketch.couponUpdate(HllUtil.pair(10, 15)); //puts it over the edge, must grow - println(hllSketch.toString(true, true, true, true)); - dha = (DirectHllArray) hllSketch.hllSketchImpl; - assertEquals(dha.getAuxHashMap().getLgAuxArrInts(), 3); - assertEquals(dha.getAuxHashMap().getAuxCount(), 4); - assertTrue(hllSketch.hasMemorySegment()); - assertFalse(hllSketch.isOffHeap()); - assertFalse(hllSketch.isSameResource(wseg)); - arena.close(); - assertFalse(wseg.scope().isAlive()); - } - - @Test - public void checkDiffToByteArr() { - final int lgK = 12; //this combination should create an Aux with ~18 exceptions - final int lgU = 19; - final TgtHllType type = TgtHllType.HLL_4; - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, type); - final byte[] segByteArr = new byte[bytes]; - final MemorySegment wseg = MemorySegment.ofArray(segByteArr); - final HllSketch heapSk = new HllSketch(lgK, type); - final HllSketch dirSk = new HllSketch(lgK, type, wseg); - for (int i = 0; i < (1 << lgU); i++) { - heapSk.update(i); - dirSk.update(i); //problem starts here. - } - final AbstractHllArray heapHllArr = (AbstractHllArray) heapSk.hllSketchImpl; - final AbstractHllArray dirHllArr = (AbstractHllArray) dirSk.hllSketchImpl; - assert dirHllArr instanceof DirectHllArray; - final AuxHashMap heapAux = heapHllArr.getAuxHashMap(); - assert heapAux instanceof HeapAuxHashMap; - final AuxHashMap dirAux = dirHllArr.getAuxHashMap(); - assert dirAux instanceof DirectAuxHashMap; - println("HeapAuxCount: " + heapAux.getAuxCount()); - println("DirAuxCount: " + dirAux.getAuxCount()); - final int heapCurMin = heapHllArr.getCurMin(); - final int dirCurMin = dirHllArr.getCurMin(); - println("HeapCurMin: " + heapCurMin); - println("DirCurMin: " + dirCurMin); - - - PairIterator auxItr; - auxItr = heapHllArr.getAuxIterator(); - println("\nHeap Pairs"); - //println(itr.getHeader()); - while (auxItr.nextValid()) { - println("" + auxItr.getPair()); - } - auxItr = dirHllArr.getAuxIterator(); - println("\nDirect Pairs"); - //println(itr.getHeader()); - while (auxItr.nextValid()) { - println(""+ auxItr.getPair()); - } - - PairIterator hllItr; - hllItr = heapSk.iterator(); - println("Heap HLL arr"); - println(hllItr.getHeader()); - while (hllItr.nextValid()) { - if ((hllItr.getValue() - heapCurMin) > 14) { - println(hllItr.getString() + ", " + hllItr.getPair()); - } - } - hllItr = dirSk.iterator(); - println("Direct HLL arr"); - println(hllItr.getHeader()); - while (hllItr.nextValid()) { - if ((hllItr.getValue() - dirCurMin) > 14) { - println(hllItr.getString() + ", " + hllItr.getPair()); - } - } - - final byte[] heapImg = heapSk.toUpdatableByteArray(); - final MemorySegment heapImgSeg = MemorySegment.ofArray(heapImg); - final byte[] dirImg = dirSk.toUpdatableByteArray(); - final MemorySegment dirImgSeg = MemorySegment.ofArray(dirImg); - - println("heapLen: " + heapImg.length + ", dirLen: " + dirImg.length - + ", segObjLen: "+segByteArr.length); - final int auxStart = 40 + (1 << (lgK -1)); - println("AuxStart: " + auxStart); - - - println(String.format("%14s%14s%14s", "dir wseg", "heap to b[]", "direct to b[]")); - for (int i = auxStart; i < heapImg.length; i += 4) { - println(String.format("%14d%14d%14d", - wseg.get(JAVA_INT_UNALIGNED, i), heapImgSeg.get(JAVA_INT_UNALIGNED, i), dirImgSeg.get(JAVA_INT_UNALIGNED, i))); - assert segByteArr[i] == heapImg[i]; - assert heapImg[i] == dirImg[i] : "i: " + i; - } - assertEquals(heapImg, dirImg); - } - - @Test - public void exerciseHeapAndDirectAux() { - initSketchAndMap(true, true); //direct, compact - initSketchAndMap(false, true); //heap, compact - initSketchAndMap(true, false); //direct, updatable - initSketchAndMap(false, false); //heap, updatable - } - - static void initSketchAndMap(final boolean direct, final boolean compact) { - final int lgK = 15; //this combination should create an Aux with ~18 exceptions - final int lgU = 20; - println("HLL_4, lgK: " + lgK + ", lgU: " + lgU); - final HashMap map = new HashMap<>(); - - //create sketch - HllSketch sketch; - if (direct) { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, TgtHllType.HLL_4); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - sketch = new HllSketch(lgK, TgtHllType.HLL_4, wseg); - } else { - sketch = new HllSketch(lgK, TgtHllType.HLL_4); - } - for (int i = 0; i < (1 << lgU); i++) { sketch.update(i); } - - //check Ser Bytes - assertEquals(sketch.getUpdatableSerializationBytes(), 40 + (1 << (lgK - 1)) + (4 << LG_AUX_ARR_INTS[lgK]) ); - - //extract the auxHashMap entries into a HashMap for easy checking - //extract direct aux iterator - final AbstractHllArray absDirectHllArr = (AbstractHllArray) sketch.hllSketchImpl; - - //the auxHashMap must exist for this test - final AuxHashMap auxMap = absDirectHllArr.getAuxHashMap(); - final int auxCount = auxMap.getAuxCount(); - assertEquals(auxMap.getCompactSizeBytes(), auxCount << 2); - final int auxArrInts = 1 << auxMap.getLgAuxArrInts(); - assertEquals(auxMap.getUpdatableSizeBytes(), auxArrInts << 2); - - final PairIterator itr = absDirectHllArr.getAuxIterator(); - - println("Source Aux Array."); - println(itr.getHeader()); - while (itr.nextValid()) { - map.put(itr.getSlot(), itr.getValue()); //create the aux reference map - println(itr.getString()); - } - final double est = sketch.getEstimate(); - println("\nHLL Array of original sketch: should match Source Aux Array."); - checkHllArr(sketch, map); //check HLL arr consistencies - - //serialize the direct sk as compact - final byte[] byteArr = (compact) ? sketch.toCompactByteArray() : sketch.toUpdatableByteArray(); - - //Heapify the byteArr image & check estimate - final HllSketch heapSk = HllSketch.heapify(MemorySegment.ofArray(byteArr)); - assertEquals(heapSk.getEstimate(), est, 0.0); - println("\nAux Array of heapified serialized sketch."); - checkAux(heapSk, map); //check Aux consistencies - println("\nHLL Array of heapified serialized sketch."); - checkHllArr(heapSk, map); //check HLL arr consistencies - - //Wrap the image as read-only & check estimate - final HllSketch wrapSk = HllSketch.wrap(MemorySegment.ofArray(byteArr)); - assertEquals(wrapSk.getEstimate(), est, 0.0); - println("\nAux Array of wrapped RO serialized sketch."); - checkAux(wrapSk, map); - println("\nHLL Array of wrapped RO serialized sketch."); - checkHllArr(wrapSk, map); - - println(wrapSk.toString(false, false, true, true)); - } - - //check HLL array consistencies with the map - static void checkHllArr(final HllSketch sk, final HashMap map) { - //extract aux iterator, which must exist for this test - final AbstractHllArray absHllArr = (AbstractHllArray) sk.hllSketchImpl; - final int curMin = absHllArr.getCurMin(); - //println("CurMin: " + curMin); - final PairIterator hllArrItr = sk.iterator(); - println(hllArrItr.getHeader()); - while (hllArrItr.nextValid()) { - final int hllArrVal = hllArrItr.getValue(); - if ((hllArrItr.getValue() - curMin) > 14) { - final int mapVal = map.get(hllArrItr.getSlot()); - println(hllArrItr.getString()); - assertEquals(hllArrVal, mapVal); - } - } - } - - //Check Aux consistencies to the map - static void checkAux(final HllSketch sk, final HashMap map) { - final AbstractHllArray absHllArr = (AbstractHllArray) sk.hllSketchImpl; - //extract aux iterator, which must exist for this test - final PairIterator heapAuxItr = absHllArr.getAuxIterator(); - println(heapAuxItr.getHeader()); - while (heapAuxItr.nextValid()) { - final int afterVal = heapAuxItr.getValue(); - if (afterVal > 14) { - println(heapAuxItr.getString()); - final int auxSlot = heapAuxItr.getSlot(); - assert map.containsKey(auxSlot); - final int beforeVal = map.get(heapAuxItr.getSlot()); - assertEquals(afterVal, beforeVal); - } - } - } - - @Test - public void checkDirectReadOnlyCompactAux() { - final int lgK = 15; //this combination should create an Aux with ~18 exceptions - final int lgU = 20; - final HllSketch sk = new HllSketch(lgK, TgtHllType.HLL_4); - for (int i = 0; i < (1 << lgU); i++) { sk.update(i); } - - } - - @Test - public void checkMustReplace() { - final int lgK = 7; - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, TgtHllType.HLL_4); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = new HllSketch(lgK, TgtHllType.HLL_4, wseg); - for (int i = 0; i < 25; i++) { sk.update(i); } - final DirectHllArray dHllArr = (DirectHllArray) sk.hllSketchImpl; - final AuxHashMap map = dHllArr.getNewAuxHashMap(); - map.mustAdd(100, 5); - int val = map.mustFindValueFor(100); - assertEquals(val, 5); - - map.mustReplace(100, 10); - val = map.mustFindValueFor(100); - assertEquals(val, 10); - - assertTrue(map.hasMemorySegment()); - assertFalse(map.isOffHeap()); - assertNull(map.copy()); - assertNull(map.getAuxIntArr()); - - try { - map.mustAdd(100, 12); - fail(); - } catch (final SketchesStateException e) { - //expected - } - - try { - map.mustFindValueFor(101); - fail(); - } catch (final SketchesStateException e) { - //expected - } - - try { - map.mustReplace(101, 5); - fail(); - } catch (final SketchesStateException e) { - //expected - } - } - - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/DirectCouponListTest.java b/src/test/java/org/apache/datasketches/hll/DirectCouponListTest.java deleted file mode 100644 index b3bdc63b6..000000000 --- a/src/test/java/org/apache/datasketches/hll/DirectCouponListTest.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.hll.PreambleUtil.LG_ARR_BYTE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.hll.AbstractCoupons; -import org.apache.datasketches.hll.CurMode; -import org.apache.datasketches.hll.HllSketch; -import org.apache.datasketches.hll.TgtHllType; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class DirectCouponListTest { - - @Test - public void promotionTests() { - //true means convert to compact array - promotions(8, 7, TgtHllType.HLL_8, true, CurMode.LIST); - promotions(8, 7, TgtHllType.HLL_8, false, CurMode.LIST); - promotions(8, 24, TgtHllType.HLL_8, true, CurMode.SET); - promotions(8, 24, TgtHllType.HLL_8, false, CurMode.SET); - promotions(8, 25, TgtHllType.HLL_8, true, CurMode.HLL); - promotions(8, 25, TgtHllType.HLL_8, false, CurMode.HLL); - promotions(8, 25, TgtHllType.HLL_6, true, CurMode.HLL); - promotions(8, 25, TgtHllType.HLL_6, false, CurMode.HLL); - promotions(8, 25, TgtHllType.HLL_4, true, CurMode.HLL); - promotions(8, 25, TgtHllType.HLL_4, false, CurMode.HLL); - - promotions(4, 7, TgtHllType.HLL_8, true, CurMode.LIST); - promotions(4, 7, TgtHllType.HLL_8, false, CurMode.LIST); - promotions(4, 8, TgtHllType.HLL_8, true, CurMode.HLL); - promotions(4, 8, TgtHllType.HLL_8, false, CurMode.HLL); - promotions(4, 8, TgtHllType.HLL_6, true, CurMode.HLL); - promotions(4, 8, TgtHllType.HLL_6, false, CurMode.HLL); - promotions(4, 8, TgtHllType.HLL_4, true, CurMode.HLL); - promotions(4, 8, TgtHllType.HLL_4, false, CurMode.HLL); - promotions(4, 25, TgtHllType.HLL_4, true, CurMode.HLL); - promotions(4, 25, TgtHllType.HLL_4, false, CurMode.HLL); - } - - private static void promotions(final int lgConfigK, final int n, final TgtHllType tgtHllType, final boolean compact, - final CurMode tgtMode) { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType); - HllSketch hllSketch; - - //println("DIRECT"); - byte[] barr1; - MemorySegment wseg; - try (Arena arena = Arena.ofConfined()) { - wseg = arena.allocate(bytes); - hllSketch = new HllSketch(lgConfigK, tgtHllType, wseg); - assertTrue(hllSketch.isEmpty()); - - for (int i = 0; i < n; i++) { - hllSketch.update(i); - } - //println(hllSketch.toString(true, true, false, false)); - assertFalse(hllSketch.isEmpty()); - assertEquals(hllSketch.getCurMode(), tgtMode); - assertTrue(hllSketch.hasMemorySegment()); - assertTrue(hllSketch.isOffHeap()); - assertTrue(hllSketch.isSameResource(wseg)); - - //convert direct sketch to byte[] - barr1 = (compact) ? hllSketch.toCompactByteArray() : hllSketch.toUpdatableByteArray(); - //println(PreambleUtil.toString(barr1)); - hllSketch.reset(); - assertTrue(hllSketch.isEmpty()); - } catch (final Exception e) { - throw new RuntimeException(e); - } - - //println("HEAP"); - final HllSketch hllSketch2 = new HllSketch(lgConfigK, tgtHllType); - for (int i = 0; i < n; i++) { - hllSketch2.update(i); - } - //println(hllSketch2.toString(true, true, false, false)); - //println(PreambleUtil.toString(barr2)); - assertEquals(hllSketch2.getCurMode(), tgtMode); - assertFalse(hllSketch2.hasMemorySegment()); - assertFalse(hllSketch2.isOffHeap()); - assertFalse(hllSketch2.isSameResource(wseg)); - final byte[] barr2 = (compact) ? hllSketch2.toCompactByteArray() : hllSketch2.toUpdatableByteArray(); - assertEquals(barr1.length, barr2.length, barr1.length + ", " + barr2.length); - //printDiffs(barr1, barr2); - assertEquals(barr1, barr2); - } - - @SuppressWarnings("unused") //only used when above printlns are enabled. - private static void printDiffs(final byte[] arr1, final byte[] arr2) { - final int len1 = arr1.length; - final int len2 = arr2.length; - final int minLen = Math.min(len1, len2); - for (int i = 0; i < minLen; i++) { - final int v1 = arr1[i] & 0XFF; - final int v2 = arr2[i] & 0XFF; - if (v1 == v2) { continue; } - println(i + ", " + v1 + ", " + v2); - } - } - - @Test - public void checkCouponToByteArray() { - final int lgK = 8; - final TgtHllType type = TgtHllType.HLL_8; - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, type); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = new HllSketch(lgK, type, wseg); - int i; - for (i = 0; i < 7; i++) { sk.update(i); } //LIST - - //toCompactSeg Arr from compact seg - byte[] compactByteArr = sk.toCompactByteArray(); - MemorySegment compactSeg = MemorySegment.ofArray(compactByteArr); - HllSketch skCompact = HllSketch.wrap(compactSeg); - byte[] compactByteArr2 = skCompact.toCompactByteArray(); - assertEquals(compactByteArr2, compactByteArr); - - //now check to UpdatableByteArr from compact seg - byte[] updatableByteArr = sk.toUpdatableByteArray(); - byte[] updatableByteArr2 = skCompact.toUpdatableByteArray(); - assertEquals(updatableByteArr2.length, updatableByteArr.length); - assertEquals(skCompact.getEstimate(), sk.getEstimate()); - - - sk.update(i); //SET - //toCompactSeg Arr from compact seg - compactByteArr = sk.toCompactByteArray(); - compactSeg = MemorySegment.ofArray(compactByteArr); - skCompact = HllSketch.wrap(compactSeg); - compactByteArr2 = skCompact.toCompactByteArray(); - assertEquals(compactByteArr2, compactByteArr); - - //now check to UpdatableByteArr from compact seg - updatableByteArr = sk.toUpdatableByteArray(); - updatableByteArr2 = skCompact.toUpdatableByteArray(); - assertEquals(updatableByteArr2.length, updatableByteArr.length); - assertEquals(skCompact.getEstimate(), sk.getEstimate()); - } - - @Test - public void checkDirectGetCouponIntArr() { - final int lgK = 8; - final TgtHllType type = TgtHllType.HLL_8; - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, type); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = new HllSketch(lgK, type, wseg); - final AbstractCoupons absCoup = (AbstractCoupons)sk.hllSketchImpl; - assertNull(absCoup.getCouponIntArr()); - } - - @Test - public void checkBasicGetLgCouponArrInts() { - final int lgK = 8; - final TgtHllType type = TgtHllType.HLL_8; - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, type); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = new HllSketch(lgK, type, wseg); - for (int i = 0; i < 7; i++) { sk.update(i); } - assertEquals(sk.getCurMode(), CurMode.LIST); - assertEquals(((AbstractCoupons) sk.hllSketchImpl).getLgCouponArrInts(), 3); - sk.update(7); - assertEquals(sk.getCurMode(), CurMode.SET); - assertEquals(((AbstractCoupons) sk.hllSketchImpl).getLgCouponArrInts(), 5); - - sk.reset(); - for (int i = 0; i < 7; i++) { sk.update(i); } - final byte lgArr = wseg.get(JAVA_BYTE, LG_ARR_BYTE); - wseg.set(JAVA_BYTE, LG_ARR_BYTE, (byte) 0); //corrupt to 0 - assertEquals(((AbstractCoupons) sk.hllSketchImpl).getLgCouponArrInts(), 3); - wseg.set(JAVA_BYTE, LG_ARR_BYTE, lgArr); //put correct value back - sk.update(7); - assertEquals(sk.getCurMode(), CurMode.SET); - assertEquals(sk.hllSketchImpl.curMode, CurMode.SET); - wseg.set(JAVA_BYTE, LG_ARR_BYTE, (byte) 0); //corrupt to 0 again - assertEquals(((AbstractCoupons) sk.hllSketchImpl).getLgCouponArrInts(), 5); - } - - @Test - public void checkHeapifyGetLgCouponArrInts() { - final int lgK = 8; - final TgtHllType type = TgtHllType.HLL_8; - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, type); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = new HllSketch(lgK, type, wseg); - for (int i = 0; i < 8; i++) { sk.update(i); } - assertEquals(sk.getCurMode(), CurMode.SET); - final double est1 = sk.getEstimate(); - - wseg.set(JAVA_BYTE, LG_ARR_BYTE, (byte) 0); //corrupt to 0 - final HllSketch sk2 = HllSketch.heapify(wseg); - final double est2 = sk2.getEstimate(); - assertEquals(est2, est1, 0.0); - //println(sk2.toString(true, true, true, true)); - //println(PreambleUtil.toString(wseg)); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/DirectHllSketchTest.java b/src/test/java/org/apache/datasketches/hll/DirectHllSketchTest.java deleted file mode 100644 index 4b9554b5e..000000000 --- a/src/test/java/org/apache/datasketches/hll/DirectHllSketchTest.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.HashSet; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesReadOnlyException; -import org.apache.datasketches.hll.AbstractHllArray; -import org.apache.datasketches.hll.CurMode; -import org.apache.datasketches.hll.HllSketch; -import org.apache.datasketches.hll.IntMemorySegmentPairIterator; -import org.apache.datasketches.hll.PairIterator; -import org.apache.datasketches.hll.TgtHllType; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class DirectHllSketchTest { - - @Test - public void checkNoWriteAccess() { - noWriteAccess(TgtHllType.HLL_4, 7); - noWriteAccess(TgtHllType.HLL_4, 24); - noWriteAccess(TgtHllType.HLL_4, 25); - noWriteAccess(TgtHllType.HLL_6, 25); - noWriteAccess(TgtHllType.HLL_8, 25); - } - - private static void noWriteAccess(final TgtHllType tgtHllType, final int n) { - final int lgConfigK = 8; - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = new HllSketch(lgConfigK, tgtHllType, wseg); - - for (int i = 0; i < n; i++) { sk.update(i); } - - final HllSketch sk2 = HllSketch.wrap(wseg); - try { - sk2.update(1); - fail(); - } catch (final SketchesReadOnlyException e) { - //expected - } - } - - @Test - public void checkCompactToUpdatable() { - final int lgConfigK = 15; - final int n = 1 << 20; - final TgtHllType type = TgtHllType.HLL_4; - - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, type); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - //create first direct updatable sketch - final HllSketch sk = new HllSketch(lgConfigK, type, wseg); - for (int i = 0; i < n; i++) { sk.update(i); } - //Create compact byte arr - final byte[] cByteArr = sk.toCompactByteArray(); //16496 = (auxStart)16424 + 72 - final MemorySegment cseg = MemorySegment.ofArray(cByteArr); - //Create updatable byte arr - final byte[] uByteArr = sk.toUpdatableByteArray(); //16936 = (auxStart)16424 + 512 - //get auxStart and auxArrInts for updatable - final AbstractHllArray absArr = (AbstractHllArray)sk.hllSketchImpl; - final int auxStart = absArr.auxStart; - final int auxArrInts = 1 << absArr.getAuxHashMap().getLgAuxArrInts(); - //hash set to check result - final HashSet set = new HashSet<>(); - //create HashSet of values - final PairIterator itr = new IntMemorySegmentPairIterator(uByteArr, auxStart, auxArrInts, lgConfigK); - //println(itr.getHeader()); - int validCount = 0; - while (itr.nextValid()) { - set.add(itr.getPair()); - validCount++; - //println(itr.getString()); - } - - //Wrap the compact image as read-only - final HllSketch sk2 = HllSketch.wrap(cseg); //cseg is 16496 - //serialize it to updatable image - final byte[] uByteArr2 = sk2.toUpdatableByteArray(); - final PairIterator itr2 = new IntMemorySegmentPairIterator(uByteArr2, auxStart, auxArrInts, lgConfigK); - //println(itr2.getHeader()); - int validCount2 = 0; - while (itr2.nextValid()) { - final boolean exists = set.contains(itr2.getPair()); - if (exists) { validCount2++; } - //println(itr2.getString()); - } - assertEquals(validCount, validCount2); - } - - @Test - public void checkPutKxQ1_Misc() { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(4, TgtHllType.HLL_4); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = new HllSketch(4, TgtHllType.HLL_4, wseg); - for (int i = 0; i < 8; i++) { sk.update(i); } - assertTrue(sk.getCurMode() == CurMode.HLL); - final AbstractHllArray absArr = (AbstractHllArray)sk.hllSketchImpl; - absArr.putKxQ1(1.0); - assertEquals(absArr.getKxQ1(), 1.0); - absArr.putKxQ1(0.0); - - final MemorySegment seg = wseg; - final HllSketch sk2 = HllSketch.wrap(seg); - try { - sk2.reset(); - fail(); - } catch (final SketchesArgumentException e) { - //expected - } - } - - @Test - public void checkToCompactByteArr() { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(4, TgtHllType.HLL_4); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = new HllSketch(4, TgtHllType.HLL_4, wseg); - for (int i = 0; i < 8; i++) { sk.update(i); } - final byte[] compByteArr = sk.toCompactByteArray(); - final MemorySegment compSeg = MemorySegment.ofArray(compByteArr); - final HllSketch sk2 = HllSketch.wrap(compSeg); - final byte[] compByteArr2 = sk2.toCompactByteArray(); - assertEquals(compByteArr2, compByteArr); - } - - @Test - public void checkToUpdatableByteArr() { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(4, TgtHllType.HLL_4); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = new HllSketch(4, TgtHllType.HLL_4, wseg); - for (int i = 0; i < 8; i++) { sk.update(i); } - final byte[] udByteArr = sk.toUpdatableByteArray(); - final byte[] compByteArr = sk.toCompactByteArray(); - final MemorySegment compSeg = MemorySegment.ofArray(compByteArr); - final HllSketch sk2 = HllSketch.wrap(compSeg); - final byte[] udByteArr2 = sk2.toUpdatableByteArray(); - assertEquals(udByteArr2, udByteArr); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/DirectUnionTest.java b/src/test/java/org/apache/datasketches/hll/DirectUnionTest.java deleted file mode 100644 index 114530a86..000000000 --- a/src/test/java/org/apache/datasketches/hll/DirectUnionTest.java +++ /dev/null @@ -1,462 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.Math.min; -import static org.apache.datasketches.hll.TgtHllType.HLL_4; -import static org.apache.datasketches.hll.TgtHllType.HLL_6; -import static org.apache.datasketches.hll.TgtHllType.HLL_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.hll.HllSketch; -import org.apache.datasketches.hll.HllUtil; -import org.apache.datasketches.hll.RelativeErrorTables; -import org.apache.datasketches.hll.TgtHllType; -import org.apache.datasketches.hll.HllUnion; - -/** - * @author Lee Rhodes - */ -public class DirectUnionTest { - static final String LS = System.getProperty("line.separator"); - - static final int[] nArr = {1, 3, 10, 30, 100, 300, 1000, 3000, 10000, 30000}; - - // n1,... lgK,... tgtHll, Mode Ooo Est - static final String hdrFmt = - "%6s%6s%6s" + "%8s%5s%5s%5s" + "%7s%6s" + "%7s%6s%6s" +"%3s%2s%2s"+ "%13s%12s"; - static final String hdr = String.format(hdrFmt, - "n1", "n2", "tot", - "lgMaxK", "lgK1", "lgK2", "lgKR", - "tgt1", "tgt2", - "Mode1", "Mode2", "ModeR", - "1", "2", "R", - "Est", "Err%"); - - /** - * The task here is to check the transition boundaries as the sketch morphs between LIST to - * SET to HLL modes. The transition points vary as a function of lgConfigK. In addition, - * this checks that the union operation is operating properly based on the order the - * sketches are presented to the union. - */ - @Test - public void checkUnions() { - //HLL_4: t=0, HLL_6: t=1, HLL_8: t=2 - final int t1 = 2; //type = HLL_8 - final int t2 = 2; - final int rt = 2; //result type - println("TgtR: " + TgtHllType.values()[rt].toString()); - - int lgK1 = 7; - int lgK2 = 7; - int lgMaxK = 7; - int n1 = 7; - int n2 = 7; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 = 8; - n2 = 7; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 = 7; - n2 = 8; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 = 8; - n2 = 8; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 = 7; - n2 = 14; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - println("++END BASE GROUP++"); - - int i = 0; - for (i = 7; i <= 13; i++) - { - lgK1 = i; - lgK2 = i; - lgMaxK = i; - { - n1 = ((1 << (i - 3)) * 3)/4; //compute the transition point - n2 = n1; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 -= 2; - n2 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - } - println("--END MINOR GROUP--"); - lgK1 = i; - lgK2 = i + 1; - lgMaxK = i; - { - n1 = ((1 << (i - 3)) * 3)/4; - n2 = n1; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 -= 2; - n2 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - } - println("--END MINOR GROUP--"); - lgK1 = i + 1; - lgK2 = i; - lgMaxK = i; - { - n1 = ((1 << (i - 3)) * 3)/4; - n2 = n1; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 -= 2; - n2 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - } - println("--END MINOR GROUP--"); - lgK1 = i + 1; - lgK2 = i + 1; - lgMaxK = i; - { - n1 = ((1 << (i - 3)) * 3)/4; - n2 = n1; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 -= 2; - n2 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - } - println("++END MAJOR GROUP++"); - } //End for - } - - @Test - public void check() { //n1=8, n2=7, lgK1=lgK2=lgMaxK=7, all HLL_8 - basicUnion(8, 7, 7, 7, 7, 2, 2, 2); - } - - private static void basicUnion(final int n1, final int n2, final int lgK1, final int lgK2, - final int lgMaxK, final int t1, final int t2, final int rt) { - long v = 0; - final int tot = n1 + n2; - final TgtHllType type1 = TgtHllType.values()[t1]; - final String t1str = type1.toString(); - final TgtHllType type2 = TgtHllType.values()[t2]; - final String t2str = type2.toString(); - final TgtHllType resultType = TgtHllType.values()[rt]; - //String rtStr = resultType.toString(); - - final HllSketch h1 = new HllSketch(lgK1, type1); - final HllSketch h2 = new HllSketch(lgK2, type2); - final int lgControlK = min(min(lgK1, lgK2), lgMaxK); //min of all 3 - final HllSketch control = new HllSketch(lgControlK, resultType); - final String dataFmt = "%6d%6d%6d," + "%7d%5d%5d%5d," + "%6s%6s," + "%6s%6s%6s," - +"%2s%2s%2s," + "%12f%12f%%"; - - for (long i = 0; i < n1; i++) { - h1.update(v + i); - control.update(v + i); - } - v += n1; - for (long i = 0; i < n2; i++) { - h2.update(v + i); - control.update(v + i); - } - v += n2; - - final String h1SketchStr = ("H1 SKETCH: \n" + h1.toString()); - final String h2SketchStr = ("H2 SKETCH: \n" + h2.toString()); - - final HllUnion union = newUnion(lgMaxK); - union.update(h1); - - final String uH1SketchStr = ("Union after H1: \n" + union.getResult(resultType).toString()); - //println(uH1SketchStr); - - union.update(h2); - final HllSketch result = union.getResult(resultType); - final int lgKR = result.getLgConfigK(); - - final String uSketchStr =("Union after H2: \n" + result.toString()); - - final double uEst = result.getEstimate(); - final double uUb = result.getUpperBound(2); - final double uLb = result.getLowerBound(2); - final double rerr = ((uEst/tot) - 1.0) * 100; - final String mode1 = h1.getCurMode().toString(); - final String mode2 = h2.getCurMode().toString(); - final String modeR = result.getCurMode().toString(); - - //Control - final String cSketchStr = ("CONTROL SKETCH: \n" + control.toString()); - final double controlEst = control.getEstimate(); - final double controlUb = control.getUpperBound(2); - final double controlLb = control.getLowerBound(2); - final String h1ooo = h1.isOutOfOrder() ? "T" : "F"; - final String h2ooo = h2.isOutOfOrder() ? "T" : "F"; - final String resultooo = result.isOutOfOrder() ? "T" : "F"; - final String row = String.format(dataFmt, - n1, n2, tot, - lgMaxK, lgK1, lgK2, lgKR, - t1str, t2str, - mode1, mode2, modeR, - h1ooo, h2ooo, resultooo, - uEst, rerr); - println(h1SketchStr); - println(h2SketchStr); - println(uH1SketchStr); - println(uSketchStr); - println(cSketchStr); - println(hdr); - println(row); - assertTrue((controlUb - controlEst) >= 0); - assertTrue((uUb - uEst) >= 0); - assertTrue((controlEst - controlLb) >= 0); - assertTrue((uEst -uLb) >= 0); - } - - @Test - public void checkToFromUnion1() { - for (int i = 0; i < 10; i++) { - final int n = nArr[i]; - for (int lgK = 4; lgK <= 13; lgK++) { - toFrom1(lgK, HLL_4, n); - toFrom1(lgK, HLL_6, n); - toFrom1(lgK, HLL_8, n); - } - println("======="); - } - } - - private static void toFrom1(final int lgK, final TgtHllType tgtHllType, final int n) { - final HllUnion srcU = newUnion(lgK); - final HllSketch srcSk = new HllSketch(lgK, tgtHllType); - for (int i = 0; i < n; i++) { - srcSk.update(i); - } - println("n: " + n + ", lgK: " + lgK + ", type: " + tgtHllType); - //printSketch(src, "SRC"); - srcU.update(srcSk); - - final byte[] byteArr = srcU.toCompactByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - final HllUnion dstU = HllUnion.heapify(seg); - - assertEquals(dstU.getEstimate(), srcU.getEstimate(), 0.0); - } - - @Test - public void checkToFromUnion2() { - for (int i = 0; i < 10; i++) { - final int n = nArr[i]; - for (int lgK = 4; lgK <= 13; lgK++) { - toFrom2(lgK, HLL_4, n); - toFrom2(lgK, HLL_6, n); - toFrom2(lgK, HLL_8, n); - } - println("======="); - } - } - - private static void toFrom2(final int lgK, final TgtHllType tgtHllType, final int n) { - final HllUnion srcU = newUnion(lgK); - final HllSketch srcSk = new HllSketch(lgK, tgtHllType); - for (int i = 0; i < n; i++) { - srcSk.update(i); - } - println("n: " + n + ", lgK: " + lgK + ", type: " + tgtHllType); - //printSketch(src, "SRC"); - srcU.update(srcSk); - - final byte[] byteArr = srcU.toCompactByteArray(); - final HllUnion dstU = HllUnion.heapify(byteArr); - - assertEquals(dstU.getEstimate(), srcU.getEstimate(), 0.0); - } - - @Test - public void checkCompositeEst() { - final HllUnion u = newUnion(12); - assertEquals(u.getCompositeEstimate(), 0, .03); - for (int i = 1; i <= 15; i++) { u.update(i); } - assertEquals(u.getCompositeEstimate(), 15, 15 *.03); - for (int i = 15; i <= 1000; i++) { u.update(i); } - assertEquals(u.getCompositeEstimate(), 1000, 1000 * .03); - } - - @SuppressWarnings("unused") - @Test - public void checkMisc() { - try { - final HllUnion u = newUnion(HllUtil.MIN_LOG_K - 1); - fail(); - } catch (final SketchesArgumentException e) { - //expected - } - try { - final HllUnion u = newUnion(HllUtil.MAX_LOG_K + 1); - fail(); - } catch (final SketchesArgumentException e) { - //expected - } - final HllUnion u = newUnion(7); - final HllSketch sk = u.getResult(); - assertTrue(sk.isEmpty()); - } - - @Test - public void checkHeapify() { - final HllUnion u = newUnion(16); - for (int i = 0; i < (1 << 20); i++) { - u.update(i); - } - final double est1 = u.getEstimate(); - final byte[] byteArray = u.toUpdatableByteArray(); - final HllUnion u2 = HllUnion.heapify(byteArray); - assertEquals(u2.getEstimate(), est1, 0.0); - } - - @Test //for lgK <= 12 - public void checkUbLb() { - final int lgK = 4; - final int n = 1 << 20; - final boolean oooFlag = false; - println("LgK="+lgK+", UB3, " + ((getBound(lgK, true, oooFlag, 3, n) / n) - 1)); - println("LgK="+lgK+", UB2, " + ((getBound(lgK, true, oooFlag, 2, n) / n) - 1)); - println("LgK="+lgK+", UB1, " + ((getBound(lgK, true, oooFlag, 1, n) / n) - 1)); - println("LgK="+lgK+", LB1, " + ((getBound(lgK, false, oooFlag, 1, n) / n) - 1)); - println("LgK="+lgK+", LB2, " + ((getBound(lgK, false, oooFlag, 2, n) / n) - 1)); - println("LgK="+lgK+", LB3, " + ((getBound(lgK, false, oooFlag, 3, n) / n) - 1)); - } - - @Test - public void checkEmptyCouponMisc() { - final int lgK = 8; - final HllUnion union = newUnion(lgK); - for (int i = 0; i < 20; i++) { union.update(i); } //SET mode - union.couponUpdate(0); - assertEquals(union.getEstimate(), 20.0, 0.001); - assertEquals(union.getTgtHllType(), TgtHllType.HLL_8); - assertTrue(union.hasMemorySegment()); - assertFalse(union.isOffHeap()); - final int bytes = union.getUpdatableSerializationBytes(); - assertTrue(bytes <= HllUnion.getMaxSerializationBytes(lgK)); - assertFalse(union.isCompact()); - } - - @Test - public void checkUnionWithWrap() { - final int lgConfigK = 4; - final TgtHllType type = TgtHllType.HLL_4; - final int n = 2; - final HllSketch sk = new HllSketch(lgConfigK, type); - for (int i = 0; i < n; i++) { sk.update(i); } - final double est = sk.getEstimate(); - final byte[] skByteArr = sk.toCompactByteArray(); - - final HllSketch sk2 = HllSketch.wrap(MemorySegment.ofArray(skByteArr)); - assertEquals(sk2.getEstimate(), est, 0.0); - - final HllUnion union = newUnion(lgConfigK); - union.update(HllSketch.wrap(MemorySegment.ofArray(skByteArr))); - assertEquals(union.getEstimate(), est, 0.0); - } - - @Test - public void checkUnionWithWrap2() { - final int lgConfigK = 10; - final int n = 128; - final HllSketch sk1 = new HllSketch(lgConfigK); - for (int i = 0; i < n; i++) { sk1.update(i); } - final double est1 = sk1.getEstimate(); - final byte[] byteArr1 = sk1.toCompactByteArray(); - - final HllUnion union = newUnion(lgConfigK); - union.update(HllSketch.wrap(MemorySegment.ofArray(byteArr1))); - final double est2 = union.getEstimate(); - assertEquals(est2, est1); - } - - @Test - public void checkWritableWrap() { - final int lgConfigK = 10; - final int n = 128; - final HllUnion union = newUnion(lgConfigK); - for (int i = 0; i < n; i++) { union.update(i); } - final double est = union.getEstimate(); - final HllUnion union2 = HllUnion.writableWrap(MemorySegment.ofArray(union.toUpdatableByteArray())); - final double est2 = union2.getEstimate(); - assertEquals(est2, est, 0.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkWritableWrapThrows() { - final int lgConfigK = 10; - final int n = 128; - final HllSketch sk = new HllSketch(lgConfigK, HLL_6); - for (int i = 0; i < n; i++) {sk.update(i); } - HllUnion.writableWrap(MemorySegment.ofArray(sk.toUpdatableByteArray())); - } - - private static HllUnion newUnion(final int lgK) { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, TgtHllType.HLL_8); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - return new HllUnion(lgK, wseg); - } - - private static double getBound(final int lgK, final boolean ub, final boolean oooFlag, final int numStdDev, final double est) { - final double re = RelativeErrorTables.getRelErr(ub, oooFlag, lgK, numStdDev); - return est / (1.0 + re); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - print(s + LS); - } - - /** - * @param s value to print - */ - static void print(final String s) { - //System.out.print(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/HllArrayTest.java b/src/test/java/org/apache/datasketches/hll/HllArrayTest.java deleted file mode 100644 index 3bbb01db0..000000000 --- a/src/test/java/org/apache/datasketches/hll/HllArrayTest.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.TgtHllType.HLL_4; -import static org.apache.datasketches.hll.TgtHllType.HLL_6; -import static org.apache.datasketches.hll.TgtHllType.HLL_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.hll.AbstractHllArray; -import org.apache.datasketches.hll.HllArray; -import org.apache.datasketches.hll.HllSketch; -import org.apache.datasketches.hll.TgtHllType; -import org.apache.datasketches.hll.HllUnion; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class HllArrayTest { - - @Test - public void checkCompositeEst() { - testComposite(4, HLL_8, 1000); - testComposite(5, HLL_8, 1000); - testComposite(6, HLL_8, 1000); - testComposite(13, HLL_8, 10000); - } - - @Test - public void checkBigHipGetRse() { - final HllSketch sk = new HllSketch(13, HLL_8); - for (int i = 0; i < 10000; i++) { - sk.update(i); - } - } - - private static void testComposite(final int lgK, final TgtHllType tgtHllType, final int n) { - final HllUnion u = new HllUnion(lgK); - final HllSketch sk = new HllSketch(lgK, tgtHllType); - for (int i = 0; i < n; i++) { - u.update(i); - sk.update(i); - } - u.update(sk); //merge - final HllSketch res = u.getResult(HLL_8); - res.getCompositeEstimate(); - } - - @Test - public void toByteArray_Heapify() { - int lgK = 4; - int u = 8; - toByteArrayHeapify(lgK, HLL_4, u, true); - toByteArrayHeapify(lgK, HLL_6, u, false); - toByteArrayHeapify(lgK, HLL_8, u, true); - - lgK = 16; - u = (((1 << (lgK - 3))*3)/4) + 100; - toByteArrayHeapify(lgK, HLL_4, u, false); - toByteArrayHeapify(lgK, HLL_6, u, true); - toByteArrayHeapify(lgK, HLL_8, u, false); - - lgK = 21; - u = (((1 << (lgK - 3))*3)/4) + 1000; - toByteArrayHeapify(lgK, HLL_4, u, true); - toByteArrayHeapify(lgK, HLL_6, u, false); - toByteArrayHeapify(lgK, HLL_8, u, true); - } - - private static void toByteArrayHeapify(final int lgK, final TgtHllType tgtHllType, final int u, final boolean direct) { - HllSketch sk1; - MemorySegment wseg = null; - if (direct) { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, tgtHllType); - wseg = MemorySegment.ofArray(new byte[bytes]); - sk1 = new HllSketch(lgK, tgtHllType, wseg); - } else { - sk1 = new HllSketch(lgK, tgtHllType); - } - - for (int i = 0; i < u; i++) { - sk1.update(i); - } - assert sk1.hllSketchImpl instanceof AbstractHllArray; - if (sk1.hllSketchImpl instanceof HllArray) { - assertFalse(sk1.hllSketchImpl.hasMemorySegment()); - assertFalse(sk1.isSameResource(wseg)); - } else { //DirectHllArray - assertTrue(sk1.hllSketchImpl.hasMemorySegment()); - assertTrue(sk1.isSameResource(wseg)); - } - - //sk1.update(u); - final double est1 = sk1.getEstimate(); - assertEquals(est1, u, u * .03); - assertEquals(sk1.getHipEstimate(), est1, 0.0); - - //misc calls - sk1.hllSketchImpl.putEmptyFlag(false); - sk1.hllSketchImpl.putRebuildCurMinNumKxQFlag(true); - sk1.hllSketchImpl.putRebuildCurMinNumKxQFlag(false); - - byte[] byteArray = sk1.toCompactByteArray(); - HllSketch sk2 = HllSketch.heapify(byteArray); - double est2 = sk2.getEstimate(); - assertEquals(est2, est1, 0.0); - - byteArray = sk1.toUpdatableByteArray(); - sk2 = HllSketch.heapify(byteArray); - est2 = sk2.getEstimate(); - assertEquals(est2, est1, 0.0); - - sk1.reset(); - assertEquals(sk1.getEstimate(), 0.0, 0.0); - } - - @Test - public void checkHll4Exceptions() { - final int lgK = 4; - final int k = 1 << lgK; - final HllSketch skH4 = new HllSketch(lgK, HLL_4); - for (int i = 0; i < k; i++) { skH4.update(i); } - final AbstractHllArray absHllArr = (AbstractHllArray)skH4.hllSketchImpl; - try { - absHllArr.updateSlotNoKxQ(0,0); - fail(); - } - catch (final SketchesStateException e) { } //OK - } - - @Test - public void checkDHll4Exceptions() { - final int lgK = 4; - final int k = 1 << lgK; - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, HLL_4); - final HllSketch skD4 = new HllSketch(lgK, HLL_4, MemorySegment.ofArray(new byte[bytes])); - for (int i = 0; i < k; i++) { skD4.update(i); } - final AbstractHllArray absHllArr = (AbstractHllArray)skD4.hllSketchImpl; - try { - absHllArr.updateSlotNoKxQ(0,0); - fail(); - } - catch (final SketchesStateException e) { } //OK - } - - @Test - public void checkHll6Exceptions() { - final int lgK = 4; - final int k = 1 << lgK; - final HllSketch skH6 = new HllSketch(lgK, HLL_6); - for (int i = 0; i < k; i++) { skH6.update(i); } - final AbstractHllArray absHllArr = (AbstractHllArray)skH6.hllSketchImpl; - try { - absHllArr.getNibble(0); - fail(); - } - catch (final SketchesStateException e) { } //OK - try { - absHllArr.putNibble(0,0); - fail(); - } - catch (final SketchesStateException e) { } //OK - try { - absHllArr.updateSlotNoKxQ(0,0); - fail(); - } - catch (final SketchesStateException e) { } //OK - } - - @Test - public void checkDHll6Exceptions() { - final int lgK = 4; - final int k = 1 << lgK; - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, HLL_6); - final HllSketch skD6 = new HllSketch(lgK, HLL_6, MemorySegment.ofArray(new byte[bytes])); - for (int i = 0; i < k; i++) { skD6.update(i); } - final AbstractHllArray absHllArr = (AbstractHllArray)skD6.hllSketchImpl; - try { - absHllArr.getNibble(0); - fail(); - } - catch (final SketchesStateException e) { } //OK - try { - absHllArr.putNibble(0,0); - fail(); - } - catch (final SketchesStateException e) { } //OK - try { - absHllArr.updateSlotNoKxQ(0,0); - fail(); - } - catch (final SketchesStateException e) { } //OK - } - - @Test - public void checkHll8Exceptions() { - final int lgK = 4; - final int k = 1 << lgK; - final HllSketch skH6 = new HllSketch(lgK, HLL_8); - for (int i = 0; i < k; i++) { skH6.update(i); } - final AbstractHllArray absHllArr = (AbstractHllArray)skH6.hllSketchImpl; - try { - absHllArr.getNibble(0); - fail(); - } - catch (final SketchesStateException e) { } //OK - try { - absHllArr.putNibble(0,0); - fail(); - } - catch (final SketchesStateException e) { } //OK - } - - @Test - public void checkDHll8Exceptions() { - final int lgK = 4; - final int k = 1 << lgK; - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, HLL_8); - final HllSketch skD6 = new HllSketch(lgK, HLL_8, MemorySegment.ofArray(new byte[bytes])); - for (int i = 0; i < k; i++) { skD6.update(i); } - final AbstractHllArray absHllArr = (AbstractHllArray)skD6.hllSketchImpl; - try { - absHllArr.getNibble(0); - fail(); - } - catch (final SketchesStateException e) { } //OK - try { - absHllArr.putNibble(0,0); - fail(); - } - catch (final SketchesStateException e) { } //OK - } - - @Test - public void checkIsCompact() { - final HllSketch sk = new HllSketch(4); - for (int i = 0; i < 8; i++) { sk.update(i); } - assertFalse(sk.isCompact()); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/HllSketchCrossLanguageTest.java b/src/test/java/org/apache/datasketches/hll/HllSketchCrossLanguageTest.java deleted file mode 100644 index 51932d554..000000000 --- a/src/test/java/org/apache/datasketches/hll/HllSketchCrossLanguageTest.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES; -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.getFileBytes; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; -import static org.apache.datasketches.hll.TgtHllType.HLL_4; -import static org.apache.datasketches.hll.TgtHllType.HLL_6; -import static org.apache.datasketches.hll.TgtHllType.HLL_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -/** - * Serialize binary sketches to be tested by C++ code. - * Test deserialization of binary sketches serialized by C++ code. - */ -public class HllSketchCrossLanguageTest { - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTesting() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (final int n: nArr) { - final HllSketch hll4 = new HllSketch(HllSketch.DEFAULT_LG_K, HLL_4); - final HllSketch hll6 = new HllSketch(HllSketch.DEFAULT_LG_K, HLL_6); - final HllSketch hll8 = new HllSketch(HllSketch.DEFAULT_LG_K, HLL_8); - for (int i = 0; i < n; i++) { - hll4.update(i); - } - for (int i = 0; i < n; i++) { - hll6.update(i); - } - for (int i = 0; i < n; i++) { - hll8.update(i); - } - putBytesToJavaPath("hll4_n" + n + "_java.sk", hll4.toCompactByteArray()); - putBytesToJavaPath("hll6_n" + n + "_java.sk", hll6.toCompactByteArray()); - putBytesToJavaPath("hll8_n" + n + "_java.sk", hll8.toCompactByteArray()); - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void hll4() throws IOException { - final int[] nArr = {0, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "hll4_n" + n + "_cpp.sk"); - final HllSketch sketch = HllSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(sketch.getLgConfigK(), 12); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertEquals(sketch.getEstimate(), n, n * 0.02); - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void hll6() throws IOException { - final int[] nArr = {0, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "hll6_n" + n + "_cpp.sk"); - final HllSketch sketch = HllSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(sketch.getLgConfigK(), 12); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertEquals(sketch.getEstimate(), n, n * 0.02); - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void hll8() throws IOException { - final int[] nArr = {0, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "hll8_n" + n + "_cpp.sk"); - final HllSketch sketch = HllSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(sketch.getLgConfigK(), 12); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertEquals(sketch.getEstimate(), n, n * 0.02); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/HllSketchMergeOrderTest.java b/src/test/java/org/apache/datasketches/hll/HllSketchMergeOrderTest.java deleted file mode 100644 index 1618f81e7..000000000 --- a/src/test/java/org/apache/datasketches/hll/HllSketchMergeOrderTest.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.common.Util.pwr2SeriesNext; -import static org.testng.Assert.assertTrue; - -import org.testng.annotations.Test; - -/** - * This test demonstrates that DataSketch HLL merging is not order-dependent if you use the Composite estimator. - */ -public class HllSketchMergeOrderTest { - - private static final int LgK = 11; - - @Test - public void testDataSketchHLLMergeOrderDependency() { - final int ppo = 1 << 17; //= 131,072 unique Points Per Octave. - - // Create 3 sketches with fractional powers of 2 series - final HllSketch sketchA = createUniquePowerSeriesSketch(1L << 59, ppo, 1L << 60); - final HllSketch sketchB = createUniquePowerSeriesSketch(1L << 60, ppo, 1L << 61); - final HllSketch sketchC = createUniquePowerSeriesSketch(1L << 61, ppo, 1L << 62); - - final double skAEst = sketchA.getCompositeEstimate(); - final double skBEst = sketchB.getCompositeEstimate(); - final double skCEst = sketchC.getCompositeEstimate(); - - final double skA_RE = (skAEst/ppo) - 1.0; - final double skB_RE = (skBEst/ppo) - 1.0; - final double skC_RE = (skCEst/ppo) - 1.0; - - //Print individual composite estimates and Relative Error: - println(""); - println("SketchA estimate: " + skAEst + ", RE%: " + (skA_RE * 100)); - println("SketchB estimate: " + skBEst + ", RE%: " + (skB_RE * 100)); - println("SketchC estimate: " + skCEst + ", RE%: " + (skC_RE * 100)); - - println("\nNOTE: Sketch Relative Error for Composite Estimator for LgK = 11 is +/- 4.6% at 95% confidence.\n"); - - // Test six different merge orders: - final double estABC = mergeThreeSketches(sketchA, sketchB, sketchC); - final double estACB = mergeThreeSketches(sketchA, sketchC, sketchB); - final double estBAC = mergeThreeSketches(sketchB, sketchA, sketchC); - final double estBCA = mergeThreeSketches(sketchB, sketchC, sketchA); - final double estCAB = mergeThreeSketches(sketchC, sketchA, sketchB); - final double estCBA = mergeThreeSketches(sketchC, sketchB, sketchA); - - println("Merge order ABC: " + estABC); - println("Merge order ACB: " + estACB); - println("Merge order BAC: " + estBAC); - println("Merge order BCA: " + estBCA); - println("Merge order CAB: " + estCAB); - println("Merge order CBA: " + estCBA); - - assertTrue((estABC == estACB) && (estABC == estBAC) && (estABC == estBCA) && (estABC == estCAB) && (estABC == estCBA)); - } - - /** - * Generates a power series based on fractional powers of 2 where the separation between successive values is 2^(1/ppo). - * @param baseValue starting value, inclusive - * @param ppo number of unique points per octave - * @param limit the upper limit, exclusive - * @return the loaded sketch - */ - private HllSketch createUniquePowerSeriesSketch(final long baseValue, final int ppo, final long limit) { - final HllSketch sketch = new HllSketch(LgK); - int count = 0; - long lastp = 0; - for (long p = baseValue; p < limit; p = pwr2SeriesNext(ppo, p)) { - sketch.update(p); - count++; - lastp = p; - } - println("BaseValue: " + baseValue + ", limit: " + limit + ", Count: " + count + ", lastPt: " + lastp); - return sketch; - } - - /** - * Merges three sketches in the specified order and returns the composite estimate - */ - private double mergeThreeSketches(final HllSketch s1, final HllSketch s2, final HllSketch s3) { - final HllUnion union = new HllUnion(LgK); - - union.update(s1); - union.update(s2); - union.update(s3); - - return union.getCompositeEstimate(); - } - - //@Test - /** - * Used for tweaking the generator algorithm - */ - public void checkNewGenerator() { - final long baseValue = 1L << 59; - final int ppo = 1 << 10; - final long limit = 1L << 60; - int count = 0; - long lastp = 0; - for (long p = baseValue; p < limit; p = pwr2SeriesNext(ppo, p)) { - count++; - println(count + ", " + p); - lastp = p; - } - println("\nPPO: " + ppo); - println("Count: " + count); - println("baseValue: " + baseValue); - println("last p: " + lastp); - println("limit: " + limit); - } - - private static void println(final Object o) { - //System.out.println(o.toString()); - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/HllSketchTest.java b/src/test/java/org/apache/datasketches/hll/HllSketchTest.java deleted file mode 100644 index b9cc6f298..000000000 --- a/src/test/java/org/apache/datasketches/hll/HllSketchTest.java +++ /dev/null @@ -1,468 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.HllSketch.getMaxUpdatableSerializationBytes; -import static org.apache.datasketches.hll.HllUtil.LG_AUX_ARR_INTS; -import static org.apache.datasketches.hll.HllUtil.LG_INIT_LIST_SIZE; -import static org.apache.datasketches.hll.HllUtil.LG_INIT_SET_SIZE; -import static org.apache.datasketches.hll.PreambleUtil.HASH_SET_INT_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START; -import static org.apache.datasketches.hll.PreambleUtil.LIST_INT_ARR_START; -import static org.apache.datasketches.hll.TgtHllType.HLL_4; -import static org.apache.datasketches.hll.TgtHllType.HLL_6; -import static org.apache.datasketches.hll.TgtHllType.HLL_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.hll.AbstractCoupons; -import org.apache.datasketches.hll.AbstractHllArray; -import org.apache.datasketches.hll.AuxHashMap; -import org.apache.datasketches.hll.CurMode; -import org.apache.datasketches.hll.HllSketch; -import org.apache.datasketches.hll.HllSketchImpl; -import org.apache.datasketches.hll.HllUtil; -import org.apache.datasketches.hll.PreambleUtil; -import org.apache.datasketches.hll.TgtHllType; -import org.apache.datasketches.hll.HllUnion; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class HllSketchTest { - - @Test - public void checkCopies() { - runCheckCopy(14, HLL_4, null); - runCheckCopy(8, HLL_6, null); - runCheckCopy(8, HLL_8, null); - - final int bytes = getMaxUpdatableSerializationBytes(14, TgtHllType.HLL_8); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - - runCheckCopy(14, HLL_4, wseg); - runCheckCopy(8, HLL_6, wseg); - runCheckCopy(8, HLL_8, wseg); - } - - private static void runCheckCopy(final int lgConfigK, final TgtHllType tgtHllType, final MemorySegment wseg) { - HllSketch sk; - if (wseg == null) { //heap - sk = new HllSketch(lgConfigK, tgtHllType); - } else { //direct - sk = new HllSketch(lgConfigK, tgtHllType, wseg); - } - - for (int i = 0; i < 7; i++) { - sk.update(i); - } - assertEquals(sk.getCurMode(), CurMode.LIST); - - HllSketch skCopy = sk.copy(); - assertEquals(skCopy.getCurMode(), CurMode.LIST); - HllSketchImpl impl1 = sk.hllSketchImpl; - - HllSketchImpl impl2 = skCopy.hllSketchImpl; - AbstractCoupons absCoupons1 = (AbstractCoupons) sk.hllSketchImpl; - AbstractCoupons absCoupons2 = (AbstractCoupons) skCopy.hllSketchImpl; - assertEquals(absCoupons1.getCouponCount(), absCoupons2.getCouponCount()); - assertEquals(impl1.getEstimate(), impl2.getEstimate(), 0.0); - assertFalse(impl1 == impl2); - - for (int i = 7; i < 24; i++) { - sk.update(i); - } - assertEquals(sk.getCurMode(), CurMode.SET); - - skCopy = sk.copy(); - assertEquals(skCopy.getCurMode(), CurMode.SET); - impl1 = sk.hllSketchImpl; - - impl2 = skCopy.hllSketchImpl; - absCoupons1 = (AbstractCoupons) sk.hllSketchImpl; - absCoupons2 = (AbstractCoupons) skCopy.hllSketchImpl; - assertEquals(absCoupons1.getCouponCount(), absCoupons2.getCouponCount()); - assertEquals(impl1.getEstimate(), impl2.getEstimate(), 0.0); - assertFalse(impl1 == impl2); - final int u = (sk.getTgtHllType() == TgtHllType.HLL_4) ? 100000 : 25; - for (int i = 24; i < u; i++) { - sk.update(i); - } - sk.getCompactSerializationBytes(); - assertEquals(sk.getCurMode(), CurMode.HLL); - - skCopy = sk.copy(); - assertEquals(skCopy.getCurMode(), CurMode.HLL); - impl1 = sk.hllSketchImpl; - - impl2 = skCopy.hllSketchImpl; - assertEquals(impl1.getEstimate(), impl2.getEstimate(), 0.0); - assertFalse(impl1 == impl2); - } - - @Test - public void checkCopyAs() { - copyAs(HLL_4, HLL_4, false); - copyAs(HLL_4, HLL_6, false); - copyAs(HLL_4, HLL_8, false); - copyAs(HLL_6, HLL_4, false); - copyAs(HLL_6, HLL_6, false); - copyAs(HLL_6, HLL_8, false); - copyAs(HLL_8, HLL_4, false); - copyAs(HLL_8, HLL_6, false); - copyAs(HLL_8, HLL_8, false); - copyAs(HLL_4, HLL_4, true); - copyAs(HLL_4, HLL_6, true); - copyAs(HLL_4, HLL_8, true); - copyAs(HLL_6, HLL_4, true); - copyAs(HLL_6, HLL_6, true); - copyAs(HLL_6, HLL_8, true); - copyAs(HLL_8, HLL_4, true); - copyAs(HLL_8, HLL_6, true); - copyAs(HLL_8, HLL_8, true); - } - - private static void copyAs(final TgtHllType srcType, final TgtHllType dstType, final boolean direct) { - final int lgK = 8; - final int n1 = 7; - final int n2 = 24; - final int n3 = 1000; - final int base = 0; - final int bytes = getMaxUpdatableSerializationBytes(lgK, srcType); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - - final HllSketch src = (direct) ? new HllSketch(lgK, srcType, wseg) : new HllSketch(lgK, srcType); - for (int i = 0; i < n1; i++) { src.update(i + base); } - HllSketch dst = src.copyAs(dstType); - assertEquals(dst.getEstimate(), src.getEstimate(), 0.0); - - for (int i = n1; i < n2; i++) { src.update(i); } - dst = src.copyAs(dstType); - assertEquals(dst.getEstimate(), src.getEstimate(), 0.0); - - for (int i = n2; i < n3; i++) { src.update(i); } - dst = src.copyAs(dstType); - assertEquals(dst.getEstimate(), src.getEstimate(), 0.0); - } - - @Test - public void checkMisc1() { - misc(false); - misc(true); - } - - private static void misc(final boolean direct) { - final int lgConfigK = 8; - final TgtHllType srcType = TgtHllType.HLL_8; - final int bytes = getMaxUpdatableSerializationBytes(lgConfigK, srcType); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - - final HllSketch sk = (direct) - ? new HllSketch(lgConfigK, srcType, wseg) : new HllSketch(lgConfigK, srcType); - - for (int i = 0; i < 7; i++) { sk.update(i); } //LIST - AbstractCoupons absCoupons = (AbstractCoupons) sk.hllSketchImpl; - assertEquals(absCoupons.getCouponCount(), 7); - assertEquals(sk.getCompactSerializationBytes(), 36); - assertEquals(sk.getUpdatableSerializationBytes(), 40); - - for (int i = 7; i < 24; i++) { sk.update(i); } //SET - absCoupons = (AbstractCoupons) sk.hllSketchImpl; - assertEquals(absCoupons.getCouponCount(), 24); - assertEquals(sk.getCompactSerializationBytes(), 108); - assertEquals(sk.getUpdatableSerializationBytes(), 140); - - sk.update(24); //HLL - final AbstractHllArray absHll = (AbstractHllArray) sk.hllSketchImpl; - assertNull(absHll.getAuxIterator()); - assertEquals(absHll.getCurMin(), 0); - assertEquals(absHll.getHipAccum(), 25.0, 25 * .02); - assertTrue(absHll.getNumAtCurMin() >= 0); - assertEquals(sk.getUpdatableSerializationBytes(), 40 + 256); - assertEquals(absHll.getSegDataStart(), 40); - assertEquals(absHll.getPreInts(), 10); - - - final int hllBytes = PreambleUtil.HLL_BYTE_ARR_START + (1 << lgConfigK); - assertEquals(sk.getCompactSerializationBytes(), hllBytes); - assertEquals(getMaxUpdatableSerializationBytes(lgConfigK, TgtHllType.HLL_8), hllBytes); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkNumStdDev() { - HllUtil.checkNumStdDev(0); - } - - @Test - public void checkSerSizes() { - checkSerSizes(8, TgtHllType.HLL_8, false); - checkSerSizes(8, TgtHllType.HLL_8, true); - checkSerSizes(8, TgtHllType.HLL_6, false); - checkSerSizes(8, TgtHllType.HLL_6, true); - checkSerSizes(8, TgtHllType.HLL_4, false); - checkSerSizes(8, TgtHllType.HLL_4, true); - } - - private static void checkSerSizes(final int lgConfigK, final TgtHllType tgtHllType, final boolean direct) { - final int bytes = getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = (direct) - ? new HllSketch(lgConfigK, tgtHllType, wseg) : new HllSketch(lgConfigK, tgtHllType); - int i; - - //LIST - for (i = 0; i < 7; i++) { sk.update(i); } - int expected = LIST_INT_ARR_START + (i << 2); - assertEquals(sk.getCompactSerializationBytes(), expected); - expected = LIST_INT_ARR_START + (4 << LG_INIT_LIST_SIZE); - assertEquals(sk.getUpdatableSerializationBytes(), expected); - - //SET - for (i = 7; i < 24; i++) { sk.update(i); } - expected = HASH_SET_INT_ARR_START + (i << 2); - assertEquals(sk.getCompactSerializationBytes(), expected); - expected = HASH_SET_INT_ARR_START + (4 << LG_INIT_SET_SIZE); - assertEquals(sk.getUpdatableSerializationBytes(), expected); - - //HLL - sk.update(i); - assertEquals(sk.getCurMode(), CurMode.HLL); - final AbstractHllArray absHll = (AbstractHllArray) sk.hllSketchImpl; - - int auxCountBytes = 0; - int auxArrBytes = 0; - if (absHll.tgtHllType == HLL_4) { - final AuxHashMap auxMap = absHll.getAuxHashMap(); - if (auxMap != null) { - auxCountBytes = auxMap.getAuxCount() << 2; - auxArrBytes = 4 << auxMap.getLgAuxArrInts(); - } else { - auxArrBytes = 4 << LG_AUX_ARR_INTS[lgConfigK]; - } - } - final int hllArrBytes = absHll.getHllByteArrBytes(); - expected = HLL_BYTE_ARR_START + hllArrBytes + auxCountBytes; - assertEquals(sk.getCompactSerializationBytes(), expected); - expected = HLL_BYTE_ARR_START + hllArrBytes + auxArrBytes; - assertEquals(sk.getUpdatableSerializationBytes(), expected); - final int fullAuxBytes = (tgtHllType == TgtHllType.HLL_4) ? (4 << LG_AUX_ARR_INTS[lgConfigK]) : 0; - expected = HLL_BYTE_ARR_START + hllArrBytes + fullAuxBytes; - assertEquals(getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType), expected); - } - - @SuppressWarnings("unused") - @Test - public void checkConfigKLimits() { - try { - final HllSketch sk = new HllSketch(HllUtil.MIN_LOG_K - 1); - fail(); - } catch (final SketchesArgumentException e) { - //expected - } - try { - final HllSketch sk = new HllSketch(HllUtil.MAX_LOG_K + 1); - fail(); - } catch (final SketchesArgumentException e) { - //expected - } - } - - @Test - public void exerciseToStringDetails() { - HllSketch sk = new HllSketch(15, TgtHllType.HLL_4); - for (int i = 0; i < 25; i++) { sk.update(i); } - println(sk.toString(false, true, true, true)); //SET mode - for (int i = 25; i < (1 << 12); i++) { sk.update(i); } - println(sk.toString(false, true, true, true)); //HLL mode no Aux - for (int i = (1 << 12); i < (1 << 15); i++) { sk.update(i); } //Aux with exceptions - println(sk.toString(false, true, true, true)); - println(sk.toString(false, true, true, false)); - println(sk.toString(false, true, true)); - sk = new HllSketch(8, TgtHllType.HLL_6); - for (int i = 0; i < 25; i++) { sk.update(i); } - println(sk.toString(false, true, true, true)); - } - - @SuppressWarnings("unused") - @Test - public void checkMemorySegmentNotLargeEnough() { - final int bytes = getMaxUpdatableSerializationBytes(8, TgtHllType.HLL_8); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes -1]); - try { - final HllSketch sk = new HllSketch(8, TgtHllType.HLL_8, wseg); - fail(); - } catch (final SketchesArgumentException e) { - //OK - } - } - - @Test - public void checkEmptyCoupon() { - final int lgK = 8; - final TgtHllType type = TgtHllType.HLL_8; - final HllSketch sk = new HllSketch(lgK, type); - for (int i = 0; i < 20; i++) { sk.update(i); } //SET mode - sk.couponUpdate(0); - assertEquals(sk.getEstimate(), 20.0, 0.001); - } - - @Test - public void checkCompactFlag() { - final int lgK = 8; - //LIST: follows the toByteArray request - assertEquals(checkCompact(lgK, 7, HLL_8, false, false), false); - assertEquals(checkCompact(lgK, 7, HLL_8, false, true), true); - assertEquals(checkCompact(lgK, 7, HLL_8, false, false), false); - assertEquals(checkCompact(lgK, 7, HLL_8, false, true), true); - assertEquals(checkCompact(lgK, 7, HLL_8, true, false), false); - assertEquals(checkCompact(lgK, 7, HLL_8, true, true), true); - assertEquals(checkCompact(lgK, 7, HLL_8, true, false), false); - assertEquals(checkCompact(lgK, 7, HLL_8, true, true), true); - - //SET: follows the toByteArray request - assertEquals(checkCompact(lgK, 24, HLL_8, false, false), false); - assertEquals(checkCompact(lgK, 24, HLL_8, false, true), true); - assertEquals(checkCompact(lgK, 24, HLL_8, false, false), false); - assertEquals(checkCompact(lgK, 24, HLL_8, false, true), true); - assertEquals(checkCompact(lgK, 24, HLL_8, true, false), false); - assertEquals(checkCompact(lgK, 24, HLL_8, true, true), true); - assertEquals(checkCompact(lgK, 24, HLL_8, true, false), false); - assertEquals(checkCompact(lgK, 24, HLL_8, true, true), true); - - //HLL8: always updatable - assertEquals(checkCompact(lgK, 25, HLL_8, false, false), false); - assertEquals(checkCompact(lgK, 25, HLL_8, false, true), false); - assertEquals(checkCompact(lgK, 25, HLL_8, false, false), false); - assertEquals(checkCompact(lgK, 25, HLL_8, false, true), false); - assertEquals(checkCompact(lgK, 25, HLL_8, true, false), false); - assertEquals(checkCompact(lgK, 25, HLL_8, true, true), false); - assertEquals(checkCompact(lgK, 25, HLL_8, true, false), false); - assertEquals(checkCompact(lgK, 25, HLL_8, true, true), false); - - //HLL6: always updatable - assertEquals(checkCompact(lgK, 25, HLL_6, false, false), false); - assertEquals(checkCompact(lgK, 25, HLL_6, false, true), false); - assertEquals(checkCompact(lgK, 25, HLL_6, false, false), false); - assertEquals(checkCompact(lgK, 25, HLL_6, false, true), false); - assertEquals(checkCompact(lgK, 25, HLL_6, true, false), false); - assertEquals(checkCompact(lgK, 25, HLL_6, true, true), false); - assertEquals(checkCompact(lgK, 25, HLL_6, true, false), false); - assertEquals(checkCompact(lgK, 25, HLL_6, true, true), false); - - //HLL:4 follows the toByteArray request - assertEquals(checkCompact(lgK, 25, HLL_4, false, false), false); - assertEquals(checkCompact(lgK, 25, HLL_4, false, true), true); - assertEquals(checkCompact(lgK, 25, HLL_4, false, false), false); - assertEquals(checkCompact(lgK, 25, HLL_4, false, true), true); - assertEquals(checkCompact(lgK, 25, HLL_4, true, false), false); - assertEquals(checkCompact(lgK, 25, HLL_4, true, true), true); - assertEquals(checkCompact(lgK, 25, HLL_4, true, false), false); - assertEquals(checkCompact(lgK, 25, HLL_4, true, true), true); - } - - //Creates either a direct or heap sketch, - // Serializes to either compact or updatable form. - // Confirms the hasMemorySegment() for direct, isOffHeap(), and the - // get compact or updatable serialization bytes. - // Returns true if the compact flag is set. - private static boolean checkCompact(final int lgK, final int n, final TgtHllType type, final boolean direct, - final boolean compact) { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, type); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = (direct) ? new HllSketch(lgK, type, wseg) : new HllSketch(lgK, type); - assertEquals(sk.hasMemorySegment(), direct); - assertFalse(sk.isOffHeap()); - for (int i = 0; i < n; i++) { sk.update(i); } //LOAD - final byte[] byteArr = (compact) ? sk.toCompactByteArray() : sk.toUpdatableByteArray(); - final int len = byteArr.length; - if (compact) { - assertEquals(len, sk.getCompactSerializationBytes()); - } else { - assertEquals(len, sk.getUpdatableSerializationBytes()); - } - final HllSketch sk2 = HllSketch.wrap(MemorySegment.ofArray(byteArr)); - assertEquals(sk2.getEstimate(), n, .01); - final boolean resourceCompact = sk2.isCompact(); - if (resourceCompact) { - try { - HllSketch.writableWrap(MemorySegment.ofArray(byteArr)); - fail(); - } catch (final SketchesArgumentException e) { - //OK - } - } - return resourceCompact; - //return (byteArr[5] & COMPACT_FLAG_MASK) > 0; - } - - @SuppressWarnings("unused") - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkWritableWrapOfCompact() { - final HllSketch sk = new HllSketch(); - final byte[] byteArr = sk.toCompactByteArray(); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - final HllSketch sk2 = HllSketch.writableWrap(wseg); - } - - @SuppressWarnings("unused") - @Test - public void checkJavadocExample() { - HllUnion union; HllSketch sk, sk2; - final int lgK = 12; - sk = new HllSketch(lgK, TgtHllType.HLL_4); //can be 4, 6, or 8 - for (int i = 0; i < (2 << lgK); i++) { sk.update(i); } - final byte[] arr = sk.toCompactByteArray(); - // ... - union = HllUnion.heapify(arr); //initializes the union using data from the array. - //OR, if used in an off-heap environment: - union = HllUnion.heapify(MemorySegment.ofArray(arr)); - - //To recover an updatable Heap sketch: - sk2 = HllSketch.heapify(arr); - //OR, if used in an off-heap environment: - sk2 = HllSketch.heapify(MemorySegment.ofArray(arr)); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void print(final String s) { - //System.out.print(s); //disable here - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/hll/IsomorphicTest.java b/src/test/java/org/apache/datasketches/hll/IsomorphicTest.java deleted file mode 100644 index d895246a8..000000000 --- a/src/test/java/org/apache/datasketches/hll/IsomorphicTest.java +++ /dev/null @@ -1,392 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.CurMode.HLL; -import static org.apache.datasketches.hll.CurMode.LIST; -import static org.apache.datasketches.hll.CurMode.SET; -import static org.apache.datasketches.hll.TgtHllType.HLL_4; -import static org.apache.datasketches.hll.TgtHllType.HLL_6; -import static org.apache.datasketches.hll.TgtHllType.HLL_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -@SuppressWarnings("unused") -public class IsomorphicTest { - long v = 0; - - @Test - //Merges a type1 to an empty union (heap, HLL_8), and gets result as type1, checks binary equivalence - public void isomorphicUnionUpdatableHeap() { - for (int lgK = 4; lgK <= 21; lgK++) { //All LgK - for (int cm = 0; cm <= 2; cm++) { //List, Set, Hll - if ((lgK < 8) && (cm == 1)) { continue; } //lgk < 8 list transistions directly to HLL - final CurMode curMode = CurMode.fromOrdinal(cm); - for (int t = 0; t <= 2; t++) { //HLL_4, HLL_6, HLL_8 - final TgtHllType tgtHllType1 = TgtHllType.fromOrdinal(t); - final HllSketch sk1 = buildHeapSketch(lgK, tgtHllType1, curMode); - final byte[] sk1bytes = sk1.toUpdatableByteArray(); //UPDATABLE - final HllUnion union = buildHeapUnion(lgK, null); //UNION - union.update(sk1); - final HllSketch sk2 = union.getResult(tgtHllType1); - final byte[] sk2bytes = sk2.toUpdatableByteArray(); //UPDATABLE - final String comb = "LgK=" + lgK + ", CurMode=" + curMode.toString() + ", Type:" + tgtHllType1; - checkArrays(sk1bytes, sk2bytes, comb, false); - } - } - } - } - - @Test - //Merges a type1 to an empty union (heap, HLL_8), and gets result as type1, checks binary equivalence - public void isomorphicUnionCompactHeap() { - for (int lgK = 4; lgK <= 21; lgK++) { //All LgK - for (int cm = 0; cm <= 2; cm++) { //List, Set, Hll - if ((lgK < 8) && (cm == 1)) { continue; } //lgk < 8 list transistions directly to HLL - final CurMode curMode = CurMode.fromOrdinal(cm); - for (int t = 0; t <= 2; t++) { //HLL_4, HLL_6, HLL_8 - final TgtHllType tgtHllType1 = TgtHllType.fromOrdinal(t); - final HllSketch sk1 = buildHeapSketch(lgK, tgtHllType1, curMode); - final byte[] sk1bytes = sk1.toCompactByteArray(); //COMPACT - final HllUnion union = buildHeapUnion(lgK, null); //UNION - union.update(sk1); - final HllSketch sk2 = union.getResult(tgtHllType1); - final byte[] sk2bytes = sk2.toCompactByteArray(); //COMPACT - final String comb = "LgK=" + lgK + ", CurMode=" + curMode.toString() + ", Type:" + tgtHllType1; - checkArrays(sk1bytes, sk2bytes, comb, false); - } - } - } - } - - @Test - //Converts a type1 to a different type and converts back to type1 to check binary equivalence. - public void isomorphicCopyAsUpdatableHeap() { - for (int lgK = 4; lgK <= 21; lgK++) { //All LgK - for (int cm = 0; cm <= 2; cm++) { //List, Set, Hll - if ((lgK < 8) && (cm == 1)) { continue; } //lgk < 8 list transistions directly to HLL - final CurMode curMode = CurMode.fromOrdinal(cm); - for (int t1 = 0; t1 <= 2; t1++) { //HLL_4, HLL_6, HLL_8 - final TgtHllType tgtHllType1 = TgtHllType.fromOrdinal(t1); - final HllSketch sk1 = buildHeapSketch(lgK, tgtHllType1, curMode); - final byte[] sk1bytes = sk1.toUpdatableByteArray(); //UPDATABLE - for (int t2 = 0; t2 <= 2; t2++) { //HLL_4, HLL_6, HLL_8 - if (t2 == t1) { continue; } - final TgtHllType tgtHllType2 = TgtHllType.fromOrdinal(t2); - final HllSketch sk2 = sk1.copyAs(tgtHllType2); //COPY AS - final HllSketch sk1B = sk2.copyAs(tgtHllType1); //COPY AS - final byte[] sk1Bbytes = sk1B.toUpdatableByteArray(); //UPDATABLE - final String comb = "LgK= " + lgK + ", CurMode= " + curMode.toString() - + ", Type1: " + tgtHllType1 + ", Type2: " + tgtHllType2; - checkArrays(sk1bytes, sk1Bbytes, comb, false); - } - } - } - } - } - - @Test - //Converts a type1 to a different type and converts back to type1 to check binary equivalence. - public void isomorphicCopyAsCompactHeap() { - for (int lgK = 4; lgK <= 21; lgK++) { //All LgK - for (int cm = 0; cm <= 2; cm++) { //List, Set, Hll - if ((lgK < 8) && (cm == 1)) { continue; } //lgk < 8 list transistions directly to HLL - final CurMode curMode = CurMode.fromOrdinal(cm); - for (int t1 = 0; t1 <= 2; t1++) { //HLL_4, HLL_6, HLL_8 - final TgtHllType tgtHllType1 = TgtHllType.fromOrdinal(t1); - final HllSketch sk1 = buildHeapSketch(lgK, tgtHllType1, curMode); - final byte[] sk1bytes = sk1.toCompactByteArray(); //COMPACT - for (int t2 = 0; t2 <= 2; t2++) { //HLL_4, HLL_6, HLL_8 - if (t2 == t1) { continue; } - final TgtHllType tgtHllType2 = TgtHllType.fromOrdinal(t2); - final HllSketch sk2 = sk1.copyAs(tgtHllType2); //COPY AS - final HllSketch sk3 = sk2.copyAs(tgtHllType1); //COPY AS - final byte[] sk3bytes = sk3.toCompactByteArray(); //COMPACT - final String comb = "LgK= " + lgK + ", CurMode= " + curMode.toString() - + ", Type1: " + tgtHllType1 + ", Type2: " + tgtHllType2; - checkArrays(sk1bytes, sk3bytes, comb, false); - } - } - } - } - } - - @Test - //Compares two HLL to HLL merges. The input sketch varies by tgtHllType. - //The LgKs can be equal or the source sketch is one larger. - //The result of the union is converted to HLL_8 and checked between different combinations of - //heap, MemorySegment for binary equivalence. - public void isomorphicHllMerges() { - for (int uLgK = 4; uLgK <= 20; uLgK++) { //All LgK - int skLgK = uLgK; - for (int t1 = 0; t1 <= 2; t1++) { //HLL_4, HLL_6, HLL_8 - final TgtHllType tgtHllType = TgtHllType.fromOrdinal(t1); - innerLoop(uLgK, skLgK, tgtHllType); - } - skLgK = uLgK + 1; - for (int t1 = 0; t1 <= 2; t1++) { //HLL_4, HLL_6, HLL_8 - final TgtHllType tgtHllType = TgtHllType.fromOrdinal(t1); - innerLoop(uLgK, skLgK, tgtHllType); - } - } - } - - private static void innerLoop(final int uLgK, final int skLgK, final TgtHllType tgtHllType) { - HllUnion u; - HllSketch sk; - final HllSketch skOut; - - //CASE 1 Heap HllUnion, Heap HllSketch - u = buildHeapUnionHllMode(uLgK, 0); - sk = buildHeapSketchHllMode(skLgK, tgtHllType, 1 << uLgK); - u.update(sk); - final byte[] bytesOut1 = u.getResult(HLL_8).toUpdatableByteArray(); - - //CASE 2 Heap HllUnion, MemorySegment HllSketch - u = buildHeapUnionHllMode(uLgK, 0); - sk = buildMemorySegmentSketchHllMode(skLgK, tgtHllType, 1 << uLgK); - u.update(sk); - final byte[] bytesOut2 = u.getResult(HLL_8).toUpdatableByteArray(); - - //println("Uheap/SkHeap HIP: " + bytesToDouble(bytesOut1, 8)); //HipAccum - //println("Uheap/SkSegment HIP: " + bytesToDouble(bytesOut2, 8)); //HipAccum - String comb = "uLgK: " + uLgK + ", skLgK: " + skLgK - + ", SkType: " + tgtHllType.toString() - + ", Case1: Heap HllUnion, Heap HllSketch; Case2: /Heap HllUnion, MemorySegment HllSketch"; - checkArrays(bytesOut1, bytesOut2, comb, false); - - //CASE 3 Offheap HllUnion, Heap HllSketch - u = buildMemorySegmentUnionHllMode(uLgK, 0); - sk = buildHeapSketchHllMode(skLgK, tgtHllType, 1 << uLgK); - u.update(sk); - final byte[] bytesOut3 = u.getResult(HLL_8).toUpdatableByteArray(); - - //println("Uheap/SkSegment HIP: " + bytesToDouble(bytesOut2, 8)); //HipAccum - //println("Usegment/SkHeap HIP: " + bytesToDouble(bytesOut3, 8)); //HipAccum - comb = "LgK: " + uLgK + ", skLgK: " + skLgK - + ", SkType: " + tgtHllType.toString() - + ", Case2: Heap HllUnion, MemorySegment HllSketch; Case3: /MemorySegment HllUnion, Heap HllSketch"; - checkArrays(bytesOut2, bytesOut3, comb, false); - - //Case 4 MemorySegment HllUnion, MemorySegment HllSketch - u = buildMemorySegmentUnionHllMode(uLgK, 0); - sk = buildMemorySegmentSketchHllMode(skLgK, tgtHllType, 1 << uLgK); - u.update(sk); - final byte[] bytesOut4 = u.getResult(HLL_8).toUpdatableByteArray(); - - comb = "LgK: " + uLgK + ", skLgK: " + skLgK - + ", SkType: " + tgtHllType.toString() - + ", Case2: Heap HllUnion, MemorySegment HllSketch; Case4: /MemorySegment HllUnion, MemorySegment HllSketch"; - checkArrays(bytesOut2, bytesOut4, comb, false); - } - - @Test - //Creates a binary reference: HLL_8 merged with union, HLL_8 result binary. - //Case 1: HLL_6 merged with a union, HLL_8 result binary compared with the reference. - //Case 2: HLL_4 merged with a union, Hll_8 result binary compared with the reference. - //Both Case 1 and 2 should differ in the binary output compared with the reference only for the - //HllAccum register. - public void isomorphicHllMerges2() { - byte[] bytesOut8, bytesOut6, bytesOut4; - String comb; - HllUnion u; - HllSketch sk; - for (int lgK = 4; lgK <= 4; lgK++) { //All LgK - u = buildHeapUnionHllMode(lgK, 0); - sk = buildHeapSketchHllMode(lgK, HLL_8, 1 << lgK); - u.update(sk); - bytesOut8 = u.getResult(HLL_8).toUpdatableByteArray(); //The reference - - u = buildHeapUnionHllMode(lgK, 0); - sk = buildHeapSketchHllMode(lgK, HLL_6, 1 << lgK); - u.update(sk); - bytesOut6 = u.getResult(HLL_8).toUpdatableByteArray();//should be identical except for HllAccum - - comb = "LgK: " + lgK + ", SkType: HLL_6, Compared with SkType HLL_8"; - checkArrays(bytesOut8, bytesOut6, comb, false); - - u = buildHeapUnionHllMode(lgK, 0); - sk = buildHeapSketchHllMode(lgK, HLL_4, 1 << lgK); - u.update(sk); - bytesOut4 = u.getResult(HLL_8).toUpdatableByteArray();//should be identical except for HllAccum - - comb = "LgK: " + lgK + ", SkType: HLL_4, Compared with SkType HLL_8"; - checkArrays(bytesOut8, bytesOut4, comb, false); - } - } - - private static void checkArrays(final byte[] sk1, final byte[] sk2, final String comb, final boolean omitHipAccum) { - final int len = sk1.length; - if (len != sk2.length) { - println("Sketch images not the same length: " + comb); - return; - } - print(comb + ": "); - for (int i = 0; i < len; i++) { - if ((omitHipAccum && (i >= 8) && (i <= 15)) || (sk1[i] == sk2[i])) { continue; } - print(i + " "); - fail(); - } - println(""); - } - - //BUILDERS - private HllUnion buildHeapUnion(final int lgMaxK, final CurMode curMode) { - final HllUnion u = new HllUnion(lgMaxK); - final int n = (curMode == null) ? 0 : getN(lgMaxK, curMode); - for (int i = 0; i < n; i++) { u.update(i + v); } - v += n; - return u; - } - - private HllUnion buildMemorySegmentUnion(final int lgMaxK, final CurMode curMode) { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgMaxK, TgtHllType.HLL_8); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllUnion u = new HllUnion(lgMaxK, wseg); - final int n = (curMode == null) ? 0 : getN(lgMaxK, curMode); - for (int i = 0; i < n; i++) { u.update(i + v); } - v += n; - return u; - } - - private HllSketch buildHeapSketch(final int lgK, final TgtHllType tgtHllType, final CurMode curMode) { - final HllSketch sk = new HllSketch(lgK, tgtHllType); - final int n = (curMode == null) ? 0 : getN(lgK, curMode); - for (int i = 0; i < n; i++) { sk.update(i + v); } - v += n; - return sk; - } - - private HllSketch buildMemorySegmentSketch(final int lgK, final TgtHllType tgtHllType, final CurMode curMode) { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK,tgtHllType); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = new HllSketch(lgK, tgtHllType, wseg); - final int n = (curMode == null) ? 0 : getN(lgK, curMode); - for (int i = 0; i < n; i++) { sk.update(i + v); } - v += n; - return sk; - } - - private static HllUnion buildHeapUnionHllMode(final int lgMaxK, final int startN) { - final HllUnion u = new HllUnion(lgMaxK); - final int n = getN(lgMaxK, HLL); - for (int i = 0; i < n; i++) { u.update(i + startN); } - return u; - } - - private static HllUnion buildMemorySegmentUnionHllMode(final int lgMaxK, final int startN) { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgMaxK, TgtHllType.HLL_8); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllUnion u = new HllUnion(lgMaxK, wseg); - final int n = getN(lgMaxK, HLL); - for (int i = 0; i < n; i++) { u.update(i + startN); } - return u; - } - - private static HllSketch buildHeapSketchHllMode(final int lgK, final TgtHllType tgtHllType, final int startN) { - final HllSketch sk = new HllSketch(lgK, tgtHllType); - final int n = getN(lgK, HLL); - for (int i = 0; i < n; i++) { sk.update(i + startN); } - return sk; - } - - private static HllSketch buildMemorySegmentSketchHllMode(final int lgK, final TgtHllType tgtHllType, final int startN) { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK,tgtHllType); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = new HllSketch(lgK, tgtHllType, wseg); - final int n = getN(lgK, HLL); - for (int i = 0; i < n; i++) { sk.update(i + startN); } - return sk; - } - - //if lgK >= 8, curMode != SET! - private static int getN(final int lgK, final CurMode curMode) { - if (curMode == LIST) { return 4; } - if (curMode == SET) { return 1 << (lgK - 4); } - return ((lgK < 8) && (curMode == HLL)) ? (1 << lgK) : 1 << (lgK - 3); - } - - @Test - public void checkCurMinConversion() { - final TgtHllType hll8 = HLL_8; - final TgtHllType hll4 = HLL_4; - for (int lgK = 4; lgK <= 21; lgK++) { - final HllSketch sk8 = new HllSketch(lgK, hll8); - //The Coupon Collector Problem predicts that all slots will be filled by k Log(k). - final int n = (1 << lgK) * lgK; - for (int i = 0; i < n; i++) { sk8.update(i); } - final double est8 = sk8.getEstimate(); - final AbstractHllArray aharr8 = (AbstractHllArray)sk8.hllSketchImpl; - final int curMin8 = aharr8.getCurMin(); - final int numAtCurMin8 = aharr8.getNumAtCurMin(); - final HllSketch sk4 = sk8.copyAs(hll4); - final AbstractHllArray aharr4 = (AbstractHllArray)sk4.hllSketchImpl; - final int curMin4 = ((AbstractHllArray)sk4.hllSketchImpl).getCurMin(); - final int numAtCurMin4 =aharr4.getNumAtCurMin(); - final double est4 = sk4.getEstimate(); - assertEquals(est4, est8, 0.0); - assertEquals(curMin4, 1); - //println("Est 8 = " + est8 + ", CurMin = " + curMin8 + ", #CurMin + " + numAtCurMin8); - //println("Est 4 = " + est4 + ", CurMin = " + curMin4 + ", #CurMin + " + numAtCurMin4); - } - } - - private static double bytesToDouble(final byte[] arr, final int offset) { - long v = 0; - for (int i = offset; i < (offset + 8); i++) { - v |= (arr[i] & 0XFFL) << (i * 8); - } - return Double.longBitsToDouble(v); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param o value to print - */ - static void println(final Object o) { - print(o.toString() + "\n"); - } - - /** - * @param o value to print - */ - static void print(final Object o) { - //System.out.print(o.toString()); //disable here - } - - /** - * @param fmt format - * @param args arguments - */ - static void printf(final String fmt, final Object...args) { - //System.out.printf(fmt, args); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/hll/PreambleUtilTest.java b/src/test/java/org/apache/datasketches/hll/PreambleUtilTest.java deleted file mode 100644 index d0d4c592a..000000000 --- a/src/test/java/org/apache/datasketches/hll/PreambleUtilTest.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.hll.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.hll.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.hll.PreambleUtil.SER_VER_BYTE; -import static org.apache.datasketches.hll.PreambleUtil.extractFlags; -import static org.apache.datasketches.hll.PreambleUtil.insertFamilyId; -import static org.apache.datasketches.hll.PreambleUtil.insertPreInts; -import static org.apache.datasketches.hll.PreambleUtil.insertSerVer; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.hll.CurMode; -import org.apache.datasketches.hll.HllSketch; -import org.apache.datasketches.hll.PreambleUtil; -import org.apache.datasketches.hll.TgtHllType; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class PreambleUtilTest { - - //@Test - public void preambleToString() { // Check Visually - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(8, TgtHllType.HLL_4); - final byte[] byteArr1 = new byte[bytes]; - final MemorySegment wseg1 = MemorySegment.ofArray(byteArr1); - final HllSketch sk = new HllSketch(8, TgtHllType.HLL_4, wseg1); - byte[] byteArr2 = sk.toCompactByteArray(); - MemorySegment wseg2 = MemorySegment.ofArray(byteArr2); - - assertEquals(sk.getCurMode(), CurMode.LIST); - assertTrue(sk.isEmpty()); - String s = HllSketch.toString(byteArr2); //empty sketch output - println(s); - println("LgArr: " + PreambleUtil.extractLgArr(wseg2)); - println("Empty: " + PreambleUtil.extractEmptyFlag(wseg2)); - println("Serialization Bytes: " + wseg2.byteSize()); - - for (int i = 0; i < 7; i++) { sk.update(i); } - byteArr2 = sk.toCompactByteArray(); - wseg2 = MemorySegment.ofArray(byteArr2); - assertEquals(sk.getCurMode(), CurMode.LIST); - assertFalse(sk.isEmpty()); - s = HllSketch.toString(byteArr2); - println(s); - println("LgArr: " + PreambleUtil.extractLgArr(wseg2)); - println("Empty: " + PreambleUtil.extractEmptyFlag(wseg2)); - println("Serialization Bytes: " + wseg2.byteSize()); - - for (int i = 7; i < 24; i++) { sk.update(i); } - byteArr2 = sk.toCompactByteArray(); - wseg2 = MemorySegment.ofArray(byteArr2); - assertEquals(sk.getCurMode(), CurMode.SET); - s = HllSketch.toString(byteArr2); - println(s); - println("LgArr: " + PreambleUtil.extractLgArr(wseg2)); - println("Empty: " + PreambleUtil.extractEmptyFlag(wseg2)); - println("Serialization Bytes: " + wseg2.byteSize()); - - sk.update(24); - byteArr2 = sk.toCompactByteArray(); - wseg2 = MemorySegment.ofArray(byteArr2); - assertEquals(sk.getCurMode(), CurMode.HLL); - s = HllSketch.toString(MemorySegment.ofArray(byteArr2)); - println(s); - println("LgArr: " + PreambleUtil.extractLgArr(wseg2)); - println("Empty: " + PreambleUtil.extractEmptyFlag(wseg2)); - println("Serialization Bytes: " + wseg2.byteSize()); - } - - @Test - public void checkCompactFlag() { - final HllSketch sk = new HllSketch(7); - final byte[] segObj = sk.toCompactByteArray(); - final MemorySegment wseg = MemorySegment.ofArray(segObj); - boolean compact = PreambleUtil.extractCompactFlag(wseg); - assertTrue(compact); - - PreambleUtil.insertCompactFlag(wseg, false); - compact = PreambleUtil.extractCompactFlag(wseg); - assertFalse(compact); - } - - @SuppressWarnings("unused") - @Test - public void checkCorruptMemorySegmentInput() { - final HllSketch sk = new HllSketch(12); - byte[] segObj = sk.toCompactByteArray(); - MemorySegment wseg = MemorySegment.ofArray(segObj); - HllSketch bad; - - //checkFamily - try { - wseg.set(JAVA_BYTE, FAMILY_BYTE, (byte) 0); //corrupt, should be 7 - bad = HllSketch.heapify(wseg); - fail(); - } catch (final SketchesArgumentException e) { /* OK */ } - insertFamilyId(wseg); //corrected - - //check SerVer - try { - wseg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 0); //corrupt, should be 1 - bad = HllSketch.heapify(wseg); - fail(); - } catch (final SketchesArgumentException e) { /* OK */ } - insertSerVer(wseg); //corrected - - //check bad PreInts - try { - insertPreInts(wseg, 0); //corrupt, should be 2 - bad = HllSketch.heapify(wseg); - fail(); - } catch (final SketchesArgumentException e) { /* OK */ } - insertPreInts(wseg, 2); //corrected - - //check wrong PreInts and LIST - try { - insertPreInts(wseg, 3); //corrupt, should be 2 - bad = HllSketch.heapify(wseg); - fail(); - } catch (final SketchesArgumentException e) { /* OK */ } - insertPreInts(wseg, 2); //corrected - - //move to Set mode - for (int i = 1; i <= 15; i++) { sk.update(i); } - segObj = sk.toCompactByteArray(); - wseg = MemorySegment.ofArray(segObj); - - //check wrong PreInts and SET - try { - insertPreInts(wseg, 2); //corrupt, should be 3 - bad = HllSketch.heapify(wseg); - fail(); - } catch (final SketchesArgumentException e) { /* OK */ } - insertPreInts(wseg, 3); //corrected - - //move to HLL mode - for (int i = 15; i <= 1000; i++) { sk.update(i); } - segObj = sk.toCompactByteArray(); - wseg = MemorySegment.ofArray(segObj); - - //check wrong PreInts and HLL - try { - insertPreInts(wseg, 2); //corrupt, should be 10 - bad = HllSketch.heapify(wseg); - fail(); - } catch (final SketchesArgumentException e) { /* OK */ } - insertPreInts(wseg, 10); //corrected - } - - @SuppressWarnings("unused") - @Test - public void checkExtractFlags() { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(4, TgtHllType.HLL_4); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final Object segObj = wseg.toArray(JAVA_BYTE); - final HllSketch sk = new HllSketch(4, TgtHllType.HLL_4, wseg); - final int flags = extractFlags(wseg); - assertEquals(flags, EMPTY_FLAG_MASK); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/SizeAndModeTransitions.java b/src/test/java/org/apache/datasketches/hll/SizeAndModeTransitions.java deleted file mode 100644 index 25173ea44..000000000 --- a/src/test/java/org/apache/datasketches/hll/SizeAndModeTransitions.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.testng.Assert.assertEquals; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.hll.HllSketch; -import org.apache.datasketches.hll.TgtHllType; -import org.testng.annotations.Test; - -public class SizeAndModeTransitions { - static String hfmt = "%6s %7s %4s %10s %5s %10s %10s %10s %10s %10s %14s\n"; - static String dfmt = "%6s %7s %4d %,10d %5s %,10d %,10d %,10d %,10d %,10d %,14.3f\n"; - static String[] hdr = {"Type", "Store", "LgK", "N", "Mode", "ActCBytes", "CmpBytes", "ActUBytes", "UpdBytes", "MaxBytes", "Estimate"}; - - @Test - public void checkHLL8with_withoutSeg() { - checkHLL8Heap(true); - checkHLL8Heap(false); - } - - private void checkHLL8Heap(final boolean withSeg) { - final TgtHllType tgtHllType = TgtHllType.HLL_8; - final int lgK = 10; - final int N = 97; - printf(hfmt, (Object[]) hdr); - - MemorySegment wseg = null; - HllSketch sk; - if (withSeg) { - final int maxBytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, tgtHllType); - wseg = MemorySegment.ofArray(new byte[maxBytes]); - sk = new HllSketch(lgK, tgtHllType, wseg); - } else { - sk = new HllSketch(lgK, tgtHllType); //without segment - } - final String store = withSeg ? "MemorySegment" : "Heap"; - for (int i = 1; i <= N; i++) { - sk.update(i); - if (i == 7) { checkAtN(sk, tgtHllType, store, lgK, i, "LIST", 36, 40, 1064); } - if (i == 8) { checkAtN(sk, tgtHllType, store, lgK, i, "SET", 44, 140, 1064); } - if (i == 24) { checkAtN(sk, tgtHllType, store, lgK, i, "SET", 108, 140, 1064); } - if (i == 25) { checkAtN(sk, tgtHllType, store, lgK, i, "SET", 112, 268, 1064); } - if (i == 48) { checkAtN(sk, tgtHllType, store, lgK, i, "SET", 204, 268, 1064); } - if (i == 49) { checkAtN(sk, tgtHllType, store, lgK, i, "SET", 208, 524, 1064); } - if (i == 96) { checkAtN(sk, tgtHllType, store, lgK, i, "SET", 396, 524, 1064); } - if (i == 97) { checkAtN(sk, tgtHllType, store, lgK, i, "HLL", 1064, 1064, 1064); } - } - println(""); - } - - private static void checkAtN(final HllSketch sk, final TgtHllType tgtHllType, final String store, final int lgK, final int n, final String trueMode, - final int cmpTrueBytes, final int updTrueBytes, final int maxTrueBytes) { - final int maxBytes = HllSketch.getMaxUpdatableSerializationBytes(lgK, tgtHllType); - final String type = tgtHllType.toString(); - final int cmpBytes = sk.getCompactSerializationBytes(); - final int updBytes = sk.getUpdatableSerializationBytes(); - final byte[] actCBytes = sk.toCompactByteArray(); - final byte[] actUBytes = sk.toUpdatableByteArray(); - final String mode = sk.getCurMode().toString(); - final double est = sk.getEstimate(); - printf(dfmt, type, store, lgK, n, mode, actCBytes.length, cmpBytes, actUBytes.length, updBytes, maxBytes, est); - assertEquals(mode, trueMode); - assertEquals(cmpBytes, actCBytes.length); - assertEquals(cmpBytes, cmpTrueBytes); - assertEquals(updBytes, actUBytes.length); - assertEquals(updBytes, updTrueBytes); - assertEquals(maxBytes, maxTrueBytes); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - - /** - * @param fmt format - * @param args arguments - */ - static void printf(final String fmt, final Object...args) { - //System.out.printf(fmt, args); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/TablesTest.java b/src/test/java/org/apache/datasketches/hll/TablesTest.java deleted file mode 100644 index cb249f811..000000000 --- a/src/test/java/org/apache/datasketches/hll/TablesTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.CouponMapping.xArr; -import static org.apache.datasketches.hll.CouponMapping.yArr; -import static org.apache.datasketches.hll.CubicInterpolation.usingXAndYTables; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - * - */ -public class TablesTest { - - @Test - public void checkInterpolationExceptions() { - try { - usingXAndYTables(xArr, yArr, -1); - fail(); - } catch (final SketchesArgumentException e) { - //expected - } - try { - usingXAndYTables(xArr, yArr, 11000000.0); - fail(); - } catch (final SketchesArgumentException e) { - //expected - } - } - - @Test - public void checkCornerCases() { - final int len = xArr.length; - final double x = xArr[len - 1]; - final double y = usingXAndYTables(xArr, yArr, x); - final double yExp = yArr[len - 1]; - assertEquals(y, yExp, 0.0); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/ToFromByteArrayTest.java b/src/test/java/org/apache/datasketches/hll/ToFromByteArrayTest.java deleted file mode 100644 index 537e8b99f..000000000 --- a/src/test/java/org/apache/datasketches/hll/ToFromByteArrayTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.TgtHllType.HLL_4; -import static org.apache.datasketches.hll.TgtHllType.HLL_6; -import static org.apache.datasketches.hll.TgtHllType.HLL_8; -import static org.testng.Assert.assertEquals; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.hll.HllSketch; -import org.apache.datasketches.hll.TgtHllType; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class ToFromByteArrayTest { - - static final int[] nArr = {1, 3, 10, 30, 100, 300, 1000, 3000, 10000, 30000}; - - @Test - public void checkToFromSketch1() { - for (int i = 0; i < 10; i++) { - final int n = nArr[i]; - for (int lgK = 4; lgK <= 13; lgK++) { - toFrom1(lgK, HLL_4, n); - toFrom1(lgK, HLL_6, n); - toFrom1(lgK, HLL_8, n); - } - println("======="); - } - } - - private static void toFrom1(final int lgConfigK, final TgtHllType tgtHllType, final int n) { - final HllSketch src = new HllSketch(lgConfigK, tgtHllType); - for (int i = 0; i < n; i++) { - src.update(i); - } - //println("n: " + n + ", lgK: " + lgK + ", type: " + tgtHllType); - //printSketch(src, "SRC"); - - final byte[] byteArr1 = src.toCompactByteArray(); //compact - final HllSketch dst = HllSketch.heapify(byteArr1); //using byte[] interface - //printSketch(dst, "DST"); - assertEquals(dst.getEstimate(), src.getEstimate(), 0.0); - - final byte[] byteArr2 = src.toUpdatableByteArray(); //updatable - final MemorySegment seg2 = MemorySegment.ofArray(byteArr2); - final HllSketch dst2 = HllSketch.heapify(seg2); //using MemorySegment interface - //printSketch(dst, "DST"); - assertEquals(dst2.getEstimate(), src.getEstimate(), 0.0); - - final MemorySegment seg3 = MemorySegment.ofArray(byteArr2); - final HllSketch dst3 = HllSketch.heapify(seg3); //using MemorySegment interface - //printSketch(dst, "DST"); - assertEquals(dst3.getEstimate(), src.getEstimate(), 0.0); - } - - @Test - public void checkToFromSketch2() { - for (int i = 0; i < 10; i++) { - final int n = nArr[i]; - for (int lgK = 4; lgK <= 13; lgK++) { - toFrom2(lgK, HLL_4, n); - toFrom2(lgK, HLL_6, n); - toFrom2(lgK, HLL_8, n); - } - println("======="); - } - } - - //Test direct - private static void toFrom2(final int lgConfigK, final TgtHllType tgtHllType, final int n) { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgConfigK, tgtHllType); - final byte[] byteArray = new byte[bytes]; - final MemorySegment wseg = MemorySegment.ofArray(byteArray); - final HllSketch src = new HllSketch(lgConfigK, tgtHllType, wseg); - for (int i = 0; i < n; i++) { - src.update(i); - } - //println("n: " + n + ", lgK: " + lgConfigK + ", type: " + tgtHllType); - //printSketch(src, "Source"); - - //Heapify compact - final byte[] compactByteArr = src.toCompactByteArray(); //compact - final HllSketch dst = HllSketch.heapify(compactByteArr); //using byte[] interface - //printSketch(dst, "Heapify From Compact"); - assertEquals(dst.getEstimate(), src.getEstimate(), 0.0); - - //Heapify updatable - final byte[] updatableByteArr = src.toUpdatableByteArray(); - final MemorySegment wseg2 = MemorySegment.ofArray(updatableByteArr); - final HllSketch dst2 = HllSketch.heapify(wseg2); //using MemorySegment interface - //printSketch(dst2, "Heapify From Updatable"); - assertEquals(dst2.getEstimate(), src.getEstimate(), 0.0); - - //Wrap updatable - final MemorySegment wseg3 = MemorySegment.ofArray(new byte[bytes]); - MemorySegment.copy(wseg2, 0, wseg3, 0, wseg2.byteSize()); - final HllSketch dst3 = HllSketch.writableWrap(wseg3); - //printSketch(dst3, "WritableWrap From Updatable"); - assertEquals(dst3.getEstimate(), src.getEstimate(), 0.0); - - //Wrap updatable as Read-Only - final HllSketch dst4 = HllSketch.wrap(wseg3); - assertEquals(dst4.getEstimate(), src.getEstimate(), 0.0); - } - - // static void printSketch(HllSketch sketch, String name) { - // println(name +":\n" + sketch.toString(true, true, true, false)); - // } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param o value to print - */ - static void println(final Object o) { - //System.out.println(o.toString()); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/UnionCaseTest.java b/src/test/java/org/apache/datasketches/hll/UnionCaseTest.java deleted file mode 100644 index 3279e5ec9..000000000 --- a/src/test/java/org/apache/datasketches/hll/UnionCaseTest.java +++ /dev/null @@ -1,483 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static org.apache.datasketches.hll.CurMode.LIST; -import static org.apache.datasketches.hll.CurMode.SET; -import static org.apache.datasketches.hll.HllUtil.HLL_HIP_RSE_FACTOR; -import static org.apache.datasketches.hll.HllUtil.HLL_NON_HIP_RSE_FACTOR; -import static org.apache.datasketches.hll.TgtHllType.HLL_4; -import static org.apache.datasketches.hll.TgtHllType.HLL_6; -import static org.apache.datasketches.hll.TgtHllType.HLL_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class UnionCaseTest { - private static final String LS = System.getProperty("line.separator"); - long v = 0; - final static int maxLgK = 12; - HllSketch skSource; - HllUnion uSource; - String hfmt = "%10s%10s%10s%10s%10s%10s%10s%10s%10s%10s%10s" + LS; - String hdr = String.format(hfmt, "caseNum","srcLgKStr","gdtLgKStr","srcType","gdtType", - "srcSeg","gdtSeg","srcMode","gdtMode","srcOoof","gdtOoof"); - - @Test - public void checkAllCases() { - print(hdr); - for (int i = 0; i < 24; i++) { - checkCase(i, HLL_4, false, false); - } - println(""); - - print(hdr); - for (int i = 0; i < 24; i++) { - checkCase(i, HLL_6, false, false); - } - println(""); - - print(hdr); - for (int i = 0; i < 24; i++) { - checkCase(i, HLL_8, false, false); - } - println(""); - - print(hdr); - for (int i = 0; i < 24; i++) { - checkCase(i, HLL_8, false, true); //srcUnion - } - println(""); - - print(hdr); - for (int i = 0; i < 24; i++) { - checkCase(i, HLL_4, true, false); - } - println(""); - - print(hdr); - for (int i = 0; i < 24; i++) { - checkCase(i, HLL_6, true, false); - } - println(""); - - print(hdr); - for (int i = 0; i < 24; i++) { - checkCase(i, HLL_8, true, false); - } - println(""); - - print(hdr); - for (int i = 0; i < 24; i++) { - checkCase(i, HLL_8, true, true); //srcUnion - } - println(""); - } - - private void checkCase(final int caseNum, final TgtHllType srcType, final boolean srcSeg, final boolean srcUnion) { - if (srcUnion) { - uSource = getUnionSrc(caseNum); - } else { - skSource = getSkSource(caseNum, srcType, srcSeg); - } - final boolean gdtSeg = (caseNum & 1) > 0; - final HllUnion union = getUnion(caseNum, gdtSeg); //union under test - HllSketch refSketch; - if (srcUnion) { - union.update(uSource); - refSketch = union.getResult(HLL_8); - } else { - union.update(skSource); - refSketch = skSource; - } - final int totalU = getSrcCount(caseNum, maxLgK) + getUnionCount(caseNum); - - output(caseNum, refSketch, union, totalU); - } - - private void output(final int caseNum, final HllSketch source, final HllUnion union, final int totalU) { - final double estU = union.getEstimate(); - final double err = Math.abs((estU / totalU) - 1.0); - final int gdtLgK = union.getLgConfigK(); - final boolean uooof = union.isOutOfOrder(); - final double rseFactor = (uooof) ? HLL_NON_HIP_RSE_FACTOR : HLL_HIP_RSE_FACTOR; - final double rse = (rseFactor * 3) / Math.sqrt(1 << gdtLgK); //99.7% conf - - //output other parameters - final String caseNumStr = Integer.toString(caseNum); - final String srcLgKStr = Integer.toString(source.getLgConfigK()); - final String gdtLgKStr = Integer.toString(union.getLgConfigK()); - final String srcType = source.getTgtHllType().toString(); - final String gdtType = union.getTgtHllType().toString(); - final String srcSeg = Boolean.toString(source.hasMemorySegment()); - final String gdtSeg = Boolean.toString(union.hasMemorySegment()); - final String srcMode = source.getCurMode().toString(); - final String gdtMode = union.getCurMode().toString(); - final String srcOoof = Boolean.toString(source.isOutOfOrder()); - final String gdtOoof = Boolean.toString(union.isOutOfOrder()); - printf(hfmt, caseNumStr, srcLgKStr, gdtLgKStr, srcType, gdtType, srcSeg, gdtSeg, - srcMode, gdtMode, srcOoof, gdtOoof); - assertTrue(err < rse, "Err: " + err + ", RSE: " + rse); - } - - private HllSketch getSkSource(final int caseNum, final TgtHllType tgtHllType, final boolean useMemorySegment) { - final int srcLgK = getSrcLgK(caseNum, maxLgK); - final int srcU = getSrcCount(caseNum, maxLgK); - if (useMemorySegment) { - return buildMemorySegmentSketch(srcLgK, tgtHllType, srcU); - } else { - return buildHeapSketch(srcLgK, tgtHllType, srcU); - } - } - - private HllUnion getUnionSrc(final int caseNum) { - final int srcLgK = getSrcLgK(caseNum, maxLgK); - final int srcU = getSrcCount(caseNum, maxLgK); - final HllSketch sk = buildHeapSketch(srcLgK, HLL_8, srcU); - final HllUnion u = new HllUnion(maxLgK); - u.update(sk); - return u; - } - - private HllUnion getUnion(final int caseNum, final boolean useMemorySegment) { - final int unionU = getUnionCount(caseNum); - return (useMemorySegment) ? buildMemorySegmentUnion(maxLgK, unionU) : buildHeapUnion(maxLgK, unionU); - } - - private static int getUnionCount(final int caseNum) { - final int gdtMode = (caseNum >> 1) & 3; //list, set, hll, empty - return (gdtMode == 0) ? 4 : (gdtMode == 1) ? 380 : (gdtMode == 2) ? 400 : 0; - } - - private static int getSrcCount(final int caseNum, final int maxLgK) { - final int srcLgK = getSrcLgK(caseNum, maxLgK); - return (((1 << srcLgK) * 3) / 4) + 100; //always HLL - } - - private static int getSrcLgK(final int caseNum, final int maxLgK) { - int srcLgK = maxLgK; - final int bits34 = (caseNum >> 3) & 3; - if (bits34 == 1) { srcLgK = maxLgK - 1;} - if (bits34 == 2) { srcLgK = maxLgK + 1;} - return srcLgK; - } - - @Test - public void checkMisc() { - final HllUnion u = buildHeapUnion(12, 0); - int bytes = u.getCompactSerializationBytes(); - assertEquals(bytes, 8); - bytes = HllUnion.getMaxSerializationBytes(7); - assertEquals(bytes, 40 + 128); - double v = u.getEstimate(); - assertEquals(v, 0.0, 0.0); - v = u.getLowerBound(1); - assertEquals(v, 0.0, 0.0); - v = u.getUpperBound(1); - assertEquals(v, 0.0, 0.0); - assertTrue(u.isEmpty()); - u.reset(); - assertTrue(u.isEmpty()); - println(u.toString(true, false, false, false)); - final byte[] bArr = u.toCompactByteArray(); - assertEquals(bArr.length, 8); - } - - @Test - public void checkSrcListList() { //src: LIST, gadget: LIST - final int n1 = 2; - final int n2 = 3; - final int n3 = 2; - final int sum = n1 + n2 + n3; - final HllUnion u = buildHeapUnion(12, n1); //gdt = list - final HllSketch h2 = buildHeapSketch(11, HLL_6, n2); //src = list - final HllSketch h3 = buildHeapSketch(10, HLL_8, n3); //src = list - u.update(h2); - println(u.toString()); - assertEquals(u.getCurMode(), LIST); - u.update(h3); - println(u.toString()); - assertEquals(u.getCurMode(), LIST); - assertEquals(u.getLgConfigK(), 12); - assertFalse(u.isOutOfOrder()); - final double err = sum * errorFactor(u.getLgConfigK(), u.isOutOfOrder(), 3.0); - println("ErrToll: " + err); - assertEquals(u.getEstimate(), sum, err); - } - - @Test - public void checkSrcListSet() { //src: SET, gadget: LIST - final int n1 = 5; - final int n2 = 2; - final int n3 = 16; - final int sum = n1 + n2 + n3; - final HllUnion u = buildHeapUnion(12, n1); //LIST, 5 - final HllSketch h2 = buildHeapSketch(11, HLL_6, n2); //LIST, 2 - final HllSketch h3 = buildHeapSketch(10, HLL_8, n3); //SET, 16 - u.update(h2); - println(u.toString()); - assertEquals(u.getCurMode(), LIST); - u.update(h3); - println(u.toString()); - assertEquals(u.getCurMode(), SET); - assertEquals(u.getLgConfigK(), 12); - assertFalse(u.isOutOfOrder()); - final double err = sum * errorFactor(u.getLgConfigK(), u.isOutOfOrder(), 3.0); - println("ErrToll: " + err); - assertEquals(u.getEstimate(), sum, err); - } - - @Test - public void checkSrcSetList() { //src: LIST, gadget: SET - final int n1 = 6; - final int n2 = 10; - final int n3 = 6; - final int sum = n1 + n2 + n3; - final HllUnion u = buildHeapUnion(12, n1); - final HllSketch h2 = buildHeapSketch(11, HLL_6, n2); //SET - final HllSketch h3 = buildHeapSketch(10, HLL_8, n3); //LIST - u.update(h2); - println(u.toString()); - assertEquals(u.getCurMode(), SET); - u.update(h3); - println(u.toString()); - assertEquals(u.getCurMode(), SET); - assertEquals(u.getLgConfigK(), 12); - assertFalse(u.isOutOfOrder()); - final double err = sum * errorFactor(u.getLgConfigK(), u.isOutOfOrder(), 3.0); - println("ErrToll: " + err); - assertEquals(u.getEstimate(), sum, err); - } - - @Test - public void checkSrcSetSet() { //src: SET, gadget: SET - final int n1 = 6; - final int n2 = 10; - final int n3 = 16; - final int sum = n1 + n2 + n3; - final HllUnion u = buildHeapUnion(12, n1); - final HllSketch h2 = buildHeapSketch(11, HLL_6, n2); //src: SET - final HllSketch h3 = buildHeapSketch(10, HLL_8, n3); //src: SET - u.update(h2); - println(u.toString()); - assertEquals(u.getCurMode(), SET); - u.update(h3); - println(u.toString()); - assertEquals(u.getCurMode(), SET); - assertEquals(u.getLgConfigK(), 12); - assertFalse(u.isOutOfOrder()); - final double err = sum * errorFactor(u.getLgConfigK(), u.isOutOfOrder(), 3.0); - println("ErrToll: " + err); - assertEquals(u.getEstimate(), sum, err); - } - - @Test - public void checkSrcEmptyList() { //src: LIST, gadget: empty - final int n1 = 0; - final int n2 = 0; - final int n3 = 7; - final int sum = n1 + n2 + n3; - final HllUnion u = buildHeapUnion(12, n1); //LIST empty - final HllSketch h2 = buildHeapSketch(11, HLL_6, n2); //src: LIST empty, ignored - final HllSketch h3 = buildHeapSketch(10, HLL_8, n3); //src: LIST - u.update(h2); - println(u.toString()); - assertEquals(u.getCurMode(), LIST); - u.update(h3); - println(u.toString()); - assertEquals(u.getCurMode(), LIST); - assertEquals(u.getLgConfigK(), 12); - assertFalse(u.isOutOfOrder()); - final double err = sum * errorFactor(u.getLgConfigK(), u.isOutOfOrder(), 3.0); - println("ErrToll: " + err); - assertEquals(u.getEstimate(), sum, err); - } - - @Test - public void checkSrcEmptySet() { - final int n1 = 0; - final int n2 = 0; - final int n3 = 16; - final int sum = n1 + n2 + n3; - final HllUnion u = buildHeapUnion(12, n1); //LIST empty - final HllSketch h2 = buildHeapSketch(11, HLL_6, n2); //LIST empty, ignored - final HllSketch h3 = buildHeapSketch(10, HLL_8, n3); // Src Set - u.update(h2); - println(u.toString()); - assertEquals(u.getCurMode(), LIST); - u.update(h3); - println(u.toString()); - assertEquals(u.getCurMode(), SET); - assertEquals(u.getLgConfigK(), 12); - assertFalse(u.isOutOfOrder()); - final double err = sum * errorFactor(u.getLgConfigK(), u.isOutOfOrder(), 3.0); - println("ErrToll: " + err); - assertEquals(u.getEstimate(), sum, err); - } - - @SuppressWarnings("unused") - @Test - public void checkSpecialMergeCase4() { - final HllUnion u = buildHeapUnion(12, 1 << 9); - final HllSketch sk = buildHeapSketch(12, HLL_8, 1 << 9); - - u.update(sk); - assertTrue(u.isRebuildCurMinNumKxQFlag()); - u.getCompositeEstimate(); - assertFalse(u.isRebuildCurMinNumKxQFlag()); - - u.update(sk); - assertTrue(u.isRebuildCurMinNumKxQFlag()); - u.getLowerBound(2); - assertFalse(u.isRebuildCurMinNumKxQFlag()); - - u.update(sk); - assertTrue(u.isRebuildCurMinNumKxQFlag()); - u.getUpperBound(2); - assertFalse(u.isRebuildCurMinNumKxQFlag()); - - u.update(sk); - assertTrue(u.isRebuildCurMinNumKxQFlag()); - u.getResult(); - assertFalse(u.isRebuildCurMinNumKxQFlag()); - - u.update(sk); - assertTrue(u.isRebuildCurMinNumKxQFlag()); - byte[] ba = u.toCompactByteArray(); - assertFalse(u.isRebuildCurMinNumKxQFlag()); - - u.update(sk); - assertTrue(u.isRebuildCurMinNumKxQFlag()); - ba = u.toUpdatableByteArray(); - assertFalse(u.isRebuildCurMinNumKxQFlag()); - - u.putRebuildCurMinNumKxQFlag(true); - assertTrue(u.isRebuildCurMinNumKxQFlag()); - u.putRebuildCurMinNumKxQFlag(false); - assertFalse(u.isRebuildCurMinNumKxQFlag()); - } - - @Test - public void checkRebuildCurMinNumKxQFlag1() { - final HllSketch sk = buildHeapSketch(4, HLL_8, 16); - final HllArray hllArr = (HllArray)(sk.hllSketchImpl); - hllArr.putRebuildCurMinNumKxQFlag(true); //corrupt the flag - final HllUnion union = buildHeapUnion(4, 0); - union.update(sk); - } - - @Test - public void checkRebuildCurMinNumKxQFlag2() { - final HllSketch sk = buildMemorySegmentSketch(4, HLL_8, 16); - final DirectHllArray hllArr = (DirectHllArray)(sk.hllSketchImpl); - hllArr.putRebuildCurMinNumKxQFlag(true); //corrupt the flag - final MemorySegment wseg = sk.getMemorySegment(); - HllUnion.writableWrap(wseg); - } - - @Test(expectedExceptions = SketchesStateException.class) - public void checkHllMergeToException() { - final HllSketch src = buildHeapSketch(4, HLL_8, 16); - final HllSketch tgt = buildHeapSketch(4, HLL_8, 16); - final AbstractHllArray absHllArr = (AbstractHllArray)(src.hllSketchImpl); - absHllArr.mergeTo(tgt); - } - - - private static double errorFactor(final int lgK, final boolean oooFlag, final double numStdDev) { - double f; - if (oooFlag) { - f = (1.04 * numStdDev) / Math.sqrt(1 << lgK); - } else { - f = (0.9 * numStdDev) / Math.sqrt(1 << lgK); - } - return f; - } - - //BUILDERS - private HllUnion buildHeapUnion(final int lgMaxK, final int n) { - final HllUnion u = new HllUnion(lgMaxK); - for (int i = 0; i < n; i++) { u.update(i + v); } - v += n; - return u; - } - - private HllUnion buildMemorySegmentUnion(final int lgMaxK, final int n) { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgMaxK, TgtHllType.HLL_8); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllUnion u = new HllUnion(lgMaxK, wseg); - for (int i = 0; i < n; i++) { u.update(i + v); } - v += n; - return u; - } - - private HllSketch buildHeapSketch(final int lgK, final TgtHllType tgtHllType, final int n) { - final HllSketch sk = new HllSketch(lgK, tgtHllType); - for (int i = 0; i < n; i++) { sk.update(i + v); } - v += n; - return sk; - } - - private HllSketch buildMemorySegmentSketch(final int lgK, final TgtHllType tgtHllType, final int n) { - final int bytes = HllSketch.getMaxUpdatableSerializationBytes(lgK,tgtHllType); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllSketch sk = new HllSketch(lgK, tgtHllType, wseg); - for (int i = 0; i < n; i++) { sk.update(i + v); } - v += n; - return sk; - } - - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param o value to print - */ - static void println(final Object o) { - print(o.toString() + "\n"); - } - - /** - * @param o value to print - */ - static void print(final Object o) { - //System.out.print(o.toString()); //disable here - } - - /** - * @param fmt format - * @param args arguments - */ - static void printf(final String fmt, final Object...args) { - //System.out.printf(fmt, args); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hll/UnionTest.java b/src/test/java/org/apache/datasketches/hll/UnionTest.java deleted file mode 100644 index 23c373207..000000000 --- a/src/test/java/org/apache/datasketches/hll/UnionTest.java +++ /dev/null @@ -1,525 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hll; - -import static java.lang.Math.min; -import static org.apache.datasketches.hll.TgtHllType.HLL_4; -import static org.apache.datasketches.hll.TgtHllType.HLL_6; -import static org.apache.datasketches.hll.TgtHllType.HLL_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class UnionTest { - static final String LS = System.getProperty("line.separator"); - - static final int[] nArr = {1, 3, 10, 30, 100, 300, 1000, 3000, 10000, 30000}; - - // n1,... lgK,... tgtHll, Mode Ooo Est - static final String hdrFmt = - "%6s%6s%6s" + "%8s%5s%5s%5s" + "%7s%6s" + "%7s%6s%6s" +"%3s%2s%2s"+ "%13s%12s"; - static final String hdr = String.format(hdrFmt, - "n1", "n2", "tot", - "lgMaxK", "lgK1", "lgK2", "lgKR", - "tgt1", "tgt2", - "Mode1", "Mode2", "ModeR", - "1", "2", "R", - "Est", "Err%"); - - /** - * The task here is to check the transition boundaries as the sketch morphs between LIST to - * SET to HLL modes. The transition points vary as a function of lgConfigK. In addition, - * this checks that the union operation is operating properly based on the order the - * sketches are presented to the union. - */ - @Test - public void checkUnions() { - //HLL_4: t=0, HLL_6: t=1, HLL_8: t=2 - final int t1 = 2; //type = HLL_8 - final int t2 = 2; - final int rt = 2; //result type - println("TgtR: " + TgtHllType.values()[rt].toString()); - - int lgK1 = 7; - int lgK2 = 7; - int lgMaxK = 7; - int n1 = 7; - int n2 = 7; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 = 8; - n2 = 7; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 = 7; - n2 = 8; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 = 8; - n2 = 8; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 = 7; - n2 = 14; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - println("++END BASE GROUP++"); - - int i = 0; - for (i = 7; i <= 13; i++) - { - lgK1 = i; - lgK2 = i; - lgMaxK = i; - { - n1 = ((1 << (i - 3)) * 3)/4; //compute the transition point - n2 = n1; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 -= 2; - n2 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - } - println("--END MINOR GROUP--"); - lgK1 = i; - lgK2 = i + 1; - lgMaxK = i; - { - n1 = ((1 << (i - 3)) * 3)/4; - n2 = n1; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 -= 2; - n2 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - } - println("--END MINOR GROUP--"); - lgK1 = i + 1; - lgK2 = i; - lgMaxK = i; - { - n1 = ((1 << (i - 3)) * 3)/4; - n2 = n1; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 -= 2; - n2 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - } - println("--END MINOR GROUP--"); - lgK1 = i + 1; - lgK2 = i + 1; - lgMaxK = i; - { - n1 = ((1 << (i - 3)) * 3)/4; - n2 = n1; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 -= 2; - n2 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - n1 += 2; - basicUnion(n1, n2, lgK1, lgK2, lgMaxK, t1, t2, rt); - } - println("++END MAJOR GROUP++"); - } //End for - } - - @Test - public void check() { //n1=8, n2=7, lgK1=lgK2=lgMaxK=7, all HLL_8 - basicUnion(8, 7, 7, 7, 7, 2, 2, 2); - } - - private static void basicUnion(final int n1, final int n2, final int lgK1, final int lgK2, - final int lgMaxK, final int t1, final int t2, final int rt) { - long v = 0; - final int tot = n1 + n2; - final TgtHllType type1 = TgtHllType.values()[t1]; - final String t1str = type1.toString(); - final TgtHllType type2 = TgtHllType.values()[t2]; - final String t2str = type2.toString(); - final TgtHllType resultType = TgtHllType.values()[rt]; - //String rtStr = resultType.toString(); - - final HllSketch h1 = new HllSketch(lgK1, type1); - final HllSketch h2 = new HllSketch(lgK2, type2); - final int lgControlK = min(min(lgK1, lgK2), lgMaxK); //min of all 3 - final HllSketch control = new HllSketch(lgControlK, resultType); - final String dataFmt = "%6d%6d%6d," + "%7d%5d%5d%5d," + "%6s%6s," + "%6s%6s%6s," - +"%2s%2s%2s," + "%12f%12f%%"; - - for (long i = 0; i < n1; i++) { - h1.update(v + i); - control.update(v + i); - } - v += n1; - for (long i = 0; i < n2; i++) { - h2.update(v + i); - control.update(v + i); - } - v += n2; - - final String h1SketchStr = ("H1 SKETCH: \n" + h1.toString()); - final String h2SketchStr = ("H2 SKETCH: \n" + h2.toString()); - - final HllUnion union = newUnion(lgMaxK); - union.update(h1); - - final String uH1SketchStr = ("Union after H1: \n" + union.getResult(resultType).toString()); - //println(uH1SketchStr); - - union.update(h2); - final HllSketch result = union.getResult(resultType); - final int lgKR = result.getLgConfigK(); - - final String uSketchStr =("Union after H2: \n" + result.toString()); - - final double uEst = result.getEstimate(); - final double uUb = result.getUpperBound(2); - final double uLb = result.getLowerBound(2); - final double rerr = ((uEst/tot) - 1.0) * 100; - final String mode1 = h1.getCurMode().toString(); - final String mode2 = h2.getCurMode().toString(); - final String modeR = result.getCurMode().toString(); - - //Control - final String cSketchStr = ("CONTROL SKETCH: \n" + control.toString()); - final double controlEst = control.getEstimate(); - final double controlUb = control.getUpperBound(2); - final double controlLb = control.getLowerBound(2); - final String h1ooo = h1.isOutOfOrder() ? "T" : "F"; - final String h2ooo = h2.isOutOfOrder() ? "T" : "F"; - final String resultooo = result.isOutOfOrder() ? "T" : "F"; - final String row = String.format(dataFmt, - n1, n2, tot, - lgMaxK, lgK1, lgK2, lgKR, - t1str, t2str, - mode1, mode2, modeR, - h1ooo, h2ooo, resultooo, - uEst, rerr); - println(h1SketchStr); - println(h2SketchStr); - println(uH1SketchStr); - println(uSketchStr); - println(cSketchStr); - println(hdr); - println(row); - assertTrue((controlUb - controlEst) >= 0); - assertTrue((uUb - uEst) >= 0); - assertTrue((controlEst - controlLb) >= 0); - assertTrue((uEst -uLb) >= 0); - } - - @Test - public void checkToFromUnion1() { - for (int i = 0; i < 10; i++) { - final int n = nArr[i]; - for (int lgK = 4; lgK <= 13; lgK++) { - toFrom1(lgK, HLL_4, n); - toFrom1(lgK, HLL_6, n); - toFrom1(lgK, HLL_8, n); - } - println("======="); - } - } - - private static void toFrom1(final int lgK, final TgtHllType tgtHllType, final int n) { - final HllUnion srcU = newUnion(lgK); - final HllSketch srcSk = new HllSketch(lgK, tgtHllType); - for (int i = 0; i < n; i++) { - srcSk.update(i); - } - println("n: " + n + ", lgK: " + lgK + ", type: " + tgtHllType); - //printSketch(src, "SRC"); - srcU.update(srcSk); - - final byte[] byteArr = srcU.toCompactByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - final HllUnion dstU = HllUnion.heapify(seg); - assertFalse(dstU.isSameResource(seg)); - - assertEquals(dstU.getEstimate(), srcU.getEstimate(), 0.0); - } - - @Test - public void checkToFromUnion2() { - for (int i = 0; i < 10; i++) { - final int n = nArr[i]; - for (int lgK = 4; lgK <= 13; lgK++) { - toFrom2(lgK, HLL_4, n); - toFrom2(lgK, HLL_6, n); - toFrom2(lgK, HLL_8, n); - } - println("======="); - } - } - - private static void toFrom2(final int lgK, final TgtHllType tgtHllType, final int n) { - final HllUnion srcU = newUnion(lgK); - final HllSketch srcSk = new HllSketch(lgK, tgtHllType); - for (int i = 0; i < n; i++) { - srcSk.update(i); - } - println("n: " + n + ", lgK: " + lgK + ", type: " + tgtHllType); - //printSketch(src, "SRC"); - srcU.update(srcSk); - - final byte[] byteArr = srcU.toCompactByteArray(); - final HllUnion dstU = HllUnion.heapify(byteArr); - - assertEquals(dstU.getEstimate(), srcU.getEstimate(), 0.0); - } - - @Test - public void checkCompositeEst() { - final HllUnion u = new HllUnion(); - assertEquals(u.getCompositeEstimate(), 0, .03); - for (int i = 1; i <= 15; i++) { u.update(i); } - assertEquals(u.getCompositeEstimate(), 15, 15 *.03); - for (int i = 15; i <= 1000; i++) { u.update(i); } - assertEquals(u.getCompositeEstimate(), 1000, 1000 * .03); - } - - @SuppressWarnings("unused") - @Test - public void checkMisc() { - try { - final HllUnion u = newUnion(HllUtil.MIN_LOG_K - 1); - fail(); - } catch (final SketchesArgumentException e) { - //expected - } - try { - final HllUnion u = newUnion(HllUtil.MAX_LOG_K + 1); - fail(); - } catch (final SketchesArgumentException e) { - //expected - } - final HllUnion u = newUnion(7); - final HllSketch sk = u.getResult(); - assertTrue(sk.isEmpty()); - } - - @Test - public void checkHeapify() { - final HllUnion u = newUnion(16); - for (int i = 0; i < (1 << 20); i++) { - u.update(i); - } - final double est1 = u.getEstimate(); - final byte[] byteArray = u.toUpdatableByteArray(); - final HllUnion u2 = HllUnion.heapify(byteArray); - assertEquals(u2.getEstimate(), est1, 0.0); - } - - @Test //for lgK <= 12 - public void checkUbLb() { - final int lgK = 4; - final int n = 1 << 20; - final boolean oooFlag = false; - println("LgK="+lgK+", UB3, " + ((getBound(lgK, true, oooFlag, 3, n) / n) - 1)); - println("LgK="+lgK+", UB2, " + ((getBound(lgK, true, oooFlag, 2, n) / n) - 1)); - println("LgK="+lgK+", UB1, " + ((getBound(lgK, true, oooFlag, 1, n) / n) - 1)); - println("LgK="+lgK+", LB1, " + ((getBound(lgK, false, oooFlag, 1, n) / n) - 1)); - println("LgK="+lgK+", LB2, " + ((getBound(lgK, false, oooFlag, 2, n) / n) - 1)); - println("LgK="+lgK+", LB3, " + ((getBound(lgK, false, oooFlag, 3, n) / n) - 1)); - } - - @Test - public void checkEmptyCouponMisc() { - final int lgK = 8; - final HllUnion union = newUnion(lgK); - for (int i = 0; i < 20; i++) { union.update(i); } //SET mode - union.couponUpdate(0); - assertEquals(union.getEstimate(), 20.0, 0.001); - assertEquals(union.getTgtHllType(), TgtHllType.HLL_8); - assertFalse(union.hasMemorySegment()); - assertFalse(union.isOffHeap()); - final int bytes = union.getUpdatableSerializationBytes(); - assertTrue(bytes <= HllUnion.getMaxSerializationBytes(lgK)); - assertFalse(union.isCompact()); - } - - @Test - public void checkUnionWithWrap() { - final int lgConfigK = 4; - final TgtHllType type = TgtHllType.HLL_4; - final int n = 2; - final HllSketch sk = new HllSketch(lgConfigK, type); - for (int i = 0; i < n; i++) { sk.update(i); } - final double est = sk.getEstimate(); - final byte[] skByteArr = sk.toCompactByteArray(); - - final HllSketch sk2 = HllSketch.wrap(MemorySegment.ofArray(skByteArr)); - assertEquals(sk2.getEstimate(), est, 0.0); - - final HllUnion union = newUnion(lgConfigK); - union.update(HllSketch.wrap(MemorySegment.ofArray(skByteArr))); - assertEquals(union.getEstimate(), est, 0.0); - } - - @Test - public void checkUnionWithWrap2() { - final int lgConfigK = 10; - final int n = 128; - final HllSketch sk1 = new HllSketch(lgConfigK); - for (int i = 0; i < n; i++) { sk1.update(i); } - final double est1 = sk1.getEstimate(); - final byte[] byteArr1 = sk1.toCompactByteArray(); - - final HllUnion union = newUnion(lgConfigK); - union.update(HllSketch.wrap(MemorySegment.ofArray(byteArr1))); - final double est2 = union.getEstimate(); - assertEquals(est2, est1); - } - - @Test - public void checkConversions() { - final int lgK = 4; - final HllSketch sk1 = new HllSketch(lgK, TgtHllType.HLL_8); - final HllSketch sk2 = new HllSketch(lgK, TgtHllType.HLL_8); - final int u = 1 << 20; - for (int i = 0; i < u; i++) { - sk1.update(i); - sk2.update(i + u); - } - final HllUnion union = new HllUnion(lgK); - union.update(sk1); - union.update(sk2); - final HllSketch rsk1 = union.getResult(TgtHllType.HLL_8); - final HllSketch rsk2 = union.getResult(TgtHllType.HLL_6); - final HllSketch rsk3 = union.getResult(TgtHllType.HLL_4); - final double est1 = rsk1.getEstimate(); - final double est2 = rsk2.getEstimate(); - final double est3 = rsk3.getEstimate(); - //println("Est1: " + est1); - //println("Est2: " + est2); - //println("Est3: " + est3); - //println("Result HLL8: " + rsk1.toString(true, true, true, false)); - //println("Result HLL4: " + rsk3.toString(true, true, true, false)); - - assertEquals(est2, est1, 0.0); - assertEquals(est3, est1, 0.0); - } - - @Test - public void checkUnionHeapifyRebuildAfterMerge() { - final int lgK = 12; - //Build 2 sketches in HLL (dense) mode. - final int u = 1 << (lgK - 3); //(lgK < 8) ? 16 : 1 << (lgK - 3) //allows changing lgK above - final HllSketch sk1 = new HllSketch(lgK); - final HllSketch sk2 = new HllSketch(lgK); - for (int i = 0; i < u; i++) { - sk1.update(i); - sk2.update(i + u); - } - final int bytes = HllUnion.getMaxSerializationBytes(lgK); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - final HllUnion union1 = new HllUnion(lgK, wseg); //Create original union off-heap - union1.update(sk1); - union1.update(sk2); //oooFlag = Rebuild_KxQ = TRUE - assertTrue(!union1.toString().isEmpty()); - boolean rebuild = PreambleUtil.extractRebuildCurMinNumKxQFlag(wseg); - final double hipAccum = PreambleUtil.extractHipAccum(wseg); - assertTrue(rebuild); - assertTrue(hipAccum == 0.0); - //Heapify byteArr as if it were a sketch, but it is actually a union! - final HllSketch sk3 = HllSketch.heapify(wseg); //rebuilds sk3 - rebuild = sk3.hllSketchImpl.isRebuildCurMinNumKxQFlag(); - assertFalse(rebuild); - } - - @Test //similar to above except uses HllUnion.writableWrap instead of heapify - public void druidUseCase() { - final int lgK = 12; - final int bytes = HllUnion.getMaxSerializationBytes(lgK); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - new HllUnion(lgK, wseg); // result is unused, relying on side effect - int trueCount = 0; - final int delta = 1 << (lgK - 3); //(lgK < 8) ? 16 : 1 << (lgK - 3) //allows changing lgK above - for (int i = 0; i < 3; i++) { - HllUnion.writableWrap(wseg).update(buildSketch(trueCount, delta)); - trueCount += delta; - } - boolean rebuild = PreambleUtil.extractRebuildCurMinNumKxQFlag(wseg); - final double hipAccum = PreambleUtil.extractHipAccum(wseg); - assertTrue(rebuild); - assertTrue(hipAccum == 0.0); - final HllSketch result = HllUnion.writableWrap(wseg).getResult(); //rebuilds result - rebuild = result.hllSketchImpl.isRebuildCurMinNumKxQFlag(); - assertFalse(rebuild); - final double est = result.getEstimate(); - final double err = (est / trueCount) - 1.0; - final double rse3 = (3 * 1.04)/Math.sqrt(1 << lgK); - println(err + " < " + rse3); - assertTrue(err < rse3); - } - - private static HllSketch buildSketch(final int start, final int count) { - final HllSketch sketch = new HllSketch(10); - for (int i = start; i < (start + count); i++) { - sketch.update(i); - } - return sketch; - } - - private static HllUnion newUnion(final int lgK) { - return new HllUnion(lgK); - } - - private static double getBound(final int lgK, final boolean ub, final boolean oooFlag, final int numStdDev, final double est) { - final double re = RelativeErrorTables.getRelErr(ub, oooFlag, lgK, numStdDev); - return est / (1.0 + re); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final Object s) { - print(s.toString() + LS); - } - - /** - * @param s value to print - */ - static void print(final Object s) { - //System.out.print(s.toString()); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hllmap/CouponHashMapTest.java b/src/test/java/org/apache/datasketches/hllmap/CouponHashMapTest.java deleted file mode 100644 index 955f9c42a..000000000 --- a/src/test/java/org/apache/datasketches/hllmap/CouponHashMapTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hllmap; - -import static java.nio.charset.StandardCharsets.UTF_8; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class CouponHashMapTest { - - @Test - public void getEstimateNoEntry() { - CouponHashMap map = CouponHashMap.getInstance(4, 16); - byte[] key = new byte[] {0, 0, 0, 0}; - Assert.assertEquals(map.getEstimate(key), 0.0); - Assert.assertEquals(map.getUpperBound(key), 0.0); - Assert.assertEquals(map.getLowerBound(key), 0.0); - } - - @Test - public void oneKeyOneEntry() { - CouponHashMap map = CouponHashMap.getInstance(4, 16); - byte[] key = new byte[] {0, 0, 0, 0}; - double estimate = map.update(key, (short) 1); - Assert.assertEquals(estimate, 1.0); - Assert.assertEquals(map.getEstimate(key), 1.0); - Assert.assertTrue(map.getUpperBound(key) > 1.0); - Assert.assertTrue(map.getLowerBound(key) < 1.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void keyNotFound() { - CouponHashMap map = CouponHashMap.getInstance(4, 16); - byte[] key = new byte[] {0, 0, 0, 0}; - map.update(key, (short) 1); - map.updateEstimate(map.findKey(new byte[] {1,0,0,0}), 2.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void wrongCouponsPerKey() { - CouponHashMap map = CouponHashMap.getInstance(4, 8); - println(map.toString()); //required otherwise FindBugs will show error - } - - @Test - public void delete() { - CouponHashMap map = CouponHashMap.getInstance(4, 16); - double estimate = map.update("1234".getBytes(UTF_8), (short) 1); - Assert.assertEquals(estimate, 1.0); - int index1 = map.findKey("1234".getBytes(UTF_8)); - Assert.assertTrue(index1 >= 0); - map.deleteKey(index1); - int index2 = map.findKey("1234".getBytes(UTF_8)); - // should be complement of the same index as before - Assert.assertEquals(~index2, index1); - Assert.assertEquals(map.getEstimate("1234".getBytes(UTF_8)), 0.0); - } - - @Test - public void growAndShrink() { - CouponHashMap map = CouponHashMap.getInstance(4, 16); - long sizeBytes1 = map.getTotalUsageBytes(); - for (int i = 0; i < 1000; i ++) { - byte[] key = String.format("%4s", i).getBytes(UTF_8); - map.update(key, (short) Map.coupon16(new byte[] {1})); - } - long sizeBytes2 = map.getTotalUsageBytes(); - Assert.assertTrue(sizeBytes2 > sizeBytes1); - for (int i = 0; i < 1000; i ++) { - byte[] key = String.format("%4s", i).getBytes(UTF_8); - int index = map.findKey(key); - Assert.assertTrue(index >= 0); - map.deleteKey(index); - } - long sizeBytes3 = map.getTotalUsageBytes(); - Assert.assertTrue(sizeBytes3 < sizeBytes2); - println(map.toString()); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hllmap/CouponTraverseMapTest.java b/src/test/java/org/apache/datasketches/hllmap/CouponTraverseMapTest.java deleted file mode 100644 index 4bc0277f4..000000000 --- a/src/test/java/org/apache/datasketches/hllmap/CouponTraverseMapTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hllmap; - -import static java.nio.charset.StandardCharsets.UTF_8; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class CouponTraverseMapTest { - - @Test - public void getEstimateNoEntry() { - CouponTraverseMap map = CouponTraverseMap.getInstance(4, 1); - byte[] key = new byte[] {0, 0, 0 ,0}; - Assert.assertEquals(map.getEstimate(key), 0.0); - Assert.assertEquals(map.getUpperBound(key), 0.0); - Assert.assertEquals(map.getLowerBound(key), 0.0); - } - - @Test - public void oneKeyOneEntry() { - CouponTraverseMap map = CouponTraverseMap.getInstance(4, 1); - byte[] key = new byte[] {0, 0, 0 ,0}; - double estimate = map.update(key, (short) 1); - Assert.assertEquals(estimate, 1.0); - Assert.assertEquals(map.getEstimate(key), 1.0); - Assert.assertTrue(map.getUpperBound(key) >= 1.0); - Assert.assertTrue(map.getLowerBound(key) <= 1.0); - } - - @Test - public void delete() { - CouponTraverseMap map = CouponTraverseMap.getInstance(4, 1); - double estimate = map.update("1234".getBytes(UTF_8), (short) 1); - Assert.assertEquals(estimate, 1.0); - int index1 = map.findKey("1234".getBytes(UTF_8)); - Assert.assertTrue(index1 >= 0); - map.deleteKey(index1); - int index2 = map.findKey("1234".getBytes(UTF_8)); - // should be complement of the same index as before - Assert.assertEquals(~index2, index1); - Assert.assertEquals(map.getEstimate("1".getBytes(UTF_8)), 0.0); - } - - @Test - public void growAndShrink() { - CouponTraverseMap map = CouponTraverseMap.getInstance(4, 1); - long sizeBytes1 = map.getTotalUsageBytes(); - for (int i = 0; i < 1000; i ++) { - byte[] key = String.format("%4s", i).getBytes(UTF_8); - map.update(key, (short) 1); - } - long sizeBytes2 = map.getTotalUsageBytes(); - Assert.assertTrue(sizeBytes2 > sizeBytes1); - for (int i = 0; i < 1000; i ++) { - byte[] key = String.format("%4s", i).getBytes(UTF_8); - int index = map.findKey(key); - Assert.assertTrue(index >= 0); - map.deleteKey(index); - } - long sizeBytes3 = map.getTotalUsageBytes(); - Assert.assertTrue(sizeBytes3 < sizeBytes2); - println(map.toString()); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(String s) { - //System.out.println(s); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/hllmap/HllMapTest.java b/src/test/java/org/apache/datasketches/hllmap/HllMapTest.java deleted file mode 100644 index 0d52c2f00..000000000 --- a/src/test/java/org/apache/datasketches/hllmap/HllMapTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hllmap; - -import org.apache.datasketches.common.Util; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class HllMapTest { - - @Test - public void singleKeyTest() { - int k = 1024; - int u = 1000; - int keySize = 4; - HllMap map = HllMap.getInstance(keySize, k); - Assert.assertTrue(Double.isNaN(map.getEstimate(null))); - Assert.assertTrue(map.getEntrySizeBytes() > 800); - Assert.assertEquals(map.getCapacityEntries(), 147); - Assert.assertEquals(map.getTableEntries(), 157); - Assert.assertTrue(map.getTotalUsageBytes() < 140000); -// println("Entry bytes : " + map.getEntrySizeBytes()); -// println("Capacity : " + map.getCapacityEntries()); -// println("Table Entries : " + map.getTableEntries()); -// println("Est Arr Size : " + (map.getEntrySizeBytes() * map.getTableEntries())); -// println("Size of Arrays: "+ map.getMemoryUsageBytes()); - - byte[] key = new byte[4]; - byte[] id = new byte[4]; - double est; - key = Util.intToBytes(1, key); - for (int i=1; i<= u; i++) { - id = Util.intToBytes(i, id); - short coupon = (short) Map.coupon16(id); - est = map.update(key, coupon); - if ((i % 100) == 0) { - double err = ((est/i) -1.0) * 100; - String eStr = String.format("%.3f%%", err); - println("i: "+i + "\t Est: " + est + "\t" + eStr); - } - } - byte[] key2 = Util.intToBytes(2, key); - Assert.assertEquals(map.getEstimate(key2), 0.0); - Assert.assertEquals(map.getKeySizeBytes(), 4); - -// println("Table Entries : " + map.getTableEntries()); - Assert.assertEquals(map.getCurrentCountEntries(), 1); -// println("Cur Count : " + map.getCurrentCountEntries()); -// println("RSE : " + (1/Math.sqrt(k))); - //map.printEntry(key); - } - - @Test - public void resizeTest() { - int k = 1024; - int u = 257; - int keys = 200; - int keySize = 4; - long v = 0; - HllMap map = HllMap.getInstance(keySize, k); - Assert.assertTrue(map.getEntrySizeBytes() > 800); - Assert.assertEquals(map.getCapacityEntries(), 147); - Assert.assertEquals(map.getTableEntries(), 157); - Assert.assertTrue(map.getTotalUsageBytes() < 140000); -// println("Entry bytes : " + map.getEntrySizeBytes()); -// println("Capacity : " + map.getCapacityEntries()); -// println("Table Entries : " + map.getTableEntries()); -// println("Size of Arrays: " + map.getMemoryUsageBytes()); - byte[] key = new byte[4]; - byte[] id = new byte[8]; - int i, j; - for (j=1; j<=keys; j++) { - key = Util.intToBytes(j, key); - for (i=0; i< u; i++) { - id = Util.longToBytes(++v, id); - short coupon = (short) Map.coupon16(id); - map.update(key, coupon); - } - double est = map.getEstimate(key); - Assert.assertTrue(map.getUpperBound(key) > est); - Assert.assertTrue(map.getLowerBound(key) < est); - double err = ((est/u) -1.0) * 100; - String eStr = String.format("%.3f%%", err); - println("key: " + j + "\tu: "+u + "\t Est: " + est + "\t" + eStr); - } - Assert.assertEquals(317, map.getTableEntries()); -// println("Table Entries : " + map.getTableEntries()); - Assert.assertEquals(200, map.getCurrentCountEntries()); -// println("Cur Count : " + map.getCurrentCountEntries()); -// println("Theoretical RSE: " + (1/Math.sqrt(k))); - for (j=1; j<=keys; j++) { - key = Util.intToBytes(j, key); - double est = map.getEstimate(key); - double err = ((est/u) -1.0) * 100; - String eStr = String.format("%.3f%%", err); - println("key: " + j + "\tu: "+u + "\t Est: " + est + "\t" + eStr); - } - //println(map.toString()); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hllmap/SingleCouponMapTest.java b/src/test/java/org/apache/datasketches/hllmap/SingleCouponMapTest.java deleted file mode 100644 index 401e6e491..000000000 --- a/src/test/java/org/apache/datasketches/hllmap/SingleCouponMapTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hllmap; - -import static java.nio.charset.StandardCharsets.UTF_8; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class SingleCouponMapTest { - - @Test - public void getEstimateNoEntry() { - SingleCouponMap map = SingleCouponMap.getInstance(1000, 4); - byte[] key = new byte[] {0, 0, 0, 1}; - Assert.assertEquals(map.getEstimate(key), 0.0); - Assert.assertEquals(map.getUpperBound(key), 0.0); - Assert.assertEquals(map.getLowerBound(key), 0.0); - } - - @Test - public void oneKeyOneEntry() { - int entries = 16; - int keySizeBytes = 4; - SingleCouponMap map = SingleCouponMap.getInstance(entries, keySizeBytes); - byte[] key = new byte[] {0, 0, 0, 0}; // zero key must work - byte[] id = new byte[] {1, 0, 0, 0}; - short coupon = (short) Map.coupon16(id); - double estimate = map.update(key, coupon); - Assert.assertEquals(estimate, 1.0); - Assert.assertEquals(map.getEstimate(key), 1.0); - Assert.assertTrue(map.getUpperBound(key) >= 1.0); - Assert.assertTrue(map.getLowerBound(key) <= 1.0); - } - - @Test - public void resize() { - int entries = 17; - int numKeys = 1000; - int keySizeBytes = 4; - SingleCouponMap map = SingleCouponMap.getInstance(entries, keySizeBytes); - - for (int i = 0; i < numKeys; i++) { - byte[] key = String.format("%4s", i).getBytes(UTF_8); - byte[] id = new byte[] {1, 0, 0, 0}; - short coupon = (short) Map.coupon16(id); - double estimate = map.update(key, coupon); - Assert.assertEquals(estimate, 1.0); - Assert.assertEquals(map.getEstimate(key), 1.0); - Assert.assertTrue(map.getUpperBound(key) >= 1.0); - Assert.assertTrue(map.getLowerBound(key) <= 1.0); - } - for (int i = 0; i < numKeys; i++) { - byte[] key = String.format("%4s", i).getBytes(UTF_8); - Assert.assertEquals(map.getEstimate(key), 1.0); - Assert.assertTrue(map.getUpperBound(key) >= 1.0); - Assert.assertTrue(map.getLowerBound(key) <= 1.0); - } - println(map.toString()); - Assert.assertEquals(map.getCurrentCountEntries(), numKeys); - } - - @Test - public void manyKeys() { - SingleCouponMap map = SingleCouponMap.getInstance(2000, 4); - for (int i = 1; i <= 1000; i++) { - byte[] key = String.format("%4s", i).getBytes(UTF_8); - double estimate = map.update(key, (short) 1); //bogus coupon - Assert.assertEquals(estimate, 1.0); - Assert.assertEquals(map.getEstimate(key), 1.0); - Assert.assertTrue(map.getUpperBound(key) >= 1.0); - Assert.assertTrue(map.getLowerBound(key) <= 1.0); - } - for (int i = 1; i <= 1000; i++) { - byte[] key = String.format("%4s", i).getBytes(UTF_8); - double estimate = map.update(key, (short) 2); //different bogus coupon - Assert.assertEquals(estimate, 0.0); // signal to promote - } - Assert.assertEquals(map.getCurrentCountEntries(), 1000); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/hllmap/UniqueCountMapTest.java b/src/test/java/org/apache/datasketches/hllmap/UniqueCountMapTest.java deleted file mode 100644 index 370bbefae..000000000 --- a/src/test/java/org/apache/datasketches/hllmap/UniqueCountMapTest.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.hllmap; - -import static org.apache.datasketches.hash.MurmurHash3.hash; -import static java.nio.charset.StandardCharsets.UTF_8; - -import org.testng.Assert; -import org.testng.annotations.Test; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; - -public class UniqueCountMapTest { - private final static int INIT_ENTRIES = 211; - @Test - public void nullKey() { - UniqueCountMap map = new UniqueCountMap(4); - double estimate = map.update(null, null); - Assert.assertTrue(Double.isNaN(estimate)); - Assert.assertTrue(Double.isNaN(map.getEstimate(null))); - Assert.assertTrue(Double.isNaN(map.getUpperBound(null))); - Assert.assertTrue(Double.isNaN(map.getLowerBound(null))); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void wrongSizeKeyUpdate() { - UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4); - byte[] key = new byte[] {0}; - map.update(key, null); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void wrongSizeKey() { - UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 2); - println(map.toString()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void wrongSizeKeyGetEstimate() { - UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4); - byte[] key = new byte[] {0}; - map.getEstimate(key); - } - - @Test - public void emptyMapNullValue() { - UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4); - double estimate = map.update("1234".getBytes(UTF_8), null); - Assert.assertEquals(estimate, 0.0); - } - - @Test - public void oneEntry() { - UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4); - double estimate = map.update("1234".getBytes(UTF_8), "a".getBytes(UTF_8)); - Assert.assertEquals(estimate, 1.0, 0.01); - } - - @Test - public void duplicateEntry() { - UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4); - byte[] key = "1234".getBytes(UTF_8); - double estimate = map.update(key, "a".getBytes(UTF_8)); - Assert.assertEquals(estimate, 1.0); - estimate = map.update(key, "a".getBytes(UTF_8)); - Assert.assertEquals(estimate, 1.0); - estimate = map.update(key, null); - Assert.assertEquals(estimate, 1.0); - } - - @Test - public void oneKeyTwoValues() { - UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4); - double estimate = map.update("1234".getBytes(UTF_8), "a".getBytes(UTF_8)); - Assert.assertEquals(estimate, 1.0); - estimate = map.update("1234".getBytes(UTF_8), "b".getBytes(UTF_8)); - Assert.assertEquals(estimate, 2.0, 0.02); - } - - @Test - public void oneKeyThreeValues() { - UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4); - byte[] key = "1234".getBytes(UTF_8); - double estimate = map.update(key, "a".getBytes(UTF_8)); - Assert.assertEquals(estimate, 1.0); - estimate = map.update(key, "b".getBytes(UTF_8)); - Assert.assertEquals(estimate, 2.0); - estimate = map.update(key, "c".getBytes(UTF_8)); - Assert.assertEquals(estimate, 3.0); - } - - @Test - public void oneKeyManyValues() { - UniqueCountMap map = new UniqueCountMap(INIT_ENTRIES, 4); - byte[] key = "1234".getBytes(UTF_8); - byte[] id = new byte[4]; - for (int i = 1; i <= 1000; i++) { - id = Util.intToBytes(i, id); - double estimate = map.update(key, id); - if ((i % 100) == 0) { - double err = ((estimate/i) -1.0) * 100; - String eStr = String.format("%.3f%%", err); - println("i: "+i + "\t Est: " + estimate + "\t" + eStr); - } - Assert.assertEquals(estimate, i, i * 0.10); - Assert.assertEquals(map.getEstimate(key), estimate); - Assert.assertTrue(map.getUpperBound(key) >= estimate); - Assert.assertTrue(map.getLowerBound(key) <= estimate); - } - String out = map.toString(); - println(out); - } - - @Test - public void manyKeys() { - UniqueCountMap map = new UniqueCountMap(2000, 4); - for (int i = 1; i <= 1000; i++) { - byte[] key = String.format("%4s", i).getBytes(UTF_8); - double estimate = map.update(key, new byte[] {1}); - Assert.assertEquals(estimate, 1.0); - } - Assert.assertEquals(1000, map.getActiveEntries()); - for (int i = 1; i <= 1000; i++) { - byte[] key = String.format("%4s", i).getBytes(UTF_8); - double estimate = map.update(key, new byte[] {2}); - Assert.assertEquals(estimate, 2.0); - } - Assert.assertEquals(1000, map.getActiveEntries()); - for (int i = 1; i <= 1000; i++) { - byte[] key = String.format("%4s", i).getBytes(UTF_8); - double estimate = map.update(key, new byte[] {3}); - Assert.assertEquals(estimate, 3.0); - } - Assert.assertEquals(1000, map.getActiveEntries()); - String out = map.toString(); - println(out); - } - - @Test - public void forceDeletesAndReuse() { - UniqueCountMap map = new UniqueCountMap(156, 4); - byte[] key = new byte[4]; - byte[] id = new byte[8]; - for (int v = 1; v <= 200; v++) { - long h = (int) hash(new long[]{v}, 0L)[0]; - id = Util.longToBytes(h, id); - for(int k = 1; k <= 147; k++) { - key = Util.intToBytes(k, key); - map.update(key, id); - } - } - //reuse - for (int v = 1; v <= 200; v++) { - long h = (int) hash(new long[]{v}, 0L)[0]; - id = Util.longToBytes(h, id); - for(int k = 1+147; k <= (2 * 147); k++) { - key = Util.intToBytes(k, key); - map.update(key, id); - } - } - Assert.assertNotNull(map.getBaseMap()); - Assert.assertNotNull(map.getHllMap()); - //println(map.toString()); - } - - - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllCrossLanguageTest.java b/src/test/java/org/apache/datasketches/kll/KllCrossLanguageTest.java deleted file mode 100644 index 3ce30ec1e..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllCrossLanguageTest.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES; -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_HISTORICAL_FILES; -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.getFileBytes; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; -import static org.apache.datasketches.common.TestUtil.resPath; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.lang.foreign.MemorySegment; -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.TestUtil; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIteratorAPI; -import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator; -import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI; -import org.apache.datasketches.quantilescommon.QuantilesLongsSketchIterator; -import org.testng.annotations.Test; - -/** - * Methods for cross language integration testing - */ -public class KllCrossLanguageTest { - private final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateKllDoublesSketchBinaries() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000}; - for (final int n: nArr) { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(); - for (int i = 1; i <= n; i++) { sk.update(i); } - putBytesToJavaPath("kll_double_n" + n + "_java.sk", sk.toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateKllFloatsSketchBinaries() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000}; - for (final int n: nArr) { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - for (int i = 1; i <= n; i++) { sk.update(i); } - putBytesToJavaPath("kll_float_n" + n + "_java.sk", sk.toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateKllLongsSketchBinaries() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000}; - for (final int n: nArr) { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(); - for (int i = 1; i <= n; i++) { sk.update(i); } - putBytesToJavaPath("kll_long_n" + n + "_java.sk", sk.toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateKllItemsSketchBinaries() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000}; - for (final int n: nArr) { - final int digits = Util.numDigits(n); - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - for (int i = 1; i <= n; i++) { sk.update(Util.longToFixedLengthString(i, digits)); } - putBytesToJavaPath("kll_string_n" + n + "_java.sk", sk.toByteArray()); - } - } - - @Test(groups = {CHECK_CPP_HISTORICAL_FILES}) - public void checkCppKllDoublesSketchOneItemVersion1() { - final byte[] byteArr = TestUtil.getFileBytes(resPath, "kll_sketch_double_one_item_v1.sk"); - final KllDoublesSketch sk = KllDoublesSketch.heapify(MemorySegment.ofArray(byteArr)); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getMaxItem(), 1.0); - } - - @Test(groups = {CHECK_CPP_HISTORICAL_FILES}) - public void checkCppKllFloatsSketchOneItemVersion1() { - final byte[] byteArr = TestUtil.getFileBytes(resPath, "kll_sketch_float_one_item_v1.sk"); - final KllFloatsSketch sk = KllFloatsSketch.heapify(MemorySegment.ofArray(byteArr)); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getMaxItem(), 1.0F); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void kllFloat() throws IOException { - final int[] nArr = {0, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "kll_float_n" + n + "_cpp.sk"); - final KllFloatsSketch sketch = KllFloatsSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(sketch.getK(), 200); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertTrue(n > 100 ? sketch.isEstimationMode() : !sketch.isEstimationMode()); - assertEquals(sketch.getN(), n); - if (n > 0) { - assertEquals(sketch.getMinItem(), 1); - assertEquals(sketch.getMaxItem(), n); - long weight = 0; - final QuantilesFloatsSketchIterator it = sketch.iterator(); - while (it.next()) { - assertTrue(it.getQuantile() >= sketch.getMinItem()); - assertTrue(it.getQuantile() <= sketch.getMaxItem()); - weight += it.getWeight(); - } - assertEquals(weight, n); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void kllDouble() throws IOException { - final int[] nArr = {0, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "kll_double_n" + n + "_cpp.sk"); - final KllDoublesSketch sketch = KllDoublesSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(sketch.getK(), 200); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertTrue(n > 100 ? sketch.isEstimationMode() : !sketch.isEstimationMode()); - assertEquals(sketch.getN(), n); - if (n > 0) { - assertEquals(sketch.getMinItem(), 1); - assertEquals(sketch.getMaxItem(), n); - long weight = 0; - final QuantilesDoublesSketchIteratorAPI it = sketch.iterator(); - while (it.next()) { - assertTrue(it.getQuantile() >= sketch.getMinItem()); - assertTrue(it.getQuantile() <= sketch.getMaxItem()); - weight += it.getWeight(); - } - assertEquals(weight, n); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void kllString() throws IOException { - // sketch contains numbers in strings to make meaningful assertions - final Comparator numericOrder = new Comparator() { - @Override - public int compare(final String s1, final String s2) { - try { - final int i1 = Integer.parseInt(s1); - final int i2 = Integer.parseInt(s2); - return Integer.compare(i1, i2); - } catch (final NumberFormatException e) { - throw new RuntimeException(e); - } - } - }; - final int[] nArr = {0, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "kll_string_n" + n + "_cpp.sk"); - final KllHeapItemsSketch sketch = new KllHeapItemsSketch<>( - MemorySegment.ofArray(bytes), - numericOrder, - new ArrayOfStringsSerDe() - ); - assertEquals(sketch.getK(), 200); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertTrue(n > 100 ? sketch.isEstimationMode() : !sketch.isEstimationMode()); - assertEquals(sketch.getN(), n); - if (n > 0) { - assertEquals(sketch.getMinItem(), Integer.toString(1)); - assertEquals(sketch.getMaxItem(), Integer.toString(n)); - long weight = 0; - final QuantilesGenericSketchIteratorAPI it = sketch.iterator(); - while (it.next()) { - assertTrue(numericOrder.compare(it.getQuantile(), sketch.getMinItem()) >= 0); - assertTrue(numericOrder.compare(it.getQuantile(), sketch.getMaxItem()) <= 0); - weight += it.getWeight(); - } - assertEquals(weight, n); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void kllLong() throws IOException { - final int[] nArr = {0, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath,"kll_long_n" + n + "_cpp.sk"); - final KllLongsSketch sketch = KllLongsSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(sketch.getK(), 200); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertTrue(n > 100 ? sketch.isEstimationMode() : !sketch.isEstimationMode()); - assertEquals(sketch.getN(), n); - if (n > 0) { - assertEquals(sketch.getMinItem(), 1); - assertEquals(sketch.getMaxItem(), n); - long weight = 0; - final QuantilesLongsSketchIterator it = sketch.iterator(); - while (it.next()) { - assertTrue(it.getQuantile() >= sketch.getMinItem()); - assertTrue(it.getQuantile() <= sketch.getMaxItem()); - weight += it.getWeight(); - } - assertEquals(weight, n); - } - } - } -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDirectCompactDoublesSketchTest.java b/src/test/java/org/apache/datasketches/kll/KllDirectCompactDoublesSketchTest.java deleted file mode 100644 index 5dd2a8699..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDirectCompactDoublesSketchTest.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDirectDoublesSketch; -import org.apache.datasketches.kll.KllDoublesSketch; -import org.apache.datasketches.kll.KllHelper; -import org.testng.annotations.Test; - -public class KllDirectCompactDoublesSketchTest { - - @Test - public void checkRODirectUpdatable_ROandWritable() { - final int k = 20; - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); //request updatable - final MemorySegment srcSeg = MemorySegment.ofArray(byteArr).asReadOnly(); //cast to MemorySegment -> read only - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(srcSeg); - assertTrue(sk2 instanceof KllDirectDoublesSketch); - - assertTrue(sk2.isMemorySegmentUpdatableFormat()); - assertTrue(sk2.isReadOnly()); - assertEquals(sk2.getMinItem(), 1.0); - assertEquals(sk2.getMaxItem(), 21.0); - - final MemorySegment srcWseg = MemorySegment.ofArray(byteArr); - final KllDoublesSketch sk3 = KllDoublesSketch.wrap(srcWseg); - assertTrue(sk3 instanceof KllDirectDoublesSketch); - println(sk3.toString(true, false)); - assertFalse(sk3.isReadOnly()); - sk3.update(22.0); - assertEquals(sk3.getMinItem(), 1.0); - assertEquals(sk3.getMaxItem(), 22.0); - } - - @Test - public void checkRODirectCompact() { - final int k = 20; - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - final MemorySegment srcSeg = MemorySegment.ofArray(sk.toByteArray()); //compact RO fmt - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(srcSeg); - assertTrue(sk2.isCompactMemorySegmentFormat()); - //println(sk2.toString(true, false)); - assertFalse(sk2.isMemorySegmentUpdatableFormat()); - assertTrue(sk2.isReadOnly()); - assertEquals(sk2.getMinItem(), 1.0); - assertEquals(sk2.getMaxItem(), 21.0); - final MemorySegment srcSeg2 = MemorySegment.ofArray(sk2.toByteArray()); - final KllDoublesSketch sk3 = KllDoublesSketch.wrap(srcSeg2); - assertTrue(sk3.isCompactMemorySegmentFormat()); - assertFalse(sk2.isMemorySegmentUpdatableFormat()); - //println(sk3.toString(true, false)); - assertTrue(sk3.isReadOnly()); - assertEquals(sk3.getMinItem(), 1.0); - assertEquals(sk3.getMaxItem(), 21.0); - } - - @Test - public void checkDirectCompactSingleItem() { - final int k = 20; - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - - sk.update(1); - KllDoublesSketch sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertTrue(sk2.isCompactMemorySegmentFormat()); - //println(sk2.toString(true, false)); - assertTrue(sk2.isReadOnly()); - assertEquals(sk2.getDoubleSingleItem(), 1.0); - - sk.update(2); - sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertEquals(sk2.getN(), 2); - try { - sk2.getDoubleSingleItem(); - fail(); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkDirectCompactGetDoubleItemsArray() { - final int k = 20; - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - - KllDoublesSketch sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - double[] itemsArr = sk2.getDoubleItemsArray(); - for (int i = 0; i < 20; i++) { assertEquals(itemsArr[i], 0.0); } - - sk.update(1); - sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - itemsArr = sk2.getDoubleItemsArray(); - for (int i = 0; i < 19; i++) { assertEquals(itemsArr[i], 0.0); } - assertEquals(itemsArr[19], 1.0); - - for (int i = 2; i <= 21; i++) { sk.update(i); } - sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - itemsArr = sk2.getDoubleItemsArray(); - assertEquals(itemsArr.length, 33); - assertEquals(itemsArr[22], 21); - } - - @Test - public void checkHeapAndDirectCompactGetRetainedItemsArray() { - final int k = 20; - - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - double[] retArr = sk.getDoubleRetainedItemsArray(); - assertEquals(retArr.length, 0); - - KllDoublesSketch sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - retArr = sk2.getDoubleRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 0); - - sk.update(1.0); - retArr = sk.getDoubleRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 1); - assertEquals(retArr[0], 1.0); - - sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - retArr = sk2.getDoubleRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 1); - assertEquals(retArr[0], 1.0); - - for (int i = 2; i <= 21; i++) { sk.update(i); } - retArr = sk.getDoubleRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 11); - - sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertEquals(retArr.length, sk2.getNumRetained()); - assertEquals(retArr.length, 11); - } - - @Test - public void checkMinAndMax() { - final int k = 20; - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - KllDoublesSketch sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - try { sk2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - sk.update(1); - sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertEquals(sk2.getMaxItem(),1.0); - assertEquals(sk2.getMinItem(),1.0); - for (int i = 2; i <= 21; i++) { sk.update(i); } - sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertEquals(sk2.getMaxItem(),21.0); - assertEquals(sk2.getMinItem(),1.0); - } - - @Test - public void checkQuantile() { - final KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance(); - for (int i = 1; i <= 1000; i++) { sk1.update(i); } - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk1.toByteArray())); - final double med2 = sk2.getQuantile(0.5); - final double med1 = sk1.getQuantile(0.5); - assertEquals(med1, med2); - println("Med1: " + med1); - println("Med2: " + med2); - } - - @Test - public void checkCompactSingleItemMerge() { - final int k = 20; - final KllDoublesSketch skH1 = KllDoublesSketch.newHeapInstance(k); //Heap with 1 (single) - skH1.update(21); - final KllDoublesSketch skDC1 = KllDoublesSketch.wrap(MemorySegment.ofArray(skH1.toByteArray())); //Direct Compact with 1 (single) - final KllDoublesSketch skH20 = KllDoublesSketch.newHeapInstance(k); //Heap with 20 - for (int i = 1; i <= 20; i++) { skH20.update(i); } - skH20.merge(skDC1); - assertEquals(skH20.getN(), 21); - - final MemorySegment wseg = MemorySegment.ofArray(new byte[1000]); - final KllDoublesSketch skDU20 = KllDoublesSketch.newDirectInstance(k, wseg, null);//Direct Updatable with 21 - for (int i = 1; i <= 20; i++) { skDU20.update(i); } - skDU20.merge(skDC1); - assertEquals(skDU20.getN(), 21); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - private final static boolean enablePrinting = false; - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDirectCompactFloatsSketchTest.java b/src/test/java/org/apache/datasketches/kll/KllDirectCompactFloatsSketchTest.java deleted file mode 100644 index 512781c9c..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDirectCompactFloatsSketchTest.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDirectFloatsSketch; -import org.apache.datasketches.kll.KllFloatsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllPreambleUtil; -import org.apache.datasketches.kll.KllSketch.SketchType; -import org.testng.annotations.Test; - -public class KllDirectCompactFloatsSketchTest { - - @Test - public void checkRODirectUpdatable_ROandWritable() { - final int k = 20; - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); //request updatable - final MemorySegment srcSeg = MemorySegment.ofArray(byteArr).asReadOnly(); //cast to MemorySegment -> read only - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(srcSeg); - assertTrue(sk2 instanceof KllDirectFloatsSketch); - - assertTrue(sk2.isMemorySegmentUpdatableFormat()); - assertTrue(sk2.isReadOnly()); - assertEquals(sk2.getMinItem(), 1.0F); - assertEquals(sk2.getMaxItem(), 21.0F); - - final MemorySegment srcWseg = MemorySegment.ofArray(byteArr); - final KllFloatsSketch sk3 = KllFloatsSketch.wrap(srcWseg); - assertTrue(sk3 instanceof KllDirectFloatsSketch); - println(sk3.toString(true, false)); - assertFalse(sk3.isReadOnly()); - sk3.update(22.0F); - assertEquals(sk2.getMinItem(), 1.0F); - assertEquals(sk2.getMaxItem(), 22.0F); - } - - @Test - public void checkRODirectCompact() { - final int k = 20; - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - final MemorySegment srcSeg = MemorySegment.ofArray(sk.toByteArray()); //compact RO fmt - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(srcSeg); - assertTrue(sk2.isCompactMemorySegmentFormat()); - //println(sk2.toString(true, false)); - assertFalse(sk2.isMemorySegmentUpdatableFormat()); - assertTrue(sk2.isReadOnly()); - assertEquals(sk2.getMinItem(), 1.0F); - assertEquals(sk2.getMaxItem(), 21.0F); - final MemorySegment srcSeg2 = MemorySegment.ofArray(sk2.toByteArray()); - final KllFloatsSketch sk3 = KllFloatsSketch.wrap((MemorySegment)srcSeg2); - assertTrue(sk3.isCompactMemorySegmentFormat()); - assertFalse(sk2.isMemorySegmentUpdatableFormat()); - //println(sk3.toString(true, false)); - assertTrue(sk3.isReadOnly()); - assertEquals(sk3.getMinItem(), 1.0F); - assertEquals(sk3.getMaxItem(), 21.0F); - } - - @Test - public void checkDirectCompactSingleItem() { - final int k = 20; - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - - sk.update(1); - KllFloatsSketch sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertTrue(sk2.isCompactMemorySegmentFormat()); - //println(sk2.toString(true, false)); - assertTrue(sk2.isReadOnly()); - assertEquals(sk2.getFloatSingleItem(), 1.0F); - - sk.update(2); - sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertEquals(sk2.getN(), 2); - try { - sk2.getFloatSingleItem(); - fail(); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkDirectCompactGetFloatItemsArray() { - final int k = 20; - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - - KllFloatsSketch sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - float[] itemsArr = sk2.getFloatItemsArray(); - for (int i = 0; i < 20; i++) { assertEquals(itemsArr[i], 0F); } - - sk.update(1); - sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - itemsArr = sk2.getFloatItemsArray(); - for (int i = 0; i < 19; i++) { assertEquals(itemsArr[i], 0F); } - assertEquals(itemsArr[19], 1F); - - for (int i = 2; i <= 21; i++) { sk.update(i); } - sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - itemsArr = sk2.getFloatItemsArray(); - assertEquals(itemsArr.length, 33); - assertEquals(itemsArr[22], 21); - } - - @Test - public void checkHeapAndDirectCompactGetRetainedItemsArray() { - final int k = 20; - - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - float[] retArr = sk.getFloatRetainedItemsArray(); - assertEquals(retArr.length, 0); - - KllFloatsSketch sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - retArr = sk2.getFloatRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 0); - - sk.update(1f); - retArr = sk.getFloatRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 1); - assertEquals(retArr[0], 1f); - - sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - retArr = sk2.getFloatRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 1); - assertEquals(retArr[0], 1f); - - for (int i = 2; i <= 21; i++) { sk.update(i); } - retArr = sk.getFloatRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 11); - - sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertEquals(retArr.length, sk2.getNumRetained()); - assertEquals(retArr.length, 11); - } - - @Test - public void checkMinAndMax() { - final int k = 20; - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - KllFloatsSketch sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - try { sk2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - sk.update(1); - sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertEquals(sk2.getMaxItem(),1.0F); - assertEquals(sk2.getMinItem(),1.0F); - for (int i = 2; i <= 21; i++) { sk.update(i); } - sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertEquals(sk2.getMaxItem(),21.0F); - assertEquals(sk2.getMinItem(),1.0F); - } - - @Test - public void checkQuantile() { - final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(); - for (int i = 1; i <= 2; i++) { sk1.update(i); } - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk1.toByteArray())); - final double med2 = sk2.getQuantile(0.5); - final double med1 = sk1.getQuantile(0.5); - assertEquals(med1, med2); - println("Med1: " + med1); - println("Med2: " + med2); - } - - @Test - public void checkCompactSingleItemMerge() { - final int k = 20; - final KllFloatsSketch skH1 = KllFloatsSketch.newHeapInstance(k); //Heap with 1 (single) - skH1.update(21); - final KllFloatsSketch skDC1 = KllFloatsSketch.wrap(MemorySegment.ofArray(skH1.toByteArray())); //Direct Compact with 1 (single) - final KllFloatsSketch skH20 = KllFloatsSketch.newHeapInstance(k); //Heap with 20 - for (int i = 1; i <= 20; i++) { skH20.update(i); } - skH20.merge(skDC1); - assertEquals(skH20.getN(), 21); - - final MemorySegment wseg = MemorySegment.ofArray(new byte[1000]); - final KllFloatsSketch skDU20 = KllFloatsSketch.newDirectInstance(k, wseg, null);//Direct Updatable with 21 - for (int i = 1; i <= 20; i++) { skDU20.update(i); } - skDU20.merge(skDC1); - assertEquals(skDU20.getN(), 21); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - private final static boolean enablePrinting = false; - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDirectCompactItemsSketchIteratorTest.java b/src/test/java/org/apache/datasketches/kll/KllDirectCompactItemsSketchIteratorTest.java deleted file mode 100644 index a41eb321e..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDirectCompactItemsSketchIteratorTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.kll.KllDirectCompactItemsSketch; -import org.apache.datasketches.kll.KllItemsSketch; -import org.apache.datasketches.quantilescommon.GenericSortedViewIterator; -import org.apache.datasketches.quantilescommon.ItemsSketchSortedView; -import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI; -import org.testng.Assert; -import org.testng.annotations.Test; - -@SuppressWarnings("unused") -public class KllDirectCompactItemsSketchIteratorTest { - private final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - - @Test - public void emptySketch() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final byte[] byteArr = sk.toByteArray(); - final KllItemsSketch sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(byteArr), Comparator.naturalOrder(), serDe); - assertTrue(sk2 instanceof KllDirectCompactItemsSketch); - final QuantilesGenericSketchIteratorAPI itr = sk2.iterator(); - assertFalse(itr.next()); - } - - @Test - public void oneItemSketch() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sk.update("1"); - final byte[] byteArr = sk.toByteArray(); - final KllItemsSketch sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(byteArr), Comparator.naturalOrder(), serDe); - assertTrue(sk2 instanceof KllDirectCompactItemsSketch); - final QuantilesGenericSketchIteratorAPI itr = sk2.iterator(); - assertTrue(itr.next()); - assertEquals(itr.getQuantile(), "1"); - assertEquals(itr.getWeight(), 1); - assertFalse(itr.next()); - } - - @Test - public void twoItemSketchForIterator() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sk.update("1"); - sk.update("2"); - final byte[] byteArr = sk.toByteArray(); - final KllItemsSketch sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(byteArr), Comparator.naturalOrder(), serDe); - assertTrue(sk2 instanceof KllDirectCompactItemsSketch); - final QuantilesGenericSketchIteratorAPI itr = sk2.iterator(); - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), "2"); - assertEquals(itr.getWeight(), 1); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), "1"); - assertEquals(itr.getWeight(), 1); - } - - @Test - public void twoItemSketchForSortedViewIterator() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - sk.update("1"); - sk.update("2"); - println(sk.toString(true, true)); - final byte[] byteArr = sk.toByteArray(); - final KllItemsSketch sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(byteArr), Comparator.naturalOrder(), serDe); - assertTrue(sk2 instanceof KllDirectCompactItemsSketch); - final ItemsSketchSortedView sv = sk2.getSortedView(); - final GenericSortedViewIterator itr = sv.iterator(); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), "1"); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 0); - assertEquals(itr.getNaturalRank(INCLUSIVE), 1); - assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0); - assertEquals(itr.getNormalizedRank(INCLUSIVE), 0.5); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), "2"); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 1); - assertEquals(itr.getNaturalRank(INCLUSIVE), 2); - assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0.5); - assertEquals(itr.getNormalizedRank(INCLUSIVE), 1.0); - } - - @Test - public void bigSketches() { - final int digits = 6; - for (int n = 1000; n < 100_000; n += 2000) { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - for (int i = 0; i < n; i++) { - sk.update(Util.longToFixedLengthString(i, digits)); - } - final byte[] byteArr = sk.toByteArray(); - final KllItemsSketch sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(byteArr), Comparator.naturalOrder(), serDe); - assertTrue(sk2 instanceof KllDirectCompactItemsSketch); - final QuantilesGenericSketchIteratorAPI itr = sk2.iterator(); - int count = 0; - int weight = 0; - while (itr.next()) { - count++; - weight += (int)itr.getWeight(); - } - Assert.assertEquals(count, sk.getNumRetained()); - Assert.assertEquals(weight, n); - } - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDirectCompactItemsSketchTest.java b/src/test/java/org/apache/datasketches/kll/KllDirectCompactItemsSketchTest.java deleted file mode 100644 index 4a1d0f176..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDirectCompactItemsSketchTest.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.kll.KllDirectCompactItemsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllItemsSketch; -import org.testng.annotations.Test; - -public class KllDirectCompactItemsSketchTest { - public ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - - @Test - public void checkRODirectCompact() { - final int k = 20; - final int n = 21; - final int digits = Util.numDigits(n); - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - for (int i = 1; i <= n; i++) { sk.update(Util.longToFixedLengthString(i, digits)); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); //request for updatable is denied -> COMPACT, RO - final MemorySegment srcSeg = MemorySegment.ofArray(byteArr); //compact RO fmt - final KllItemsSketch sk2 = KllItemsSketch.wrap(srcSeg, Comparator.naturalOrder(), serDe); - assertTrue(sk2 instanceof KllDirectCompactItemsSketch); - println(sk2.toString(true, false)); - assertFalse(sk2.isMemorySegmentUpdatableFormat()); - assertTrue(sk2.isReadOnly()); - assertEquals(sk2.getMinItem(), " 1"); - assertEquals(sk2.getMaxItem(), "21"); - } - - @Test - public void checkDirectCompactSingleItem() { - final int k = 20; - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - - sk.update("1"); - KllItemsSketch sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(sk.toByteArray()), Comparator.naturalOrder(), serDe); - assertTrue(sk2 instanceof KllDirectCompactItemsSketch); - //println(sk2.toString(true, false)); - assertTrue(sk2.isReadOnly()); - assertEquals(sk2.getSingleItem(), "1"); - - sk.update("2"); - sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(sk.toByteArray()), Comparator.naturalOrder(), serDe); - assertEquals(sk2.getN(), 2); - try { - sk2.getSingleItem(); //not a single item - fail(); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkHeapGetFullItemsArray() { - final int k = 20; - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - - String[] itemsArr = sk.getTotalItemsArray(); - for (int j = 0; j < k; j++) { assertNull(itemsArr[j]); } - - sk.update(" 1"); //single - itemsArr = sk.getTotalItemsArray(); - for (int j = 0; j < (k - 1); j++) { assertNull(itemsArr[j]); } - assertEquals(itemsArr[k - 1], " 1"); - - sk.update(" 2"); //multiple - itemsArr = sk.getTotalItemsArray(); - for (int j = 0; j < (k - 2); j++) { assertNull(itemsArr[j]); } - assertEquals(itemsArr[k - 1], " 1"); - assertEquals(itemsArr[k - 2], " 2"); - } - - @Test - public void checkDirectCompactGetFullItemsArray() { - final int k = 20; - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - - KllItemsSketch sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(sk.toByteArray()), Comparator.naturalOrder(), serDe); - String[] itemsArr = sk2.getTotalItemsArray(); //empty - for (int j = 0; j < k; j++) { assertNull(itemsArr[j]); } - - sk.update(" 1"); //single - sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(sk.toByteArray()), Comparator.naturalOrder(), serDe); - itemsArr = sk2.getTotalItemsArray(); - for (int j = 0; j < (k - 1); j++) { assertNull(itemsArr[j]); } - assertEquals(itemsArr[k - 1], " 1"); - - sk.update(" 2"); //multi - sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(sk.toByteArray()), Comparator.naturalOrder(), serDe); - itemsArr = sk2.getTotalItemsArray(); - for (int j = 0; j < (k - 2); j++) { assertNull(itemsArr[j]); } - assertEquals(itemsArr[k - 1], " 1"); - assertEquals(itemsArr[k - 2], " 2"); - } - - @Test - public void checkHeapAndDirectCompactGetRetainedItemsArray() { - final int k = 20; - - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - String[] retArr = sk.getRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 0); - - KllItemsSketch sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(sk.toByteArray()), Comparator.naturalOrder(), serDe); - retArr = sk2.getRetainedItemsArray(); - assertEquals(retArr.length, sk2.getNumRetained()); - assertEquals(retArr.length, 0); - - sk.update(" 1"); - retArr = sk.getRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 1); - assertEquals(retArr[0], " 1"); - - sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(sk.toByteArray()), Comparator.naturalOrder(), serDe); - retArr = sk2.getRetainedItemsArray(); - assertEquals(retArr.length, sk2.getNumRetained()); - assertEquals(retArr.length, 1); - assertEquals(retArr[0], " 1"); - - for (int i = 2; i <= 21; i++) { sk.update(Util.longToFixedLengthString(i, 2)); } - retArr = sk.getRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 11); - - sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(sk.toByteArray()), Comparator.naturalOrder(), serDe); - assertEquals(retArr.length, sk2.getNumRetained()); - assertEquals(retArr.length, 11); - } - - @Test - public void checkMinAndMax() { - final int k = 20; - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - KllItemsSketch sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(sk.toByteArray()), Comparator.naturalOrder(), serDe); - try { sk2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - sk.update(" 1"); - sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(sk.toByteArray()), Comparator.naturalOrder(), serDe); - assertEquals(sk2.getMaxItem()," 1"); - assertEquals(sk2.getMinItem()," 1"); - for (int i = 2; i <= 21; i++) { sk.update(Util.longToFixedLengthString(i, 2)); } - sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(sk.toByteArray()), Comparator.naturalOrder(), serDe); - assertEquals(sk2.getMaxItem(),"21"); - assertEquals(sk2.getMinItem()," 1"); - } - - @Test - public void checkQuantile() { - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - for (int i = 1; i <= 1000; i++) { sk1.update(Util.longToFixedLengthString(i, 4)); } - final KllItemsSketch sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(sk1.toByteArray()), Comparator.naturalOrder(), serDe); - final String med2 = sk2.getQuantile(0.5); - final String med1 = sk1.getQuantile(0.5); - assertEquals(med1, med2); - println("Med1: " + med1); - println("Med2: " + med2); - } - - @Test - public void checkCompactSingleItemMerge() { - final int k = 20; - final KllItemsSketch skH1 = - KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); //Heap with 1 (single) - skH1.update("21"); - final KllItemsSketch skDC1 = //Direct Compact with 1 (single) - KllItemsSketch.wrap(MemorySegment.ofArray(skH1.toByteArray()), Comparator.naturalOrder(), serDe); - final KllItemsSketch skH20 = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); //Heap with 20 - for (int i = 1; i <= 20; i++) { skH20.update(Util.longToFixedLengthString(i, 2)); } - skH20.merge(skDC1); - assertEquals(skH20.getN(), 21); - } - - private final static boolean enablePrinting = false; - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDirectCompactLongsSketchTest.java b/src/test/java/org/apache/datasketches/kll/KllDirectCompactLongsSketchTest.java deleted file mode 100644 index d4a373453..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDirectCompactLongsSketchTest.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDirectLongsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllLongsSketch; -import org.apache.datasketches.kll.KllSketch.SketchStructure; -import org.testng.annotations.Test; - -public class KllDirectCompactLongsSketchTest { - - @Test - public void checkRODirectUpdatable_ROandWritable() { - final int k = 20; - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); //request updatable - final MemorySegment srcSeg = MemorySegment.ofArray(byteArr).asReadOnly(); //cast to MemorySegment -> read only - final KllLongsSketch sk2 = KllLongsSketch.wrap(srcSeg); - assertTrue(sk2 instanceof KllDirectLongsSketch); - - assertTrue(sk2.isMemorySegmentUpdatableFormat()); - assertTrue(sk2.isReadOnly()); - assertEquals(sk2.getMinItem(), 1L); - assertEquals(sk2.getMaxItem(), 21L); - - final MemorySegment srcWseg = MemorySegment.ofArray(byteArr); - final KllLongsSketch sk3 = KllLongsSketch.wrap(srcWseg); - assertTrue(sk3 instanceof KllDirectLongsSketch); - println(sk3.toString(true, false)); - assertFalse(sk3.isReadOnly()); - sk3.update(22); - assertEquals(sk2.getMinItem(), 1L); - assertEquals(sk2.getMaxItem(), 22L); - } - - @Test - public void checkRODirectCompact() { - final int k = 20; - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - // go from heap to MemorySegment - final MemorySegment srcSeg = MemorySegment.ofArray(sk.toByteArray()); //compact RO fmt - final KllLongsSketch sk2 = KllLongsSketch.wrap(srcSeg); - assertTrue(sk2.hasMemorySegment()); - assertTrue(sk2.sketchStructure == SketchStructure.COMPACT_FULL); - assertTrue(sk2.isCompactMemorySegmentFormat()); - assertFalse(sk2.isMemorySegmentUpdatableFormat()); - assertTrue(sk2.isReadOnly()); - assertEquals(sk2.getMinItem(), 1L); - assertEquals(sk2.getMaxItem(), 21L); - // go from MemorySegment to byte array back to MemorySegment - final MemorySegment srcSeg2 = MemorySegment.ofArray(sk2.toByteArray()); - // wrap it back to a sketch - final KllLongsSketch sk3 = KllLongsSketch.wrap(srcSeg2); - assertTrue(sk2.hasMemorySegment()); - assertTrue(sk2.sketchStructure == SketchStructure.COMPACT_FULL); - assertTrue(sk2.isCompactMemorySegmentFormat()); - assertFalse(sk2.isMemorySegmentUpdatableFormat()); - assertTrue(sk2.isReadOnly()); - assertEquals(sk2.getMinItem(), 1L); - assertEquals(sk2.getMaxItem(), 21L); - } - - @Test - public void checkDirectCompactSingleItem() { - final int k = 20; - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - - sk.update(1); - KllLongsSketch sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertTrue(sk2.sketchStructure == SketchStructure.COMPACT_SINGLE); - //println(sk2.toString(true, false)); - assertTrue(sk2.isReadOnly()); - assertEquals(sk2.getLongSingleItem(), 1L); - - sk.update(2); - sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertEquals(sk2.getN(), 2); - try { - sk2.getLongSingleItem(); - fail(); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkDirectCompactGetLongItemsArray() { - final int k = 20; - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - - KllLongsSketch sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - long[] itemsArr = sk2.getLongItemsArray(); - for (int i = 0; i < 20; i++) { assertEquals(itemsArr[i], 0); } - - sk.update(1); - sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - itemsArr = sk2.getLongItemsArray(); - for (int i = 0; i < 19; i++) { assertEquals(itemsArr[i], 0); } - assertEquals(itemsArr[19], 1L); - - for (int i = 2; i <= 21; i++) { sk.update(i); } - sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - itemsArr = sk2.getLongItemsArray(); - assertEquals(itemsArr.length, 33); - assertEquals(itemsArr[22], 21); - } - - @Test - public void checkHeapAndDirectCompactGetRetainedItemsArray() { - final int k = 20; - - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - long[] retArr = sk.getLongRetainedItemsArray(); - assertEquals(retArr.length, 0); - - KllLongsSketch sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - retArr = sk2.getLongRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 0); - - sk.update(1); - retArr = sk.getLongRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 1); - assertEquals(retArr[0], 1L); - - sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - retArr = sk2.getLongRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 1); - assertEquals(retArr[0], 1L); - - for (int i = 2; i <= 21; i++) { sk.update(i); } - retArr = sk.getLongRetainedItemsArray(); - assertEquals(retArr.length, sk.getNumRetained()); - assertEquals(retArr.length, 11); - - sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertEquals(retArr.length, sk2.getNumRetained()); - assertEquals(retArr.length, 11); - } - - @Test - public void checkMinAndMax() { - final int k = 20; - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - KllLongsSketch sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - try { sk2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - sk.update(1); - sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertEquals(sk2.getMaxItem(),1L); - assertEquals(sk2.getMinItem(),1L); - for (int i = 2; i <= 21; i++) { sk.update(i); } - sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - assertEquals(sk2.getMaxItem(),21L); - assertEquals(sk2.getMinItem(),1L); - } - - @Test - public void checkQuantile() { - final KllLongsSketch sk1 = KllLongsSketch.newHeapInstance(); - for (int i = 1; i <= 1000; i++) { sk1.update(i); } - final KllLongsSketch sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk1.toByteArray())); - final long med2 = sk2.getQuantile(0.5); - final long med1 = sk1.getQuantile(0.5); - assertEquals(med1, med2); - println("Med1: " + med1); - println("Med2: " + med2); - } - - @Test - public void checkCompactSingleItemMerge() { - final int k = 20; - final KllLongsSketch skH1 = KllLongsSketch.newHeapInstance(k); //Heap with 1 (single) - skH1.update(21); - final KllLongsSketch skDC1 = KllLongsSketch.wrap(MemorySegment.ofArray(skH1.toByteArray())); //Direct Compact with 1 (single) - final KllLongsSketch skH20 = KllLongsSketch.newHeapInstance(k); //Heap with 20 - for (int i = 1; i <= 20; i++) { skH20.update(i); } - skH20.merge(skDC1); - assertEquals(skH20.getN(), 21); - - final MemorySegment wseg = MemorySegment.ofArray(new byte[1000]); - final KllLongsSketch skDU20 = KllLongsSketch.newDirectInstance(k, wseg, null);//Direct Updatable with 21 - for (int i = 1; i <= 20; i++) { skDU20.update(i); } - skDU20.merge(skDC1); - assertEquals(skDU20.getN(), 21); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - private final static boolean enablePrinting = false; - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDirectDoublesSketchIteratorTest.java b/src/test/java/org/apache/datasketches/kll/KllDirectDoublesSketchIteratorTest.java deleted file mode 100644 index 06a0b8ce1..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDirectDoublesSketchIteratorTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.kll.KllDoublesSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIteratorAPI; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class KllDirectDoublesSketchIteratorTest { - - @Test - public void emptySketch() { - final KllDoublesSketch sketch = getDDSketch(200, 0); - final QuantilesDoublesSketchIteratorAPI it = sketch.iterator(); - Assert.assertFalse(it.next()); - } - - @Test - public void oneItemSketch() { - final KllDoublesSketch sketch = getDDSketch(200, 0); - sketch.update(0); - final QuantilesDoublesSketchIteratorAPI it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getQuantile(), 0); - Assert.assertEquals(it.getWeight(), 1); - Assert.assertFalse(it.next()); - } - - @Test - public void bigSketches() { - for (int n = 1000; n < 11000; n += 2000) { - final KllDoublesSketch sketch = getDDSketch(200, 0); - for (int i = 0; i < n; i++) { - sketch.update(i); - } - final QuantilesDoublesSketchIteratorAPI it = sketch.iterator(); - int count = 0; - int weight = 0; - while (it.next()) { - count++; - weight += (int)it.getWeight(); - } - Assert.assertEquals(count, sketch.getNumRetained()); - Assert.assertEquals(weight, n); - } - } - - private static KllDoublesSketch getDDSketch(final int k, final int n) { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { sk.update(i); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - - return KllDoublesSketch.wrap(wseg); - } - -} - diff --git a/src/test/java/org/apache/datasketches/kll/KllDirectDoublesSketchTest.java b/src/test/java/org/apache/datasketches/kll/KllDirectDoublesSketchTest.java deleted file mode 100644 index 00cab5d32..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDirectDoublesSketchTest.java +++ /dev/null @@ -1,697 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_DOUBLES_SKETCH; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDoublesSketch; -import org.apache.datasketches.kll.KllFloatsSketch; -import org.apache.datasketches.kll.KllHeapDoublesSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllPreambleUtil; -import org.apache.datasketches.kll.KllSketch; -import org.apache.datasketches.kll.KllSketch.SketchStructure; -import org.testng.annotations.Test; - -public class KllDirectDoublesSketchTest { - - private static final double PMF_EPS_FOR_K_8 = 0.35; // PMF rank error (epsilon) for k=8 - private static final double PMF_EPS_FOR_K_128 = 0.025; // PMF rank error (epsilon) for k=128 - private static final double PMF_EPS_FOR_K_256 = 0.013; // PMF rank error (epsilon) for k=256 - private static final double NUMERIC_NOISE_TOLERANCE = 1E-6; - - @Test - public void empty() { - final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0); - sketch.update(Double.NaN); // this must not change anything - assertTrue(sketch.isEmpty()); - assertEquals(sketch.getN(), 0); - assertEquals(sketch.getNumRetained(), 0); - try { sketch.getRank(0.5); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantile(0.5); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantiles(new double[] {0.0, 1.0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getPMF(new double[] {0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getCDF(new double[0]); fail(); } catch (final SketchesArgumentException e) {} - assertNotNull(sketch.toString(true, true)); - assertNotNull(sketch.toString()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantileInvalidArg() { - final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0); - sketch.update(1); - sketch.getQuantile(-1.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantilesInvalidArg() { - final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0); - sketch.update(1); - sketch.getQuantiles(new double[] {2.0}); - } - - @Test - public void oneValue() { - final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0); - sketch.update(1); - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getN(), 1); - assertEquals(sketch.getNumRetained(), 1); - assertEquals(sketch.getRank(1, EXCLUSIVE), 0.0); - assertEquals(sketch.getRank(2, EXCLUSIVE), 1.0); - assertEquals(sketch.getMinItem(), 1.0); - assertEquals(sketch.getMaxItem(), 1.0); - assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 1.0); - } - - @Test - public void manyValuesEstimationMode() { - final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0); - final int n = 1_000_000; - - for (int i = 0; i < n; i++) { - sketch.update(i); - } - assertEquals(sketch.getN(), n); - - // test getRank - for (int i = 0; i < n; i++) { - final double trueRank = (double) i / n; - assertEquals(sketch.getRank(i), trueRank, PMF_EPS_FOR_K_256, "for value " + i); - } - - // test getPMF - final double[] pmf = sketch.getPMF(new double[] {n / 2.0}); // split at median - assertEquals(pmf.length, 2); - assertEquals(pmf[0], 0.5, PMF_EPS_FOR_K_256); - assertEquals(pmf[1], 0.5, PMF_EPS_FOR_K_256); - assertEquals(sketch.getMinItem(), 0.0); // min value is exact - assertEquals(sketch.getMaxItem(), n - 1.0); // max value is exact - - // check at every 0.1 percentage point - final double[] ranks = new double[1001]; - final double[] reverseFractions = new double[1001]; // check that ordering doesn't matter - for (int i = 0; i <= 1000; i++) { - ranks[i] = (double) i / 1000; - reverseFractions[1000 - i] = ranks[i]; - } - final double[] quantiles = sketch.getQuantiles(ranks); - final double[] reverseQuantiles = sketch.getQuantiles(reverseFractions); - double previousQuantile = 0.0; - for (int i = 0; i <= 1000; i++) { - final double quantile = sketch.getQuantile(ranks[i]); - assertEquals(quantile, quantiles[i]); - assertEquals(quantile, reverseQuantiles[1000 - i]); - assertTrue(previousQuantile <= quantile); - previousQuantile = quantile; - } - } - - @Test - public void getRankGetCdfGetPmfConsistency() { - final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0); - final int n = 1000; - final double[] values = new double[n]; - for (int i = 0; i < n; i++) { - sketch.update(i); - values[i] = i; - } - final double[] ranks = sketch.getCDF(values); - final double[] pmf = sketch.getPMF(values); - double sumPmf = 0; - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i]), NUMERIC_NOISE_TOLERANCE, - "rank vs CDF for value " + i); - sumPmf += pmf[i]; - assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i); - } - sumPmf += pmf[n]; - assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE); - assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE); - } - - @Test - public void merge() { - final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0); - final KllDoublesSketch sketch2 = getUpdatableDirectDoublesSketch(200, 0); - final int n = 10_000; - for (int i = 0; i < n; i++) { - sketch1.update(i * 1.0); - sketch2.update(((2 * n) - i - 1) * 1.0); - } - - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), (n - 1) * 1.0); - - assertEquals(sketch2.getMinItem(), n * 1.0); - assertEquals(sketch2.getMaxItem(), ((2 * n) - 1) * 1.0); - - sketch1.merge(sketch2); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2L * n); - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), ((2 * n) - 1) * 1.0); - assertEquals(sketch1.getQuantile(0.5), n * 1.0, n * PMF_EPS_FOR_K_256); - } - - @Test - public void mergeLowerK() { - final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(256, 0); - final KllDoublesSketch sketch2 = getUpdatableDirectDoublesSketch(128, 0); - final int n = 10_000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - sketch2.update((2 * n) - i - 1); - } - - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), n - 1.0); - - assertEquals(sketch2.getMinItem(), n); - assertEquals(sketch2.getMaxItem(), (2.0 * n) - 1.0); - - assertTrue(sketch1.getNormalizedRankError(false) < sketch2.getNormalizedRankError(false)); - assertTrue(sketch1.getNormalizedRankError(true) < sketch2.getNormalizedRankError(true)); - sketch1.merge(sketch2); - - // sketch1 must get "contaminated" by the lower K in sketch2 - assertEquals(sketch1.getNormalizedRankError(false), sketch2.getNormalizedRankError(false)); - assertEquals(sketch1.getNormalizedRankError(true), sketch2.getNormalizedRankError(true)); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2 * n); - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), (2.0 * n) - 1.0); - assertEquals(sketch1.getQuantile(0.5), n, n * PMF_EPS_FOR_K_128); - } - - @Test - public void mergeEmptyLowerK() { - final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(256, 0); - final KllDoublesSketch sketch2 = getUpdatableDirectDoublesSketch(128, 0); - final int n = 10_000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - - // rank error should not be affected by a merge with an empty sketch with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), n - 1.0); - assertEquals(sketch1.getQuantile(0.5), n / 2.0, (n / 2) * PMF_EPS_FOR_K_256); - - //merge the other way - sketch2.merge(sketch1); - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), n - 1.0); - assertEquals(sketch1.getQuantile(0.5), n / 2.0, (n / 2) * PMF_EPS_FOR_K_256); - } - - @Test - public void mergeExactModeLowerK() { - final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(256, 0); - final KllDoublesSketch sketch2 = getUpdatableDirectDoublesSketch(128, 0); - final int n = 10000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - sketch2.update(1); - - // rank error should not be affected by a merge with a sketch in exact mode with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - } - - @Test - public void mergeMinMinValueFromOther() { - final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0); - final KllDoublesSketch sketch2 = getUpdatableDirectDoublesSketch(200, 0); - sketch1.update(1); - sketch2.update(2); - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), 1.0); - } - - @Test - public void mergeMinAndMaxFromOther() { - final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0); - final KllDoublesSketch sketch2 = getUpdatableDirectDoublesSketch(200, 0); - final int n = 1_000_000; - for (int i = 1; i <= n; i++) { - sketch1.update(i); - } - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), 1); - assertEquals(sketch2.getMaxItem(), n); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooSmall() { - getUpdatableDirectDoublesSketch(KllSketch.DEFAULT_M - 1, 0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooLarge() { - getUpdatableDirectDoublesSketch(KllSketch.MAX_K + 1, 0); - } - - @Test - public void minK() { - final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(KllSketch.DEFAULT_M, 0); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getK(), KllSketch.DEFAULT_M); - assertEquals(sketch.getQuantile(0.5), 500, 500 * PMF_EPS_FOR_K_8); - } - - @Test - public void maxK() { - final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(KllSketch.MAX_K, 0); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getK(), KllSketch.MAX_K); - assertEquals(sketch.getQuantile(0.5), 500, 500 * PMF_EPS_FOR_K_256); - } - - @Test - public void serializeDeserializeEmptyViaCompactHeapify() { - final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0); - final byte[] bytes = sketch1.toByteArray(); //compact - final KllDoublesSketch sketch2 = KllDoublesSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(false)); - assertTrue(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained()); - assertEquals(sketch2.getN(), sketch1.getN()); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - try { sketch2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sketch2.currentSerializedSizeBytes(false), - sketch1.currentSerializedSizeBytes(false)); - } - - @Test - public void serializeDeserializeEmptyViaUpdatableWritableWrap() { - final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0); - final byte[] bytes = KllHelper.toByteArray(sketch1, true); - final KllDoublesSketch sketch2 = - KllDoublesSketch.wrap(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true)); - assertTrue(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained()); - assertEquals(sketch2.getN(), sketch1.getN()); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - try { sketch2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sketch2.currentSerializedSizeBytes(true), - sketch1.currentSerializedSizeBytes(true)); - } - - @Test - public void serializeDeserializeOneValueViaCompactHeapify() { - final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0); - sketch1.update(1); - final byte[] bytes = sketch1.toByteArray(); - final KllDoublesSketch sketch2 = KllDoublesSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(false)); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), 1); - assertEquals(sketch2.getN(), 1); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - assertTrue(Double.isFinite(sketch2.getMinItem())); - assertTrue(Double.isFinite(sketch2.getMaxItem())); - assertEquals(sketch2.currentSerializedSizeBytes(false), 8 + Double.BYTES); - } - - @Test - public void serializeDeserializeOneValueViaUpdatableWritableWrap() { - final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0); - sketch1.update(1); - final byte[] bytes = KllHelper.toByteArray(sketch1, true); - final KllDoublesSketch sketch2 = - KllDoublesSketch.wrap(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true)); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), 1); - assertEquals(sketch2.getN(), 1); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - assertEquals(sketch2.getMinItem(), 1.0); - assertEquals(sketch2.getMaxItem(), 1.0); - assertEquals(sketch2.currentSerializedSizeBytes(false), 8 + Double.BYTES); - assertEquals(sketch2.currentSerializedSizeBytes(true), bytes.length); - } - - @Test - public void serializeDeserializeFullViaCompactHeapify() { - final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 1000); - final byte[] byteArr1 = sketch1.toByteArray(); //compact - final KllDoublesSketch sketch2 = KllDoublesSketch.heapify(MemorySegment.ofArray(byteArr1)); - assertEquals(byteArr1.length, sketch1.currentSerializedSizeBytes(false)); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained()); - assertEquals(sketch2.getN(), sketch1.getN()); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - assertEquals(sketch2.getMinItem(), sketch1.getMinItem()); - assertEquals(sketch2.getMaxItem(), sketch1.getMaxItem()); - assertEquals(sketch2.currentSerializedSizeBytes(false), sketch1.currentSerializedSizeBytes(false)); - } - - @Test - public void serializeDeserializeFullViaUpdatableWritableWrap() { - final KllDoublesSketch sketch1 = getUpdatableDirectDoublesSketch(200, 0); - final int n = 1000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - final byte[] bytes = KllHelper.toByteArray(sketch1, true); //updatable - final KllDoublesSketch sketch2 = - KllDoublesSketch.wrap(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true)); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained()); - assertEquals(sketch2.getN(), sketch1.getN()); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - assertEquals(sketch2.getMinItem(), sketch1.getMinItem()); - assertEquals(sketch2.getMaxItem(), sketch1.getMaxItem()); - assertEquals(sketch2.currentSerializedSizeBytes(true), sketch1.currentSerializedSizeBytes(true)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void outOfOrderSplitPoints() { - final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0); - sketch.update(0); - sketch.getCDF(new double[] {1, 0}); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void nanSplitPoint() { - final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 0); - sketch.update(0); - sketch.getCDF(new double[] {Double.NaN}); - } - - @Test - public void checkSimpleMergeDirect() { //used for troubleshooting - final int k = 20; - final int n1 = 21; - final int n2 = 43; - final KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance(k); - final KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= n1; i++) { - sk1.update(i); - } - for (int i = 1; i <= n2; i++) { - sk2.update(i + 100); - } - println("SK1:"); - println(sk1.toString(true, true)); - println("SK2:"); - println(sk2.toString(true, true)); - final MemorySegment wseg1 = MemorySegment.ofArray(KllHelper.toByteArray(sk1, true)); - final MemorySegment wseg2 = MemorySegment.ofArray(KllHelper.toByteArray(sk2, true)); - final KllDoublesSketch dsk1 = KllDoublesSketch.wrap(wseg1); - final KllDoublesSketch dsk2 = KllDoublesSketch.wrap(wseg2); - println("BEFORE MERGE"); - println(dsk1.toString(true, true)); - dsk1.merge(dsk2); - println("AFTER MERGE"); - println(dsk1.toString(true, true)); - } - - @Test - public void checkSketchInitializeDirectDoubleUpdatableMemorySegment() { - final int k = 20; //don't change this - KllDoublesSketch sk; - KllDoublesSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - println("#### CASE: DOUBLE FULL DIRECT FROM UPDATABLE"); - sk2 = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk2.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(compBytes, KLL_DOUBLES_SKETCH, true)); - sk = KllDoublesSketch.wrap(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 33); - assertEquals(sk.levelsArr.length, 3); - assertEquals(sk.getMaxItem(), 21.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: DOUBLE EMPTY HEAPIFIED FROM UPDATABLE"); - sk2 = KllDoublesSketch.newHeapInstance(k); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(compBytes, KLL_DOUBLES_SKETCH, true)); - sk = KllDoublesSketch.wrap(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.levelsArr.length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: DOUBLE SINGLE HEAPIFIED FROM UPDATABLE"); - sk2 = KllDoublesSketch.newHeapInstance(k); - sk2.update(1); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(compBytes, KLL_DOUBLES_SKETCH, true)); - sk = KllDoublesSketch.wrap(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.levelsArr.length, 2); - assertEquals(sk.getMaxItem(), 1.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test - public void checkGetMemorySegment() { - final KllDoublesSketch sketch = getUpdatableDirectDoublesSketch(200, 200); - assertEquals(sketch.getK(), 200); - assertEquals(sketch.getN(), 200); - assertFalse(sketch.isEmpty()); - assertTrue(sketch.isMemorySegmentUpdatableFormat()); - assertFalse(sketch.isEstimationMode()); - assertTrue(sketch.isKllDoublesSketch()); - assertFalse(sketch.isLevelZeroSorted()); - assertFalse(sketch.isKllFloatsSketch()); - - final MemorySegment wseg = sketch.getMemorySegment(); - final KllDoublesSketch sk = KllHeapDoublesSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), 200); - assertEquals(sk.getN(), 200); - assertFalse(sk.isEmpty()); - assertFalse(sk.isMemorySegmentUpdatableFormat()); - assertFalse(sk.isEstimationMode()); - assertTrue(sk.isKllDoublesSketch()); - assertFalse(sk.isLevelZeroSorted()); - assertFalse(sk.isKllFloatsSketch()); - } - - @Test - public void checkReset() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(20, dstSeg, null); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final long n1 = sk.getN(); - final double min1 = sk.getMinItem(); - final double max1 = sk.getMaxItem(); - sk.reset(); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final long n2 = sk.getN(); - final double min2 = sk.getMinItem(); - final double max2 = sk.getMaxItem(); - assertEquals(n2, n1); - assertEquals(min2, min1); - assertEquals(max2, max1); - } - - @Test - public void checkHeapify() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(20, dstSeg, null); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final KllDoublesSketch sk2 = KllHeapDoublesSketch.heapifyImpl(dstSeg); - assertEquals(sk2.getMinItem(), 1.0); - assertEquals(sk2.getMaxItem(), 100.0); - } - - @Test - public void checkMergeKllDoublesSketch() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(20, dstSeg, null); - for (int i = 1; i <= 21; i++) { sk.update(i); } - final KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++ ) { sk2.update(i + 100); } - sk.merge(sk2); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getMaxItem(), 121.0); - } - - @Test - public void checkReverseMergeKllDoubleSketch() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(20, dstSeg, null); - for (int i = 1; i <= 21; i++) { sk.update(i); } - final KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++ ) { sk2.update(i + 100); } - sk2.merge(sk); - assertEquals(sk2.getMinItem(), 1.0); - assertEquals(sk2.getMaxItem(), 121.0); - } - - @Test - public void checkWritableWrapOfCompactForm() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++ ) { sk.update(i); } - final MemorySegment srcSeg = MemorySegment.ofArray(sk.toByteArray()); - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(srcSeg); - assertEquals(sk2.getMinItem(), 1.0); - assertEquals(sk2.getMaxItem(), 21.0); - } - - @Test - public void checkReadOnlyExceptions() { - final int k = 20; - final double[] dblArr = {}; - final double dblV = 1.0; - final int idx = 1; - final boolean bool = true; - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - try { sk2.incN(1); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.incNumLevels(); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setDoubleItemsArray(dblArr); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setDoubleItemsArrayAt(idx, dblV); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setLevelZeroSorted(bool); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setMaxItem(dblV); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setMinItem(dblV); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setMinK(idx); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setN(idx); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setNumLevels(idx); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkMergeExceptions() { - final KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance(20); - final MemorySegment srcSeg1 = MemorySegment.ofArray(sk1.toByteArray()); - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(srcSeg1); - sk2.merge(sk1); - } - - @Test - public void checkVectorUpdate() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(20, dstSeg, null); - final double[] v = new double[21]; - for (int i = 0; i < 21; i++) { v[i] = i + 1; } - sk.update(v, 0, 21); - println(sk.toString(true, true)); - final int[] levelsArr = sk.getLevelsArray(SketchStructure.UPDATABLE); - assertEquals(levelsArr[0], 22); - final double[] doublesArr = sk.getDoubleItemsArray(); - assertEquals(doublesArr[22], 21); - } - - @Test - public void checkWeightedUpdate() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(8, dstSeg, null); - for (int i = 0; i < 16; i++) { - sk.update(i + 1, 16); - } - println(sk.toString(true, true)); - assertEquals(sk.getN(), 256); - assertEquals(sk.getMaxItem(), 16.0); - assertEquals(sk.getMinItem(), 1.0); - } - - private static KllDoublesSketch getUpdatableDirectDoublesSketch(final int k, final int n) { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { sk.update(i); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - return KllDoublesSketch.wrap(wseg); - } - - @Test - public void checkMergeExceptionsWrongType() { - final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(20); - final KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(20); - try { sk1.merge(sk2); fail(); } catch (final ClassCastException e) { } - try { sk2.merge(sk1); fail(); } catch (final ClassCastException e) { } - } - - private final static boolean enablePrinting = false; - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDirectFloatsSketchIteratorTest.java b/src/test/java/org/apache/datasketches/kll/KllDirectFloatsSketchIteratorTest.java deleted file mode 100644 index b47c9ef18..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDirectFloatsSketchIteratorTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.kll.KllFloatsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class KllDirectFloatsSketchIteratorTest { - - @Test - public void emptySketch() { - final KllFloatsSketch sketch = getDFSketch(200, 0); - final QuantilesFloatsSketchIterator it = sketch.iterator(); - Assert.assertFalse(it.next()); - } - - @Test - public void oneItemSketch() { - final KllFloatsSketch sketch = getDFSketch(200, 0); - sketch.update(0); - final QuantilesFloatsSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getQuantile(), 0f); - Assert.assertEquals(it.getWeight(), 1); - Assert.assertFalse(it.next()); - } - - @Test - public void bigSketches() { - for (int n = 1000; n < 11000; n += 2000) { - final KllFloatsSketch sketch = getDFSketch(200, 0); - for (int i = 0; i < n; i++) { - sketch.update(i); - } - final QuantilesFloatsSketchIterator it = sketch.iterator(); - int count = 0; - int weight = 0; - while (it.next()) { - count++; - weight += (int)it.getWeight(); - } - Assert.assertEquals(count, sketch.getNumRetained()); - Assert.assertEquals(weight, n); - } - } - - private static KllFloatsSketch getDFSketch(final int k, final int n) { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { sk.update(i); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - - return KllFloatsSketch.wrap(wseg); - } - -} - diff --git a/src/test/java/org/apache/datasketches/kll/KllDirectFloatsSketchTest.java b/src/test/java/org/apache/datasketches/kll/KllDirectFloatsSketchTest.java deleted file mode 100644 index ca1e35463..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDirectFloatsSketchTest.java +++ /dev/null @@ -1,697 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_FLOATS_SKETCH; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDoublesSketch; -import org.apache.datasketches.kll.KllFloatsSketch; -import org.apache.datasketches.kll.KllHeapFloatsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllPreambleUtil; -import org.apache.datasketches.kll.KllSketch; -import org.apache.datasketches.kll.KllSketch.SketchStructure; -import org.testng.annotations.Test; - -public class KllDirectFloatsSketchTest { - - private static final double PMF_EPS_FOR_K_8 = 0.35; // PMF rank error (epsilon) for k=8 - private static final double PMF_EPS_FOR_K_128 = 0.025; // PMF rank error (epsilon) for k=128 - private static final double PMF_EPS_FOR_K_256 = 0.013; // PMF rank error (epsilon) for k=256 - private static final double NUMERIC_NOISE_TOLERANCE = 1E-6; - - @Test - public void empty() { - final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0); - sketch.update(Float.NaN); // this must not change anything - assertTrue(sketch.isEmpty()); - assertEquals(sketch.getN(), 0); - assertEquals(sketch.getNumRetained(), 0); - try { sketch.getRank(0.5f); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantile(0.5); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantiles(new double[] {0.0, 1.0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getPMF(new float[] {0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getCDF(new float[0]); fail(); } catch (final SketchesArgumentException e) {} - assertNotNull(sketch.toString(true, true)); - assertNotNull(sketch.toString()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantileInvalidArg() { - final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0); - sketch.update(1); - sketch.getQuantile(-1.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantilesInvalidArg() { - final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0); - sketch.update(1); - sketch.getQuantiles(new double[] {2.0}); - } - - @Test - public void oneValue() { - final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0); - sketch.update(1); - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getN(), 1); - assertEquals(sketch.getNumRetained(), 1); - assertEquals(sketch.getRank(1, EXCLUSIVE), 0.0); - assertEquals(sketch.getRank(2, EXCLUSIVE), 1.0); - assertEquals(sketch.getMinItem(), 1f); - assertEquals(sketch.getMaxItem(), 1f); - assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 1f); - } - - @Test - public void manyValuesEstimationMode() { - final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0); - final int n = 1_000_000; - - for (int i = 0; i < n; i++) { - sketch.update(i); - } - assertEquals(sketch.getN(), n); - - // test getRank - for (int i = 0; i < n; i++) { - final double trueRank = (double) i / n; - assertEquals(sketch.getRank(i), trueRank, PMF_EPS_FOR_K_256, "for value " + i); - } - - // test getPMF - final double[] pmf = sketch.getPMF(new float[] {n / 2.0f}); // split at median - assertEquals(pmf.length, 2); - assertEquals(pmf[0], 0.5, PMF_EPS_FOR_K_256); - assertEquals(pmf[1], 0.5, PMF_EPS_FOR_K_256); - assertEquals(sketch.getMinItem(), 0.0f); // min value is exact - assertEquals(sketch.getMaxItem(), n - 1.0f); // max value is exact - - // check at every 0.1 percentage point - final double[] ranks = new double[1001]; - final double[] reverseRanks = new double[1001]; // check that ordering doesn't matter - for (int i = 0; i <= 1000; i++) { - ranks[i] = (double) i / 1000; - reverseRanks[1000 - i] = ranks[i]; - } - final float[] quantiles = sketch.getQuantiles(ranks); - final float[] reverseQuantiles = sketch.getQuantiles(reverseRanks); - float previousQuantile = 0.0f; - for (int i = 0; i <= 1000; i++) { - final float quantile = sketch.getQuantile(ranks[i]); - assertEquals(quantile, quantiles[i]); - assertEquals(quantile, reverseQuantiles[1000 - i]); - assertTrue(previousQuantile <= quantile); - previousQuantile = quantile; - } - } - - @Test - public void getRankGetCdfGetPmfConsistency() { - final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0); - final int n = 1000; - final float[] values = new float[n]; - for (int i = 0; i < n; i++) { - sketch.update(i); - values[i] = i; - } - final double[] ranks = sketch.getCDF(values); - final double[] pmf = sketch.getPMF(values); - double sumPmf = 0; - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i]), NUMERIC_NOISE_TOLERANCE, - "rank vs CDF for value " + i); - sumPmf += pmf[i]; - assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i); - } - sumPmf += pmf[n]; - assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE); - assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE); - } - - @Test - public void merge() { - final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0); - final KllFloatsSketch sketch2 = getUpdatableDirectFloatSketch(200, 0); - final int n = 10_000; - for (int i = 0; i < n; i++) { - sketch1.update(i * 1.0F); - sketch2.update(((2 * n) - i - 1) * 1.0F); - } - - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), (n - 1) * 1.0); - - assertEquals(sketch2.getMinItem(), n * 1.0); - assertEquals(sketch2.getMaxItem(), ((2 * n) - 1) * 1.0); - - sketch1.merge(sketch2); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2L * n); - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), ((2 * n) - 1) * 1.0F); - assertEquals(sketch1.getQuantile(0.5), n * 1.0F, n * PMF_EPS_FOR_K_256); - } - - @Test - public void mergeLowerK() { - final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(256, 0); - final KllFloatsSketch sketch2 = getUpdatableDirectFloatSketch(128, 0); - final int n = 10_000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - sketch2.update((2 * n) - i - 1); - } - - assertEquals(sketch1.getMinItem(), 0.0f); - assertEquals(sketch1.getMaxItem(), n - 1f); - - assertEquals(sketch2.getMinItem(), n); - assertEquals(sketch2.getMaxItem(), (2f * n) - 1f); - - assertTrue(sketch1.getNormalizedRankError(false) < sketch2.getNormalizedRankError(false)); - assertTrue(sketch1.getNormalizedRankError(true) < sketch2.getNormalizedRankError(true)); - sketch1.merge(sketch2); - - // sketch1 must get "contaminated" by the lower K in sketch2 - assertEquals(sketch1.getNormalizedRankError(false), sketch2.getNormalizedRankError(false)); - assertEquals(sketch1.getNormalizedRankError(true), sketch2.getNormalizedRankError(true)); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2 * n); - assertEquals(sketch1.getMinItem(), 0.0f); - assertEquals(sketch1.getMaxItem(), (2.0f * n) - 1.0f); - assertEquals(sketch1.getQuantile(0.5), n, n * PMF_EPS_FOR_K_128); - } - - @Test - public void mergeEmptyLowerK() { - final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(256, 0); - final KllFloatsSketch sketch2 = getUpdatableDirectFloatSketch(128, 0); - final int n = 10_000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - - // rank error should not be affected by a merge with an empty sketch with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), 0.0f); - assertEquals(sketch1.getMaxItem(), n - 1.0f); - assertEquals(sketch1.getQuantile(0.5), n / 2.0f, (n / 2) * PMF_EPS_FOR_K_256); - - //merge the other way - sketch2.merge(sketch1); - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), 0.0f); - assertEquals(sketch1.getMaxItem(), n - 1.0f); - assertEquals(sketch1.getQuantile(0.5), n / 2.0f, (n / 2) * PMF_EPS_FOR_K_256); - } - - @Test - public void mergeExactModeLowerK() { - final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(256, 0); - final KllFloatsSketch sketch2 = getUpdatableDirectFloatSketch(128, 0); - final int n = 10000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - sketch2.update(1); - - // rank error should not be affected by a merge with a sketch in exact mode with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - } - - @Test - public void mergeMinMinValueFromOther() { - final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0); - final KllFloatsSketch sketch2 = getUpdatableDirectFloatSketch(200, 0); - sketch1.update(1); - sketch2.update(2); - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), 1.0F); - } - - @Test - public void mergeMinAndMaxFromOther() { - final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0); - final KllFloatsSketch sketch2 = getUpdatableDirectFloatSketch(200, 0); - final int n = 1_000_000; - for (int i = 1; i <= n; i++) { - sketch1.update(i); - } - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), 1F); - assertEquals(sketch2.getMaxItem(), 1_000_000F); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooSmall() { - getUpdatableDirectFloatSketch(KllSketch.DEFAULT_M - 1, 0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooLarge() { - getUpdatableDirectFloatSketch(KllSketch.MAX_K + 1, 0); - } - - @Test - public void minK() { - final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(KllSketch.DEFAULT_M, 0); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getK(), KllSketch.DEFAULT_M); - assertEquals(sketch.getQuantile(0.5), 500, 500 * PMF_EPS_FOR_K_8); - } - - @Test - public void maxK() { - final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(KllSketch.MAX_K, 0); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getK(), KllSketch.MAX_K); - assertEquals(sketch.getQuantile(0.5), 500, 500 * PMF_EPS_FOR_K_256); - } - - @Test - public void serializeDeserializeEmptyViaCompactHeapify() { - final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0); - final byte[] bytes = sketch1.toByteArray(); //compact - final KllFloatsSketch sketch2 = KllFloatsSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(false)); - assertTrue(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained()); - assertEquals(sketch2.getN(), sketch1.getN()); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - try { sketch2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sketch2.currentSerializedSizeBytes(false), - sketch1.currentSerializedSizeBytes(false)); - } - - @Test - public void serializeDeserializeEmptyViaUpdatableWritableWrap() { - final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0); - final byte[] bytes = KllHelper.toByteArray(sketch1, true); - final KllFloatsSketch sketch2 = - KllFloatsSketch.wrap(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true)); - assertTrue(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained()); - assertEquals(sketch2.getN(), sketch1.getN()); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - try { sketch2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sketch2.currentSerializedSizeBytes(true), - sketch1.currentSerializedSizeBytes(true)); - } - - @Test - public void serializeDeserializeOneValueViaCompactHeapify() { - final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0); - sketch1.update(1); - final byte[] bytes = sketch1.toByteArray(); - final KllFloatsSketch sketch2 = KllFloatsSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(false)); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), 1); - assertEquals(sketch2.getN(), 1); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - assertTrue(Float.isFinite(sketch2.getMinItem())); - assertTrue(Float.isFinite(sketch2.getMaxItem())); - assertEquals(sketch2.currentSerializedSizeBytes(false), 8 + Float.BYTES); - } - - @Test - public void serializeDeserializeOneValueViaUpdatableWritableWrap() { - final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0); - sketch1.update(1); - final byte[] bytes = KllHelper.toByteArray(sketch1, true); - final KllFloatsSketch sketch2 = - KllFloatsSketch.wrap(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true)); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), 1); - assertEquals(sketch2.getN(), 1); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - assertEquals(sketch2.getMinItem(), 1.0f); - assertEquals(sketch2.getMaxItem(), 1.0f); - assertEquals(sketch2.currentSerializedSizeBytes(false), 8 + Float.BYTES); - assertEquals(sketch2.currentSerializedSizeBytes(true), bytes.length); - } - - @Test - public void serializeDeserializeFullViaCompactHeapify() { - final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 1000); - final byte[] byteArr1 = sketch1.toByteArray(); //compact - final KllFloatsSketch sketch2 = KllFloatsSketch.heapify(MemorySegment.ofArray(byteArr1)); - assertEquals(byteArr1.length, sketch1.currentSerializedSizeBytes(false)); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained()); - assertEquals(sketch2.getN(), sketch1.getN()); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - assertEquals(sketch2.getMinItem(), sketch1.getMinItem()); - assertEquals(sketch2.getMaxItem(), sketch1.getMaxItem()); - assertEquals(sketch2.currentSerializedSizeBytes(false), sketch1.currentSerializedSizeBytes(false)); - } - - @Test - public void serializeDeserializeFullViaUpdatableWritableWrap() { - final KllFloatsSketch sketch1 = getUpdatableDirectFloatSketch(200, 0); - final int n = 1000; - for (int i = 1; i <= n; i++) { - sketch1.update(i); - } - final byte[] bytes = KllHelper.toByteArray(sketch1, true); //updatable - final KllFloatsSketch sketch2 = - KllFloatsSketch.wrap(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true)); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained()); - assertEquals(sketch2.getN(), sketch1.getN()); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - assertEquals(sketch2.getMinItem(), sketch1.getMinItem()); - assertEquals(sketch2.getMaxItem(), sketch1.getMaxItem()); - assertEquals(sketch2.currentSerializedSizeBytes(true), sketch1.currentSerializedSizeBytes(true)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void outOfOrderSplitPoints() { - final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0); - sketch.update(0); - sketch.getCDF(new float[] {1, 0}); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void nanSplitPoint() { - final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 0); - sketch.update(0); - sketch.getCDF(new float[] {Float.NaN}); - } - - @Test - public void checkSimpleMergeDirect() { //used for troubleshooting - final int k = 20; - final int n1 = 21; - final int n2 = 43; - final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(k); - final KllFloatsSketch sk2 = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= n1; i++) { - sk1.update(i); - } - for (int i = 1; i <= n2; i++) { - sk2.update(i + 100); - } - println("SK1:"); - println(sk1.toString(true, true)); - println("SK2:"); - println(sk2.toString(true, true)); - final MemorySegment wseg1 = MemorySegment.ofArray(KllHelper.toByteArray(sk1, true)); - final MemorySegment wseg2 = MemorySegment.ofArray(KllHelper.toByteArray(sk2, true)); - final KllFloatsSketch dsk1 = KllFloatsSketch.wrap(wseg1); - final KllFloatsSketch dsk2 = KllFloatsSketch.wrap(wseg2); - println("BEFORE MERGE"); - println(dsk1.toString(true, true)); - dsk1.merge(dsk2); - println("AFTER MERGE"); - println(dsk1.toString(true, true)); - } - - @Test - public void checkSketchInitializeDirectFloatUpdatableMemorySegment() { - final int k = 20; //don't change this - KllFloatsSketch sk; - KllFloatsSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - println("#### CASE: FLOAT FULL DIRECT FROM UPDATABLE"); - sk2 = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk2.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(compBytes, KLL_FLOATS_SKETCH, true)); - sk = KllFloatsSketch.wrap(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: FLOAT EMPTY HEAPIFIED FROM UPDATABLE"); - sk2 = KllFloatsSketch.newHeapInstance(k); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(compBytes, KLL_FLOATS_SKETCH, true)); - sk = KllFloatsSketch.wrap(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: FLOAT SINGLE HEAPIFIED FROM UPDATABLE"); - sk2 = KllFloatsSketch.newHeapInstance(k); - sk2.update(1); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(compBytes, KLL_FLOATS_SKETCH, true)); - sk = KllFloatsSketch.wrap(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test - public void checkGetMemorySegment() { - final KllFloatsSketch sketch = getUpdatableDirectFloatSketch(200, 200); - assertEquals(sketch.getK(), 200); - assertEquals(sketch.getN(), 200); - assertFalse(sketch.isEmpty()); - assertTrue(sketch.isMemorySegmentUpdatableFormat()); - assertFalse(sketch.isEstimationMode()); - assertTrue(sketch.isKllFloatsSketch()); - assertFalse(sketch.isLevelZeroSorted()); - assertFalse(sketch.isKllDoublesSketch()); - - final MemorySegment wseg = sketch.getMemorySegment(); - final KllFloatsSketch sk = KllHeapFloatsSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), 200); - assertEquals(sk.getN(), 200); - assertFalse(sk.isEmpty()); - assertFalse(sk.isMemorySegmentUpdatableFormat()); - assertFalse(sk.isEstimationMode()); - assertTrue(sk.isKllFloatsSketch()); - assertFalse(sk.isLevelZeroSorted()); - assertFalse(sk.isKllDoublesSketch()); - } - - @Test - public void checkReset() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[3000]); - final KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(20, dstSeg, null); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final long n1 = sk.getN(); - final float min1 = sk.getMinItem(); - final float max1 = sk.getMaxItem(); - sk.reset(); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final long n2 = sk.getN(); - final float min2 = sk.getMinItem(); - final float max2 = sk.getMaxItem(); - assertEquals(n2, n1); - assertEquals(min2, min1); - assertEquals(max2, max1); - } - - @Test - public void checkHeapify() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(20, dstSeg, null); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final KllFloatsSketch sk2 = KllHeapFloatsSketch.heapifyImpl(dstSeg); - assertEquals(sk2.getMinItem(), 1.0); - assertEquals(sk2.getMaxItem(), 100.0); - } - - @Test - public void checkMergeKllFloatsSketch() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(20, dstSeg, null); - for (int i = 1; i <= 21; i++) { sk.update(i); } - final KllFloatsSketch sk2 = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++ ) { sk2.update(i + 100); } - sk.merge(sk2); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getMaxItem(), 121.0); - } - - @Test - public void checkReverseMergeKllFloatsSketch() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(20, dstSeg, null); - for (int i = 1; i <= 21; i++) { sk.update(i); } - final KllFloatsSketch sk2 = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++ ) { sk2.update(i + 100); } - sk2.merge(sk); - assertEquals(sk2.getMinItem(), 1.0); - assertEquals(sk2.getMaxItem(), 121.0); - } - - @Test - public void checkWritableWrapOfCompactForm() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++ ) { sk.update(i); } - final MemorySegment srcSeg = MemorySegment.ofArray(sk.toByteArray()); - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(srcSeg); - assertEquals(sk2.getMinItem(), 1.0F); - assertEquals(sk2.getMaxItem(), 21.0F); - } - - @Test - public void checkReadOnlyExceptions() { - final int k = 20; - final float[] fltArr = {}; - final float fltV = 1.0f; - final int idx = 1; - final boolean bool = true; - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - try { sk2.incN(1); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.incNumLevels(); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setFloatItemsArray(fltArr); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setFloatItemsArrayAt(idx, fltV); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setLevelZeroSorted(bool); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setMaxItem(fltV); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setMinItem(fltV); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setMinK(idx); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setN(idx); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setNumLevels(idx); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkMergeExceptions() { - final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(20); - final MemorySegment srcSeg1 = MemorySegment.ofArray(sk1.toByteArray()); - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(srcSeg1); - sk2.merge(sk1); - } - - @Test - public void checkVectorUpdate() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(20, dstSeg, null); - final float[] v = new float[21]; - for (int i = 0; i < 21; i++) { v[i] = i + 1; } - sk.update(v, 0, 21); - println(sk.toString(true, true)); - final int[] levelsArr = sk.getLevelsArray(SketchStructure.UPDATABLE); - assertEquals(levelsArr[0], 22); - final float[] floatsArr = sk.getFloatItemsArray(); - assertEquals(floatsArr[22], 21); - } - - @Test - public void checkWeightedUpdate() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(8, dstSeg, null); - for (int i = 0; i < 16; i++) { - sk.update(i + 1, 16); - } - println(sk.toString(true, true)); - assertEquals(sk.getN(), 256); - assertEquals(sk.getMaxItem(), 16F); - assertEquals(sk.getMinItem(), 1F); - } - - private static KllFloatsSketch getUpdatableDirectFloatSketch(final int k, final int n) { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { sk.update(i); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - return KllFloatsSketch.wrap(wseg); - } - - @Test - public void checkMergeExceptionsWrongType() { - final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(20); - final KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(20); - try { sk1.merge(sk2); fail(); } catch (final ClassCastException e) { } - try { sk2.merge(sk1); fail(); } catch (final ClassCastException e) { } - } - - private final static boolean enablePrinting = false; - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDirectLongsSketchIteratorTest.java b/src/test/java/org/apache/datasketches/kll/KllDirectLongsSketchIteratorTest.java deleted file mode 100644 index 83228b293..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDirectLongsSketchIteratorTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllLongsSketch; -import org.apache.datasketches.quantilescommon.QuantilesLongsSketchIterator; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class KllDirectLongsSketchIteratorTest { - - @Test - public void emptySketch() { - final KllLongsSketch sketch = getDLSketch(200, 0); - final QuantilesLongsSketchIterator it = sketch.iterator(); - Assert.assertFalse(it.next()); - } - - @Test - public void oneItemSketch() { - final KllLongsSketch sketch = getDLSketch(200, 0); - sketch.update(0); - final QuantilesLongsSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getQuantile(), 0); - Assert.assertEquals(it.getWeight(), 1); - Assert.assertFalse(it.next()); - } - - @Test - public void bigSketches() { - for (int n = 1000; n < 11000; n += 2000) { - final KllLongsSketch sketch = getDLSketch(200, 0); - for (int i = 0; i < n; i++) { - sketch.update(i); - } - final QuantilesLongsSketchIterator it = sketch.iterator(); - int count = 0; - int weight = 0; - while (it.next()) { - count++; - weight += (int)it.getWeight(); - } - Assert.assertEquals(count, sketch.getNumRetained()); - Assert.assertEquals(weight, n); - } - } - - private static KllLongsSketch getDLSketch(final int k, final int n) { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { sk.update(i); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - - return KllLongsSketch.wrap(wseg); - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDirectLongsSketchTest.java b/src/test/java/org/apache/datasketches/kll/KllDirectLongsSketchTest.java deleted file mode 100644 index e4c3438ea..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDirectLongsSketchTest.java +++ /dev/null @@ -1,689 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_LONGS_SKETCH; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDoublesSketch; -import org.apache.datasketches.kll.KllHeapLongsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllLongsSketch; -import org.apache.datasketches.kll.KllPreambleUtil; -import org.apache.datasketches.kll.KllSketch; -import org.apache.datasketches.kll.KllSketch.SketchStructure; -import org.testng.annotations.Test; - -public class KllDirectLongsSketchTest { - - private static final double PMF_EPS_FOR_K_8 = 0.35; // PMF rank error (epsilon) for k=8 - private static final double PMF_EPS_FOR_K_128 = 0.025; // PMF rank error (epsilon) for k=128 - private static final double PMF_EPS_FOR_K_256 = 0.013; // PMF rank error (epsilon) for k=256 - private static final double NUMERIC_NOISE_TOLERANCE = 1E-6; - - @Test - public void empty() { - final KllLongsSketch sketch = getUpdatableDirectLongSketch(200, 0); - assertTrue(sketch.isEmpty()); - assertEquals(sketch.getN(), 0); - assertEquals(sketch.getNumRetained(), 0); - try { sketch.getRank(0); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantile(0.5); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantiles(new double[] {0.0, 1.0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getPMF(new long[] {0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getCDF(new long[0]); fail(); } catch (final SketchesArgumentException e) {} - assertNotNull(sketch.toString(true, true)); - assertNotNull(sketch.toString()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantileInvalidArg() { - final KllLongsSketch sketch = getUpdatableDirectLongSketch(200, 0); - sketch.update(1); - sketch.getQuantile(-1.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantilesInvalidArg() { - final KllLongsSketch sketch = getUpdatableDirectLongSketch(200, 0); - sketch.update(1); - sketch.getQuantiles(new double[] {2.0}); - } - - @Test - public void oneValue() { - final KllLongsSketch sketch = getUpdatableDirectLongSketch(200, 0); - sketch.update(1); - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getN(), 1); - assertEquals(sketch.getNumRetained(), 1); - assertEquals(sketch.getRank(1, EXCLUSIVE), 0.0); - assertEquals(sketch.getRank(2, EXCLUSIVE), 1.0); - assertEquals(sketch.getMinItem(), 1L); - assertEquals(sketch.getMaxItem(), 1L); - assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 1L); - } - - @Test - public void manyValuesEstimationMode() { - final KllLongsSketch sketch = getUpdatableDirectLongSketch(200, 0); - final int n = 1_000_000; - - for (int i = 0; i < n; i++) { - sketch.update(i); - } - assertEquals(sketch.getN(), n); - - // test getRank - for (int i = 0; i < n; i++) { - final double trueRank = (double) i / n; - assertEquals(sketch.getRank(i), trueRank, PMF_EPS_FOR_K_256, "for value " + i); - } - - // test getPMF - final double[] pmf = sketch.getPMF(new long[] {n / 2}); // split at median - assertEquals(pmf.length, 2); - assertEquals(pmf[0], 0.5, PMF_EPS_FOR_K_256); - assertEquals(pmf[1], 0.5, PMF_EPS_FOR_K_256); - assertEquals(sketch.getMinItem(), 0); // min value is exact - assertEquals(sketch.getMaxItem(), n - 1L); // max value is exact - - // check at every 0.1 percentage point - final double[] ranks = new double[1001]; - final double[] reverseRanks = new double[1001]; // check that ordering doesn't matter - for (int i = 0; i <= 1000; i++) { - ranks[i] = (double) i / 1000; - reverseRanks[1000 - i] = ranks[i]; - } - final long[] quantiles = sketch.getQuantiles(ranks); - final long[] reverseQuantiles = sketch.getQuantiles(reverseRanks); - long previousQuantile = 0; - for (int i = 0; i <= 1000; i++) { - final long quantile = sketch.getQuantile(ranks[i]); - assertEquals(quantile, quantiles[i]); - assertEquals(quantile, reverseQuantiles[1000 - i]); - assertTrue(previousQuantile <= quantile); - previousQuantile = quantile; - } - } - - @Test - public void getRankGetCdfGetPmfConsistency() { - final KllLongsSketch sketch = getUpdatableDirectLongSketch(200, 0); - final int n = 1000; - final long[] values = new long[n]; - for (int i = 0; i < n; i++) { - sketch.update(i); - values[i] = i; - } - final double[] ranks = sketch.getCDF(values); - final double[] pmf = sketch.getPMF(values); - double sumPmf = 0; - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i]), NUMERIC_NOISE_TOLERANCE, - "rank vs CDF for value " + i); - sumPmf += pmf[i]; - assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i); - } - sumPmf += pmf[n]; - assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE); - assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE); - } - - @Test - public void merge() { - final KllLongsSketch sketch1 = getUpdatableDirectLongSketch(200, 0); - final KllLongsSketch sketch2 = getUpdatableDirectLongSketch(200, 0); - final int n = 10_000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - sketch2.update((2 * n) - i - 1); - } - - assertEquals(sketch1.getMinItem(), 0); - assertEquals(sketch1.getMaxItem(), n - 1); - - assertEquals(sketch2.getMinItem(), n); - assertEquals(sketch2.getMaxItem(), (2 * n) - 1); - - sketch1.merge(sketch2); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2L * n); - assertEquals(sketch1.getMinItem(), 0); - assertEquals(sketch1.getMaxItem(), (2 * n) - 1L); - assertEquals(sketch1.getQuantile(0.5), n, n * PMF_EPS_FOR_K_256); - } - - @Test - public void mergeLowerK() { - final KllLongsSketch sketch1 = getUpdatableDirectLongSketch(256, 0); - final KllLongsSketch sketch2 = getUpdatableDirectLongSketch(128, 0); - final int n = 10_000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - sketch2.update((2 * n) - i - 1); - } - - assertEquals(sketch1.getMinItem(), 0); - assertEquals(sketch1.getMaxItem(), n - 1); - - assertEquals(sketch2.getMinItem(), n); - assertEquals(sketch2.getMaxItem(), (2 * n) - 1); - - assertTrue(sketch1.getNormalizedRankError(false) < sketch2.getNormalizedRankError(false)); - assertTrue(sketch1.getNormalizedRankError(true) < sketch2.getNormalizedRankError(true)); - sketch1.merge(sketch2); - - // sketch1 must get "contaminated" by the lower K in sketch2 - assertEquals(sketch1.getNormalizedRankError(false), sketch2.getNormalizedRankError(false)); - assertEquals(sketch1.getNormalizedRankError(true), sketch2.getNormalizedRankError(true)); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2 * n); - assertEquals(sketch1.getMinItem(), 0); - assertEquals(sketch1.getMaxItem(), (2 * n) - 1); - assertEquals(sketch1.getQuantile(0.5), n, n * PMF_EPS_FOR_K_128); - } - - @Test - public void mergeEmptyLowerK() { - final KllLongsSketch sketch1 = getUpdatableDirectLongSketch(256, 0); - final KllLongsSketch sketch2 = getUpdatableDirectLongSketch(128, 0); - final int n = 10_000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - - // rank error should not be affected by a merge with an empty sketch with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), 0); - assertEquals(sketch1.getMaxItem(), n - 1); - assertEquals(sketch1.getQuantile(0.5), n / 2, (n / 2) * PMF_EPS_FOR_K_256); - - //merge the other way - sketch2.merge(sketch1); - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), 0); - assertEquals(sketch1.getMaxItem(), n - 1); - assertEquals(sketch1.getQuantile(0.5), n / 2, (n / 2) * PMF_EPS_FOR_K_256); - } - - @Test - public void mergeExactModeLowerK() { - final KllLongsSketch sketch1 = getUpdatableDirectLongSketch(256, 0); - final KllLongsSketch sketch2 = getUpdatableDirectLongSketch(128, 0); - final int n = 10000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - sketch2.update(1); - - // rank error should not be affected by a merge with a sketch in exact mode with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - } - - @Test - public void mergeMinMinValueFromOther() { - final KllLongsSketch sketch1 = getUpdatableDirectLongSketch(200, 0); - final KllLongsSketch sketch2 = getUpdatableDirectLongSketch(200, 0); - sketch1.update(1); - sketch2.update(2); - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), 1L); - } - - @Test - public void mergeMinAndMaxFromOther() { - final KllLongsSketch sketch1 = getUpdatableDirectLongSketch(200, 0); - final KllLongsSketch sketch2 = getUpdatableDirectLongSketch(200, 0); - final int n = 1_000_000; - for (int i = 1; i <= n; i++) { - sketch1.update(i); - } - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), 1L); - assertEquals(sketch2.getMaxItem(), 1_000_000L); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooSmall() { - getUpdatableDirectLongSketch(KllSketch.DEFAULT_M - 1, 0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooLarge() { - getUpdatableDirectLongSketch(KllSketch.MAX_K + 1, 0); - } - - @Test - public void minK() { - final KllLongsSketch sketch = getUpdatableDirectLongSketch(KllSketch.DEFAULT_M, 0); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getK(), KllSketch.DEFAULT_M); - assertEquals(sketch.getQuantile(0.5), 500, 500 * PMF_EPS_FOR_K_8); - } - - @Test - public void maxK() { - final KllLongsSketch sketch = getUpdatableDirectLongSketch(KllSketch.MAX_K, 0); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getK(), KllSketch.MAX_K); - assertEquals(sketch.getQuantile(0.5), 500, 500 * PMF_EPS_FOR_K_256); - } - - @Test - public void serializeDeserializeEmptyViaCompactHeapify() { - final KllLongsSketch sketch1 = getUpdatableDirectLongSketch(200, 0); - final byte[] bytes = sketch1.toByteArray(); //compact - final KllLongsSketch sketch2 = KllLongsSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(false)); - assertTrue(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained()); - assertEquals(sketch2.getN(), sketch1.getN()); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - try { sketch2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sketch2.currentSerializedSizeBytes(false), - sketch1.currentSerializedSizeBytes(false)); - } - - @Test - public void serializeDeserializeEmptyViaUpdatableWritableWrap() { - final KllLongsSketch sketch1 = getUpdatableDirectLongSketch(200, 0); - final byte[] bytes = KllHelper.toByteArray(sketch1, true); - final KllLongsSketch sketch2 = - KllLongsSketch.wrap(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true)); - assertTrue(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained()); - assertEquals(sketch2.getN(), sketch1.getN()); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - try { sketch2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sketch2.currentSerializedSizeBytes(true), - sketch1.currentSerializedSizeBytes(true)); - } - - @Test - public void serializeDeserializeOneValueViaCompactHeapify() { - final KllLongsSketch sketch1 = getUpdatableDirectLongSketch(200, 0); - sketch1.update(1); - final byte[] bytes = sketch1.toByteArray(); - final KllLongsSketch sketch2 = KllLongsSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(false)); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), 1); - assertEquals(sketch2.getN(), 1); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - assertTrue(sketch2.getMinItem() < Long.MAX_VALUE); - assertTrue(sketch2.getMaxItem() > Long.MIN_VALUE); - assertEquals(sketch2.currentSerializedSizeBytes(false), 8 + Long.BYTES); - } - - @Test - public void serializeDeserializeOneValueViaUpdatableWritableWrap() { - final KllLongsSketch sketch1 = getUpdatableDirectLongSketch(200, 0); - sketch1.update(1); - final byte[] bytes = KllHelper.toByteArray(sketch1, true); - final KllLongsSketch sketch2 = - KllLongsSketch.wrap(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true)); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), 1); - assertEquals(sketch2.getN(), 1); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - assertEquals(sketch2.getMinItem(), 1L); - assertEquals(sketch2.getMaxItem(), 1L); - assertEquals(sketch2.currentSerializedSizeBytes(false), 8 + Long.BYTES); - assertEquals(sketch2.currentSerializedSizeBytes(true), bytes.length); - } - - @Test - public void serializeDeserializeFullViaCompactHeapify() { - final KllLongsSketch sketch1 = getUpdatableDirectLongSketch(200, 1000); - final byte[] byteArr1 = sketch1.toByteArray(); //compact - final KllLongsSketch sketch2 = KllLongsSketch.heapify(MemorySegment.ofArray(byteArr1)); - assertEquals(byteArr1.length, sketch1.currentSerializedSizeBytes(false)); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained()); - assertEquals(sketch2.getN(), sketch1.getN()); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - assertEquals(sketch2.getMinItem(), sketch1.getMinItem()); - assertEquals(sketch2.getMaxItem(), sketch1.getMaxItem()); - assertEquals(sketch2.currentSerializedSizeBytes(false), sketch1.currentSerializedSizeBytes(false)); - } - - @Test - public void serializeDeserializeFullViaUpdatableWritableWrap() { - final KllLongsSketch sketch1 = getUpdatableDirectLongSketch(200, 0); - final int n = 1000; - for (int i = 1; i <= n; i++) { - sketch1.update(i); - } - final byte[] bytes = KllHelper.toByteArray(sketch1, true); //updatable - final KllLongsSketch sketch2 = - KllLongsSketch.wrap(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sketch1.currentSerializedSizeBytes(true)); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch2.getNumRetained(), sketch1.getNumRetained()); - assertEquals(sketch2.getN(), sketch1.getN()); - assertEquals(sketch2.getNormalizedRankError(false), sketch1.getNormalizedRankError(false)); - assertEquals(sketch2.getMinItem(), sketch1.getMinItem()); - assertEquals(sketch2.getMaxItem(), sketch1.getMaxItem()); - assertEquals(sketch2.currentSerializedSizeBytes(true), sketch1.currentSerializedSizeBytes(true)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void outOfOrderSplitPoints() { - final KllLongsSketch sketch = getUpdatableDirectLongSketch(200, 0); - sketch.update(0); - sketch.getCDF(new long[] {1, 0}); - } - - @Test - public void checkSimpleMergeDirect() { //used for troubleshooting - final int k = 20; - final int n1 = 21; - final int n2 = 43; - final KllLongsSketch sk1 = KllLongsSketch.newHeapInstance(k); - final KllLongsSketch sk2 = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= n1; i++) { - sk1.update(i); - } - for (int i = 1; i <= n2; i++) { - sk2.update(i + 100); - } - println("SK1:"); - println(sk1.toString(true, true)); - println("SK2:"); - println(sk2.toString(true, true)); - final MemorySegment wseg1 = MemorySegment.ofArray(KllHelper.toByteArray(sk1, true)); - final MemorySegment wseg2 = MemorySegment.ofArray(KllHelper.toByteArray(sk2, true)); - final KllLongsSketch dsk1 = KllLongsSketch.wrap(wseg1); - final KllLongsSketch dsk2 = KllLongsSketch.wrap(wseg2); - println("BEFORE MERGE"); - println(dsk1.toString(true, true)); - dsk1.merge(dsk2); - println("AFTER MERGE"); - println(dsk1.toString(true, true)); - } - - @Test - public void checkSketchInitializeDirectLongUpdatableMemorySegment() { - final int k = 20; //don't change this - KllLongsSketch sk; - KllLongsSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - println("#### CASE: LONG FULL DIRECT FROM UPDATABLE"); - sk2 = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk2.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(compBytes, KLL_LONGS_SKETCH, true)); - sk = KllLongsSketch.wrap(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21); - assertEquals(sk.getMinItem(), 1); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: LONG EMPTY HEAPIFIED FROM UPDATABLE"); - sk2 = KllLongsSketch.newHeapInstance(k); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(compBytes, KLL_LONGS_SKETCH, true)); - sk = KllLongsSketch.wrap(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: LONG SINGLE HEAPIFIED FROM UPDATABLE"); - sk2 = KllLongsSketch.newHeapInstance(k); - sk2.update(1); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(compBytes, KLL_LONGS_SKETCH, true)); - sk = KllLongsSketch.wrap(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1L); - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test - public void checkGetMemorySegment() { - final KllLongsSketch sketch = getUpdatableDirectLongSketch(200, 200); - assertEquals(sketch.getK(), 200); - assertEquals(sketch.getN(), 200); - assertFalse(sketch.isEmpty()); - assertTrue(sketch.isMemorySegmentUpdatableFormat()); - assertFalse(sketch.isEstimationMode()); - assertTrue(sketch.isKllLongsSketch()); - assertFalse(sketch.isLevelZeroSorted()); - assertFalse(sketch.isKllDoublesSketch()); - - final MemorySegment wseg = sketch.getMemorySegment(); - final KllLongsSketch sk = KllHeapLongsSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), 200); - assertEquals(sk.getN(), 200); - assertFalse(sk.isEmpty()); - assertFalse(sk.isMemorySegmentUpdatableFormat()); - assertFalse(sk.isEstimationMode()); - assertTrue(sk.isKllLongsSketch()); - assertFalse(sk.isLevelZeroSorted()); - assertFalse(sk.isKllDoublesSketch()); - } - - @Test - public void checkReset() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[3000]); - final KllLongsSketch sk = KllLongsSketch.newDirectInstance(20, dstSeg, null); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final long n1 = sk.getN(); - final long min1 = sk.getMinItem(); - final long max1 = sk.getMaxItem(); - sk.reset(); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final long n2 = sk.getN(); - final long min2 = sk.getMinItem(); - final long max2 = sk.getMaxItem(); - assertEquals(n2, n1); - assertEquals(min2, min1); - assertEquals(max2, max1); - } - - @Test - public void checkHeapify() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllLongsSketch sk = KllLongsSketch.newDirectInstance(20, dstSeg, null); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final KllLongsSketch sk2 = KllHeapLongsSketch.heapifyImpl(dstSeg); - assertEquals(sk2.getMinItem(), 1L); - assertEquals(sk2.getMaxItem(), 100L); - } - - @Test - public void checkMergeKllLongsSketch() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllLongsSketch sk = KllLongsSketch.newDirectInstance(20, dstSeg, null); - for (int i = 1; i <= 21; i++) { sk.update(i); } - final KllLongsSketch sk2 = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++ ) { sk2.update(i + 100); } - sk.merge(sk2); - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getMaxItem(), 121L); - } - - @Test - public void checkReverseMergeKllLongsSketch() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllLongsSketch sk = KllLongsSketch.newDirectInstance(20, dstSeg, null); - for (int i = 1; i <= 21; i++) { sk.update(i); } - final KllLongsSketch sk2 = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++ ) { sk2.update(i + 100); } - sk2.merge(sk); - assertEquals(sk2.getMinItem(), 1L); - assertEquals(sk2.getMaxItem(), 121L); - } - - @Test - public void checkWritableWrapOfCompactForm() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++ ) { sk.update(i); } - final MemorySegment srcSeg = MemorySegment.ofArray(sk.toByteArray()); - final KllLongsSketch sk2 = KllLongsSketch.wrap(srcSeg); - assertEquals(sk2.getMinItem(), 1L); - assertEquals(sk2.getMaxItem(), 21L); - } - - @Test - public void checkReadOnlyExceptions() { - final int k = 20; - final long[] fltArr = {}; - final long fltV = 1; - final int idx = 1; - final boolean bool = true; - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - final KllLongsSketch sk2 = KllLongsSketch.wrap(MemorySegment.ofArray(sk.toByteArray())); - try { sk2.incN(1); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.incNumLevels(); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setLongItemsArray(fltArr); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setLongItemsArrayAt(idx, fltV); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setLevelZeroSorted(bool); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setMaxItem(fltV); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setMinItem(fltV); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setMinK(idx); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setN(idx); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setNumLevels(idx); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkMergeExceptions() { - final KllLongsSketch sk1 = KllLongsSketch.newHeapInstance(20); - final MemorySegment srcSeg1 = MemorySegment.ofArray(sk1.toByteArray()); - final KllLongsSketch sk2 = KllLongsSketch.wrap(srcSeg1); - sk2.merge(sk1); - } - - @Test - public void checkVectorUpdate() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllLongsSketch sk = KllLongsSketch.newDirectInstance(20, dstSeg, null); - final long[] v = new long[21]; - for (int i = 0; i < 21; i++) { v[i] = i + 1; } - sk.update(v, 0, 21); - println(sk.toString(true, true)); - final int[] levelsArr = sk.getLevelsArray(SketchStructure.UPDATABLE); - assertEquals(levelsArr[0], 22); - final long[] longsArr = sk.getLongItemsArray(); - assertEquals(longsArr[22], 21); - } - - @Test - public void checkWeightedUpdate() { - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllLongsSketch sk = KllLongsSketch.newDirectInstance(8, dstSeg, null); - for (int i = 0; i < 16; i++) { - sk.update(i + 1, 16); - } - println(sk.toString(true, true)); - assertEquals(sk.getN(), 256); - assertEquals(sk.getMaxItem(), 16L); - assertEquals(sk.getMinItem(), 1L); - } - - private static KllLongsSketch getUpdatableDirectLongSketch(final int k, final int n) { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { sk.update(i); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - return KllLongsSketch.wrap(wseg); - } - - @Test - public void checkMergeExceptionsWrongType() { - final KllLongsSketch sk1 = KllLongsSketch.newHeapInstance(20); - final KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(20); - try { sk1.merge(sk2); fail(); } catch (final ClassCastException e) { } - try { sk2.merge(sk1); fail(); } catch (final ClassCastException e) { } - } - - private final static boolean enablePrinting = false; - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDoublesSketchIteratorTest.java b/src/test/java/org/apache/datasketches/kll/KllDoublesSketchIteratorTest.java deleted file mode 100644 index ff66caccd..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDoublesSketchIteratorTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import org.apache.datasketches.kll.KllDoublesSketch; -import org.apache.datasketches.quantilescommon.DoublesSortedViewIterator; -import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIteratorAPI; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class KllDoublesSketchIteratorTest { - - @Test - public void emptySketch() { - KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - QuantilesDoublesSketchIteratorAPI it = sketch.iterator(); - Assert.assertFalse(it.next()); - } - - @Test - public void oneItemSketch() { - KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - sketch.update(1); - QuantilesDoublesSketchIteratorAPI it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getQuantile(), 1.0); - Assert.assertEquals(it.getWeight(), 1); - Assert.assertFalse(it.next()); - } - - @Test - public void twoItemSketchForIterator() { - KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - sketch.update(1); - sketch.update(2); - QuantilesDoublesSketchIteratorAPI itr = sketch.iterator(); - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 2.0); - assertEquals(itr.getWeight(), 1); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 1.0); - assertEquals(itr.getWeight(), 1); - } - - @Test - public void twoItemSketchForSortedViewIterator() { - KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - sketch.update(1); - sketch.update(2); - DoublesSortedViewIterator itr = sketch.getSortedView().iterator(); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 1.0); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 0); - assertEquals(itr.getNaturalRank(INCLUSIVE), 1); - assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0); - assertEquals(itr.getNormalizedRank(INCLUSIVE), 0.5); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 2.0); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 1); - assertEquals(itr.getNaturalRank(INCLUSIVE), 2); - assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0.5); - assertEquals(itr.getNormalizedRank(INCLUSIVE), 1.0); - } - - @Test - public void bigSketches() { - for (int n = 1000; n < 100000; n += 2000) { - KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - for (int i = 0; i < n; i++) { - sketch.update(i); - } - QuantilesDoublesSketchIteratorAPI it = sketch.iterator(); - int count = 0; - int weight = 0; - while (it.next()) { - count++; - weight += (int)it.getWeight(); - } - Assert.assertEquals(count, sketch.getNumRetained()); - Assert.assertEquals(weight, n); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDoublesSketchSerDeTest.java b/src/test/java/org/apache/datasketches/kll/KllDoublesSketchSerDeTest.java deleted file mode 100644 index e0aa282af..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDoublesSketchSerDeTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDoublesSketch; -import org.testng.annotations.Test; - -public class KllDoublesSketchSerDeTest { - - @Test - public void serializeDeserializeEmpty() { - final int N = 20; - - final KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance(N); - //Empty: from heap -> byte[] -> heap - final byte[] bytes = sk1.toByteArray(); - final KllDoublesSketch sk2 = KllDoublesSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sk1.getSerializedSizeBytes()); - assertTrue(sk2.isEmpty()); - assertEquals(sk2.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk2.getN(), sk1.getN()); - assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - try { sk2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - - //Empty: from heap -> byte[] -> off heap - final KllDoublesSketch sk3 = KllDoublesSketch.wrap(MemorySegment.ofArray(bytes)); - assertTrue(sk3.isEmpty()); - assertEquals(sk3.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk3.getN(), sk1.getN()); - assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - try { sk3.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk3.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap -> byte[] -> compare byte[] - final byte[] bytes2 = sk3.toByteArray(); - assertEquals(bytes, bytes2); - } - - @Test - public void serializeDeserializeOneValue() { - final KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance(); - sk1.update(1.0); - - //from heap -> byte[] -> heap - final byte[] bytes = sk1.toByteArray(); - final KllDoublesSketch sk2 = KllDoublesSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sk1.getSerializedSizeBytes()); - assertFalse(sk2.isEmpty()); - assertEquals(sk2.getNumRetained(), 1); - assertEquals(sk2.getN(), 1); - assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk2.getMinItem(), 1.0); - assertEquals(sk2.getMaxItem(), 1.0); - assertEquals(sk2.getSerializedSizeBytes(), Long.BYTES + Double.BYTES); - - //from heap -> byte[] -> off heap - final KllDoublesSketch sk3 = KllDoublesSketch.wrap(MemorySegment.ofArray(bytes)); - assertFalse(sk3.isEmpty()); - assertEquals(sk3.getNumRetained(), 1); - assertEquals(sk3.getN(), 1); - assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk3.getMinItem(), 1.0); - assertEquals(sk3.getMaxItem(), 1.0); - assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap -> byte[] -> compare byte[] - final byte[] bytes2 = sk3.toByteArray(); - assertEquals(bytes, bytes2); - } - - @Test - public void serializeDeserializeMultipleValues() { - final KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance(); - final int n = 1000; - for (int i = 0; i < n; i++) { - sk1.update(i); - } - assertEquals(sk1.getMinItem(), 0.0); - assertEquals(sk1.getMaxItem(), 999.0); - - //from heap -> byte[] -> heap - final byte[] bytes = sk1.toByteArray(); - final KllDoublesSketch sk2 = KllDoublesSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sk1.getSerializedSizeBytes()); - assertFalse(sk2.isEmpty()); - assertEquals(sk2.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk2.getN(), sk1.getN()); - assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk2.getMinItem(), sk1.getMinItem()); - assertEquals(sk2.getMaxItem(), sk1.getMaxItem()); - assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - - //from heap -> byte[] -> off heap - final KllDoublesSketch sk3 = KllDoublesSketch.wrap(MemorySegment.ofArray(bytes)); - assertFalse(sk3.isEmpty()); - assertEquals(sk3.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk3.getN(), sk1.getN()); - assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk3.getMinItem(), sk1.getMinItem()); - assertEquals(sk3.getMaxItem(), sk1.getMaxItem()); - assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap -> byte[] -> compare byte[] - final byte[] bytes2 = sk3.toByteArray(); - assertEquals(bytes, bytes2); - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDoublesSketchTest.java b/src/test/java/org/apache/datasketches/kll/KllDoublesSketchTest.java deleted file mode 100644 index f2706af79..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDoublesSketchTest.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.Math.min; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_DOUBLES_SKETCH; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDoublesSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllSketch; -import org.apache.datasketches.quantilescommon.DoublesSortedView; -import org.apache.datasketches.quantilescommon.DoublesSortedViewIterator; -import org.testng.annotations.Test; - -public class KllDoublesSketchTest { - private static final String LS = System.getProperty("line.separator"); - private static final double PMF_EPS_FOR_K_8 = KllSketch.getNormalizedRankError(8, true); - private static final double PMF_EPS_FOR_K_128 = KllSketch.getNormalizedRankError(128, true); - private static final double PMF_EPS_FOR_K_256 = KllSketch.getNormalizedRankError(256, true); - private static final double NUMERIC_NOISE_TOLERANCE = 1E-6; - - @Test - public void empty() { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - sketch.update(Double.NaN); // this must not change anything - assertTrue(sketch.isEmpty()); - assertEquals(sketch.getN(), 0); - assertEquals(sketch.getNumRetained(), 0); - try { sketch.getRank(0); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantile(0.5); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantiles(new double[] {0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getPMF(new double[] {0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getCDF(new double[] {0}); fail(); } catch (final SketchesArgumentException e) {} - assertNotNull(sketch.toString(true, true)); - assertNotNull(sketch.toString()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantileInvalidArg() { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - sketch.update(1); - sketch.getQuantile(-1.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantilesInvalidArg() { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - sketch.update(1); - sketch.getQuantiles(new double[] {2.0}); - } - - @Test - public void oneValue() { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - sketch.update(1); - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getN(), 1); - assertEquals(sketch.getNumRetained(), 1); - assertEquals(sketch.getRank(0.0, EXCLUSIVE), 0.0); - assertEquals(sketch.getRank(1.0, EXCLUSIVE), 0.0); - assertEquals(sketch.getRank(2.0, EXCLUSIVE), 1.0); - assertEquals(sketch.getRank(0.0, INCLUSIVE), 0.0); - assertEquals(sketch.getRank(1.0, INCLUSIVE), 1.0); - assertEquals(sketch.getRank(2.0, INCLUSIVE), 1.0); - assertEquals(sketch.getMinItem(), 1.0); - assertEquals(sketch.getMaxItem(), 1.0); - assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 1.0); - assertEquals(sketch.getQuantile(0.5, INCLUSIVE), 1.0); - } - - @Test - public void tenValues() { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= 10; i++) { sketch.update(i); } - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getN(), 10); - assertEquals(sketch.getNumRetained(), 10); - for (int i = 1; i <= 10; i++) { - assertEquals(sketch.getRank(i, EXCLUSIVE), (i - 1) / 10.0); - assertEquals(sketch.getRank(i, INCLUSIVE), i / 10.0); - } - final double[] qArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - double[] rOut = sketch.getRanks(qArr); //inclusive - for (int i = 0; i < qArr.length; i++) { - assertEquals(rOut[i], (i + 1) / 10.0); - } - rOut = sketch.getRanks(qArr, EXCLUSIVE); //exclusive - for (int i = 0; i < qArr.length; i++) { - assertEquals(rOut[i], i / 10.0); - } - - for (int i = 0; i >= 10; i++) { - final double rank = i/10.0; - double q = rank == 1.0 ? i : i + 1; - assertEquals(sketch.getQuantile(rank, EXCLUSIVE), q); - q = rank == 0 ? i + 1.0 : i; - assertEquals(sketch.getQuantile(rank, INCLUSIVE), q); - } - - { - // getQuantile() and getQuantiles() equivalence EXCLUSIVE - final double[] quantiles = - sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}, EXCLUSIVE); - for (int i = 0; i <= 10; i++) { - assertEquals(sketch.getQuantile(i / 10.0, EXCLUSIVE), quantiles[i]); - } - } - { - // getQuantile() and getQuantiles() equivalence INCLUSIVE - final double[] quantiles = - sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}, INCLUSIVE); - for (int i = 0; i <= 10; i++) { - assertEquals(sketch.getQuantile(i / 10.0, INCLUSIVE), quantiles[i]); - } - } - } - - @Test - public void manyValuesEstimationMode() { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - final int n = 1_000_000; - - for (int i = 0; i < n; i++) { - sketch.update(i); - } - assertEquals(sketch.getN(), n); - - // test getRank - for (int i = 0; i < n; i++) { - final double trueRank = (double) i / n; - assertEquals(sketch.getRank(i), trueRank, PMF_EPS_FOR_K_256, "for value " + i); - } - - // test getPMF - final double[] pmf = sketch.getPMF(new double[] {n / 2.0}); // split at median - assertEquals(pmf.length, 2); - assertEquals(pmf[0], 0.5, PMF_EPS_FOR_K_256); - assertEquals(pmf[1], 0.5, PMF_EPS_FOR_K_256); - - assertEquals(sketch.getMinItem(), 0.0); // min value is exact - assertEquals(sketch.getMaxItem(), n - 1.0); // max value is exact - - // check at every 0.1 percentage point - final double[] fractions = new double[1001]; - final double[] reverseFractions = new double[1001]; // check that ordering doesn't matter - for (int i = 0; i <= 1000; i++) { - fractions[i] = (double) i / 1000; - reverseFractions[1000 - i] = fractions[i]; - } - final double[] quantiles = sketch.getQuantiles(fractions); - final double[] reverseQuantiles = sketch.getQuantiles(reverseFractions); - double previousQuantile = 0; - for (int i = 0; i <= 1000; i++) { - final double quantile = sketch.getQuantile(fractions[i]); - assertEquals(quantile, quantiles[i]); - assertEquals(quantile, reverseQuantiles[1000 - i]); - assertTrue(previousQuantile <= quantile); - previousQuantile = quantile; - } - } - - @Test - public void getRankGetCdfGetPmfConsistency() { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - final int n = 1000; - final double[] values = new double[n]; - for (int i = 0; i < n; i++) { - sketch.update(i); - values[i] = i; - } - { // inclusive = false (default) - final double[] ranks = sketch.getCDF(values); - final double[] pmf = sketch.getPMF(values); - double sumPmf = 0; - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i]), NUMERIC_NOISE_TOLERANCE, - "rank vs CDF for value " + i); - sumPmf += pmf[i]; - assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i); - } - sumPmf += pmf[n]; - assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE); - assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE); - } - { // inclusive = true - final double[] ranks = sketch.getCDF(values, INCLUSIVE); - final double[] pmf = sketch.getPMF(values, INCLUSIVE); - double sumPmf = 0; - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i], INCLUSIVE), NUMERIC_NOISE_TOLERANCE, - "rank vs CDF for value " + i); - sumPmf += pmf[i]; - assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i); - } - sumPmf += pmf[n]; - assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE); - assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE); - } - } - - @Test - public void merge() { - final KllDoublesSketch sketch1 = KllDoublesSketch.newHeapInstance(); - final KllDoublesSketch sketch2 = KllDoublesSketch.newHeapInstance(); - final int n = 10000; - for (int i = 0; i < n; i++) { - sketch1.update(i * 1.0); - sketch2.update(((2 * n) - i - 1) * 1.0); - } - - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), (n - 1) * 1.0); - - assertEquals(sketch2.getMinItem(), n * 1.0); - assertEquals(sketch2.getMaxItem(), ((2 * n) - 1) * 1.0); - - sketch1.merge(sketch2); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2L * n); - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), ((2 * n) - 1) * 1.0); - assertEquals(sketch1.getQuantile(0.5), n * 1.0, 2 * n * PMF_EPS_FOR_K_256); - } - - @Test - public void mergeLowerK() { - final KllDoublesSketch sketch1 = KllDoublesSketch.newHeapInstance(256); - final KllDoublesSketch sketch2 = KllDoublesSketch.newHeapInstance(128); - final int n = 10000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - sketch2.update((2 * n) - i - 1); - } - - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), n - 1); - - assertEquals(sketch2.getMinItem(), n); - assertEquals(sketch2.getMaxItem(), (2.0 * n) - 1.0); - - assertTrue(sketch1.getNormalizedRankError(false) < sketch2.getNormalizedRankError(false)); - assertTrue(sketch1.getNormalizedRankError(true) < sketch2.getNormalizedRankError(true)); - sketch1.merge(sketch2); - - // sketch1 must get "contaminated" by the lower K in sketch2 - assertEquals(sketch1.getNormalizedRankError(false), sketch2.getNormalizedRankError(false)); - assertEquals(sketch1.getNormalizedRankError(true), sketch2.getNormalizedRankError(true)); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2 * n); - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), (2.0 * n) - 1.0); - assertEquals(sketch1.getQuantile(0.5), n, 2 * n * PMF_EPS_FOR_K_128); - } - - @Test - public void mergeEmptyLowerK() { - final KllDoublesSketch sketch1 = KllDoublesSketch.newHeapInstance(256); - final KllDoublesSketch sketch2 = KllDoublesSketch.newHeapInstance(128); - final int n = 10_000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - - // rank error should not be affected by a merge with an empty sketch with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), n - 1.0); - assertEquals(sketch1.getQuantile(0.5), n / 2.0, n * PMF_EPS_FOR_K_256); - - //merge the other way - sketch2.merge(sketch1); - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), 0.0); - assertEquals(sketch1.getMaxItem(), n - 1.0); - assertEquals(sketch1.getQuantile(0.5), n / 2.0, n * PMF_EPS_FOR_K_256); - } - - @Test - public void mergeExactModeLowerK() { - final KllDoublesSketch sketch1 = KllDoublesSketch.newHeapInstance(256); - final KllDoublesSketch sketch2 = KllDoublesSketch.newHeapInstance(128); - final int n = 10000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - sketch2.update(1); - - // rank error should not be affected by a merge with a sketch in exact mode with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - } - - @Test - public void mergeMinMinValueFromOther() { - final KllDoublesSketch sketch1 = KllDoublesSketch.newHeapInstance(); - final KllDoublesSketch sketch2 = KllDoublesSketch.newHeapInstance(); - sketch1.update(1); - sketch2.update(2); - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), 1.0); - } - - @Test - public void mergeMinAndMaxFromOther() { - final KllDoublesSketch sketch1 = KllDoublesSketch.newHeapInstance(); - for (int i = 1; i <= 1_000_000; i++) { - sketch1.update(i); - } - final KllDoublesSketch sketch2 = KllDoublesSketch.newHeapInstance(10); - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), 1.0); - assertEquals(sketch2.getMaxItem(), 1_000_000.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooSmall() { - KllDoublesSketch.newHeapInstance(KllSketch.DEFAULT_M - 1); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooLarge() { - KllDoublesSketch.newHeapInstance(KllSketch.MAX_K + 1); - } - - @Test - public void minK() { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(KllSketch.DEFAULT_M); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getK(), KllSketch.DEFAULT_M); - assertEquals(sketch.getQuantile(0.5), 500.0, 1000 * PMF_EPS_FOR_K_8); - } - - @Test - public void maxK() { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(KllSketch.MAX_K); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getK(), KllSketch.MAX_K); - assertEquals(sketch.getQuantile(0.5), 500, 1000 * PMF_EPS_FOR_K_256); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void outOfOrderSplitPoints() { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - sketch.update(0); - sketch.getCDF(new double[] {1.0, 0.0}); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void nanSplitPoint() { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - sketch.update(0); - sketch.getCDF(new double[] {Double.NaN}); - } - - @Test - public void checkReset() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final long n1 = sk.getN(); - final double min1 = sk.getMinItem(); - final double max1 = sk.getMaxItem(); - sk.reset(); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final long n2 = sk.getN(); - final double min2 = sk.getMinItem(); - final double max2 = sk.getMaxItem(); - assertEquals(n2, n1); - assertEquals(min2, min1); - assertEquals(max2, max1); - } - - @Test - public void checkReadOnlyUpdate() { - final KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance(20); - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(seg); - try { sk2.update(1); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkNewDirectInstanceAndSize() { - final MemorySegment wseg = MemorySegment.ofArray(new byte[3000]); - KllDoublesSketch.newDirectInstance(wseg); - try { KllDoublesSketch.newDirectInstance(null); fail(); } - catch (final NullPointerException e) { } - final int updateSize = KllSketch.getMaxSerializedSizeBytes(200, 0, KLL_DOUBLES_SKETCH, true); - final int compactSize = KllSketch.getMaxSerializedSizeBytes(200, 0, KLL_DOUBLES_SKETCH, false); - assertTrue(compactSize < updateSize); - } - - @Test - public void sortedView() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(); - sk.update(3); - sk.update(1); - sk.update(2); - - final DoublesSortedView view = sk.getSortedView(); - final DoublesSortedViewIterator itr = view.iterator(); - assertEquals(itr.next(), true); - assertEquals(itr.getQuantile(), 1); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 0); - assertEquals(itr.getNaturalRank(INCLUSIVE), 1); - assertEquals(itr.next(), true); - assertEquals(itr.getQuantile(), 2); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 1); - assertEquals(itr.getNaturalRank(INCLUSIVE), 2); - assertEquals(itr.next(), true); - assertEquals(itr.getQuantile(), 3); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 2); - assertEquals(itr.getNaturalRank(INCLUSIVE), 3); - assertEquals(itr.next(), false); - } - - @Test //also visual - public void checkCDF_PDF() { - final double[] cdfI = {.25, .50, .75, 1.0, 1.0 }; - final double[] cdfE = {0.0, .25, .50, .75, 1.0 }; - final double[] pmfI = {.25, .25, .25, .25, 0.0 }; - final double[] pmfE = {0.0, .25, .25, .25, .25 }; - final double toll = 1E-10; - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(); - final double[] doublesIn = {10, 20, 30, 40}; - for (int i = 0; i < doublesIn.length; i++) { sketch.update(doublesIn[i]); } - final double[] sp = { 10, 20, 30, 40 }; - println("SplitPoints:"); - for (int i = 0; i < sp.length; i++) { - printf("%10.2f", sp[i]); - } - println(""); - println("INCLUSIVE:"); - double[] cdf = sketch.getCDF(sp, INCLUSIVE); - double[] pmf = sketch.getPMF(sp, INCLUSIVE); - printf("%10s%10s" + LS, "CDF", "PMF"); - for (int i = 0; i < cdf.length; i++) { - printf("%10.2f%10.2f" + LS, cdf[i], pmf[i]); - assertEquals(cdf[i], cdfI[i], toll); - assertEquals(pmf[i], pmfI[i], toll); - } - println("EXCLUSIVE"); - cdf = sketch.getCDF(sp, EXCLUSIVE); - pmf = sketch.getPMF(sp, EXCLUSIVE); - printf("%10s%10s" + LS, "CDF", "PMF"); - for (int i = 0; i < cdf.length; i++) { - printf("%10.2f%10.2f" + LS, cdf[i], pmf[i]); - assertEquals(cdf[i], cdfE[i], toll); - assertEquals(pmf[i], pmfE[i], toll); - } - } - - @Test - public void checkWrapCase1Doubles() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment seg = MemorySegment.ofArray(sk.toByteArray()).asReadOnly(); - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(seg); - - assertTrue(seg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkWritableWrapCase6And2Doubles() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment wseg = MemorySegment.ofArray(KllHelper.toByteArray(sk, true)); - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(wseg); - - assertFalse(wseg.isReadOnly()); - assertFalse(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkKllSketchCase5Doubles() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(wseg); - - assertFalse(wseg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkKllSketchCase3Doubles() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment seg = MemorySegment.ofArray(KllHelper.toByteArray(sk, true)).asReadOnly(); - final MemorySegment wseg = seg; - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(wseg); - - assertTrue(wseg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkKllSketchCase7Doubles() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment seg = MemorySegment.ofArray(KllHelper.toByteArray(sk, true)).asReadOnly(); - final MemorySegment wseg = seg; - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(wseg); - - assertTrue(wseg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkReadOnlyExceptions() { - final int[] intArr = {}; - final int intV = 2; - final int idx = 1; - final KllDoublesSketch sk1 = KllDoublesSketch.newHeapInstance(20); - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - final KllDoublesSketch sk2 = KllDoublesSketch.wrap(seg); - try { sk2.setLevelsArray(intArr); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setLevelsArrayAt(idx,intV); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkIsSameResource() { - final int cap = 128; - final MemorySegment wseg = MemorySegment.ofArray(new byte[cap]); - final MemorySegment slice1 = wseg.asSlice(0, 64); - final MemorySegment slice2 = wseg.asSlice(64, 64); - assertFalse(slice1 == slice2); - assertFalse(MemorySegmentStatus.isSameResource(slice1, slice2)); - - final MemorySegment slice3 = wseg.asSlice(0, 64); - assertFalse(slice1 == slice3); - assertTrue(MemorySegmentStatus.isSameResource(slice1, slice3)); - - final byte[] byteArr1 = KllDoublesSketch.newHeapInstance(20).toByteArray(); - MemorySegment.copy(byteArr1, 0, slice1, JAVA_BYTE, 0, byteArr1.length); - final KllDoublesSketch sk1 = KllDoublesSketch.wrap(slice1); - - final byte[] byteArr2 = KllDoublesSketch.newHeapInstance(20).toByteArray(); - MemorySegment.copy(byteArr2, 0, slice2, JAVA_BYTE, 0, byteArr2.length); - assertFalse(sk1.isSameResource(slice2)); - - final byte[] byteArr3 = KllDoublesSketch.newHeapInstance(20).toByteArray(); - MemorySegment.copy(byteArr3, 0, slice3, JAVA_BYTE, 0, byteArr3.length); - assertTrue(sk1.isSameResource(slice3)); - } - - @Test - public void checkSortedViewAfterReset() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20); - sk.update(1.0); - final DoublesSortedView sv = sk.getSortedView(); - final double dsv = sv.getQuantile(1.0, INCLUSIVE); - assertEquals(dsv, 1.0); - sk.reset(); - try { sk.getSortedView(); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkVectorUpdate() { - final boolean withLevels = false; - final boolean withLevelsAndItems = true; - final int k = 20; - final int n = 108; - final int maxVsz = 40; //max vector size - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - int j = 1; - int rem; - while ((rem = (n - j) + 1) > 0) { - final int vecSz = min(rem, maxVsz); - final double[] v = new double[vecSz]; - for (int i = 0; i < vecSz; i++) { v[i] = j++; } - sk.update(v, 0, vecSz); - } - println(LS + "#<<< END STATE # >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - println(""); - assertEquals(sk.getN(), 108); - assertEquals(sk.getMaxItem(), 108.0); - assertEquals(sk.getMinItem(), 1.0); - } - - @Test - public void vectorizedUpdates() { - final int trials = 1; - final int M = 1; //number of vectors - final int N = 1000; //vector size - final int K = 256; - final double[] values = new double[N]; - double vIn = 1.0; - long totN = 0; - final long startTime = System.nanoTime(); - for (int t = 0; t < trials; t++) { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(K); - for (int m = 0; m < M; m++) { - for (int n = 0; n < N; n++) { - values[n] = vIn++; //fill vector - } - sketch.update(values, 0, N); //vector input - } - totN = sketch.getN(); - assertEquals(totN, M * N); - assertEquals(sketch.getMinItem(), 1.0); - assertEquals(sketch.getMaxItem(), totN); - assertEquals(sketch.getQuantile(0.5), totN / 2.0, totN * PMF_EPS_FOR_K_256 * 2.0); //wider tolerance - } - final long runTime = System.nanoTime() - startTime; - println("Vectorized Updates"); - printf(" Vector size : %,12d" + LS, N); - printf(" Num Vectors : %,12d" + LS, M); - printf(" Total Input : %,12d" + LS, totN); - printf(" Run Time mS : %,12.3f" + LS, runTime / 1e6); - final double trialTime = runTime / (1e6 * trials); - printf(" mS / Trial : %,12.3f" + LS, trialTime); - final double updateTime = runTime / (1.0 * totN * trials); - printf(" nS / Update : %,12.3f" + LS, updateTime); - } - - @Test - public void nonVectorizedUpdates() { - final int trials = 1; - final int M = 1; //number of vectors - final int N = 1000; //vector size - final int K = 256; - final double[] values = new double[N]; - double vIn = 1.0; - long totN = 0; - final long startTime = System.nanoTime(); - for (int t = 0; t < trials; t++) { - final KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(K); - for (int m = 0; m < M; m++) { - for (int n = 0; n < N; n++) { - values[n] = vIn++; //fill vector - } - for (int i = 0; i < N; i++) { - sketch.update(values[i]); //single item input - } - } - totN = sketch.getN(); - assertEquals(totN, M * N); - assertEquals(sketch.getMinItem(), 1.0); - assertEquals(sketch.getMaxItem(), totN); - assertEquals(sketch.getQuantile(0.5), totN / 2.0, totN * PMF_EPS_FOR_K_256 * 2.0); //wider tolerance - } - final long runTime = System.nanoTime() - startTime; - println("Vectorized Updates"); - printf(" Vector size : %,12d" + LS, N); - printf(" Num Vectors : %,12d" + LS, M); - printf(" Total Input : %,12d" + LS, totN); - printf(" Run Time mS : %,12.3f" + LS, runTime / 1e6); - final double trialTime = runTime / (1e6 * trials); - printf(" mS / Trial : %,12.3f" + LS, trialTime); - final double updateTime = runTime / (1.0 * totN * trials); - printf(" nS / Update : %,12.3f" + LS, updateTime); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } -} diff --git a/src/test/java/org/apache/datasketches/kll/KllDoublesValidationTest.java b/src/test/java/org/apache/datasketches/kll/KllDoublesValidationTest.java deleted file mode 100644 index 6f19c0405..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllDoublesValidationTest.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.common.Util.isOdd; - -import org.apache.datasketches.kll.KllDoublesSketch; -import org.testng.Assert; -import org.testng.annotations.Test; - -/* A test record contains: - 0. testIndex - 1. K - 2. N - 3. stride (for generating the input) - 4. numLevels - 5. numSamples - 6. hash of the retained samples -*/ - -// These results are for the version that delays the roll up until the next value comes in. -// The @Test annotations have to be enabled to use this class and a section in KllDoublesHelper also -// needs to be enabled. -@SuppressWarnings("unused") -public class KllDoublesValidationTest { - - //Used only with manual running of checkTestResults(..) - private static final long[] correctResultsWithReset = { - 0, 200, 180, 3246533, 1, 180, 1098352976109474698L, - 1, 200, 198, 8349603, 1, 198, 686681527497651888L, - 2, 200, 217, 676491, 2, 117, 495856134049157644L, - 3, 200, 238, 3204507, 2, 138, 44453438498725402L, - 4, 200, 261, 2459373, 2, 161, 719830627391926938L, - 5, 200, 287, 5902143, 2, 187, 389303173170515580L, - 6, 200, 315, 5188793, 2, 215, 985218890825795000L, - 7, 200, 346, 801923, 2, 246, 589362992166904413L, - 8, 200, 380, 2466269, 2, 280, 1081848693781775853L, - 9, 200, 418, 5968041, 2, 318, 533825689515788397L, - 10, 200, 459, 3230027, 2, 243, 937332670315558786L, - 11, 200, 504, 5125875, 2, 288, 1019197831515566845L, - 12, 200, 554, 4195571, 3, 230, 797351479150148224L, - 13, 200, 609, 2221181, 3, 285, 451246040374318529L, - 14, 200, 669, 5865503, 3, 345, 253851269470815909L, - 15, 200, 735, 831703, 3, 411, 491974970526372303L, - 16, 200, 808, 4830785, 3, 327, 1032107507126916277L, - 17, 200, 888, 1356257, 3, 407, 215225420986342944L, - 18, 200, 976, 952071, 3, 417, 600280049738270697L, - 19, 200, 1073, 6729833, 3, 397, 341758522977365969L, - 20, 200, 1180, 6017925, 3, 406, 1080227312339182949L, - 21, 200, 1298, 4229891, 3, 401, 1092460534756675086L, - 22, 200, 1427, 7264889, 4, 320, 884533400696890024L, - 23, 200, 1569, 5836327, 4, 462, 660575800011134382L, - 24, 200, 1725, 5950087, 4, 416, 669373957401387528L, - 25, 200, 1897, 2692555, 4, 406, 607308667566496888L, - 26, 200, 2086, 1512443, 4, 459, 744260340112029032L, - 27, 200, 2294, 2681171, 4, 434, 199120609113802485L, - 28, 200, 2523, 3726521, 4, 450, 570993497599288304L, - 29, 200, 2775, 2695247, 4, 442, 306717093329516310L, - 30, 200, 3052, 5751175, 5, 400, 256024589545754217L, - 31, 200, 3357, 1148897, 5, 514, 507276662329207479L, - 32, 200, 3692, 484127, 5, 457, 1082660223488175122L, - 33, 200, 4061, 6414559, 5, 451, 620820308918522117L, - 34, 200, 4467, 5587461, 5, 466, 121975084804459305L, - 35, 200, 4913, 1615017, 5, 483, 152986529342916376L, - 36, 200, 5404, 6508535, 5, 492, 858526451332425960L, - 37, 200, 5944, 2991657, 5, 492, 624906434274621995L, - 38, 200, 6538, 6736565, 6, 511, 589153542019036049L, - 39, 200, 7191, 1579893, 6, 507, 10255312374117907L, - 40, 200, 7910, 412509, 6, 538, 570863587164194186L, - 41, 200, 8701, 1112089, 6, 477, 553100668286355347L, - 42, 200, 9571, 1258813, 6, 526, 344845406406036297L, - 43, 200, 10528, 1980049, 6, 508, 411846569527905064L, - 44, 200, 11580, 2167127, 6, 520, 966876726203675488L, - 45, 200, 12738, 1975435, 7, 561, 724125506920592732L, - 46, 200, 14011, 4289627, 7, 560, 753686005174215572L, - 47, 200, 15412, 5384001, 7, 494, 551637841878573955L, - 48, 200, 16953, 2902685, 7, 560, 94602851752354802L, - 49, 200, 18648, 4806445, 7, 562, 597672400688514221L, - 50, 200, 20512, 2085, 7, 529, 417280161591969960L, - 51, 200, 22563, 6375939, 7, 558, 11300453985206678L, - 52, 200, 24819, 7837057, 7, 559, 283668599967437754L, - 53, 200, 27300, 6607975, 8, 561, 122183647493325363L, - 54, 200, 30030, 1519191, 8, 550, 1145227891427321202L, - 55, 200, 33033, 808061, 8, 568, 71070843834364939L, - 56, 200, 36336, 2653529, 8, 570, 450311772805359006L, - 57, 200, 39969, 2188957, 8, 561, 269670427054904115L, - 58, 200, 43965, 5885655, 8, 539, 1039064186324091890L, - 59, 200, 48361, 6185889, 8, 574, 178055275082387938L, - 60, 200, 53197, 208767, 9, 579, 139766040442973048L, - 61, 200, 58516, 2551345, 9, 569, 322655279254252950L, - 62, 200, 64367, 1950873, 9, 569, 101542216315768285L, - 63, 200, 70803, 2950429, 9, 582, 72294008568551853L, - 64, 200, 77883, 3993977, 9, 572, 299014330559512530L, - 65, 200, 85671, 428871, 9, 585, 491351721800568188L, - 66, 200, 94238, 6740849, 9, 577, 656204268858348899L, - 67, 200, 103661, 2315497, 9, 562, 829926273188300764L, - 68, 200, 114027, 5212835, 10, 581, 542222554617639557L, - 69, 200, 125429, 4213475, 10, 593, 713339189579860773L, - 70, 200, 137971, 2411583, 10, 592, 649651658985845357L, - 71, 200, 151768, 5243307, 10, 567, 1017459402785275179L, - 72, 200, 166944, 2468367, 10, 593, 115034451827634398L, - 73, 200, 183638, 2210923, 10, 583, 365735165000548572L, - 74, 200, 202001, 321257, 10, 591, 928479940794929153L, - 75, 200, 222201, 8185105, 11, 600, 780163958693677795L, - 76, 200, 244421, 6205349, 11, 598, 132454307780236135L, - 77, 200, 268863, 3165901, 11, 600, 369824066179493948L, - 78, 200, 295749, 2831723, 11, 595, 80968411797441666L, - 79, 200, 325323, 464193, 11, 594, 125773061716381917L, - 80, 200, 357855, 7499035, 11, 576, 994150328579932916L, - 81, 200, 393640, 1514479, 11, 596, 111092193875842594L, - 82, 200, 433004, 668493, 12, 607, 497338041653302784L, - 83, 200, 476304, 3174931, 12, 606, 845986926165673887L, - 84, 200, 523934, 914611, 12, 605, 354993119685278556L, - 85, 200, 576327, 7270385, 12, 602, 937679531753465428L, - 86, 200, 633959, 1956979, 12, 598, 659413123921208266L, - 87, 200, 697354, 3137635, 12, 606, 874228711599628459L, - 88, 200, 767089, 214923, 12, 608, 1077644643342432307L, - 89, 200, 843797, 3084545, 13, 612, 79317113064339979L, - 90, 200, 928176, 7800899, 13, 612, 357414065779796772L, - 91, 200, 1020993, 6717253, 13, 615, 532723577905833296L, - 92, 200, 1123092, 5543015, 13, 614, 508695073250223746L, - 93, 200, 1235401, 298785, 13, 616, 34344606952783179L, - 94, 200, 1358941, 4530313, 13, 607, 169924026179364121L, - 95, 200, 1494835, 4406457, 13, 612, 1026773494313671061L, - 96, 200, 1644318, 1540983, 13, 614, 423454640036650614L, - 97, 200, 1808749, 7999631, 14, 624, 466122870338520329L, - 98, 200, 1989623, 4295537, 14, 621, 609309853701283445L, - 99, 200, 2188585, 7379971, 14, 622, 141739898871015642L, - 100, 200, 2407443, 6188931, 14, 621, 22515080776738923L, - 101, 200, 2648187, 6701239, 14, 619, 257441864177795548L, - 102, 200, 2913005, 2238709, 14, 623, 867028825821064773L, - 103, 200, 3204305, 5371075, 14, 625, 1110615471273395112L, - 104, 200, 3524735, 7017341, 15, 631, 619518037415974467L, - 105, 200, 3877208, 323337, 15, 633, 513230912593541122L, - 106, 200, 4264928, 6172471, 15, 628, 885861662583325072L, - 107, 200, 4691420, 5653803, 15, 633, 754052473303005204L, - 108, 200, 5160562, 1385265, 15, 630, 294993765757975100L, - 109, 200, 5676618, 4350899, 15, 617, 1073144684944932303L, - 110, 200, 6244279, 1272235, 15, 630, 308982934296855020L, - 111, 200, 6868706, 1763939, 16, 638, 356231694823272867L, - 112, 200, 7555576, 3703411, 16, 636, 20043268926300101L, - 113, 200, 8311133, 6554171, 16, 637, 121111429906734123L, - }; - - private static int[] makeInputArray(int n, int stride) { - assert isOdd(stride); - int mask = (1 << 23) - 1; // because library items are single-precision floats - int cur = 0; - int[] arr = new int[n]; - for (int i = 0; i < n; i++) { - cur += stride; - cur &= mask; - arr[i] = cur; - } - return arr; - } - - //@Test //only enabled to test the above makeInputArray(..) - public void testMakeInputArray() { - final int[] array = { 3654721, 7309442, 2575555, 6230276, 1496389, 5151110 }; - Assert.assertEquals(makeInputArray(6, 3654721), array); - } - - private static long simpleHashOfSubArray(final double[] arr, final int start, final int subLength) { - final long multiplier = 738219921; // an arbitrary odd 30-bit number - final long mask60 = (1L << 60) - 1; - long accum = 0; - for (int i = start; i < (start + subLength); i++) { - accum += (long) arr[i]; - accum *= multiplier; - accum &= mask60; - accum ^= accum >> 30; - } - return accum; - } - - //@Test //only enabled to test the above simpleHashOfSubArray(..) - public void testHash() { - double[] array = { 907500, 944104, 807020, 219921, 678370, 955217, 426885 }; - Assert.assertEquals(simpleHashOfSubArray(array, 1, 5), 1141543353991880193L); - } - - /* - * Please note that this test should be run with a modified version of KllDoublesHelper - * that chooses directions alternately instead of randomly. - * See the instructions at the bottom of that class. - */ - - //@Test //NEED TO ENABLE HERE AND BELOW FOR VALIDATION - public void checkTestResults() { - int numTests = correctResultsWithReset.length / 7; - for (int testI = 0; testI < numTests; testI++) { - //KllDoublesHelper.nextOffset = 0; //NEED TO ENABLE - assert (int) correctResultsWithReset[7 * testI] == testI; - int k = (int) correctResultsWithReset[(7 * testI) + 1]; - int n = (int) correctResultsWithReset[(7 * testI) + 2]; - int stride = (int) correctResultsWithReset[(7 * testI) + 3]; - int[] inputArray = makeInputArray(n, stride); - KllDoublesSketch sketch = KllDoublesSketch.newHeapInstance(k); - for (int i = 0; i < n; i++) { - sketch.update(inputArray[i]); - } - int numLevels = sketch.getNumLevels(); - int numSamples = sketch.getNumRetained(); - int[] levels = sketch.getLevelsArray(sketch.sketchStructure); - long hashedSamples = simpleHashOfSubArray(sketch.getDoubleItemsArray(), levels[0], numSamples); - System.out.print(testI); - assert correctResultsWithReset[(7 * testI) + 4] == numLevels; - assert correctResultsWithReset[(7 * testI) + 5] == numSamples; - assert correctResultsWithReset[7 * testI + 6] == hashedSamples; - if (correctResultsWithReset[(7 * testI) + 6] == hashedSamples) { - System.out.println(" pass"); - } else { - System.out.print(" " + correctResultsWithReset[(7 * testI) + 6] + " != " + hashedSamples); - System.out.println(" fail"); - System.out.println(sketch.toString(true, true)); - break; - } - } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllFloatsSketchIteratorTest.java b/src/test/java/org/apache/datasketches/kll/KllFloatsSketchIteratorTest.java deleted file mode 100644 index f89253b21..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllFloatsSketchIteratorTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import org.apache.datasketches.kll.KllFloatsSketch; -import org.apache.datasketches.quantilescommon.FloatsSortedViewIterator; -import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class KllFloatsSketchIteratorTest { - - @Test - public void emptySketch() { - KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - QuantilesFloatsSketchIterator it = sketch.iterator(); - Assert.assertFalse(it.next()); - } - - @Test - public void oneItemSketch() { - KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - sketch.update(1); - QuantilesFloatsSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getQuantile(), 1.0f); - Assert.assertEquals(it.getWeight(), 1); - Assert.assertFalse(it.next()); - } - - @Test - public void twoItemSketchForIterator() { - KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - sketch.update(1); - sketch.update(2); - QuantilesFloatsSketchIterator itr = sketch.iterator(); - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 2.0f); - assertEquals(itr.getWeight(), 1); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 1.0f); - assertEquals(itr.getWeight(), 1); - } - - @Test - public void twoItemSketchForSortedViewIterator() { - KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - sketch.update(1); - sketch.update(2); - FloatsSortedViewIterator itr = sketch.getSortedView().iterator(); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 1.0f); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 0); - assertEquals(itr.getNaturalRank(INCLUSIVE), 1); - assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0); - assertEquals(itr.getNormalizedRank(INCLUSIVE), 0.5); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 2.0f); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 1); - assertEquals(itr.getNaturalRank(INCLUSIVE), 2); - assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0.5); - assertEquals(itr.getNormalizedRank(INCLUSIVE), 1.0); - } - - @Test - public void bigSketches() { - for (int n = 1000; n < 100000; n += 2000) { - KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - for (int i = 0; i < n; i++) { - sketch.update(i); - } - QuantilesFloatsSketchIterator it = sketch.iterator(); - int count = 0; - int weight = 0; - while (it.next()) { - count++; - weight += (int)it.getWeight(); - } - Assert.assertEquals(count, sketch.getNumRetained()); - Assert.assertEquals(weight, n); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllFloatsSketchSerDeTest.java b/src/test/java/org/apache/datasketches/kll/KllFloatsSketchSerDeTest.java deleted file mode 100644 index aa05ca0a2..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllFloatsSketchSerDeTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllFloatsSketch; -import org.testng.annotations.Test; - -public class KllFloatsSketchSerDeTest { - - @Test - public void serializeDeserializeEmpty() { - final int N = 20; - - final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(N); - //Empty: from heap -> byte[] -> heap - final byte[] bytes = sk1.toByteArray(); - final KllFloatsSketch sk2 = KllFloatsSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sk1.getSerializedSizeBytes()); - assertTrue(sk2.isEmpty()); - assertEquals(sk2.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk2.getN(), sk1.getN()); - assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - try { sk2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - - //Empty: from heap -> byte[] -> off heap - final KllFloatsSketch sk3 = KllFloatsSketch.wrap(MemorySegment.ofArray(bytes)); - assertTrue(sk3.isEmpty()); - assertEquals(sk3.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk3.getN(), sk1.getN()); - assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - try { sk3.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk3.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap -> byte[] -> compare byte[] - final byte[] bytes2 = sk3.toByteArray(); - assertEquals(bytes, bytes2); - } - - @Test - public void serializeDeserializeOneValue() { - final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(); - sk1.update(1); - - //from heap -> byte[] -> heap - final byte[] bytes = sk1.toByteArray(); - final KllFloatsSketch sk2 = KllFloatsSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sk1.getSerializedSizeBytes()); - assertFalse(sk2.isEmpty()); - assertEquals(sk2.getNumRetained(), 1); - assertEquals(sk2.getN(), 1); - assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk2.getMinItem(), 1.0F); - assertEquals(sk2.getMaxItem(), 1.0F); - assertEquals(sk2.getSerializedSizeBytes(), Long.BYTES + Float.BYTES); - - //from heap -> byte[] -> off heap - final KllFloatsSketch sk3 = KllFloatsSketch.wrap(MemorySegment.ofArray(bytes)); - assertFalse(sk3.isEmpty()); - assertEquals(sk3.getNumRetained(), 1); - assertEquals(sk3.getN(), 1); - assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk3.getMinItem(), 1.0f); - assertEquals(sk3.getMaxItem(), 1.0f); - assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap -> byte[] -> compare byte[] - final byte[] bytes2 = sk3.toByteArray(); - assertEquals(bytes, bytes2); - } - - @Test - public void serializeDeserializeMultipleValues() { - final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(); - final int n = 1000; - for (int i = 0; i < n; i++) { - sk1.update(i); - } - assertEquals(sk1.getMinItem(), 0.0f); - assertEquals(sk1.getMaxItem(), 999.0f); - - //from heap -> byte[] -> heap - final byte[] bytes = sk1.toByteArray(); - final KllFloatsSketch sk2 = KllFloatsSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sk1.getSerializedSizeBytes()); - assertFalse(sk2.isEmpty()); - assertEquals(sk2.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk2.getN(), sk1.getN()); - assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk2.getMinItem(), sk1.getMinItem()); - assertEquals(sk2.getMaxItem(), sk1.getMaxItem()); - assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - - //from heap -> byte[] -> off heap - final KllFloatsSketch sk3 = KllFloatsSketch.wrap(MemorySegment.ofArray(bytes)); - assertFalse(sk3.isEmpty()); - assertEquals(sk3.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk3.getN(), sk1.getN()); - assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk3.getMinItem(), sk1.getMinItem()); - assertEquals(sk3.getMaxItem(), sk1.getMaxItem()); - assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap -> byte[] -> compare byte[] - final byte[] bytes2 = sk3.toByteArray(); - assertEquals(bytes, bytes2); - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllFloatsSketchTest.java b/src/test/java/org/apache/datasketches/kll/KllFloatsSketchTest.java deleted file mode 100644 index 06d81bf09..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllFloatsSketchTest.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.Math.min; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_FLOATS_SKETCH; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllFloatsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllSketch; -import org.apache.datasketches.quantilescommon.FloatsSortedView; -import org.apache.datasketches.quantilescommon.FloatsSortedViewIterator; -import org.testng.annotations.Test; - -public class KllFloatsSketchTest { - private static final String LS = System.getProperty("line.separator"); - private static final double PMF_EPS_FOR_K_8 = KllSketch.getNormalizedRankError(8, true); - private static final double PMF_EPS_FOR_K_128 = KllSketch.getNormalizedRankError(128, true); - private static final double PMF_EPS_FOR_K_256 = KllSketch.getNormalizedRankError(256, true); - private static final double NUMERIC_NOISE_TOLERANCE = 1E-6; - - @Test - public void empty() { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - sketch.update(Float.NaN); // this must not change anything - assertTrue(sketch.isEmpty()); - assertEquals(sketch.getN(), 0); - assertEquals(sketch.getNumRetained(), 0); - try { sketch.getRank(0); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantile(0.5); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantiles(new double[] {0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getPMF(new float[] {0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getCDF(new float[] {0}); fail(); } catch (final SketchesArgumentException e) {} - assertNotNull(sketch.toString(true, true)); - assertNotNull(sketch.toString()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantileInvalidArg() { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - sketch.update(1); - sketch.getQuantile(-1.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantilesInvalidArg() { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - sketch.update(1); - sketch.getQuantiles(new double[] {2.0}); - } - - @Test - public void oneValue() { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - sketch.update(1); - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getN(), 1); - assertEquals(sketch.getNumRetained(), 1); - assertEquals(sketch.getRank(0.0f, EXCLUSIVE), 0.0); - assertEquals(sketch.getRank(1.0f, EXCLUSIVE), 0.0); - assertEquals(sketch.getRank(2.0f, EXCLUSIVE), 1.0); - assertEquals(sketch.getRank(0.0f, INCLUSIVE), 0.0); - assertEquals(sketch.getRank(1.0f, INCLUSIVE), 1.0); - assertEquals(sketch.getRank(2.0f, INCLUSIVE), 1.0); - assertEquals(sketch.getMinItem(), 1.0f); - assertEquals(sketch.getMaxItem(), 1.0f); - assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 1.0f); - assertEquals(sketch.getQuantile(0.5, INCLUSIVE), 1.0f); - } - - @Test - public void tenValues() { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= 10; i++) { sketch.update(i); } - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getN(), 10); - assertEquals(sketch.getNumRetained(), 10); - for (int i = 1; i <= 10; i++) { - assertEquals(sketch.getRank(i, EXCLUSIVE), (i - 1) / 10.0); - assertEquals(sketch.getRank(i, INCLUSIVE), i / 10.0); - } - final float[] qArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - double[] rOut = sketch.getRanks(qArr); //inclusive - for (int i = 0; i < qArr.length; i++) { - assertEquals(rOut[i], (i + 1) / 10.0); - } - rOut = sketch.getRanks(qArr, EXCLUSIVE); //exclusive - for (int i = 0; i < qArr.length; i++) { - assertEquals(rOut[i], i / 10.0); - } - - for (int i = 0; i >= 10; i++) { - final double rank = i/10.0; - float q = rank == 1.0 ? i : i + 1; - assertEquals(sketch.getQuantile(rank, EXCLUSIVE), q); - q = (float)(rank == 0 ? i + 1.0 : i); - assertEquals(sketch.getQuantile(rank, INCLUSIVE), q); - } - - { - // getQuantile() and getQuantiles() equivalence EXCLUSIVE - final float[] quantiles = - sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}, EXCLUSIVE); - for (int i = 0; i <= 10; i++) { - assertEquals(sketch.getQuantile(i / 10.0, EXCLUSIVE), quantiles[i]); - } - } - { - // getQuantile() and getQuantiles() equivalence INCLUSIVE - final float[] quantiles = - sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}, INCLUSIVE); - for (int i = 0; i <= 10; i++) { - assertEquals(sketch.getQuantile(i / 10.0, INCLUSIVE), quantiles[i]); - } - } - } - - @Test - public void manyValuesEstimationMode() { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - final int n = 1_000_000; - - for (int i = 0; i < n; i++) { - sketch.update(i); - } - assertEquals(sketch.getN(), n); - - // test getRank - for (int i = 0; i < n; i++) { - final double trueRank = (double) i / n; - assertEquals(sketch.getRank(i), trueRank, PMF_EPS_FOR_K_256, "for value " + i); - } - - // test getPMF - final double[] pmf = sketch.getPMF(new float[] {n / 2.0F}); // split at median - assertEquals(pmf.length, 2); - assertEquals(pmf[0], 0.5, PMF_EPS_FOR_K_256); - assertEquals(pmf[1], 0.5, PMF_EPS_FOR_K_256); - - assertEquals(sketch.getMinItem(), 0f); // min value is exact - assertEquals(sketch.getMaxItem(), n - 1f); // max value is exact - - // check at every 0.1 percentage point - final double[] fractions = new double[1001]; - final double[] reverseFractions = new double[1001]; // check that ordering doesn't matter - for (int i = 0; i <= 1000; i++) { - fractions[i] = (double) i / 1000; - reverseFractions[1000 - i] = fractions[i]; - } - final float[] quantiles = sketch.getQuantiles(fractions); - final float[] reverseQuantiles = sketch.getQuantiles(reverseFractions); - float previousQuantile = 0; - for (int i = 0; i <= 1000; i++) { - final float quantile = sketch.getQuantile(fractions[i]); - assertEquals(quantile, quantiles[i]); - assertEquals(quantile, reverseQuantiles[1000 - i]); - assertTrue(previousQuantile <= quantile); - previousQuantile = quantile; - } - } - - @Test - public void getRankGetCdfGetPmfConsistency() { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - final int n = 1000; - final float[] values = new float[n]; - for (int i = 0; i < n; i++) { - sketch.update(i); - values[i] = i; - } - { // inclusive = false (default) - final double[] ranks = sketch.getCDF(values); - final double[] pmf = sketch.getPMF(values); - double sumPmf = 0; - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i]), NUMERIC_NOISE_TOLERANCE, - "rank vs CDF for value " + i); - sumPmf += pmf[i]; - assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i); - } - sumPmf += pmf[n]; - assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE); - assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE); - } - { // inclusive = true - final double[] ranks = sketch.getCDF(values, INCLUSIVE); - final double[] pmf = sketch.getPMF(values, INCLUSIVE); - double sumPmf = 0; - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i], INCLUSIVE), NUMERIC_NOISE_TOLERANCE, - "rank vs CDF for value " + i); - sumPmf += pmf[i]; - assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i); - } - sumPmf += pmf[n]; - assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE); - assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE); - } - } - - @Test - public void merge() { - final KllFloatsSketch sketch1 = KllFloatsSketch.newHeapInstance(); - final KllFloatsSketch sketch2 = KllFloatsSketch.newHeapInstance(); - final int n = 10000; - for (int i = 0; i < n; i++) { - sketch1.update(i * 1.0f); - sketch2.update(((2 * n) - i - 1) * 1.0f); - } - - assertEquals(sketch1.getMinItem(), 0.0f); - assertEquals(sketch1.getMaxItem(), (n - 1) * 1.0f); - - assertEquals(sketch2.getMinItem(), n * 1.0f); - assertEquals(sketch2.getMaxItem(), ((2 * n) - 1) * 1.0f); - - sketch1.merge(sketch2); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2L * n); - assertEquals(sketch1.getMinItem(), 0.0f); - assertEquals(sketch1.getMaxItem(), ((2 * n) - 1) * 1.0f); - assertEquals(sketch1.getQuantile(0.5), n * 1.0f, 2 * n * PMF_EPS_FOR_K_256); - } - - @Test - public void mergeLowerK() { - final KllFloatsSketch sketch1 = KllFloatsSketch.newHeapInstance(256); - final KllFloatsSketch sketch2 = KllFloatsSketch.newHeapInstance(128); - final int n = 10000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - sketch2.update((2 * n) - i - 1); - } - - assertEquals(sketch1.getMinItem(), 0.0f); - assertEquals(sketch1.getMaxItem(), n - 1f); - - assertEquals(sketch2.getMinItem(), n); - assertEquals(sketch2.getMaxItem(), (2f * n) - 1.0f); - - assertTrue(sketch1.getNormalizedRankError(false) < sketch2.getNormalizedRankError(false)); - assertTrue(sketch1.getNormalizedRankError(true) < sketch2.getNormalizedRankError(true)); - sketch1.merge(sketch2); - - // sketch1 must get "contaminated" by the lower K in sketch2 - assertEquals(sketch1.getNormalizedRankError(false), sketch2.getNormalizedRankError(false)); - assertEquals(sketch1.getNormalizedRankError(true), sketch2.getNormalizedRankError(true)); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2 * n); - assertEquals(sketch1.getMinItem(), 0.0f); - assertEquals(sketch1.getMaxItem(), (2.0f * n) - 1.0f); - assertEquals(sketch1.getQuantile(0.5), n, 2 * n * PMF_EPS_FOR_K_128); - } - - @Test - public void mergeEmptyLowerK() { - final KllFloatsSketch sketch1 = KllFloatsSketch.newHeapInstance(256); - final KllFloatsSketch sketch2 = KllFloatsSketch.newHeapInstance(128); - final int n = 10_000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - - // rank error should not be affected by a merge with an empty sketch with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), 0.0f); - assertEquals(sketch1.getMaxItem(), n - 1.0f); - assertEquals(sketch1.getQuantile(0.5), n / 2.0f, n * PMF_EPS_FOR_K_256); - - //merge the other way - sketch2.merge(sketch1); - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), 0f); - assertEquals(sketch1.getMaxItem(), n - 1.0f); - assertEquals(sketch1.getQuantile(0.5), n / 2.0f, n * PMF_EPS_FOR_K_256); - } - - @Test - public void mergeExactModeLowerK() { - final KllFloatsSketch sketch1 = KllFloatsSketch.newHeapInstance(256); - final KllFloatsSketch sketch2 = KllFloatsSketch.newHeapInstance(128); - final int n = 10000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - sketch2.update(1); - - // rank error should not be affected by a merge with a sketch in exact mode with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - } - - @Test - public void mergeMinMinValueFromOther() { - final KllFloatsSketch sketch1 = KllFloatsSketch.newHeapInstance(); - final KllFloatsSketch sketch2 = KllFloatsSketch.newHeapInstance(); - sketch1.update(1); - sketch2.update(2); - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), 1.0F); - } - - @Test - public void mergeMinAndMaxFromOther() { - final KllFloatsSketch sketch1 = KllFloatsSketch.newHeapInstance(); - for (int i = 1; i <= 1_000_000; i++) { - sketch1.update(i); - } - final KllFloatsSketch sketch2 = KllFloatsSketch.newHeapInstance(10); - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), 1.0F); - assertEquals(sketch2.getMaxItem(), 1_000_000.0F); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooSmall() { - KllFloatsSketch.newHeapInstance(KllSketch.DEFAULT_M - 1); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooLarge() { - KllFloatsSketch.newHeapInstance(KllSketch.MAX_K + 1); - } - - @Test - public void minK() { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(KllSketch.DEFAULT_M); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getK(), KllSketch.DEFAULT_M); - assertEquals(sketch.getQuantile(.5), 500.0f, 1000 * PMF_EPS_FOR_K_8); - } - - @Test - public void maxK() { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(KllSketch.MAX_K); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getK(), KllSketch.MAX_K); - assertEquals(sketch.getQuantile(0.5), 500, 1000 * PMF_EPS_FOR_K_256); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void outOfOrderSplitPoints() { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - sketch.update(0); - sketch.getCDF(new float[] {1.0f, 0.0f}); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void nanSplitPoint() { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - sketch.update(0); - sketch.getCDF(new float[] {Float.NaN}); - } - - @Test - public void checkReset() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final long n1 = sk.getN(); - final float min1 = sk.getMinItem(); - final float max1 = sk.getMaxItem(); - sk.reset(); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final long n2 = sk.getN(); - final float min2 = sk.getMinItem(); - final float max2 = sk.getMaxItem(); - assertEquals(n2, n1); - assertEquals(min2, min1); - assertEquals(max2, max1); - } - - @Test - public void checkReadOnlyUpdate() { - final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(20); - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(seg); - try { sk2.update(1); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkNewDirectInstanceAndSize() { - final MemorySegment wseg = MemorySegment.ofArray(new byte[3000]); - KllFloatsSketch.newDirectInstance(wseg); - try { KllFloatsSketch.newDirectInstance(null); fail(); } - catch (final NullPointerException e) { } - final int updateSize = KllSketch.getMaxSerializedSizeBytes(200, 0, KLL_FLOATS_SKETCH, true); - final int compactSize = KllSketch.getMaxSerializedSizeBytes(200, 0, KLL_FLOATS_SKETCH, false); - assertTrue(compactSize < updateSize); - } - - @Test - public void sortedView() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - sk.update(3); - sk.update(1); - sk.update(2); - - final FloatsSortedView view = sk.getSortedView(); - final FloatsSortedViewIterator itr = view.iterator(); - assertEquals(itr.next(), true); - assertEquals(itr.getQuantile(), 1); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 0); - assertEquals(itr.getNaturalRank(INCLUSIVE), 1); - assertEquals(itr.next(), true); - assertEquals(itr.getQuantile(), 2); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 1); - assertEquals(itr.getNaturalRank(INCLUSIVE), 2); - assertEquals(itr.next(), true); - assertEquals(itr.getQuantile(), 3); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 2); - assertEquals(itr.getNaturalRank(INCLUSIVE), 3); - assertEquals(itr.next(), false); - } - - @Test //also visual - public void checkCDF_PDF() { - final double[] cdfI = {.25, .50, .75, 1.0, 1.0 }; - final double[] cdfE = {0.0, .25, .50, .75, 1.0 }; - final double[] pmfI = {.25, .25, .25, .25, 0.0 }; - final double[] pmfE = {0.0, .25, .25, .25, .25 }; - final double toll = 1E-10; - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(); - final float[] floatIn = {10, 20, 30, 40}; - for (int i = 0; i < floatIn.length; i++) { sketch.update(floatIn[i]); } - final float[] sp = { 10, 20, 30, 40 }; - println("SplitPoints:"); - for (int i = 0; i < sp.length; i++) { - printf("%10.2f", sp[i]); - } - println(""); - println("INCLUSIVE:"); - double[] cdf = sketch.getCDF(sp, INCLUSIVE); - double[] pmf = sketch.getPMF(sp, INCLUSIVE); - printf("%10s%10s" + LS, "CDF", "PMF"); - for (int i = 0; i < cdf.length; i++) { - printf("%10.2f%10.2f" + LS, cdf[i], pmf[i]); - assertEquals(cdf[i], cdfI[i], toll); - assertEquals(pmf[i], pmfI[i], toll); - } - println("EXCLUSIVE"); - cdf = sketch.getCDF(sp, EXCLUSIVE); - pmf = sketch.getPMF(sp, EXCLUSIVE); - printf("%10s%10s" + LS, "CDF", "PMF"); - for (int i = 0; i < cdf.length; i++) { - printf("%10.2f%10.2f" + LS, cdf[i], pmf[i]); - assertEquals(cdf[i], cdfE[i], toll); - assertEquals(pmf[i], pmfE[i], toll); - } - } - - @Test - public void checkWrapCase1Floats() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment seg = MemorySegment.ofArray(sk.toByteArray()).asReadOnly(); - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(seg); - - assertTrue(seg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkWritableWrapCase6And2Floats() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment wseg = MemorySegment.ofArray(KllHelper.toByteArray(sk, true)); - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(wseg); - - assertFalse(wseg.isReadOnly()); - assertFalse(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkKllSketchCase5Floats() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(wseg); - - assertFalse(wseg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkKllSketchCase3Floats() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment seg = MemorySegment.ofArray(KllHelper.toByteArray(sk, true)).asReadOnly(); - final MemorySegment wseg = (MemorySegment) seg; - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(wseg); - - assertTrue(wseg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkKllSketchCase7Floats() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment seg = MemorySegment.ofArray(KllHelper.toByteArray(sk, true)).asReadOnly(); - final MemorySegment wseg = (MemorySegment) seg; - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(wseg); - - assertTrue(wseg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkReadOnlyExceptions() { - final int[] intArr = {}; - final int intV = 2; - final int idx = 1; - final KllFloatsSketch sk1 = KllFloatsSketch.newHeapInstance(20); - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - final KllFloatsSketch sk2 = KllFloatsSketch.wrap(seg); - try { sk2.setLevelsArray(intArr); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setLevelsArrayAt(idx,intV); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkIsSameResource() { - final int cap = 128; - final MemorySegment wseg = MemorySegment.ofArray(new byte[cap]); - final MemorySegment slice1 = wseg.asSlice(0, 64); - final MemorySegment slice2 = wseg.asSlice(64, 64); - assertFalse(slice1 == slice2); - assertFalse(MemorySegmentStatus.isSameResource(slice1, slice2)); - - final MemorySegment slice3 = wseg.asSlice(0, 64); - assertFalse(slice1 == slice3); - assertTrue(MemorySegmentStatus.isSameResource(slice1, slice3)); - - final byte[] byteArr1 = KllFloatsSketch.newHeapInstance(20).toByteArray(); - MemorySegment.copy(byteArr1, 0, slice1, JAVA_BYTE, 0, byteArr1.length); - final KllFloatsSketch sk1 = KllFloatsSketch.wrap(slice1); - - final byte[] byteArr2 = KllFloatsSketch.newHeapInstance(20).toByteArray(); - MemorySegment.copy(byteArr2, 0, slice2, JAVA_BYTE, 0, byteArr2.length); - assertFalse(sk1.isSameResource(slice2)); - - final byte[] byteArr3 = KllFloatsSketch.newHeapInstance(20).toByteArray(); - MemorySegment.copy(byteArr3, 0, slice3, JAVA_BYTE, 0, byteArr3.length); - assertTrue(sk1.isSameResource(slice3)); - } - - @Test - public void checkSortedViewAfterReset() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20); - sk.update(1.0f); - final FloatsSortedView sv = sk.getSortedView(); - final float fsv = sv.getQuantile(1.0, INCLUSIVE); - assertEquals(fsv, 1.0f); - sk.reset(); - try { sk.getSortedView(); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkVectorUpdate() { - final boolean withLevels = false; - final boolean withLevelsAndItems = true; - final int k = 20; - final int n = 108; - final int maxVsz = 40; //max vector size - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - int j = 1; - int rem; - while ((rem = (n - j) + 1) > 0) { - final int vecSz = min(rem, maxVsz); - final float[] v = new float[vecSz]; - for (int i = 0; i < vecSz; i++) { v[i] = j++; } - sk.update(v, 0, vecSz); - } - println(LS + "#<<< END STATE # >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - println(""); - assertEquals(sk.getN(), 108); - assertEquals(sk.getMaxItem(), 108F); - assertEquals(sk.getMinItem(), 1F); - } - - @Test - public void vectorizedUpdates() { - final int trials = 1; - final int M = 1; //number of vectors - final int N = 1000; //vector size - final int K = 256; - final float[] values = new float[N]; - float vIn = 1.0F; - long totN = 0; - final long startTime = System.nanoTime(); - for (int t = 0; t < trials; t++) { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(K); - for (int m = 0; m < M; m++) { - for (int n = 0; n < N; n++) { - values[n] = vIn++; //fill vector - } - sketch.update(values, 0, N); //vector input - } - totN = sketch.getN(); - assertEquals(totN, M * N); - assertEquals(sketch.getMinItem(), 1.0F); - assertEquals(sketch.getMaxItem(), totN); - assertEquals(sketch.getQuantile(0.5), (float)(totN / 2.0), totN * PMF_EPS_FOR_K_256 * 2.0); //wider tolerance - } - final long runTime = System.nanoTime() - startTime; - println("Vectorized Updates"); - printf(" Vector size : %,12d" + LS, N); - printf(" Num Vectors : %,12d" + LS, M); - printf(" Total Input : %,12d" + LS, totN); - printf(" Run Time mS : %,12.3f" + LS, runTime / 1e6); - final double trialTime = runTime / (1e6 * trials); - printf(" mS / Trial : %,12.3f" + LS, trialTime); - final double updateTime = runTime / (1.0 * totN * trials); - printf(" nS / Update : %,12.3f" + LS, updateTime); - } - - @Test - public void nonVectorizedUpdates() { - final int trials = 1; - final int M = 1; //number of vectors - final int N = 1000; //vector size - final int K = 256; - final float[] values = new float[N]; - float vIn = 1.0F; - long totN = 0; - final long startTime = System.nanoTime(); - for (int t = 0; t < trials; t++) { - final KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(K); - for (int m = 0; m < M; m++) { - for (int n = 0; n < N; n++) { - values[n] = vIn++; //fill vector - } - for (int i = 0; i < N; i++) { - sketch.update(values[i]); //single item input - } - } - totN = sketch.getN(); - assertEquals(totN, M * N); - assertEquals(sketch.getMinItem(), 1.0); - assertEquals(sketch.getMaxItem(), totN); - assertEquals(sketch.getQuantile(0.5), (float)(totN / 2.0), totN * PMF_EPS_FOR_K_256 * 2.0); //wider tolerance - } - final long runTime = System.nanoTime() - startTime; - println("Vectorized Updates"); - printf(" Vector size : %,12d" + LS, N); - printf(" Num Vectors : %,12d" + LS, M); - printf(" Total Input : %,12d" + LS, totN); - printf(" Run Time mS : %,12.3f" + LS, runTime / 1e6); - final double trialTime = runTime / (1e6 * trials); - printf(" mS / Trial : %,12.3f" + LS, trialTime); - final double updateTime = runTime / (1.0 * totN * trials); - printf(" nS / Update : %,12.3f" + LS, updateTime); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } -} diff --git a/src/test/java/org/apache/datasketches/kll/KllFloatsValidationTest.java b/src/test/java/org/apache/datasketches/kll/KllFloatsValidationTest.java deleted file mode 100644 index beeb0d570..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllFloatsValidationTest.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.common.Util.isOdd; - -import org.apache.datasketches.kll.KllFloatsSketch; -import org.testng.Assert; -import org.testng.annotations.Test; - -/* A test record contains: - 0. testIndex - 1. K - 2. N - 3. stride (for generating the input) - 4. numLevels - 5. numSamples - 6. hash of the retained samples -*/ - -// These results are for the version that delays the roll up until the next value comes in. -// The @Test annotations have to be enabled to use this class and a section in KllFloatsHelper also -// needs to be enabled. -@SuppressWarnings("unused") -public class KllFloatsValidationTest { - - //Used only with manual running of checkTestResults(..) - private static final long[] correctResultsWithReset = { - 0, 200, 180, 3246533, 1, 180, 1098352976109474698L, - 1, 200, 198, 8349603, 1, 198, 686681527497651888L, - 2, 200, 217, 676491, 2, 117, 495856134049157644L, - 3, 200, 238, 3204507, 2, 138, 44453438498725402L, - 4, 200, 261, 2459373, 2, 161, 719830627391926938L, - 5, 200, 287, 5902143, 2, 187, 389303173170515580L, - 6, 200, 315, 5188793, 2, 215, 985218890825795000L, - 7, 200, 346, 801923, 2, 246, 589362992166904413L, - 8, 200, 380, 2466269, 2, 280, 1081848693781775853L, - 9, 200, 418, 5968041, 2, 318, 533825689515788397L, - 10, 200, 459, 3230027, 2, 243, 937332670315558786L, - 11, 200, 504, 5125875, 2, 288, 1019197831515566845L, - 12, 200, 554, 4195571, 3, 230, 797351479150148224L, - 13, 200, 609, 2221181, 3, 285, 451246040374318529L, - 14, 200, 669, 5865503, 3, 345, 253851269470815909L, - 15, 200, 735, 831703, 3, 411, 491974970526372303L, - 16, 200, 808, 4830785, 3, 327, 1032107507126916277L, - 17, 200, 888, 1356257, 3, 407, 215225420986342944L, - 18, 200, 976, 952071, 3, 417, 600280049738270697L, - 19, 200, 1073, 6729833, 3, 397, 341758522977365969L, - 20, 200, 1180, 6017925, 3, 406, 1080227312339182949L, - 21, 200, 1298, 4229891, 3, 401, 1092460534756675086L, - 22, 200, 1427, 7264889, 4, 320, 884533400696890024L, - 23, 200, 1569, 5836327, 4, 462, 660575800011134382L, - 24, 200, 1725, 5950087, 4, 416, 669373957401387528L, - 25, 200, 1897, 2692555, 4, 406, 607308667566496888L, - 26, 200, 2086, 1512443, 4, 459, 744260340112029032L, - 27, 200, 2294, 2681171, 4, 434, 199120609113802485L, - 28, 200, 2523, 3726521, 4, 450, 570993497599288304L, - 29, 200, 2775, 2695247, 4, 442, 306717093329516310L, - 30, 200, 3052, 5751175, 5, 400, 256024589545754217L, - 31, 200, 3357, 1148897, 5, 514, 507276662329207479L, - 32, 200, 3692, 484127, 5, 457, 1082660223488175122L, - 33, 200, 4061, 6414559, 5, 451, 620820308918522117L, - 34, 200, 4467, 5587461, 5, 466, 121975084804459305L, - 35, 200, 4913, 1615017, 5, 483, 152986529342916376L, - 36, 200, 5404, 6508535, 5, 492, 858526451332425960L, - 37, 200, 5944, 2991657, 5, 492, 624906434274621995L, - 38, 200, 6538, 6736565, 6, 511, 589153542019036049L, - 39, 200, 7191, 1579893, 6, 507, 10255312374117907L, - 40, 200, 7910, 412509, 6, 538, 570863587164194186L, - 41, 200, 8701, 1112089, 6, 477, 553100668286355347L, - 42, 200, 9571, 1258813, 6, 526, 344845406406036297L, - 43, 200, 10528, 1980049, 6, 508, 411846569527905064L, - 44, 200, 11580, 2167127, 6, 520, 966876726203675488L, - 45, 200, 12738, 1975435, 7, 561, 724125506920592732L, - 46, 200, 14011, 4289627, 7, 560, 753686005174215572L, - 47, 200, 15412, 5384001, 7, 494, 551637841878573955L, - 48, 200, 16953, 2902685, 7, 560, 94602851752354802L, - 49, 200, 18648, 4806445, 7, 562, 597672400688514221L, - 50, 200, 20512, 2085, 7, 529, 417280161591969960L, - 51, 200, 22563, 6375939, 7, 558, 11300453985206678L, - 52, 200, 24819, 7837057, 7, 559, 283668599967437754L, - 53, 200, 27300, 6607975, 8, 561, 122183647493325363L, - 54, 200, 30030, 1519191, 8, 550, 1145227891427321202L, - 55, 200, 33033, 808061, 8, 568, 71070843834364939L, - 56, 200, 36336, 2653529, 8, 570, 450311772805359006L, - 57, 200, 39969, 2188957, 8, 561, 269670427054904115L, - 58, 200, 43965, 5885655, 8, 539, 1039064186324091890L, - 59, 200, 48361, 6185889, 8, 574, 178055275082387938L, - 60, 200, 53197, 208767, 9, 579, 139766040442973048L, - 61, 200, 58516, 2551345, 9, 569, 322655279254252950L, - 62, 200, 64367, 1950873, 9, 569, 101542216315768285L, - 63, 200, 70803, 2950429, 9, 582, 72294008568551853L, - 64, 200, 77883, 3993977, 9, 572, 299014330559512530L, - 65, 200, 85671, 428871, 9, 585, 491351721800568188L, - 66, 200, 94238, 6740849, 9, 577, 656204268858348899L, - 67, 200, 103661, 2315497, 9, 562, 829926273188300764L, - 68, 200, 114027, 5212835, 10, 581, 542222554617639557L, - 69, 200, 125429, 4213475, 10, 593, 713339189579860773L, - 70, 200, 137971, 2411583, 10, 592, 649651658985845357L, - 71, 200, 151768, 5243307, 10, 567, 1017459402785275179L, - 72, 200, 166944, 2468367, 10, 593, 115034451827634398L, - 73, 200, 183638, 2210923, 10, 583, 365735165000548572L, - 74, 200, 202001, 321257, 10, 591, 928479940794929153L, - 75, 200, 222201, 8185105, 11, 600, 780163958693677795L, - 76, 200, 244421, 6205349, 11, 598, 132454307780236135L, - 77, 200, 268863, 3165901, 11, 600, 369824066179493948L, - 78, 200, 295749, 2831723, 11, 595, 80968411797441666L, - 79, 200, 325323, 464193, 11, 594, 125773061716381917L, - 80, 200, 357855, 7499035, 11, 576, 994150328579932916L, - 81, 200, 393640, 1514479, 11, 596, 111092193875842594L, - 82, 200, 433004, 668493, 12, 607, 497338041653302784L, - 83, 200, 476304, 3174931, 12, 606, 845986926165673887L, - 84, 200, 523934, 914611, 12, 605, 354993119685278556L, - 85, 200, 576327, 7270385, 12, 602, 937679531753465428L, - 86, 200, 633959, 1956979, 12, 598, 659413123921208266L, - 87, 200, 697354, 3137635, 12, 606, 874228711599628459L, - 88, 200, 767089, 214923, 12, 608, 1077644643342432307L, - 89, 200, 843797, 3084545, 13, 612, 79317113064339979L, - 90, 200, 928176, 7800899, 13, 612, 357414065779796772L, - 91, 200, 1020993, 6717253, 13, 615, 532723577905833296L, - 92, 200, 1123092, 5543015, 13, 614, 508695073250223746L, - 93, 200, 1235401, 298785, 13, 616, 34344606952783179L, - 94, 200, 1358941, 4530313, 13, 607, 169924026179364121L, - 95, 200, 1494835, 4406457, 13, 612, 1026773494313671061L, - 96, 200, 1644318, 1540983, 13, 614, 423454640036650614L, - 97, 200, 1808749, 7999631, 14, 624, 466122870338520329L, - 98, 200, 1989623, 4295537, 14, 621, 609309853701283445L, - 99, 200, 2188585, 7379971, 14, 622, 141739898871015642L, - 100, 200, 2407443, 6188931, 14, 621, 22515080776738923L, - 101, 200, 2648187, 6701239, 14, 619, 257441864177795548L, - 102, 200, 2913005, 2238709, 14, 623, 867028825821064773L, - 103, 200, 3204305, 5371075, 14, 625, 1110615471273395112L, - 104, 200, 3524735, 7017341, 15, 631, 619518037415974467L, - 105, 200, 3877208, 323337, 15, 633, 513230912593541122L, - 106, 200, 4264928, 6172471, 15, 628, 885861662583325072L, - 107, 200, 4691420, 5653803, 15, 633, 754052473303005204L, - 108, 200, 5160562, 1385265, 15, 630, 294993765757975100L, - 109, 200, 5676618, 4350899, 15, 617, 1073144684944932303L, - 110, 200, 6244279, 1272235, 15, 630, 308982934296855020L, - 111, 200, 6868706, 1763939, 16, 638, 356231694823272867L, - 112, 200, 7555576, 3703411, 16, 636, 20043268926300101L, - 113, 200, 8311133, 6554171, 16, 637, 121111429906734123L, - }; - - private static int[] makeInputArray(int n, int stride) { - assert isOdd(stride); - int mask = (1 << 23) - 1; // because library items are single-precision floats - int cur = 0; - int[] arr = new int[n]; - for (int i = 0; i < n; i++) { - cur += stride; - cur &= mask; - arr[i] = cur; - } - return arr; - } - - //@Test //only enabled to test the above makeInputArray(..) - public void testMakeInputArray() { - final int[] array = { 3654721, 7309442, 2575555, 6230276, 1496389, 5151110 }; - Assert.assertEquals(makeInputArray(6, 3654721), array); - } - - private static long simpleHashOfSubArray(final float[] arr, final int start, final int subLength) { - final long multiplier = 738219921; // an arbitrary odd 30-bit number - final long mask60 = (1L << 60) - 1; - long accum = 0; - for (int i = start; i < (start + subLength); i++) { - accum += (long) arr[i]; - accum *= multiplier; - accum &= mask60; - accum ^= accum >> 30; - } - return accum; - } - - //@Test //only enabled to test the above simpleHashOfSubArray(..) - public void testHash() { - float[] array = { 907500, 944104, 807020, 219921, 678370, 955217, 426885 }; - Assert.assertEquals(simpleHashOfSubArray(array, 1, 5), 1141543353991880193L); - } - - /* - * Please note that this test should be run with a modified version of KllFloatsHelper - * that chooses directions alternately instead of randomly. - * See the instructions at the bottom of that class. - */ - - //@Test //NEED TO ENABLE HERE AND BELOW FOR VALIDATION - public void checkTestResults() { - int numTests = correctResultsWithReset.length / 7; - for (int testI = 0; testI < numTests; testI++) { - //KllFloatsHelper.nextOffset = 0; //NEED TO ENABLE - assert (int) correctResultsWithReset[7 * testI] == testI; - int k = (int) correctResultsWithReset[(7 * testI) + 1]; - int n = (int) correctResultsWithReset[(7 * testI) + 2]; - int stride = (int) correctResultsWithReset[(7 * testI) + 3]; - int[] inputArray = makeInputArray(n, stride); - KllFloatsSketch sketch = KllFloatsSketch.newHeapInstance(k); - for (int i = 0; i < n; i++) { - sketch.update(inputArray[i]); - } - int numLevels = sketch.getNumLevels(); - int numSamples = sketch.getNumRetained(); - int[] levels = sketch.getLevelsArray(sketch.sketchStructure); - long hashedSamples = simpleHashOfSubArray(sketch.getFloatItemsArray(), levels[0], numSamples); - System.out.print(testI); - assert correctResultsWithReset[(7 * testI) + 4] == numLevels; - assert correctResultsWithReset[(7 * testI) + 5] == numSamples; - assert correctResultsWithReset[7 * testI + 6] == hashedSamples; - if (correctResultsWithReset[(7 * testI) + 6] == hashedSamples) { - System.out.println(" pass"); - } else { - System.out.print(" " + correctResultsWithReset[(7 * testI) + 6] + " != " + hashedSamples); - System.out.println(" fail"); - System.out.println(sketch.toString(true, true)); - break; - } - } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllHelperTest.java b/src/test/java/org/apache/datasketches/kll/KllHelperTest.java deleted file mode 100644 index 5acb068a0..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllHelperTest.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.kll.KllHelper.checkM; -import static org.apache.datasketches.kll.KllSketch.getMaxSerializedSizeBytes; -import static org.apache.datasketches.kll.KllSketch.SketchType.*; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; -import java.util.Comparator; -import java.util.Enumeration; -import java.util.Hashtable; - -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.kll.KllDoublesSketch; -import org.apache.datasketches.kll.KllFloatsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllItemsSketch; -import org.apache.datasketches.kll.KllSketch; -import org.apache.datasketches.kll.KllSketch.SketchType; -import org.testng.annotations.Test; - -public class KllHelperTest { - public ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - - - @Test - public void checkConvertToCumulative() { - final long[] array = {1,2,3,2,1}; - final long out = KllHelper.convertToCumulative(array); - assertEquals(out, 9); - } - - @Test - public void checkCheckM() { - try { - checkM(0); - fail(); - } catch (final SketchesArgumentException e) {} - try { - checkM(3); - fail(); - } catch (final SketchesArgumentException e) {} - try { - checkM(10); - fail(); - } catch (final SketchesArgumentException e) {} - } - - @Test - public void checkGetKFromEps() { - final int k = KllSketch.DEFAULT_K; - final double eps = KllHelper.getNormalizedRankError(k, false); - final double epsPmf = KllHelper.getNormalizedRankError(k, true); - final int kEps = KllSketch.getKFromEpsilon(eps, false); - final int kEpsPmf = KllSketch.getKFromEpsilon(epsPmf, true); - assertEquals(kEps, k); - assertEquals(kEpsPmf, k); - } - - @Test - public void checkIntCapAux() { - int lvlCap = KllHelper.levelCapacity(10, 61, 0, 8); - assertEquals(lvlCap, 8); - lvlCap = KllHelper.levelCapacity(10, 61, 60, 8); - assertEquals(lvlCap, 10); - } - - @Test - public void checkSuperLargeKandLevels() { - //This is beyond what the sketch can be configured for. - final int size = KllHelper.computeTotalItemCapacity(1 << 29, 8, 61); - assertEquals(size, 1_610_612_846); - } - - @Test - public void checkUbOnNumLevels() { - assertEquals(KllHelper.ubOnNumLevels(0), 1); - } - - @Test - public void checkUpdatableSerDeDouble() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(200); - for (int i = 1; i <= 533; i++) { sk.update(i); } - final int retained = sk.getNumRetained(); - final int numLevels = ((KllSketch)sk).getNumLevels(); - println("NumLevels: " + numLevels); - println("NumRetained: " + retained); - - final byte[] compByteArr1 = sk.toByteArray(); - final int compBytes1 = compByteArr1.length; - println("compBytes1: " + compBytes1); - - final byte[] upByteArr1 = KllHelper.toByteArray(sk, true); - final int upBytes1 = upByteArr1.length; - println("upBytes1: " + upBytes1); - - MemorySegment seg; - KllDoublesSketch sk2; - - seg = MemorySegment.ofArray(compByteArr1); - sk2 = KllDoublesSketch.heapify(seg); - final byte[] compByteArr2 = sk2.toByteArray(); - final int compBytes2 = compByteArr2.length; - println("compBytes2: " + compBytes2); - assertEquals(compBytes1, compBytes2); - assertEquals(sk2.getNumRetained(), retained); - - seg = MemorySegment.ofArray(compByteArr2); - sk2 = KllDoublesSketch.heapify(seg); - final byte[] upByteArr2 = KllHelper.toByteArray(sk2, true); - final int upBytes2 = upByteArr2.length; - println("upBytes2: " + upBytes2); - assertEquals(upBytes1, upBytes2); - assertEquals(sk2.getNumRetained(), retained); - } - - @Test - public void checkUpdatableSerDeFloat() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(200); - for (int i = 1; i <= 533; i++) { sk.update(i); } - final int retained = sk.getNumRetained(); - final int numLevels = ((KllSketch)sk).getNumLevels(); - println("NumLevels: " + numLevels); - println("NumRetained: " + retained); - - final byte[] compByteArr1 = sk.toByteArray(); - final int compBytes1 = compByteArr1.length; - println("compBytes1: " + compBytes1); - - final byte[] upByteArr1 = KllHelper.toByteArray(sk, true); - final int upBytes1 = upByteArr1.length; - println("upBytes1: " + upBytes1); - - MemorySegment seg; - KllFloatsSketch sk2; - - seg = MemorySegment.ofArray(compByteArr1); - sk2 = KllFloatsSketch.heapify(seg); - final byte[] compByteArr2 = sk2.toByteArray(); - final int compBytes2 = compByteArr2.length; - println("compBytes2: " + compBytes2); - assertEquals(compBytes1, compBytes2); - assertEquals(sk2.getNumRetained(), retained); - - seg = MemorySegment.ofArray(compByteArr2); - sk2 = KllFloatsSketch.heapify(seg); - final byte[] upByteArr2 = KllHelper.toByteArray(sk2, true); - final int upBytes2 = upByteArr2.length; - println("upBytes2: " + upBytes2); - assertEquals(upBytes1, upBytes2); - assertEquals(sk2.getNumRetained(), retained); - } - - @Test - public void checkUpdatableSerDeItem() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(200, Comparator.naturalOrder(), serDe); - final int n = 533; - final int digits = Util.numDigits(n); - for (int i = 1; i <= n; i++) { sk.update(Util.longToFixedLengthString(i, digits)); } - - final int retained = sk.getNumRetained(); - final int numLevels = ((KllSketch)sk).getNumLevels(); - println("NumLevels: " + numLevels); - println("NumRetained: " + retained); - - final byte[] compByteArr1 = sk.toByteArray(); - final int compBytes1 = compByteArr1.length; - println("compBytes1: " + compBytes1); - - final byte[] upByteArr1 = KllHelper.toByteArray(sk, true); - final int upBytes1 = upByteArr1.length; - println("upBytes1: " + upBytes1); - assertEquals(upBytes1, compBytes1); //only true for Items Sketch - - MemorySegment seg; - KllItemsSketch sk2; - - seg = MemorySegment.ofArray(compByteArr1); - sk2 = KllItemsSketch.heapify(seg, Comparator.naturalOrder(), serDe); - final byte[] compByteArr2 = sk2.toByteArray(); - final int compBytes2 = compByteArr2.length; - println("compBytes2: " + compBytes2); - assertEquals(compBytes1, compBytes2); - assertEquals(sk2.getNumRetained(), retained); - - seg = MemorySegment.ofArray(compByteArr2); - sk2 = KllItemsSketch.heapify(seg, Comparator.naturalOrder(), serDe); - final byte[] upByteArr2 = KllHelper.toByteArray(sk2, true); - final int upBytes2 = upByteArr2.length; - println("upBytes2: " + upBytes2); - assertEquals(upBytes1, upBytes2); - assertEquals(sk2.getNumRetained(), retained); - } - - - @Test - public void getMaxCompactDoublesSerializedSizeBytes() { - final int sizeBytes = - KllSketch.getMaxSerializedSizeBytes(KllSketch.DEFAULT_K, 1L << 30, KLL_DOUBLES_SKETCH, false); - assertEquals(sizeBytes, 5704); - } - - @Test - public void getMaxCompactFloatsSerializedSizeBytes() { - final int sizeBytes = - KllSketch.getMaxSerializedSizeBytes(KllSketch.DEFAULT_K, 1L << 30, KLL_FLOATS_SKETCH, false); - assertEquals(sizeBytes, 2908); - } - - @Test - public void getMaxUpdatableDoubleSerializedSizeBytes() { - final int sizeBytes = - KllSketch.getMaxSerializedSizeBytes(KllSketch.DEFAULT_K, 1L << 30, KLL_DOUBLES_SKETCH, true); - assertEquals(sizeBytes, 5708); - } - - @Test - public void getMaxUpdatableFloatsSerializedSizeBytes() { - final int sizeBytes = - KllSketch.getMaxSerializedSizeBytes(KllSketch.DEFAULT_K, 1L << 30, KLL_FLOATS_SKETCH, true); - assertEquals(sizeBytes, 2912); - } - - @Test - public void getMaxUpdatableItemsSerializedSizeBytes() { - try { - KllSketch.getMaxSerializedSizeBytes(KllSketch.DEFAULT_K, 1L << 30, KLL_ITEMS_SKETCH, true); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void getStatsAtNumLevels() { - final int k = 200; - final int m = 8; - final int numLevels = 23; - final KllHelper.LevelStats lvlStats = - KllHelper.getFinalSketchStatsAtNumLevels(k, m, numLevels, true); - assertEquals(lvlStats.numItems, 697); - assertEquals(lvlStats.n, 1257766904); - } - - @Test - public void getStatsAtNumLevels2() { - final int k = 20; - final int m = KllSketch.DEFAULT_M; - final int numLevels = 2; - final KllHelper.LevelStats lvlStats = - KllHelper.getFinalSketchStatsAtNumLevels(k, m, numLevels, true); - assertEquals(lvlStats.numLevels, 2); - assertEquals(lvlStats.numItems, 33); - } - - @Test - public void testGetAllLevelStatsDoubles() { - final long n = 1L << 30; - final int k = 200; - final int m = KllSketch.DEFAULT_M; - final KllHelper.GrowthStats gStats = - KllHelper.getGrowthSchemeForGivenN(k, m, n, KLL_DOUBLES_SKETCH, true); - assertEquals(gStats.maxN, 1_257_766_904); - assertEquals(gStats.numLevels, 23); - assertEquals(gStats.maxItems, 697); - assertEquals(gStats.compactBytes, 5704); - assertEquals(gStats.updatableBytes, 5708); - } - - @Test - public void testGetAllLevelStatsFloats() { - final long n = 1L << 30; - final int k = 200; - final int m = KllSketch.DEFAULT_M; - final KllHelper.GrowthStats gStats = - KllHelper.getGrowthSchemeForGivenN(k, m, n, KLL_FLOATS_SKETCH, true); - assertEquals(gStats.maxN, 1_257_766_904); - assertEquals(gStats.numLevels, 23); - assertEquals(gStats.maxItems, 697); - assertEquals(gStats.compactBytes, 2908); - assertEquals(gStats.updatableBytes, 2912); - } - - @Test - public void testGetAllLevelStatsDoubles2() { - final long n = 533; - final int k = 200; - final int m = KllSketch.DEFAULT_M; - final KllHelper.GrowthStats gStats = - KllHelper.getGrowthSchemeForGivenN(k, m, n, KLL_DOUBLES_SKETCH, true); - assertEquals(gStats.maxN, 533); - assertEquals(gStats.numLevels, 2); - assertEquals(gStats.maxItems, 333); - assertEquals(gStats.compactBytes, 2708); - assertEquals(gStats.updatableBytes, 2712); - } - - @Test - public void testGetAllLevelStatsFloats2() { - final long n = 533; - final int k = 200; - final int m = KllSketch.DEFAULT_M; - final KllHelper.GrowthStats gStats = - KllHelper.getGrowthSchemeForGivenN(k, m, n, KLL_FLOATS_SKETCH, true); - assertEquals(gStats.maxN, 533); - assertEquals(gStats.numLevels, 2); - assertEquals(gStats.maxItems, 333); - assertEquals(gStats.compactBytes, 1368); - assertEquals(gStats.updatableBytes, 1372); - } - - @Test - public void testGetAllLevelStatsItems() { - final long n = 533; - final int k = 200; - final int m = KllSketch.DEFAULT_M; - try { - KllHelper.getGrowthSchemeForGivenN(k, m, n, KLL_ITEMS_SKETCH, true); - } catch (final SketchesArgumentException e) { } - } - - /** - * Println Object o - * @param o object to print - */ - static void println(final Object o) { - //System.out.println(o.toString()); - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllItemsSketchSerDeTest.java b/src/test/java/org/apache/datasketches/kll/KllItemsSketchSerDeTest.java deleted file mode 100644 index be0c405c2..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllItemsSketchSerDeTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.kll.KllItemsSketch; -import org.testng.annotations.Test; - -public class KllItemsSketchSerDeTest { - private final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - - @Test - public void serializeDeserializeEmpty() { - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - //from heap -> byte[] -> heap - final byte[] bytes = sk1.toByteArray(); - final KllItemsSketch sk2 = KllItemsSketch.heapify(MemorySegment.ofArray(bytes), Comparator.naturalOrder(), serDe); - assertEquals(bytes.length, sk1.getSerializedSizeBytes()); - assertTrue(sk2.isEmpty()); - assertEquals(sk2.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk2.getN(), sk1.getN()); - assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - try { sk2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap - final KllItemsSketch sk3 = KllItemsSketch.wrap(MemorySegment.ofArray(bytes), Comparator.naturalOrder(), serDe); - assertTrue(sk3.isEmpty()); - assertEquals(sk3.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk3.getN(), sk1.getN()); - assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - try { sk3.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk3.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap -> byte[] -> compare byte[] - final byte[] bytes2 = sk3.toByteArray(); - assertEquals(bytes, bytes2); - } - - @Test - public void serializeDeserializeOneValue() { - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - sk1.update(" 1"); - //from heap -> byte[] -> heap - final byte[] bytes = sk1.toByteArray(); - final KllItemsSketch sk2 = KllItemsSketch.heapify(MemorySegment.ofArray(bytes), Comparator.naturalOrder(), serDe); - assertEquals(bytes.length, sk1.getSerializedSizeBytes()); - assertFalse(sk2.isEmpty()); - assertEquals(sk2.getNumRetained(), 1); - assertEquals(sk2.getN(), 1); - assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk2.getMinItem(), " 1"); - assertEquals(sk2.getMaxItem(), " 1"); - assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap - final KllItemsSketch sk3 = KllItemsSketch.wrap(MemorySegment.ofArray(bytes), Comparator.naturalOrder(), serDe); - assertFalse(sk3.isEmpty()); - assertEquals(sk3.getNumRetained(), 1); - assertEquals(sk3.getN(), 1); - assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk3.getMinItem(), " 1"); - assertEquals(sk3.getMaxItem(), " 1"); - assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap -> byte[] -> compare byte[] - final byte[] bytes2 = sk3.toByteArray(); - assertEquals(bytes, bytes2); - } - - @Test - public void serializeDeserializeMultipleValues() { - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final int n = 1000; - for (int i = 0; i < n; i++) { - sk1.update(Util.longToFixedLengthString(i, 4)); - } - assertEquals(sk1.getMinItem(), " 0"); - assertEquals(sk1.getMaxItem(), " 999"); - //from heap -> byte[] -> heap - final byte[] bytes = sk1.toByteArray(); - final KllItemsSketch sk2 = KllItemsSketch.heapify(MemorySegment.ofArray(bytes), Comparator.naturalOrder(), serDe); - assertEquals(bytes.length, sk1.getSerializedSizeBytes()); - assertFalse(sk2.isEmpty()); - assertEquals(sk2.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk2.getN(), sk1.getN()); - assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk2.getMinItem(), sk1.getMinItem()); - assertEquals(sk2.getMaxItem(), sk1.getMaxItem()); - assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap - final KllItemsSketch sk3 = KllItemsSketch.wrap(MemorySegment.ofArray(bytes), Comparator.naturalOrder(), serDe); - assertFalse(sk3.isEmpty()); - assertEquals(sk3.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk3.getN(), sk1.getN()); - assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk3.getMinItem(), sk1.getMinItem()); - assertEquals(sk3.getMaxItem(), sk1.getMaxItem()); - assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap -> byte[] -> compare byte[] - final byte[] bytes2 = sk3.toByteArray(); - assertEquals(bytes, bytes2); - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllItemsSketchTest.java b/src/test/java/org/apache/datasketches/kll/KllItemsSketchTest.java deleted file mode 100644 index 193c1e502..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllItemsSketchTest.java +++ /dev/null @@ -1,799 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.Math.ceil; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_ITEMS_SKETCH; -import static org.apache.datasketches.quantilescommon.LongsAsOrderableStrings.getString; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.Comparator; -import java.util.Random; - -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.kll.KllItemsSketch; -import org.apache.datasketches.kll.KllMemorySegmentValidate; -import org.apache.datasketches.kll.KllPreambleUtil; -import org.apache.datasketches.kll.KllSketch; -import org.apache.datasketches.kll.KllSketch.SketchType; -import org.apache.datasketches.quantilescommon.GenericSortedView; -import org.apache.datasketches.quantilescommon.GenericSortedViewIterator; -import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI; -import org.testng.annotations.Test; - -public class KllItemsSketchTest { - private static final double PMF_EPS_FOR_K_8 = 0.35; // PMF rank error (epsilon) for k=8 - private static final double PMF_EPS_FOR_K_128 = 0.025; // PMF rank error (epsilon) for k=128 - private static final double PMF_EPS_FOR_K_256 = 0.013; // PMF rank error (epsilon) for k=256 - private static final double NUMERIC_NOISE_TOLERANCE = 1E-6; - private final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - - @Test - public void empty() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sketch.update(null); // this must not change anything - assertTrue(sketch.isEmpty()); - assertEquals(sketch.getN(), 0); - assertEquals(sketch.getNumRetained(), 0); - try { sketch.getRank("", INCLUSIVE); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantile(0.5); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantiles(new double[] {0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getPMF(new String[] {""}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getCDF(new String[] {""}); fail(); } catch (final SketchesArgumentException e) {} - assertNotNull(sketch.toString(true, true)); - assertNotNull(sketch.toString()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantileInvalidArg() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sketch.update("A"); - sketch.getQuantile(-1.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantilesInvalidArg() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sketch.update("A"); - sketch.getQuantiles(new double[] {2.0}); - } - - @Test - public void oneValue() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sketch.update("A"); - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getN(), 1); - assertEquals(sketch.getNumRetained(), 1); - assertEquals(sketch.getRank("A", EXCLUSIVE), 0.0); - assertEquals(sketch.getRank("B", EXCLUSIVE), 1.0); - assertEquals(sketch.getRank("A", EXCLUSIVE), 0.0); - assertEquals(sketch.getRank("B", EXCLUSIVE), 1.0); - assertEquals(sketch.getRank("@", INCLUSIVE), 0.0); - assertEquals(sketch.getRank("A", INCLUSIVE), 1.0); - assertEquals(sketch.getMinItem(),"A"); - assertEquals(sketch.getMaxItem(), "A"); - assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), "A"); - assertEquals(sketch.getQuantile(0.5, INCLUSIVE), "A"); - } - - @Test - public void tenValues() { - final String[] tenStr = {"A","B","C","D","E","F","G","H","I","J"}; - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - final int strLen = tenStr.length; - final double dblStrLen = strLen; - for (int i = 1; i <= strLen; i++) { sketch.update(tenStr[i - 1]); } - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getN(), strLen); - assertEquals(sketch.getNumRetained(), strLen); - for (int i = 1; i <= strLen; i++) { - assertEquals(sketch.getRank(tenStr[i - 1], EXCLUSIVE), (i - 1) / dblStrLen); - assertEquals(sketch.getRank(tenStr[i - 1], INCLUSIVE), i / dblStrLen); - } - final String[] qArr = tenStr; - double[] rOut = sketch.getRanks(qArr); //inclusive - for (int i = 0; i < qArr.length; i++) { - assertEquals(rOut[i], (i + 1) / dblStrLen); - } - rOut = sketch.getRanks(qArr, EXCLUSIVE); //exclusive - for (int i = 0; i < qArr.length; i++) { - assertEquals(rOut[i], i / 10.0); - } - - for (int i = 0; i <= strLen; i++) { - final double rank = i/dblStrLen; - String q = rank == 1.0 ? tenStr[i-1] : tenStr[i]; - assertEquals(sketch.getQuantile(rank, EXCLUSIVE), q); - q = rank == 0 ? tenStr[i] : tenStr[i - 1]; - assertEquals(sketch.getQuantile(rank, INCLUSIVE), q); //ERROR - } - - { - // getQuantile() and getQuantiles() equivalence EXCLUSIVE - final String[] quantiles = - sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}, EXCLUSIVE); - for (int i = 0; i <= 10; i++) { - assertEquals(sketch.getQuantile(i / 10.0, EXCLUSIVE), quantiles[i]); - } - } - { - // getQuantile() and getQuantiles() equivalence INCLUSIVE - final String[] quantiles = - sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1}, INCLUSIVE); - for (int i = 0; i <= 10; i++) { - assertEquals(sketch.getQuantile(i / 10.0, INCLUSIVE), quantiles[i]); - } - } - } - - @Test - public void manyValuesEstimationMode() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final int n = 1_000_000; - final int digits = Util.numDigits(n); - - for (int i = 1; i <= n; i++) { - sketch.update(Util.longToFixedLengthString(i, digits)); - assertEquals(sketch.getN(), i); - } - - // test getRank - for (int i = 1; i <= n; i++) { - final double trueRank = (double) i / n; - final String s = Util.longToFixedLengthString(i, digits); - final double r = sketch.getRank(s); - assertEquals(r, trueRank, PMF_EPS_FOR_K_256, "for value " + s); - } - - // test getPMF - final String s = Util.longToFixedLengthString(n/2, digits); - final double[] pmf = sketch.getPMF(new String[] {s}); // split at median - assertEquals(pmf.length, 2); - assertEquals(pmf[0], 0.5, PMF_EPS_FOR_K_256); - assertEquals(pmf[1], 0.5, PMF_EPS_FOR_K_256); - - assertEquals(sketch.getMinItem(), Util.longToFixedLengthString(1, digits)); - assertEquals(sketch.getMaxItem(), Util.longToFixedLengthString(n, digits)); - - // check at every 0.1 percentage point - final double[] fractions = new double[1001]; - final double[] reverseFractions = new double[1001]; // check that ordering doesn't matter - for (int i = 0; i <= 1000; i++) { - fractions[i] = (double) i / 1000; - reverseFractions[1000 - i] = fractions[i]; - } - final String[] quantiles = sketch.getQuantiles(fractions); - final String[] reverseQuantiles = sketch.getQuantiles(reverseFractions); - String previousQuantile = ""; - for (int i = 0; i <= 1000; i++) { - final String quantile = sketch.getQuantile(fractions[i]); - assertEquals(quantile, quantiles[i]); - assertEquals(quantile, reverseQuantiles[1000 - i]); - assertTrue(Util.le(previousQuantile, quantile, Comparator.naturalOrder())); - previousQuantile = quantile; - } - } - - @Test - public void getRankGetCdfGetPmfConsistency() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final int n = 1000; - final int digits = Util.numDigits(n); - final String[] quantiles = new String[n]; - for (int i = 0; i < n; i++) { - final String str = Util.longToFixedLengthString(i, digits); - sketch.update(str); - quantiles[i] = str; - } - { //EXCLUSIVE - final double[] ranks = sketch.getCDF(quantiles, EXCLUSIVE); - final double[] pmf = sketch.getPMF(quantiles, EXCLUSIVE); - double sumPmf = 0; - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(quantiles[i], EXCLUSIVE), NUMERIC_NOISE_TOLERANCE, "rank vs CDF for value " + i); - sumPmf += pmf[i]; - assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i); - } - sumPmf += pmf[n]; - assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE); - assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE); - } - { // INCLUSIVE (default) - final double[] ranks = sketch.getCDF(quantiles, INCLUSIVE); - final double[] pmf = sketch.getPMF(quantiles, INCLUSIVE); - double sumPmf = 0; - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(quantiles[i], INCLUSIVE), NUMERIC_NOISE_TOLERANCE, - "rank vs CDF for value " + i); - sumPmf += pmf[i]; - assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i); - } - sumPmf += pmf[n]; - assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE); - assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE); - } - } - - @Test - public void merge() { - final KllItemsSketch sketch1 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final KllItemsSketch sketch2 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final int n = 10000; - final int digits = Util.numDigits(2 * n); - for (int i = 0; i < n; i++) { - sketch1.update(Util.longToFixedLengthString(i, digits)); - sketch2.update(Util.longToFixedLengthString((2 * n) - i - 1, digits)); - } - - assertEquals(sketch1.getMinItem(), Util.longToFixedLengthString(0, digits)); - assertEquals(sketch1.getMaxItem(), Util.longToFixedLengthString(n - 1, digits)); - - assertEquals(sketch2.getMinItem(), Util.longToFixedLengthString(n, digits)); - assertEquals(sketch2.getMaxItem(), Util.longToFixedLengthString((2 * n) - 1, digits)); - - sketch1.merge(sketch2); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2L * n); - assertEquals(sketch1.getMinItem(), Util.longToFixedLengthString(0, digits)); - assertEquals(sketch1.getMaxItem(), Util.longToFixedLengthString((2 * n) - 1, digits)); - final String upperBound = Util.longToFixedLengthString(n + (int)ceil(n * PMF_EPS_FOR_K_256), digits); - final String lowerBound = Util.longToFixedLengthString(n - (int)ceil(n * PMF_EPS_FOR_K_256), digits); - final String median = sketch1.getQuantile(0.5); - assertTrue(Util.le(median, upperBound, Comparator.naturalOrder())); - assertTrue(Util.le(lowerBound, median, Comparator.naturalOrder())); - } - - @Test - public void mergeLowerK() { - final KllItemsSketch sketch1 = KllItemsSketch.newHeapInstance(256, Comparator.naturalOrder(), serDe); - final KllItemsSketch sketch2 = KllItemsSketch.newHeapInstance(128, Comparator.naturalOrder(), serDe); - final int n = 10000; - final int digits = Util.numDigits(2 * n); - for (int i = 0; i < n; i++) { - sketch1.update(Util.longToFixedLengthString(i, digits)); - sketch2.update(Util.longToFixedLengthString((2 * n) - i - 1, digits)); - } - - assertEquals(sketch1.getMinItem(), Util.longToFixedLengthString(0, digits)); - assertEquals(sketch1.getMaxItem(), Util.longToFixedLengthString(n - 1, digits)); - - assertEquals(sketch2.getMinItem(), Util.longToFixedLengthString(n, digits)); - assertEquals(sketch2.getMaxItem(), Util.longToFixedLengthString((2 * n) - 1, digits)); - - assertTrue(sketch1.getNormalizedRankError(false) < sketch2.getNormalizedRankError(false)); - assertTrue(sketch1.getNormalizedRankError(true) < sketch2.getNormalizedRankError(true)); - sketch1.merge(sketch2); - - // sketch1 must get "contaminated" by the lower K in sketch2 - assertEquals(sketch1.getNormalizedRankError(false), sketch2.getNormalizedRankError(false)); - assertEquals(sketch1.getNormalizedRankError(true), sketch2.getNormalizedRankError(true)); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2 * n); - assertEquals(sketch1.getMinItem(), Util.longToFixedLengthString(0, digits)); - assertEquals(sketch1.getMaxItem(), Util.longToFixedLengthString((2 * n) - 1, digits)); - final String upperBound = Util.longToFixedLengthString(n + (int)ceil(2 * n * PMF_EPS_FOR_K_128), digits); - final String lowerBound = Util.longToFixedLengthString(n - (int)ceil(2 * n * PMF_EPS_FOR_K_128), digits); - final String median = sketch1.getQuantile(0.5); - assertTrue(Util.le(median, upperBound, Comparator.naturalOrder())); - assertTrue(Util.le(lowerBound, median, Comparator.naturalOrder())); - } - - @Test - public void mergeEmptyLowerK() { - final KllItemsSketch sketch1 = KllItemsSketch.newHeapInstance(256, Comparator.naturalOrder(), serDe); - final KllItemsSketch sketch2 = KllItemsSketch.newHeapInstance(128, Comparator.naturalOrder(), serDe); - final int n = 10000; - final int digits = Util.numDigits(n); - for (int i = 0; i < n; i++) { - sketch1.update(Util.longToFixedLengthString(i, digits)); //sketch2 is empty - } - - // rank error should not be affected by a merge with an empty sketch with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - { - assertFalse(sketch1.isEmpty()); - assertTrue(sketch2.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), Util.longToFixedLengthString(0, digits)); - assertEquals(sketch1.getMaxItem(), Util.longToFixedLengthString(n - 1, digits)); - final String upperBound = Util.longToFixedLengthString((n / 2) + (int)ceil(n * PMF_EPS_FOR_K_256), digits); - final String lowerBound = Util.longToFixedLengthString((n / 2) - (int)ceil(n * PMF_EPS_FOR_K_256), digits); - final String median = sketch1.getQuantile(0.5); - assertTrue(Util.le(median, upperBound, Comparator.naturalOrder())); - assertTrue(Util.le(lowerBound, median, Comparator.naturalOrder())); - } - { - //merge the other way - sketch2.merge(sketch1); - assertFalse(sketch1.isEmpty()); - assertFalse(sketch2.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch2.getN(), n); - assertEquals(sketch1.getMinItem(), Util.longToFixedLengthString(0, digits)); - assertEquals(sketch1.getMaxItem(), Util.longToFixedLengthString(n - 1, digits)); - assertEquals(sketch2.getMinItem(), Util.longToFixedLengthString(0, digits)); - assertEquals(sketch2.getMaxItem(), Util.longToFixedLengthString(n - 1, digits)); - final String upperBound = Util.longToFixedLengthString((n / 2) + (int)ceil(n * PMF_EPS_FOR_K_128), digits); - final String lowerBound = Util.longToFixedLengthString((n / 2) - (int)ceil(n * PMF_EPS_FOR_K_128), digits); - final String median = sketch2.getQuantile(0.5); - assertTrue(Util.le(median, upperBound, Comparator.naturalOrder())); - assertTrue(Util.le(lowerBound, median, Comparator.naturalOrder())); - } - } - - @Test - public void mergeExactModeLowerK() { - final KllItemsSketch sketch1 = KllItemsSketch.newHeapInstance(256, Comparator.naturalOrder(), serDe); - final KllItemsSketch sketch2 = KllItemsSketch.newHeapInstance(128, Comparator.naturalOrder(), serDe); - final int n = 10000; - final int digits = Util.numDigits(n); - for (int i = 0; i < n; i++) { - sketch1.update(Util.longToFixedLengthString(i, digits)); - } - sketch2.update(Util.longToFixedLengthString(1, digits)); - - // rank error should not be affected by a merge with a sketch in exact mode with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - } - - @Test - public void mergeMinMinValueFromOther() { - final KllItemsSketch sketch1 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final KllItemsSketch sketch2 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sketch1.update(Util.longToFixedLengthString(1, 1)); - sketch2.update(Util.longToFixedLengthString(2, 1)); - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), Util.longToFixedLengthString(1, 1)); - } - - @Test - public void mergeMinAndMaxFromOther() { - final KllItemsSketch sketch1 = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final KllItemsSketch sketch2 = KllItemsSketch.newHeapInstance(10, Comparator.naturalOrder(), serDe); - final int n = 1_000_000; - final int digits = Util.numDigits(n); - for (int i = 1; i <= 1_000_000; i++) { - sketch1.update(Util.longToFixedLengthString(i, digits)); //sketch2 is empty - } - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), Util.longToFixedLengthString(1, digits)); - assertEquals(sketch2.getMaxItem(), Util.longToFixedLengthString(n, digits)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooSmall() { - KllItemsSketch.newHeapInstance(KllSketch.DEFAULT_M - 1, Comparator.naturalOrder(), serDe); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooLarge() { - KllItemsSketch.newHeapInstance(KllSketch.MAX_K + 1, Comparator.naturalOrder(), serDe); - } - - @Test - public void minK() { - final KllItemsSketch sketch = - KllItemsSketch.newHeapInstance(KllSketch.DEFAULT_M,Comparator.naturalOrder(), serDe); - final int n = 1000; - final int digits = Util.numDigits(n); - for (int i = 0; i < n; i++) { - sketch.update(Util.longToFixedLengthString(i, digits)); - } - assertEquals(sketch.getK(), KllSketch.DEFAULT_M); - final String upperBound = Util.longToFixedLengthString((n / 2) + (int)ceil(n * PMF_EPS_FOR_K_8), digits); - final String lowerBound = Util.longToFixedLengthString((n / 2) - (int)ceil(n * PMF_EPS_FOR_K_8), digits); - final String median = sketch.getQuantile(0.5); - assertTrue(Util.le(median, upperBound, Comparator.naturalOrder())); - assertTrue(Util.le(lowerBound, median, Comparator.naturalOrder())); - } - - @Test - public void maxK() { - final KllItemsSketch sketch = - KllItemsSketch.newHeapInstance(KllSketch.MAX_K,Comparator.naturalOrder(), serDe); - final int n = 1000; - final int digits = Util.numDigits(n); - for (int i = 0; i < n; i++) { - sketch.update(Util.longToFixedLengthString(i, digits)); - } - assertEquals(sketch.getK(), KllSketch.MAX_K); - final String upperBound = Util.longToFixedLengthString((n / 2) + (int)ceil(n * PMF_EPS_FOR_K_256), digits); - final String lowerBound = Util.longToFixedLengthString((n / 2) - (int)ceil(n * PMF_EPS_FOR_K_256), digits); - final String median = sketch.getQuantile(0.5); - assertTrue(Util.le(median, upperBound, Comparator.naturalOrder())); - assertTrue(Util.le(lowerBound, median, Comparator.naturalOrder())); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void outOfOrderSplitPoints() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final String s0 = Util.longToFixedLengthString(0, 1); - final String s1 = Util.longToFixedLengthString(1, 1); - sketch.update(s0); - sketch.getCDF(new String[] {s1, s0}); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void nullSplitPoint() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sketch.update(Util.longToFixedLengthString(0, 1)); - sketch.getCDF(new String[] {null}); - } - - - - @Test - public void checkReset() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - final int n = 100; - final int digits = Util.numDigits(n); - for (int i = 1; i <= n; i++) { sketch.update(Util.longToFixedLengthString(i, digits)); } - final long n1 = sketch.getN(); - final String min1 = sketch.getMinItem(); - final String max1 = sketch.getMaxItem(); - sketch.reset(); - for (int i = 1; i <= 100; i++) { sketch.update(Util.longToFixedLengthString(i, digits)); } - final long n2 = sketch.getN(); - final String min2 = sketch.getMinItem(); - final String max2 = sketch.getMaxItem(); - assertEquals(n2, n1); - assertEquals(min2, min1); - assertEquals(max2, max1); - } - - @Test - public void checkReadOnlyUpdate() { - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - final KllItemsSketch sk2 = KllItemsSketch.wrap(seg, Comparator.naturalOrder(), serDe); - try { sk2.update("A"); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkNewDirectInstanceAndSmallSize() { - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - KllItemsSketch sk2 = KllItemsSketch.wrap(seg, Comparator.naturalOrder(), serDe); - int sizeBytes = sk2.currentSerializedSizeBytes(false); - assertEquals(sizeBytes, 8); - - sk1.update("A"); - seg = MemorySegment.ofArray(sk1.toByteArray()); - sk2 = KllItemsSketch.wrap(seg, Comparator.naturalOrder(), serDe); - sizeBytes = sk2.currentSerializedSizeBytes(false); - assertEquals(sizeBytes, 8 + 5); - - sk1.update("B"); - seg = MemorySegment.ofArray(sk1.toByteArray()); - sk2 = KllItemsSketch.wrap(seg, Comparator.naturalOrder(), serDe); - sizeBytes = sk2.currentSerializedSizeBytes(false); - assertEquals(sizeBytes, 20 + 4 + (2 * 5) + (2 * 5)); - } - - @Test - public void sortedView() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - sk.update("A"); - sk.update("AB"); - sk.update("ABC"); - - final GenericSortedView view = sk.getSortedView(); - final GenericSortedViewIterator itr = view.iterator(); - assertEquals(itr.next(), true); - assertEquals(itr.getQuantile(), "A"); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 0); - assertEquals(itr.getNaturalRank(INCLUSIVE), 1); - assertEquals(itr.next(), true); - assertEquals(itr.getQuantile(), "AB"); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 1); - assertEquals(itr.getNaturalRank(INCLUSIVE), 2); - assertEquals(itr.next(), true); - assertEquals(itr.getQuantile(), "ABC"); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 2); - assertEquals(itr.getNaturalRank(INCLUSIVE), 3); - assertEquals(itr.next(), false); - } - - @Test //also visual - public void checkCDF_PDF() { - final double[] cdfI = {.25, .50, .75, 1.0, 1.0 }; - final double[] cdfE = {0.0, .25, .50, .75, 1.0 }; - final double[] pmfI = {.25, .25, .25, .25, 0.0 }; - final double[] pmfE = {0.0, .25, .25, .25, .25 }; - final double toll = 1E-10; - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - final String[] strIn = {"A", "AB", "ABC", "ABCD"}; - for (int i = 0; i < strIn.length; i++) { sketch.update(strIn[i]); } - final String[] sp = {"A", "AB", "ABC", "ABCD"}; - println("SplitPoints:"); - for (int i = 0; i < sp.length; i++) { - printf("%10s", sp[i]); - } - println(""); - println("INCLUSIVE:"); - double[] cdf = sketch.getCDF(sp, INCLUSIVE); - double[] pmf = sketch.getPMF(sp, INCLUSIVE); - printf("%10s%10s\n", "CDF", "PMF"); - for (int i = 0; i < cdf.length; i++) { - printf("%10.2f%10.2f\n", cdf[i], pmf[i]); - assertEquals(cdf[i], cdfI[i], toll); - assertEquals(pmf[i], pmfI[i], toll); - } - println("EXCLUSIVE"); - cdf = sketch.getCDF(sp, EXCLUSIVE); - pmf = sketch.getPMF(sp, EXCLUSIVE); - printf("%10s%10s\n", "CDF", "PMF"); - for (int i = 0; i < cdf.length; i++) { - printf("%10.2f%10.2f\n", cdf[i], pmf[i]); - assertEquals(cdf[i], cdfE[i], toll); - assertEquals(pmf[i], pmfE[i], toll); - } - } - - @Test - public void checkWrapCase1Items() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - final int n = 21; - final int digits = Util.numDigits(n); - for (int i = 1; i <= n; i++) { sk.update(Util.longToFixedLengthString(i, digits)); } - - final MemorySegment seg = MemorySegment.ofArray(sk.toByteArray()).asReadOnly(); - final KllItemsSketch sk2 = KllItemsSketch.wrap(seg, Comparator.naturalOrder(), serDe); - - assertTrue(seg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkReadOnlyExceptions() { - final int[] intArr = {}; - final int intV = 2; - final int idx = 1; - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - final KllItemsSketch sk2 = KllItemsSketch.wrap(seg, Comparator.naturalOrder(), serDe); - try { sk2.setLevelsArray(intArr); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setLevelsArrayAt(idx,intV); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkIsSameResource() { - final int cap = 128; - final MemorySegment wseg = MemorySegment.ofArray(new byte[cap]); //heap - final MemorySegment slice1 = wseg.asSlice(0, 64); - final MemorySegment slice2 = wseg.asSlice(64, 64); - assertFalse(slice1 == slice2); - assertFalse(MemorySegmentStatus.isSameResource(slice1, slice2)); //same original resource, but different offsets - - final MemorySegment slice3 = wseg.asSlice(0, 64); - assertFalse(slice1 == slice3); - assertTrue(MemorySegmentStatus.isSameResource(slice1, slice3)); //same original resource, same offsets, different views. - slice1.set(JAVA_INT_UNALIGNED, 0, -1); - assertEquals(-1, slice3.get(JAVA_INT_UNALIGNED, 0)); //proof - slice1.set(JAVA_INT_UNALIGNED, 0, 0); - - final byte[] byteArr1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe).toByteArray(); - MemorySegment.copy(byteArr1, 0, slice1, JAVA_BYTE, 0, byteArr1.length); - final KllItemsSketch sk1 = KllItemsSketch.wrap(slice1, Comparator.naturalOrder(), serDe); - - final byte[] byteArr2 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe).toByteArray(); - MemorySegment.copy(byteArr2, 0, slice2, JAVA_BYTE, 0, byteArr2.length); - assertFalse(sk1.isSameResource(slice2)); //same original resource, but different offsets - - final byte[] byteArr3 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe).toByteArray(); - MemorySegment.copy(byteArr3, 0, slice3, JAVA_BYTE, 0, byteArr3.length); - assertTrue(sk1.isSameResource(slice3)); //same original resource, same offsets, different views. - } - - // New added tests specially for KllItemsSketch - @Test - public void checkHeapifyEmpty() { - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(seg, SketchType.KLL_ITEMS_SKETCH, serDe); - assertEquals(segVal.sketchStructure, COMPACT_EMPTY); - assertEquals(seg.byteSize(), 8); - final KllItemsSketch sk2 = KllItemsSketch.heapify(seg, Comparator.naturalOrder(), serDe); - assertEquals(sk2.sketchStructure, UPDATABLE); - assertEquals(sk2.getN(), 0); - assertFalse(sk2.isReadOnly()); - try { sk2.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - println(sk1.toString(true, true)); - println(""); - println(KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe)); - } - - @Test - public void checkHeapifySingleItem() { - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - sk1.update("A"); - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(seg, SketchType.KLL_ITEMS_SKETCH, serDe); - assertEquals(segVal.sketchStructure, COMPACT_SINGLE); - assertEquals(seg.byteSize(), segVal.sketchBytes); - final KllItemsSketch sk2 = KllItemsSketch.heapify(seg, Comparator.naturalOrder(), serDe); - assertEquals(sk2.sketchStructure, UPDATABLE); - assertEquals(sk2.getN(), 1); - assertFalse(sk2.isReadOnly()); - assertEquals(sk2.getMinItem(), "A"); - assertEquals(sk2.getMaxItem(), "A"); - println(sk1.toString(true, true)); - println(""); - println(KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe)); - } - - @Test - public void checkHeapifyFewItems() { - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - sk1.update("A"); - sk1.update("AB"); - sk1.update("ABC"); - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(seg, SketchType.KLL_ITEMS_SKETCH, serDe); - assertEquals(segVal.sketchStructure, COMPACT_FULL); - assertEquals(seg.byteSize(), segVal.sketchBytes); - println(sk1.toString(true, true)); - println(""); - println(KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe)); - } - - @Test - public void checkHeapifyManyItems() { - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - final int n = 109; - final int digits = Util.numDigits(n); - for (int i = 1; i <= n; i++) { - sk1.update(Util.longToFixedLengthString(i, digits)); - } - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - final KllMemorySegmentValidate segVal = new KllMemorySegmentValidate(seg, SketchType.KLL_ITEMS_SKETCH, serDe); - assertEquals(segVal.sketchStructure, COMPACT_FULL); - assertEquals(seg.byteSize(), segVal.sketchBytes); - println(sk1.toString(true, true)); - println(""); - println(KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe)); - } - - @Test - public void checkWrapCausingLevelsCompaction() { - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - final int n = 109; - final int digits = Util.numDigits(n); - for (int i = 1; i <= n; i++) { - sk1.update(Util.longToFixedLengthString(i, digits)); - } - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()).asReadOnly(); - final KllItemsSketch sk2 = KllItemsSketch.wrap(seg, Comparator.naturalOrder(), serDe); - assertTrue(seg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); //not off-heap - println(sk1.toString(true, true)); - println(""); - println(sk2.toString(true, true)); - println(""); - println(KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe)); - } - - @Test - public void checkExceptions() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - try { sk.getTotalItemsByteArr(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getTotalItemsNumBytes(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.setMemorySegment(null); fail(); } catch (final SketchesArgumentException e) { } - final byte[] byteArr = sk.toByteArray(); - final KllItemsSketch sk2 = KllItemsSketch.wrap(MemorySegment.ofArray(byteArr), Comparator.naturalOrder(), serDe); - try { sk2.incN(1); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setItemsArray(null); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setItemsArrayAt(0, null); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setLevelZeroSorted(false); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setMaxItem(null); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setMinItem(null); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setMinK(0); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setN(0); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkSortedViewAfterReset() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - sk.update("1"); - final GenericSortedView sv = sk.getSortedView(); - final String ssv = sv.getQuantile(1.0, INCLUSIVE); - assertEquals(ssv, "1"); - sk.reset(); - try { sk.getSortedView(); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - //There is no guarantee that L0 is sorted after a merge. - //The issue is, during a merge, L0 must be sorted prior to a compaction to a higher level. - //Otherwise the higher levels would not be sorted properly. - public void checkL0SortDuringMergeIssue527() throws NumberFormatException { - final Random rand = new Random(); - final KllItemsSketch sk1 = KllItemsSketch.newHeapInstance(8, Comparator.reverseOrder(), serDe); - final KllItemsSketch sk2 = KllItemsSketch.newHeapInstance(8, Comparator.reverseOrder(), serDe); - final int n = 26; //don't change this - for (int i = 1; i <= n; i++ ) { - final int j = rand.nextInt(n) + 1; - sk1.update(getString(j, 3)); - sk2.update(getString(j +100, 3)); - } - sk1.merge(sk2); - println(sk1.toString(true, true)); //L1 and above should be sorted in reverse. Ignore L0. - final int lvl1size = sk1.levelsArr[2] - sk1.levelsArr[1]; - final QuantilesGenericSketchIteratorAPI itr = sk1.iterator(); - itr.next(); - int prev = Integer.parseInt(itr.getQuantile().trim()); - for (int i = 1; i < lvl1size; i++) { - if (itr.next()) { - final int v = Integer.parseInt(itr.getQuantile().trim()); - assertTrue(v <= prev); - prev = v; - } - } - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllItemsSketchiteratorTest.java b/src/test/java/org/apache/datasketches/kll/KllItemsSketchiteratorTest.java deleted file mode 100644 index 1e8623b47..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllItemsSketchiteratorTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.kll.KllItemsSketch; -import org.apache.datasketches.quantilescommon.GenericSortedViewIterator; -import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class KllItemsSketchiteratorTest { - private final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - - @Test - public void emptySketch() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final QuantilesGenericSketchIteratorAPI it = sketch.iterator(); - Assert.assertFalse(it.next()); - } - - @Test - public void oneItemSketch() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sketch.update("1"); - final QuantilesGenericSketchIteratorAPI it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getQuantile(), "1"); - Assert.assertEquals(it.getWeight(), 1); - Assert.assertFalse(it.next()); - } - - @Test - public void twoItemSketchForIterator() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sketch.update("1"); - sketch.update("2"); - final QuantilesGenericSketchIteratorAPI itr = sketch.iterator(); - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), "2"); - assertEquals(itr.getWeight(), 1); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), "1"); - assertEquals(itr.getWeight(), 1); - } - - @Test - public void twoItemSketchForSortedViewIterator() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sketch.update("1"); - sketch.update("2"); - final GenericSortedViewIterator itr = sketch.getSortedView().iterator(); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), "1"); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 0); - assertEquals(itr.getNaturalRank(INCLUSIVE), 1); - assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0); - assertEquals(itr.getNormalizedRank(INCLUSIVE), 0.5); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), "2"); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 1); - assertEquals(itr.getNaturalRank(INCLUSIVE), 2); - assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0.5); - assertEquals(itr.getNormalizedRank(INCLUSIVE), 1.0); - } - - @Test - public void bigSketches() { - final int digits = 6; - for (int n = 1000; n < 100_000; n += 2000) { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - for (int i = 0; i < n; i++) { - sketch.update(Util.longToFixedLengthString(i, digits)); - } - final QuantilesGenericSketchIteratorAPI it = sketch.iterator(); - int count = 0; - int weight = 0; - while (it.next()) { - count++; - weight += (int)it.getWeight(); - } - Assert.assertEquals(count, sketch.getNumRetained()); - Assert.assertEquals(weight, n); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllLongsSketchIteratorTest.java b/src/test/java/org/apache/datasketches/kll/KllLongsSketchIteratorTest.java deleted file mode 100644 index 69d947afd..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllLongsSketchIteratorTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import org.apache.datasketches.kll.KllLongsSketch; -import org.apache.datasketches.quantilescommon.LongsSortedViewIterator; -import org.apache.datasketches.quantilescommon.QuantilesLongsSketchIterator; -import org.testng.Assert; -import org.testng.annotations.Test; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -public class KllLongsSketchIteratorTest { - - @Test - public void emptySketch() { - KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - QuantilesLongsSketchIterator it = sketch.iterator(); - Assert.assertFalse(it.next()); - } - - @Test - public void oneItemSketch() { - KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - sketch.update(1); - QuantilesLongsSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getQuantile(), 1L); - Assert.assertEquals(it.getWeight(), 1); - Assert.assertFalse(it.next()); - } - - @Test - public void twoItemSketchForIterator() { - KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - sketch.update(1); - sketch.update(2); - QuantilesLongsSketchIterator itr = sketch.iterator(); - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 2L); - assertEquals(itr.getWeight(), 1); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 1L); - assertEquals(itr.getWeight(), 1); - } - - @Test - public void twoItemSketchForSortedViewIterator() { - KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - sketch.update(1); - sketch.update(2); - LongsSortedViewIterator itr = sketch.getSortedView().iterator(); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 1L); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 0); - assertEquals(itr.getNaturalRank(INCLUSIVE), 1); - assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0); - assertEquals(itr.getNormalizedRank(INCLUSIVE), 0.5); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 2L); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 1); - assertEquals(itr.getNaturalRank(INCLUSIVE), 2); - assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0.5); - assertEquals(itr.getNormalizedRank(INCLUSIVE), 1.0); - } - - @Test - public void bigSketches() { - for (int n = 1000; n < 100000; n += 2000) { - KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - for (int i = 0; i < n; i++) { - sketch.update(i); - } - QuantilesLongsSketchIterator it = sketch.iterator(); - int count = 0; - int weight = 0; - while (it.next()) { - count++; - weight += (int)it.getWeight(); - } - Assert.assertEquals(count, sketch.getNumRetained()); - Assert.assertEquals(weight, n); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllLongsSketchSerDeTest.java b/src/test/java/org/apache/datasketches/kll/KllLongsSketchSerDeTest.java deleted file mode 100644 index c36f0a4f4..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllLongsSketchSerDeTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllLongsSketch; -import org.testng.annotations.Test; - -public class KllLongsSketchSerDeTest { - - @Test - public void serializeDeserializeEmpty() { - final int N = 20; - - final KllLongsSketch sk1 = KllLongsSketch.newHeapInstance(N); - //Empty: from heap -> byte[] -> heap - final byte[] bytes = sk1.toByteArray(); - final KllLongsSketch sk2 = KllLongsSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sk1.getSerializedSizeBytes()); - assertTrue(sk2.isEmpty()); - assertEquals(sk2.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk2.getN(), sk1.getN()); - assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - try { sk2.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk2.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - - //Empty: from heap -> byte[] -> off heap - final KllLongsSketch sk3 = KllLongsSketch.wrap(MemorySegment.ofArray(bytes)); - assertTrue(sk3.isEmpty()); - assertEquals(sk3.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk3.getN(), sk1.getN()); - assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - try { sk3.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sk3.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap -> byte[] -> compare byte[] - final byte[] bytes2 = sk3.toByteArray(); - assertEquals(bytes, bytes2); - } - - @Test - public void serializeDeserializeOneValue() { - final KllLongsSketch sk1 = KllLongsSketch.newHeapInstance(); - sk1.update(1); - - //from heap -> byte[] -> heap - final byte[] bytes = sk1.toByteArray(); - final KllLongsSketch sk2 = KllLongsSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sk1.getSerializedSizeBytes()); - assertFalse(sk2.isEmpty()); - assertEquals(sk2.getNumRetained(), 1); - assertEquals(sk2.getN(), 1); - assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk2.getMinItem(), 1L); - assertEquals(sk2.getMaxItem(), 1L); - assertEquals(sk2.getSerializedSizeBytes(), Long.BYTES + Long.BYTES); - - //from heap -> byte[] -> off heap - final KllLongsSketch sk3 = KllLongsSketch.wrap(MemorySegment.ofArray(bytes)); - assertFalse(sk3.isEmpty()); - assertEquals(sk3.getNumRetained(), 1); - assertEquals(sk3.getN(), 1); - assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk3.getMinItem(), 1L); - assertEquals(sk3.getMaxItem(), 1L); - assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap -> byte[] -> compare byte[] - final byte[] bytes2 = sk3.toByteArray(); - assertEquals(bytes, bytes2); - } - - @Test - public void serializeDeserializeMultipleValues() { - final KllLongsSketch sk1 = KllLongsSketch.newHeapInstance(); - final int n = 1000; - for (int i = 0; i < n; i++) { - sk1.update(i); - } - assertEquals(sk1.getMinItem(), 0); - assertEquals(sk1.getMaxItem(), 999L); - - //from heap -> byte[] -> heap - final byte[] bytes = sk1.toByteArray(); - final KllLongsSketch sk2 = KllLongsSketch.heapify(MemorySegment.ofArray(bytes)); - assertEquals(bytes.length, sk1.getSerializedSizeBytes()); - assertFalse(sk2.isEmpty()); - assertEquals(sk2.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk2.getN(), sk1.getN()); - assertEquals(sk2.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk2.getMinItem(), sk1.getMinItem()); - assertEquals(sk2.getMaxItem(), sk1.getMaxItem()); - assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - - //from heap -> byte[] -> off heap - final KllLongsSketch sk3 = KllLongsSketch.wrap(MemorySegment.ofArray(bytes)); - assertFalse(sk3.isEmpty()); - assertEquals(sk3.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk3.getN(), sk1.getN()); - assertEquals(sk3.getNormalizedRankError(false), sk1.getNormalizedRankError(false)); - assertEquals(sk3.getMinItem(), sk1.getMinItem()); - assertEquals(sk3.getMaxItem(), sk1.getMaxItem()); - assertEquals(sk3.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - //from heap -> byte[] -> off heap -> byte[] -> compare byte[] - final byte[] bytes2 = sk3.toByteArray(); - assertEquals(bytes, bytes2); - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllLongsSketchTest.java b/src/test/java/org/apache/datasketches/kll/KllLongsSketchTest.java deleted file mode 100644 index 0721d6335..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllLongsSketchTest.java +++ /dev/null @@ -1,720 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.Math.min; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_LONGS_SKETCH; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllLongsSketch; -import org.apache.datasketches.kll.KllSketch; -import org.apache.datasketches.quantilescommon.LongsSortedView; -import org.apache.datasketches.quantilescommon.LongsSortedViewIterator; -import org.testng.annotations.Test; - -public class KllLongsSketchTest { - private static final String LS = System.getProperty("line.separator"); - private static final double PMF_EPS_FOR_K_8 = KllSketch.getNormalizedRankError(8, true); - private static final double PMF_EPS_FOR_K_128 = KllSketch.getNormalizedRankError(128, true); - private static final double PMF_EPS_FOR_K_256 = KllSketch.getNormalizedRankError(256, true); - private static final double NUMERIC_NOISE_TOLERANCE = 1E-6; - - @Test - public void empty() { - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - assertTrue(sketch.isEmpty()); - assertEquals(sketch.getN(), 0); - assertEquals(sketch.getNumRetained(), 0); - try { sketch.getRank(0); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMinItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantile(0.5); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getQuantiles(new double[] {0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getPMF(new long[] {0}); fail(); } catch (final SketchesArgumentException e) {} - try { sketch.getCDF(new long[] {0}); fail(); } catch (final SketchesArgumentException e) {} - assertNotNull(sketch.toString(true, true)); - assertNotNull(sketch.toString()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantileInvalidArg() { - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - sketch.update(1); - sketch.getQuantile(-1.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void getQuantilesInvalidArg() { - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - sketch.update(1); - sketch.getQuantiles(new double[] {2.0}); - } - - @Test - public void oneValue() { - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - sketch.update(1); - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getN(), 1); - assertEquals(sketch.getNumRetained(), 1); - assertEquals(sketch.getRank(0L, EXCLUSIVE), 0.0); - assertEquals(sketch.getRank(1L, EXCLUSIVE), 0.0); - assertEquals(sketch.getRank(2L, EXCLUSIVE), 1.0); - assertEquals(sketch.getRank(0L, INCLUSIVE), 0.0); - assertEquals(sketch.getRank(1L, INCLUSIVE), 1.0); - assertEquals(sketch.getRank(2L, INCLUSIVE), 1.0); - assertEquals(sketch.getMinItem(), 1L); - assertEquals(sketch.getMaxItem(), 1L); - assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 1L); - assertEquals(sketch.getQuantile(0.5, INCLUSIVE), 1L); - } - - @Test - public void tenValues() { - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= 10; i++) { sketch.update(i); } - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getN(), 10); - assertEquals(sketch.getNumRetained(), 10); - for (int i = 1; i <= 10; i++) { - assertEquals(sketch.getRank(i, EXCLUSIVE), (i - 1) / 10.0); - assertEquals(sketch.getRank(i, INCLUSIVE), i / 10.0); - } - final long[] qArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - double[] rOut = sketch.getRanks(qArr); //inclusive - for (int i = 0; i < qArr.length; i++) { - assertEquals(rOut[i], (i + 1) / 10.0); - } - rOut = sketch.getRanks(qArr, EXCLUSIVE); //exclusive - for (int i = 0; i < qArr.length; i++) { - assertEquals(rOut[i], i / 10.0); - } - - for (int i = 0; i >= 10; i++) { - final double rank = i/10.0; - double q = rank == 1.0 ? i : i + 1; - assertEquals(sketch.getQuantile(rank, EXCLUSIVE), q); - q = rank == 0 ? i + 1 : i; - assertEquals(sketch.getQuantile(rank, INCLUSIVE), q); - } - - { - // getQuantile() and getQuantiles() equivalence EXCLUSIVE - final long[] quantiles = - sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}, EXCLUSIVE); - for (int i = 0; i <= 10; i++) { - assertEquals(sketch.getQuantile(i / 10.0, EXCLUSIVE), quantiles[i]); - } - } - { - // getQuantile() and getQuantiles() equivalence INCLUSIVE - final long[] quantiles = - sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}, INCLUSIVE); - for (int i = 0; i <= 10; i++) { - assertEquals(sketch.getQuantile(i / 10.0, INCLUSIVE), quantiles[i]); - } - } - } - - @Test - public void manyValuesEstimationMode() { - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - final int n = 1_000_000; - - for (int i = 0; i < n; i++) { - sketch.update(i); - } - assertEquals(sketch.getN(), n); - - // test getRank - for (int i = 0; i < n; i++) { - final double trueRank = (double) i / n; - assertEquals(sketch.getRank(i), trueRank, PMF_EPS_FOR_K_256, "for value " + i); - } - - // test getPMF - final double[] pmf = sketch.getPMF(new long[] {n / 2}); // split at median - assertEquals(pmf.length, 2); - assertEquals(pmf[0], 0.5, PMF_EPS_FOR_K_256); - assertEquals(pmf[1], 0.5, PMF_EPS_FOR_K_256); - - assertEquals(sketch.getMinItem(), 0); // min value is exact - assertEquals(sketch.getMaxItem(), n - 1); // max value is exact - - // check at every 0.1 percentage point - final double[] fractions = new double[1001]; - final double[] reverseFractions = new double[1001]; // check that ordering doesn't matter - for (int i = 0; i <= 1000; i++) { - fractions[i] = (double) i / 1000; - reverseFractions[1000 - i] = fractions[i]; - } - final long[] quantiles = sketch.getQuantiles(fractions); - final long[] reverseQuantiles = sketch.getQuantiles(reverseFractions); - double previousQuantile = 0; - for (int i = 0; i <= 1000; i++) { - final double quantile = sketch.getQuantile(fractions[i]); - assertEquals(quantile, quantiles[i]); - assertEquals(quantile, reverseQuantiles[1000 - i]); - assertTrue(previousQuantile <= quantile); - previousQuantile = quantile; - } - } - - @Test - public void getRankGetCdfGetPmfConsistency() { - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - final int n = 1000; - final long[] values = new long[n]; - for (int i = 0; i < n; i++) { - sketch.update(i); - values[i] = i; - } - { // inclusive = false (default) - final double[] ranks = sketch.getCDF(values); - final double[] pmf = sketch.getPMF(values); - double sumPmf = 0; - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i]), NUMERIC_NOISE_TOLERANCE, - "rank vs CDF for value " + i); - sumPmf += pmf[i]; - assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i); - } - sumPmf += pmf[n]; - assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE); - assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE); - } - { // inclusive = true - final double[] ranks = sketch.getCDF(values, INCLUSIVE); - final double[] pmf = sketch.getPMF(values, INCLUSIVE); - double sumPmf = 0; - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i], INCLUSIVE), NUMERIC_NOISE_TOLERANCE, - "rank vs CDF for value " + i); - sumPmf += pmf[i]; - assertEquals(ranks[i], sumPmf, NUMERIC_NOISE_TOLERANCE, "CDF vs PMF for value " + i); - } - sumPmf += pmf[n]; - assertEquals(sumPmf, 1.0, NUMERIC_NOISE_TOLERANCE); - assertEquals(ranks[n], 1.0, NUMERIC_NOISE_TOLERANCE); - } - } - - @Test - public void merge() { - final KllLongsSketch sketch1 = KllLongsSketch.newHeapInstance(); - final KllLongsSketch sketch2 = KllLongsSketch.newHeapInstance(); - final int n = 10000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - sketch2.update((2 * n) - i - 1); - } - - assertEquals(sketch1.getMinItem(), 0); - assertEquals(sketch1.getMaxItem(), (n - 1)); - - assertEquals(sketch2.getMinItem(), n); - assertEquals(sketch2.getMaxItem(), ((2 * n) - 1)); - - sketch1.merge(sketch2); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2L * n); - assertEquals(sketch1.getMinItem(), 0); - assertEquals(sketch1.getMaxItem(), ((2 * n) - 1)); - assertEquals(sketch1.getQuantile(0.5), n, 2 * n * PMF_EPS_FOR_K_256); - } - - @Test - public void mergeLowerK() { - final KllLongsSketch sketch1 = KllLongsSketch.newHeapInstance(256); - final KllLongsSketch sketch2 = KllLongsSketch.newHeapInstance(128); - final int n = 10000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - sketch2.update((2 * n) - i - 1); - } - - assertEquals(sketch1.getMinItem(), 0); - assertEquals(sketch1.getMaxItem(), n - 1L); - - assertEquals(sketch2.getMinItem(), n); - assertEquals(sketch2.getMaxItem(), (2L * n) - 1L); - - assertTrue(sketch1.getNormalizedRankError(false) < sketch2.getNormalizedRankError(false)); - assertTrue(sketch1.getNormalizedRankError(true) < sketch2.getNormalizedRankError(true)); - sketch1.merge(sketch2); - - // sketch1 must get "contaminated" by the lower K in sketch2 - assertEquals(sketch1.getNormalizedRankError(false), sketch2.getNormalizedRankError(false)); - assertEquals(sketch1.getNormalizedRankError(true), sketch2.getNormalizedRankError(true)); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), 2 * n); - assertEquals(sketch1.getMinItem(), 0); - assertEquals(sketch1.getMaxItem(), (2L * n) - 1L); - assertEquals(sketch1.getQuantile(0.5), n, 2L * n * PMF_EPS_FOR_K_128); - } - - @Test - public void mergeEmptyLowerK() { - final KllLongsSketch sketch1 = KllLongsSketch.newHeapInstance(256); - final KllLongsSketch sketch2 = KllLongsSketch.newHeapInstance(128); - final int n = 10_000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - - // rank error should not be affected by a merge with an empty sketch with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), 0); - assertEquals(sketch1.getMaxItem(), n - 1); - assertEquals(sketch1.getQuantile(0.5), n / 2, n * PMF_EPS_FOR_K_256); - - //merge the other way - sketch2.merge(sketch1); - assertFalse(sketch1.isEmpty()); - assertEquals(sketch1.getN(), n); - assertEquals(sketch1.getMinItem(), 0); - assertEquals(sketch1.getMaxItem(), n - 1); - assertEquals(sketch1.getQuantile(0.5), n / 2, n * PMF_EPS_FOR_K_256); - } - - @Test - public void mergeExactModeLowerK() { - final KllLongsSketch sketch1 = KllLongsSketch.newHeapInstance(256); - final KllLongsSketch sketch2 = KllLongsSketch.newHeapInstance(128); - final int n = 10000; - for (int i = 0; i < n; i++) { - sketch1.update(i); - } - sketch2.update(1); - - // rank error should not be affected by a merge with a sketch in exact mode with lower K - final double rankErrorBeforeMerge = sketch1.getNormalizedRankError(true); - sketch1.merge(sketch2); - assertEquals(sketch1.getNormalizedRankError(true), rankErrorBeforeMerge); - } - - @Test - public void mergeMinMinValueFromOther() { - final KllLongsSketch sketch1 = KllLongsSketch.newHeapInstance(); - final KllLongsSketch sketch2 = KllLongsSketch.newHeapInstance(); - sketch1.update(1); - sketch2.update(2); - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), 1); - } - - @Test - public void mergeMinAndMaxFromOther() { - final KllLongsSketch sketch1 = KllLongsSketch.newHeapInstance(); - for (int i = 1; i <= 1_000_000; i++) { - sketch1.update(i); - } - final KllLongsSketch sketch2 = KllLongsSketch.newHeapInstance(10); - sketch2.merge(sketch1); - assertEquals(sketch2.getMinItem(), 1); - assertEquals(sketch2.getMaxItem(), 1_000_000); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooSmall() { - KllLongsSketch.newHeapInstance(KllSketch.DEFAULT_M - 1); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void kTooLarge() { - KllLongsSketch.newHeapInstance(KllSketch.MAX_K + 1); - } - - @Test - public void minK() { - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(KllSketch.DEFAULT_M); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getK(), KllSketch.DEFAULT_M); - assertEquals(sketch.getQuantile(0.5), 500, 1000 * PMF_EPS_FOR_K_8); - } - - @Test - public void maxK() { - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(KllSketch.MAX_K); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getK(), KllSketch.MAX_K); - assertEquals(sketch.getQuantile(0.5), 500, 1000 * PMF_EPS_FOR_K_256); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void outOfOrderSplitPoints() { - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - sketch.update(0); - sketch.getCDF(new long[] {1L, 0L}); - } - - @Test - public void checkReset() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final long n1 = sk.getN(); - final double min1 = sk.getMinItem(); - final double max1 = sk.getMaxItem(); - sk.reset(); - for (int i = 1; i <= 100; i++) { sk.update(i); } - final long n2 = sk.getN(); - final double min2 = sk.getMinItem(); - final double max2 = sk.getMaxItem(); - assertEquals(n2, n1); - assertEquals(min2, min1); - assertEquals(max2, max1); - } - - @Test - public void checkReadOnlyUpdate() { - final KllLongsSketch sk1 = KllLongsSketch.newHeapInstance(20); - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - final KllLongsSketch sk2 = KllLongsSketch.wrap(seg); - try { sk2.update(1); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkNewDirectInstanceAndSize() { - final MemorySegment wseg = MemorySegment.ofArray(new byte[3000]); - KllLongsSketch.newDirectInstance(wseg); - try { KllLongsSketch.newDirectInstance(null); fail(); } - catch (final NullPointerException e) { } - final int updateSize = KllSketch.getMaxSerializedSizeBytes(200, 0, KLL_LONGS_SKETCH, true); - final int compactSize = KllSketch.getMaxSerializedSizeBytes(200, 0, KLL_LONGS_SKETCH, false); - assertTrue(compactSize < updateSize); - } - - @Test - public void sortedView() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(); - sk.update(3); - sk.update(1); - sk.update(2); - - final LongsSortedView view = sk.getSortedView(); - final LongsSortedViewIterator itr = view.iterator(); - assertEquals(itr.next(), true); - assertEquals(itr.getQuantile(), 1); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 0); - assertEquals(itr.getNaturalRank(INCLUSIVE), 1); - assertEquals(itr.next(), true); - assertEquals(itr.getQuantile(), 2); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 1); - assertEquals(itr.getNaturalRank(INCLUSIVE), 2); - assertEquals(itr.next(), true); - assertEquals(itr.getQuantile(), 3); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 2); - assertEquals(itr.getNaturalRank(INCLUSIVE), 3); - assertEquals(itr.next(), false); - } - - @Test //also visual - public void checkCDF_PDF() { - final double[] cdfI = {.25, .50, .75, 1.0, 1.0 }; - final double[] cdfE = {0.0, .25, .50, .75, 1.0 }; - final double[] pmfI = {.25, .25, .25, .25, 0.0 }; - final double[] pmfE = {0.0, .25, .25, .25, .25 }; - final double toll = 1E-10; - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(); - final long[] doublesIn = {10, 20, 30, 40}; - for (int i = 0; i < doublesIn.length; i++) { sketch.update(doublesIn[i]); } - final long[] sp = { 10, 20, 30, 40 }; - println("SplitPoints:"); - for (int i = 0; i < sp.length; i++) { - printf("%10d", sp[i]); - } - println(""); - println("INCLUSIVE:"); - double[] cdf = sketch.getCDF(sp, INCLUSIVE); - double[] pmf = sketch.getPMF(sp, INCLUSIVE); - printf("%10s%10s" + LS, "CDF", "PMF"); - for (int i = 0; i < cdf.length; i++) { - printf("%10.2f%10.2f" + LS, cdf[i], pmf[i]); - assertEquals(cdf[i], cdfI[i], toll); - assertEquals(pmf[i], pmfI[i], toll); - } - println("EXCLUSIVE"); - cdf = sketch.getCDF(sp, EXCLUSIVE); - pmf = sketch.getPMF(sp, EXCLUSIVE); - printf("%10s%10s" + LS, "CDF", "PMF"); - for (int i = 0; i < cdf.length; i++) { - printf("%10.2f%10.2f" + LS, cdf[i], pmf[i]); - assertEquals(cdf[i], cdfE[i], toll); - assertEquals(pmf[i], pmfE[i], toll); - } - } - - @Test - public void checkWrapCase1Doubles() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment seg = MemorySegment.ofArray(sk.toByteArray()).asReadOnly(); - final KllLongsSketch sk2 = KllLongsSketch.wrap(seg); - - assertTrue(seg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkWritableWrapCase6And2Doubles() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment wseg = MemorySegment.ofArray(KllHelper.toByteArray(sk, true)); - final KllLongsSketch sk2 = KllLongsSketch.wrap(wseg); - - assertFalse(wseg.isReadOnly()); - assertFalse(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkKllSketchCase5Doubles() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - final KllLongsSketch sk2 = KllLongsSketch.wrap(wseg); - - assertFalse(wseg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkKllSketchCase3Doubles() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment seg = MemorySegment.ofArray(KllHelper.toByteArray(sk, true)).asReadOnly(); - final MemorySegment wseg = (MemorySegment) seg; - final KllLongsSketch sk2 = KllLongsSketch.wrap(wseg); - - assertTrue(wseg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkKllSketchCase7Doubles() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - - final MemorySegment seg = MemorySegment.ofArray(KllHelper.toByteArray(sk, true)).asReadOnly(); - final MemorySegment wseg = (MemorySegment) seg; - final KllLongsSketch sk2 = KllLongsSketch.wrap(wseg); - - assertTrue(wseg.isReadOnly()); - assertTrue(sk2.isReadOnly()); - assertFalse(sk2.isOffHeap()); - } - - @Test - public void checkReadOnlyExceptions() { - final int[] intArr = {}; - final int intV = 2; - final int idx = 1; - final KllLongsSketch sk1 = KllLongsSketch.newHeapInstance(20); - final MemorySegment seg = MemorySegment.ofArray(sk1.toByteArray()); - final KllLongsSketch sk2 = KllLongsSketch.wrap(seg); - try { sk2.setLevelsArray(intArr); fail(); } catch (final SketchesArgumentException e) { } - try { sk2.setLevelsArrayAt(idx,intV); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkIsSameResource() { - final int cap = 128; - final MemorySegment wseg = MemorySegment.ofArray(new byte[cap]); - final MemorySegment slice1 = wseg.asSlice(0, 64); - final MemorySegment slice2 = wseg.asSlice(64, 64); - assertFalse(slice1 == slice2); - assertFalse(MemorySegmentStatus.isSameResource(slice1, slice2)); - - final MemorySegment slice3 = wseg.asSlice(0, 64); - assertFalse(slice1 == slice3); - assertTrue(MemorySegmentStatus.isSameResource(slice1, slice3)); - - final byte[] byteArr1 = KllLongsSketch.newHeapInstance(20).toByteArray(); - MemorySegment.copy(byteArr1, 0, slice1, JAVA_BYTE, 0, byteArr1.length); - final KllLongsSketch sk1 = KllLongsSketch.wrap(slice1); - - final byte[] byteArr2 = KllLongsSketch.newHeapInstance(20).toByteArray(); - MemorySegment.copy(byteArr2, 0, slice2, JAVA_BYTE, 0, byteArr2.length); - assertFalse(sk1.isSameResource(slice2)); - - final byte[] byteArr3 = KllLongsSketch.newHeapInstance(20).toByteArray(); - MemorySegment.copy(byteArr3, 0, slice3, JAVA_BYTE, 0, byteArr3.length); - assertTrue(sk1.isSameResource(slice3)); - } - - @Test - public void checkSortedViewAfterReset() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(20); - sk.update(1L); - final LongsSortedView sv = sk.getSortedView(); - final long dsv = sv.getQuantile(1.0, INCLUSIVE); - assertEquals(dsv, 1L); - sk.reset(); - try { sk.getSortedView(); fail(); } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkVectorUpdate() { - final boolean withLevels = false; - final boolean withLevelsAndItems = true; - final int k = 20; - final int n = 108; - final int maxVsz = 40; //max vector size - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - int j = 1; - int rem; - while ((rem = (n - j) + 1) > 0) { - final int vecSz = min(rem, maxVsz); - final long[] v = new long[vecSz]; - for (int i = 0; i < vecSz; i++) { v[i] = j++; } - sk.update(v, 0, vecSz); - } - println(LS + "#<<< END STATE # >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - println(""); - assertEquals(sk.getN(), 108); - assertEquals(sk.getMaxItem(), 108L); - assertEquals(sk.getMinItem(), 1L); - } - - @Test - public void vectorizedUpdates() { - final int trials = 1; - final int M = 1; //number of vectors - final int N = 1000; //vector size - final int K = 256; - final long[] values = new long[N]; - long vIn = 1L; - long totN = 0; - final long startTime = System.nanoTime(); - for (int t = 0; t < trials; t++) { - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(K); - for (int m = 0; m < M; m++) { - for (int n = 0; n < N; n++) { - values[n] = vIn++; //fill vector - } - sketch.update(values, 0, N); //vector input - } - totN = sketch.getN(); - assertEquals(totN, M * N); - assertEquals(sketch.getMinItem(), 1L); - assertEquals(sketch.getMaxItem(), totN); - assertEquals(sketch.getQuantile(0.5), totN / 2, totN * PMF_EPS_FOR_K_256 * 2.0); //wider tolerance - } - final long runTime = System.nanoTime() - startTime; - println("Vectorized Updates"); - printf(" Vector size : %,12d" + LS, N); - printf(" Num Vectors : %,12d" + LS, M); - printf(" Total Input : %,12d" + LS, totN); - printf(" Run Time mS : %,12.3f" + LS, runTime / 1e6); - final double trialTime = runTime / (1e6 * trials); - printf(" mS / Trial : %,12.3f" + LS, trialTime); - final double updateTime = runTime / (1.0 * totN * trials); - printf(" nS / Update : %,12.3f" + LS, updateTime); - } - - @Test - public void nonVectorizedUpdates() { - final int trials = 1; - final int M = 1; //number of vectors - final int N = 1000; //vector size - final int K = 256; - final long[] values = new long[N]; - long vIn = 1L; - long totN = 0; - final long startTime = System.nanoTime(); - for (int t = 0; t < trials; t++) { - final KllLongsSketch sketch = KllLongsSketch.newHeapInstance(K); - for (int m = 0; m < M; m++) { - for (int n = 0; n < N; n++) { - values[n] = vIn++; //fill vector - } - for (int i = 0; i < N; i++) { - sketch.update(values[i]); //single item input - } - } - totN = sketch.getN(); - assertEquals(totN, M * N); - assertEquals(sketch.getMinItem(), 1L); - assertEquals(sketch.getMaxItem(), totN); - assertEquals(sketch.getQuantile(0.5), totN / 2, totN * PMF_EPS_FOR_K_256 * 2.0); //wider tolerance - } - final long runTime = System.nanoTime() - startTime; - println("Vectorized Updates"); - printf(" Vector size : %,12d" + LS, N); - printf(" Num Vectors : %,12d" + LS, M); - printf(" Total Input : %,12d" + LS, totN); - printf(" Run Time mS : %,12.3f" + LS, runTime / 1e6); - final double trialTime = runTime / (1e6 * trials); - printf(" mS / Trial : %,12.3f" + LS, trialTime); - final double updateTime = runTime / (1.0 * totN * trials); - printf(" nS / Update : %,12.3f" + LS, updateTime); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } -} diff --git a/src/test/java/org/apache/datasketches/kll/KllMemorySegmentRequestApp.java b/src/test/java/org/apache/datasketches/kll/KllMemorySegmentRequestApp.java deleted file mode 100644 index 893379cdc..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllMemorySegmentRequestApp.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentRequestExample; -import org.testng.annotations.Test; - -public class KllMemorySegmentRequestApp { - - @Test - /** - * This method emulates an application using an off-heap KLL sketch that needs to expand off-heap. - * This demonstrates one example of how to manage a growing off-heap KLL sketch where the - * expanded MemorySegments are also off-heap. - */ - public void checkMemorySegmentRequestExample() { - final int k = 200; - final int itemsIn = 10 * k; //will force requests for more space - - //Use the custom MemorySegmentRequestExample to do the allocations. - final MemorySegmentRequestExample mSegReqEx = new MemorySegmentRequestExample(); - - //The allocation of the original off-heap MemorySegment for the KllLongsSketch - //Note that this targets the size to only handle k values, which is quite small. - final int numBytes = KllSketch.getMaxSerializedSizeBytes(k, k, KllSketch.SketchType.KLL_LONGS_SKETCH, true); - - final MemorySegment seg = mSegReqEx.request(numBytes); - - //Create a new KllLongsSketch and pass the mSegReqEx - final KllLongsSketch sk = KllLongsSketch.newDirectInstance(k, seg, mSegReqEx); - - //Update the sketch with way more data than the original MemorySegment can handle, forcing it to request larger MemorySegments. - for (int n = 1; n <= itemsIn; n++) { sk.update(n); } - - //Check to make sure the sketch got all the data: - assertEquals(sk.getMaxItem(), 10 * k); - assertEquals(sk.getMinItem(), 1); - assertEquals(sk.getN(), 10 * k); - - //Confirm that the last MemorySegment used by the sketch is, in fact, not the same as the original one that was allocated. - assertTrue(sk.getMemorySegment() != seg); - - //All done with the sketch. Cleanup any unclosed off-heap MemorySegments including the original allocation. - mSegReqEx.cleanup(); - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllMemoryValidateTest.java b/src/test/java/org/apache/datasketches/kll/KllMemoryValidateTest.java deleted file mode 100644 index 581dc4108..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllMemoryValidateTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.kll.KllPreambleUtil.PREAMBLE_INTS_EMPTY_SINGLE; -import static org.apache.datasketches.kll.KllPreambleUtil.PREAMBLE_INTS_FULL; -import static org.apache.datasketches.kll.KllPreambleUtil.SERIAL_VERSION_EMPTY_FULL; -import static org.apache.datasketches.kll.KllPreambleUtil.SERIAL_VERSION_SINGLE; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentEmptyFlag; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentFamilyID; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentPreInts; -import static org.apache.datasketches.kll.KllPreambleUtil.setMemorySegmentSerVer; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_DOUBLES_SKETCH; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_FLOATS_SKETCH; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.Test; - -public class KllMemoryValidateTest { - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidFamily() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - final byte[] byteArr = sk.toByteArray(); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - setMemorySegmentFamilyID(wseg, Family.KLL.getID() - 1); - new KllMemorySegmentValidate(wseg, KLL_FLOATS_SKETCH); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidSerVer() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - final byte[] byteArr = sk.toByteArray(); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - setMemorySegmentSerVer(wseg, SERIAL_VERSION_EMPTY_FULL - 1); - new KllMemorySegmentValidate(wseg, KLL_FLOATS_SKETCH); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidEmptyAndSingleFormat() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - sk.update(1); - final byte[] byteArr = sk.toByteArray(); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - setMemorySegmentEmptyFlag(wseg, true); - new KllMemorySegmentValidate(wseg, KLL_FLOATS_SKETCH); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidUpdatableAndSerVer() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - final byte[] byteArr = sk.toByteArray(); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - setMemorySegmentSerVer(wseg, SERIAL_VERSION_SINGLE); - new KllMemorySegmentValidate(wseg, KLL_FLOATS_SKETCH); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidSingleAndPreInts() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - sk.update(1); - final byte[] byteArr = sk.toByteArray(); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - setMemorySegmentPreInts(wseg, PREAMBLE_INTS_FULL); - new KllMemorySegmentValidate(wseg, KLL_FLOATS_SKETCH); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidSingleAndSerVer() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - sk.update(1); - final byte[] byteArr = sk.toByteArray(); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - setMemorySegmentSerVer(wseg, SERIAL_VERSION_EMPTY_FULL); - new KllMemorySegmentValidate(wseg, KLL_FLOATS_SKETCH); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidEmptyDoublesAndPreIntsFull() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(); - final byte[] byteArr = sk.toByteArray(); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - setMemorySegmentPreInts(wseg, PREAMBLE_INTS_FULL); - new KllMemorySegmentValidate(wseg, KLL_DOUBLES_SKETCH); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidSingleDoubleCompactAndSerVer() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(); - sk.update(1); - final byte[] byteArr = sk.toByteArray(); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - setMemorySegmentSerVer(wseg, SERIAL_VERSION_EMPTY_FULL); - new KllMemorySegmentValidate(wseg, KLL_DOUBLES_SKETCH); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidDoubleUpdatableAndPreInts() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(); - final byte[] byteArr = KllHelper.toByteArray(sk, true); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - setMemorySegmentPreInts(wseg, PREAMBLE_INTS_EMPTY_SINGLE); - new KllMemorySegmentValidate(wseg, KLL_DOUBLES_SKETCH); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidFloatFullAndPreInts() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - sk.update(1); sk.update(2); - final byte[] byteArr = sk.toByteArray(); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - setMemorySegmentPreInts(wseg, PREAMBLE_INTS_EMPTY_SINGLE); - new KllMemorySegmentValidate(wseg, KLL_FLOATS_SKETCH); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidFloatUpdatableFullAndPreInts() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - sk.update(1); sk.update(2); - final byte[] byteArr = KllHelper.toByteArray(sk, true); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - setMemorySegmentPreInts(wseg, PREAMBLE_INTS_EMPTY_SINGLE); - new KllMemorySegmentValidate(wseg, KLL_FLOATS_SKETCH); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidDoubleCompactSingleAndPreInts() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(); - sk.update(1); - final byte[] byteArr = sk.toByteArray(); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - setMemorySegmentPreInts(wseg, PREAMBLE_INTS_FULL);//should be 2, single - new KllMemorySegmentValidate(wseg, KLL_DOUBLES_SKETCH); - } - -} - diff --git a/src/test/java/org/apache/datasketches/kll/KllMiscDirectDoublesTest.java b/src/test/java/org/apache/datasketches/kll/KllMiscDirectDoublesTest.java deleted file mode 100644 index 88437488b..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllMiscDirectDoublesTest.java +++ /dev/null @@ -1,462 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_DOUBLES_SKETCH; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDirectDoublesSketch; -import org.apache.datasketches.kll.KllDoublesSketch; -import org.apache.datasketches.kll.KllHeapDoublesSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllPreambleUtil; -import org.apache.datasketches.quantilescommon.DoublesSortedView; -import org.apache.datasketches.quantilescommon.DoublesSortedViewIterator; -import org.testng.annotations.Test; - -public class KllMiscDirectDoublesTest { - static final String LS = System.getProperty("line.separator"); - - @Test - public void checkBounds() { - final KllDoublesSketch kll = getDirectDoublesSketch(200, 1000); - for (int i = 0; i < 1000; i++) { - kll.update(i); - } - final double eps = kll.getNormalizedRankError(false); - final double est = kll.getQuantile(0.5); - final double ub = kll.getQuantileUpperBound(0.5); - final double lb = kll.getQuantileLowerBound(0.5); - assertEquals(ub, kll.getQuantile(.5 + eps)); - assertEquals(lb, kll.getQuantile(0.5 - eps)); - println("Ext : " + est); - println("UB : " + ub); - println("LB : " + lb); - final double rest = kll.getRank(est); - final double restUB = kll.getRankUpperBound(rest); - final double restLB = kll.getRankLowerBound(rest); - assertTrue((restUB - rest) < (2 * eps)); - assertTrue((rest - restLB) < (2 * eps)); - } - - //@Test //enable static println(..) for visual checking - public void visualCheckToString() { - final int k = 20; - final KllDoublesSketch sk = getDirectDoublesSketch(k, 0); - for (int i = 0; i < 10; i++) { sk.update(i + 1); } - println(sk.toString(true, true)); - - final KllDoublesSketch sk2 = getDirectDoublesSketch(k, 0); - for (int i = 0; i < 400; i++) { sk2.update(i + 1); } - println("\n" + sk2.toString(true, true)); - - sk2.merge(sk); - final String s2 = sk2.toString(true, true); - println(LS + s2); - } - - @Test - public void viewDirectCompactions() { - final int k = 20; - final int u = 108; - final KllDoublesSketch sk = getDirectDoublesSketch(k, 0); - for (int i = 1; i <= u; i++) { - sk.update(i); - if (sk.levelsArr[0] == 0) { - println(sk.toString(true, true)); - sk.update(++i); - println(sk.toString(true, true)); - assertEquals(sk.getDoubleItemsArray()[sk.levelsArr[0]], i); - } - } - } - - @Test - public void viewCompactionAndSortedView() { - final int k = 20; - final KllDoublesSketch sk = getDirectDoublesSketch(k, 0); - show(sk, 20); - final DoublesSortedView sv = sk.getSortedView(); - final DoublesSortedViewIterator itr = sv.iterator(); - printf("%12s%12s\n", "Value", "CumWeight"); - while (itr.next()) { - final double v = itr.getQuantile(); - final long wt = itr.getWeight(); - printf("%12.1f%12d\n", v, wt); - } - } - - private static void show(final KllDoublesSketch sk, final int limit) { - int i = (int) sk.getN(); - for ( ; i < limit; i++) { sk.update(i + 1); } - println(sk.toString(true, true)); - } - - @Test - public void checkSketchInitializeDoubleHeap() { - final int k = 20; //don't change this - KllDoublesSketch sk; - - //println("#### CASE: DOUBLE FULL HEAP"); - sk = getDirectDoublesSketch(k, 0); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - //println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: DOUBLE HEAP EMPTY"); - sk = getDirectDoublesSketch(k, 0); - //println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: DOUBLE HEAP SINGLE"); - sk = getDirectDoublesSketch(k, 0); - sk.update(1); - //println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test - public void checkSketchInitializeDoubleHeapifyCompactMemorySegment() { - final int k = 20; //don't change this - KllDoublesSketch sk; - KllDoublesSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - //println("#### CASE: DOUBLE FULL HEAPIFIED FROM COMPACT"); - sk2 = getDirectDoublesSketch(k, 0); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllDoublesSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: DOUBLE EMPTY HEAPIFIED FROM COMPACT"); - sk2 = getDirectDoublesSketch(k, 0); - //println(sk.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllDoublesSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: DOUBLE SINGLE HEAPIFIED FROM COMPACT"); - sk2 = getDirectDoublesSketch(k, 0); - sk2.update(1); - //println(sk2.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllDoublesSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test - public void checkSketchInitializeDoubleHeapifyUpdatableMemorySegment() { - final int k = 20; //don't change this - KllDoublesSketch sk; - KllDoublesSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - //println("#### CASE: DOUBLE FULL HEAPIFIED FROM UPDATABLE"); - sk2 = getDirectDoublesSketch(k, 0); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk2.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - sk = KllHeapDoublesSketch.heapifyImpl(wseg); - //println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - // println("#### CASE: DOUBLE EMPTY HEAPIFIED FROM UPDATABLE"); - sk2 = getDirectDoublesSketch(k, 0); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllHeapDoublesSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: DOUBLE SINGLE HEAPIFIED FROM UPDATABLE"); - sk2 = getDirectDoublesSketch(k, 0); - sk2.update(1); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.memorySegmentToString(wseg, true)); - sk = KllHeapDoublesSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test - public void checkMemoryToStringDoubleUpdatable() { - final int k = 20; //don't change this - KllDoublesSketch sk; - KllDoublesSketch sk2; - byte[] upBytes; - byte[] upBytes2; - MemorySegment wseg; - String s; - - println("#### CASE: DOUBLE FULL UPDATABLE"); - sk = getDirectDoublesSketch(k, 0); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllDoublesSketch.wrap(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - - println("#### CASE: DOUBLE EMPTY UPDATABLE"); - sk = getDirectDoublesSketch(k, 0); - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllDoublesSketch.wrap(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - - println("#### CASE: DOUBLE SINGLE UPDATABL"); - sk = getDirectDoublesSketch(k, 0); - sk.update(1); - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllDoublesSketch.wrap(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - } - - @Test - public void checkSimpleMerge() { - final int k = 20; - final int n1 = 21; - final int n2 = 21; - final KllDoublesSketch sk1 = getDirectDoublesSketch(k, 0); - final KllDoublesSketch sk2 = getDirectDoublesSketch(k, 0); - for (int i = 1; i <= n1; i++) { - sk1.update(i); - } - for (int i = 1; i <= n2; i++) { - sk2.update(i + 100); - } - println(sk1.toString(true, true)); - println(sk2.toString(true, true)); - sk1.merge(sk2); - println(sk1.toString(true, true)); - assertEquals(sk1.getMaxItem(), 121.0); - assertEquals(sk1.getMinItem(), 1.0); - } - - @Test - public void checkSizes() { - final KllDoublesSketch sk = getDirectDoublesSketch(20, 0); - for (int i = 1; i <= 21; i++) { sk.update(i); } - //println(sk.toString(true, true)); - final byte[] byteArr1 = KllHelper.toByteArray(sk, true); - final int size1 = sk.currentSerializedSizeBytes(true); - assertEquals(size1, byteArr1.length); - final byte[] byteArr2 = sk.toByteArray(); - final int size2 = sk.currentSerializedSizeBytes(false); - assertEquals(size2, byteArr2.length); - } - - @Test - public void checkNewInstance() { - final int k = 200; - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[6000]); - final KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(k, dstSeg, null); - for (int i = 1; i <= 10_000; i++) {sk.update(i); } - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getMaxItem(), 10000.0); - //println(sk.toString(true, true)); - } - - @Test - public void checkDifferentM() { - final int k = 20; - final int m = 4; - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[1000]); - final KllDoublesSketch sk = KllDirectDoublesSketch.newDirectUpdatableInstance(k, m, dstSeg, null); - for (int i = 1; i <= 200; i++) {sk.update(i); } - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getMaxItem(), 200.0); - } - - private static KllDoublesSketch getDirectDoublesSketch(final int k, final int n) { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { sk.update(i); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - return KllDoublesSketch.wrap(wseg); - } - - @Test - public void printlnTest() { - final String s = "PRINTING: printf in " + this.getClass().getName(); - println(s); - printf("%s\n", s); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllMiscDirectFloatsTest.java b/src/test/java/org/apache/datasketches/kll/KllMiscDirectFloatsTest.java deleted file mode 100644 index 9c795200b..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllMiscDirectFloatsTest.java +++ /dev/null @@ -1,462 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_FLOATS_SKETCH; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDirectFloatsSketch; -import org.apache.datasketches.kll.KllFloatsSketch; -import org.apache.datasketches.kll.KllHeapFloatsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllPreambleUtil; -import org.apache.datasketches.quantilescommon.FloatsSortedView; -import org.apache.datasketches.quantilescommon.FloatsSortedViewIterator; -import org.testng.annotations.Test; - -public class KllMiscDirectFloatsTest { - static final String LS = System.getProperty("line.separator"); - - @Test - public void checkBounds() { - final KllFloatsSketch kll = getDirectFloatsSketch(200, 1000); - for (int i = 0; i < 1000; i++) { - kll.update(i); - } - final double eps = kll.getNormalizedRankError(false); - final float est = kll.getQuantile(0.5); - final float ub = kll.getQuantileUpperBound(0.5); - final float lb = kll.getQuantileLowerBound(0.5); - assertEquals(ub, kll.getQuantile(.5 + eps)); - assertEquals(lb, kll.getQuantile(0.5 - eps)); - println("Ext : " + est); - println("UB : " + ub); - println("LB : " + lb); - final double rest = kll.getRank(est); - final double restUB = kll.getRankUpperBound(rest); - final double restLB = kll.getRankLowerBound(rest); - assertTrue((restUB - rest) < (2 * eps)); - assertTrue((rest - restLB) < (2 * eps)); - } - - //@Test //enable static println(..) for visual checking - public void visualCheckToString() { - final int k = 20; - final KllFloatsSketch sk = getDirectFloatsSketch(k, 0); - for (int i = 0; i < 10; i++) { sk.update(i + 1); } - println(sk.toString(true, true)); - - final KllFloatsSketch sk2 = getDirectFloatsSketch(k, 0); - for (int i = 0; i < 400; i++) { sk2.update(i + 1); } - println("\n" + sk2.toString(true, true)); - - sk2.merge(sk); - final String s2 = sk2.toString(true, true); - println(LS + s2); - } - - @Test - public void viewDirectCompactions() { - final int k = 20; - final int u = 108; - final KllFloatsSketch sk = getDirectFloatsSketch(k, 0); - for (int i = 1; i <= u; i++) { - sk.update(i); - if (sk.levelsArr[0] == 0) { - println(sk.toString(true, true)); - sk.update(++i); - println(sk.toString(true, true)); - assertEquals(sk.getFloatItemsArray()[sk.levelsArr[0]], i); - } - } - } - - @Test - public void viewCompactionAndSortedView() { - final int k = 20; - final KllFloatsSketch sk = getDirectFloatsSketch(k, 0); - show(sk, 20); - final FloatsSortedView sv = sk.getSortedView(); - final FloatsSortedViewIterator itr = sv.iterator(); - printf("%12s%12s\n", "Value", "CumWeight"); - while (itr.next()) { - final float v = itr.getQuantile(); - final long wt = itr.getWeight(); - printf("%12.1f%12d\n", v, wt); - } - } - - private static void show(final KllFloatsSketch sk, final int limit) { - int i = (int) sk.getN(); - for ( ; i < limit; i++) { sk.update(i + 1); } - println(sk.toString(true, true)); - } - - @Test - public void checkSketchInitializeFloatHeap() { - final int k = 20; //don't change this - KllFloatsSketch sk; - - //println("#### CASE: FLOAT FULL HEAP"); - sk = getDirectFloatsSketch(k, 0); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - //println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0F); - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: FLOAT HEAP EMPTY"); - sk = getDirectFloatsSketch(k, 0); - //println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: FLOAT HEAP SINGLE"); - sk = getDirectFloatsSketch(k, 0); - sk.update(1); - //println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0F); - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test - public void checkSketchInitializeFloatHeapifyCompactMemorySegment() { - final int k = 20; //don't change this - KllFloatsSketch sk; - KllFloatsSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - //println("#### CASE: FLOAT FULL HEAPIFIED FROM COMPACT"); - sk2 = getDirectFloatsSketch(k, 0); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllFloatsSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0F); - assertEquals(sk.getMinItem(), 1.0f); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: FLOAT EMPTY HEAPIFIED FROM COMPACT"); - sk2 = getDirectFloatsSketch(k, 0); - //println(sk.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllFloatsSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: FLOAT SINGLE HEAPIFIED FROM COMPACT"); - sk2 = getDirectFloatsSketch(k, 0); - sk2.update(1); - //println(sk2.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllFloatsSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0F); - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test - public void checkSketchInitializeFloatHeapifyUpdatableMemorySegment() { - final int k = 20; //don't change this - KllFloatsSketch sk; - KllFloatsSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - //println("#### CASE: FLOAT FULL HEAPIFIED FROM UPDATABLE"); - sk2 = getDirectFloatsSketch(k, 0); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk2.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2,true); - wseg = MemorySegment.ofArray(compBytes); - sk = KllHeapFloatsSketch.heapifyImpl(wseg); - //println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0F); - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - // println("#### CASE: FLOAT EMPTY HEAPIFIED FROM UPDATABLE"); - sk2 = getDirectFloatsSketch(k, 0); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllHeapFloatsSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: FLOAT SINGLE HEAPIFIED FROM UPDATABLE"); - sk2 = getDirectFloatsSketch(k, 0); - sk2.update(1); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2,true); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllHeapFloatsSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0F); - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test - public void checkMemoryToStringFloatUpdatable() { - final int k = 20; //don't change this - KllFloatsSketch sk; - KllFloatsSketch sk2; - byte[] upBytes; - byte[] upBytes2; - MemorySegment wseg; - String s; - - println("#### CASE: FLOAT FULL UPDATABLE"); - sk = getDirectFloatsSketch(k, 0); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllFloatsSketch.wrap(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - - println("#### CASE: FLOAT EMPTY UPDATABLE"); - sk = getDirectFloatsSketch(k, 0); - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllFloatsSketch.wrap(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - - println("#### CASE: FLOAT SINGLE UPDATABL"); - sk = getDirectFloatsSketch(k, 0); - sk.update(1); - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllFloatsSketch.wrap(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - } - - @Test - public void checkSimpleMerge() { - final int k = 20; - final int n1 = 21; - final int n2 = 21; - final KllFloatsSketch sk1 = getDirectFloatsSketch(k, 0); - final KllFloatsSketch sk2 = getDirectFloatsSketch(k, 0); - for (int i = 1; i <= n1; i++) { - sk1.update(i); - } - for (int i = 1; i <= n2; i++) { - sk2.update(i + 100); - } - println(sk1.toString(true, true)); - println(sk2.toString(true, true)); - sk1.merge(sk2); - println(sk1.toString(true, true)); - assertEquals(sk1.getMaxItem(), 121.0F); - assertEquals(sk1.getMinItem(), 1.0F); - } - - @Test - public void checkSizes() { - final KllFloatsSketch sk = getDirectFloatsSketch(20, 0); - for (int i = 1; i <= 21; i++) { sk.update(i); } - //println(sk.toString(true, true)); - final byte[] byteArr1 = KllHelper.toByteArray(sk, true); - final int size1 = sk.currentSerializedSizeBytes(true); - assertEquals(size1, byteArr1.length); - final byte[] byteArr2 = sk.toByteArray(); - final int size2 = sk.currentSerializedSizeBytes(false); - assertEquals(size2, byteArr2.length); - } - - @Test - public void checkNewInstance() { - final int k = 200; - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[3000]); - final KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(k, dstSeg, null); - for (int i = 1; i <= 10_000; i++) {sk.update(i); } - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getMaxItem(), 10000.0F); - //println(sk.toString(true, true)); - } - - @Test - public void checkDifferentM() { - final int k = 20; - final int m = 4; - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[1000]); - final KllFloatsSketch sk = KllDirectFloatsSketch.newDirectUpdatableInstance(k, m, dstSeg, null); - for (int i = 1; i <= 200; i++) {sk.update(i); } - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getMaxItem(), 200.0); - } - - private static KllFloatsSketch getDirectFloatsSketch(final int k, final int n) { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { sk.update(i); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - return KllFloatsSketch.wrap(wseg); - } - - @Test - public void printlnTest() { - final String s = "PRINTING: printf in " + this.getClass().getName(); - println(s); - printf("%s\n", s); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllMiscDirectLongsTest.java b/src/test/java/org/apache/datasketches/kll/KllMiscDirectLongsTest.java deleted file mode 100644 index fca3640e2..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllMiscDirectLongsTest.java +++ /dev/null @@ -1,462 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_LONGS_SKETCH; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDirectLongsSketch; -import org.apache.datasketches.kll.KllHeapLongsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllLongsSketch; -import org.apache.datasketches.kll.KllPreambleUtil; -import org.apache.datasketches.quantilescommon.LongsSortedView; -import org.apache.datasketches.quantilescommon.LongsSortedViewIterator; -import org.testng.annotations.Test; - -public class KllMiscDirectLongsTest { - static final String LS = System.getProperty("line.separator"); - - @Test - public void checkBounds() { - final KllLongsSketch kll = getDirectLongsSketch(200, 1000); - for (int i = 0; i < 1000; i++) { - kll.update(i); - } - final double eps = kll.getNormalizedRankError(false); - final long est = kll.getQuantile(0.5); - final long ub = kll.getQuantileUpperBound(0.5); - final long lb = kll.getQuantileLowerBound(0.5); - assertEquals(ub, kll.getQuantile(.5 + eps)); - assertEquals(lb, kll.getQuantile(0.5 - eps)); - println("Ext : " + est); - println("UB : " + ub); - println("LB : " + lb); - final double rest = kll.getRank(est); - final double restUB = kll.getRankUpperBound(rest); - final double restLB = kll.getRankLowerBound(rest); - assertTrue((restUB - rest) < (2 * eps)); - assertTrue((rest - restLB) < (2 * eps)); - } - - //@Test //enable static println(..) for visual checking - public void visualCheckToString() { - final int k = 20; - final KllLongsSketch sk = getDirectLongsSketch(k, 0); - for (int i = 0; i < 10; i++) { sk.update(i + 1); } - println(sk.toString(true, true)); - - final KllLongsSketch sk2 = getDirectLongsSketch(k, 0); - for (int i = 0; i < 400; i++) { sk2.update(i + 1); } - println("\n" + sk2.toString(true, true)); - - sk2.merge(sk); - final String s2 = sk2.toString(true, true); - println(LS + s2); - } - - @Test - public void viewDirectCompactions() { - final int k = 20; - final int u = 108; - final KllLongsSketch sk = getDirectLongsSketch(k, 0); - for (int i = 1; i <= u; i++) { - sk.update(i); - if (sk.levelsArr[0] == 0) { - println(sk.toString(true, true)); - sk.update(++i); - println(sk.toString(true, true)); - assertEquals(sk.getLongItemsArray()[sk.levelsArr[0]], i); - } - } - } - - @Test - public void viewCompactionAndSortedView() { - final int k = 20; - final KllLongsSketch sk = getDirectLongsSketch(k, 0); - show(sk, 20); - final LongsSortedView sv = sk.getSortedView(); - final LongsSortedViewIterator itr = sv.iterator(); - printf("%12s%12s\n", "Value", "CumWeight"); - while (itr.next()) { - final long v = itr.getQuantile(); - final long wt = itr.getWeight(); - printf("%12d%12d\n", v, wt); - } - } - - private static void show(final KllLongsSketch sk, final int limit) { - int i = (int) sk.getN(); - for ( ; i < limit; i++) { sk.update(i + 1); } - println(sk.toString(true, true)); - } - - @Test - public void checkSketchInitializeLongHeap() { - final int k = 20; //don't change this - KllLongsSketch sk; - - //println("#### CASE: LONG FULL HEAP"); - sk = getDirectLongsSketch(k, 0); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - //println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21L); - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: LONG HEAP EMPTY"); - sk = getDirectLongsSketch(k, 0); - //println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: LONG HEAP SINGLE"); - sk = getDirectLongsSketch(k, 0); - sk.update(1); - //println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1L); - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test - public void checkSketchInitializeLongHeapifyCompactMemorySegment() { - final int k = 20; //don't change this - KllLongsSketch sk; - KllLongsSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - //println("#### CASE: LONG FULL HEAPIFIED FROM COMPACT"); - sk2 = getDirectLongsSketch(k, 0); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllLongsSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21L); - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: LONG EMPTY HEAPIFIED FROM COMPACT"); - sk2 = getDirectLongsSketch(k, 0); - //println(sk.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllLongsSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: LONG SINGLE HEAPIFIED FROM COMPACT"); - sk2 = getDirectLongsSketch(k, 0); - sk2.update(1); - //println(sk2.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllLongsSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1L); - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test - public void checkSketchInitializeLongHeapifyUpdatableMemorySegment() { - final int k = 20; //don't change this - KllLongsSketch sk; - KllLongsSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - //println("#### CASE: LONG FULL HEAPIFIED FROM UPDATABLE"); - sk2 = getDirectLongsSketch(k, 0); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk2.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2,true); - wseg = MemorySegment.ofArray(compBytes); - sk = KllHeapLongsSketch.heapifyImpl(wseg); - //println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21L); - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - // println("#### CASE: LONG EMPTY HEAPIFIED FROM UPDATABLE"); - sk2 = getDirectLongsSketch(k, 0); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllHeapLongsSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - //println("#### CASE: LONG SINGLE HEAPIFIED FROM UPDATABLE"); - sk2 = getDirectLongsSketch(k, 0); - sk2.update(1); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2,true); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg)); - sk = KllHeapLongsSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1L); - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test - public void checkMemoryToStringLongUpdatable() { - final int k = 20; //don't change this - KllLongsSketch sk; - KllLongsSketch sk2; - byte[] upBytes; - byte[] upBytes2; - MemorySegment wseg; - String s; - - println("#### CASE: LONG FULL UPDATABLE"); - sk = getDirectLongsSketch(k, 0); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllLongsSketch.wrap(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - - println("#### CASE: LONG EMPTY UPDATABLE"); - sk = getDirectLongsSketch(k, 0); - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllLongsSketch.wrap(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - - println("#### CASE: LONG SINGLE UPDATABL"); - sk = getDirectLongsSketch(k, 0); - sk.update(1); - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllLongsSketch.wrap(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - } - - @Test - public void checkSimpleMerge() { - final int k = 20; - final int n1 = 21; - final int n2 = 21; - final KllLongsSketch sk1 = getDirectLongsSketch(k, 0); - final KllLongsSketch sk2 = getDirectLongsSketch(k, 0); - for (int i = 1; i <= n1; i++) { - sk1.update(i); - } - for (int i = 1; i <= n2; i++) { - sk2.update(i + 100); - } - println(sk1.toString(true, true)); - println(sk2.toString(true, true)); - sk1.merge(sk2); - println(sk1.toString(true, true)); - assertEquals(sk1.getMaxItem(), 121L); - assertEquals(sk1.getMinItem(), 1L); - } - - @Test - public void checkSizes() { - final KllLongsSketch sk = getDirectLongsSketch(20, 0); - for (int i = 1; i <= 21; i++) { sk.update(i); } - //println(sk.toString(true, true)); - final byte[] byteArr1 = KllHelper.toByteArray(sk, true); - final int size1 = sk.currentSerializedSizeBytes(true); - assertEquals(size1, byteArr1.length); - final byte[] byteArr2 = sk.toByteArray(); - final int size2 = sk.currentSerializedSizeBytes(false); - assertEquals(size2, byteArr2.length); - } - - @Test - public void checkNewInstance() { - final int k = 200; - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[3000]); - final KllLongsSketch sk = KllLongsSketch.newDirectInstance(k, dstSeg, null); - for (int i = 1; i <= 10_000; i++) {sk.update(i); } - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getMaxItem(), 10000L); - //println(sk.toString(true, true)); - } - - @Test - public void checkDifferentM() { - final int k = 20; - final int m = 4; - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[1000]); - final KllLongsSketch sk = KllDirectLongsSketch.newDirectUpdatableInstance(k, m, dstSeg, null); - for (int i = 1; i <= 200; i++) {sk.update(i); } - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getMaxItem(), 200L); - } - - private static KllLongsSketch getDirectLongsSketch(final int k, final int n) { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { sk.update(i); } - final byte[] byteArr = KllHelper.toByteArray(sk, true); - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - return KllLongsSketch.wrap(wseg); - } - - @Test - public void printlnTest() { - final String s = "PRINTING: printf in " + this.getClass().getName(); - println(s); - printf("%s\n", s); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllMiscDoublesTest.java b/src/test/java/org/apache/datasketches/kll/KllMiscDoublesTest.java deleted file mode 100644 index daab63288..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllMiscDoublesTest.java +++ /dev/null @@ -1,795 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.bitAt; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_DOUBLES_SKETCH; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDirectDoublesSketch; -import org.apache.datasketches.kll.KllDoublesHelper; -import org.apache.datasketches.kll.KllDoublesSketch; -import org.apache.datasketches.kll.KllHeapDoublesSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllPreambleUtil; -import org.apache.datasketches.kll.KllSketch; -import org.apache.datasketches.quantilescommon.DoublesSortedView; -import org.apache.datasketches.quantilescommon.DoublesSortedViewIterator; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class KllMiscDoublesTest { - - @Test - public void checkSortedViewConstruction() { - final KllDoublesSketch kll = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= 20; i++) { kll.update(i); } - final DoublesSortedView fsv = kll.getSortedView(); - final long[] cumWeights = fsv.getCumulativeWeights(); - final double[] values = fsv.getQuantiles(); - assertEquals(cumWeights.length, 20); - assertEquals(values.length, 20); - for (int i = 0; i < 20; i++) { - assertEquals(cumWeights[i], i + 1); - assertEquals(values[i], i + 1); - } - } - - @Test //set static enablePrinting = true for visual checking - public void checkBounds() { - final KllDoublesSketch kll = KllDoublesSketch.newHeapInstance(); // default k = 200 - for (int i = 0; i < 1000; i++) { - kll.update(i); - } - final double eps = kll.getNormalizedRankError(false); - final double est = kll.getQuantile(0.5); - final double ub = kll.getQuantileUpperBound(0.5); - final double lb = kll.getQuantileLowerBound(0.5); - assertEquals(ub, kll.getQuantile(.5 + eps)); - assertEquals(lb, kll.getQuantile(0.5 - eps)); - println("Ext : " + est); - println("UB : " + ub); - println("LB : " + lb); - final double rest = kll.getRank(est); - final double restUB = kll.getRankUpperBound(rest); - final double restLB = kll.getRankLowerBound(rest); - assertTrue((restUB - rest) < (2 * eps)); - assertTrue((rest - restLB) < (2 * eps)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions1() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 6, (byte) 3); //corrupt with odd M - KllDoublesSketch.heapify(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions2() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 0, (byte) 1); //corrupt preamble ints, should be 2 - KllDoublesSketch.heapify(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions3() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(); - sk.update(1.0); - sk.update(2.0); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 0, (byte) 1); //corrupt preamble ints, should be 5 - KllDoublesSketch.heapify(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions4() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 1, (byte) 0); //corrupt SerVer, should be 1 or 2 - KllDoublesSketch.heapify(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions5() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 2, (byte) 0); //corrupt FamilyID, should be 15 - KllDoublesSketch.heapify(wseg); - } - - @Test //set static enablePrinting = true for visual checking - public void checkMisc() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(8); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} //empty - println(sk.toString(true, true)); - for (int i = 0; i < 20; i++) { sk.update(i); } - println(sk.toString(true, true)); - sk.toByteArray(); - final double[] items = sk.getDoubleItemsArray(); - assertEquals(items.length, 16); - final int[] levels = sk.getLevelsArray(sk.sketchStructure); - assertEquals(levels.length, 3); - assertEquals(sk.getNumLevels(), 2); - } - - @Test //set static enablePrinting = true for visual checking - public void visualCheckToString() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20); - int n = 21; - for (int i = 1; i <= n; i++) { sk.update(i); } - println(sk.toString(true, true)); - assertEquals(sk.getNumLevels(), 2); - assertEquals(sk.getMinItem(), 1); - assertEquals(sk.getMaxItem(), 21); - assertEquals(sk.getNumRetained(), 11); - - final KllDoublesSketch sk2 = KllDoublesSketch.newHeapInstance(20); - n = 400; - for (int i = 101; i <= (n + 100); i++) { sk2.update(i); } - println(LS + sk2.toString(true, true)); - assertEquals(sk2.getNumLevels(), 5); - assertEquals(sk2.getMinItem(), 101); - assertEquals(sk2.getMaxItem(), 500); - assertEquals(sk2.getNumRetained(), 52); - - sk2.merge(sk); - println(LS + sk2.toString(true, true)); - assertEquals(sk2.getNumLevels(), 5); - assertEquals(sk2.getMinItem(), 1); - assertEquals(sk2.getMaxItem(), 500); - assertEquals(sk2.getNumRetained(), 56); - } - - @Test //set static enablePrinting = true for visual checking - public void viewHeapCompactions() { - final int k = 20; - final int n = 108; - final boolean withLevels = false; - final boolean withLevelsAndItems = true; - int compaction = 0; - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { - sk.update(i); - if (sk.levelsArr[0] == 0) { - println(LS + "#<<< BEFORE COMPACTION # " + (++compaction) + " >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - sk.update(++i); - println(LS + "#<<< AFTER COMPACTION # " + (compaction) + " >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - assertEquals(sk.getDoubleItemsArray()[sk.levelsArr[0]], i); - } - } - println(LS + "#<<< END STATE # >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - println(""); - } - - @Test //set static enablePrinting = true for visual checking - public void viewDirectCompactions() { - final int k = 20; - final int n = 108; - final boolean withLevels = false; - final boolean withLevelsAndItems = true; - int compaction = 0; - final int sizeBytes = KllSketch.getMaxSerializedSizeBytes(k, n, KLL_DOUBLES_SKETCH, true); - final MemorySegment wseg = MemorySegment.ofArray(new byte[sizeBytes]); - final KllDoublesSketch sk = KllDoublesSketch.newDirectInstance(k, wseg, null); - for (int i = 1; i <= n; i++) { - sk.update(i); - if (sk.levelsArr[0] == 0) { - println(LS + "#<<< BEFORE COMPACTION # " + (++compaction) + " >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - sk.update(++i); - println(LS + "#<<< AFTER COMPACTION # " + (compaction) + " >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - assertEquals(sk.getDoubleItemsArray()[sk.levelsArr[0]], i); - } - } - println(LS + "#<<< END STATE # >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - println(""); - } - - @Test //set static enablePrinting = true for visual checking - public void viewCompactionAndSortedView() { - final int n = 43; - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= n; i++) { sk.update(i); } - println(sk.toString(true, true)); - final DoublesSortedView sv = sk.getSortedView(); - final DoublesSortedViewIterator itr = sv.iterator(); - println("### SORTED VIEW"); - printf("%6s %12s %12s" + LS, "Idx", "Value", "CumWeight"); - int i = 0; - while (itr.next()) { - final double v = itr.getQuantile(); - final long wt = itr.getWeight(); - printf("%6d %12.1f %12d" + LS, i, v, wt); - i++; - } - assertEquals(sv.getMinItem(), 1.0); - assertEquals(sv.getMaxItem(), n * 1.0); - } - - @Test //set static enablePrinting = true for visual checking - public void checkWeightedUpdates1() { - final int k = 20; - final int weight = 127; - final double item = 10.0; - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - println(sk.toString(true, true)); - sk.update(item, weight); - println(sk.toString(true, true)); - assertEquals(sk.getNumRetained(), 7); - assertEquals(sk.getN(), weight); - sk.update(item, weight); - println(sk.toString(true, true)); - assertEquals(sk.getNumRetained(), 14); - assertEquals(sk.getN(), 254); - } - - @Test //set static enablePrinting = true for visual checking - public void checkWeightedUpdates2() { - final int k = 20; - final int initial = 1000; - final int weight = 127; - final double item = 10.0; - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= initial; i++) { sk.update(i + 1000); } - println(sk.toString(true, true)); - sk.update(item, weight); - println(sk.toString(true, true)); - assertEquals(sk.getNumRetained(), 65); - assertEquals(sk.getN(), 1127); - - final DoublesSortedViewIterator itr = sk.getSortedView().iterator(); - println("### SORTED VIEW"); - printf("%12s %12s %12s" + LS, "Value", "Weight", "NaturalRank"); - long cumWt = 0; - while (itr.next()) { - final double v = itr.getQuantile(); - final long wt = itr.getWeight(); - final long natRank = itr.getNaturalRank(INCLUSIVE); - cumWt += wt; - assertEquals(cumWt, natRank); - printf("%12.1f %12d %12d" + LS, v, wt, natRank); - } - assertEquals(cumWt, sk.getN()); - } - - @Test //set static enablePrinting = true for visual checking - public void checkCreateItemsArray() { //used with weighted updates - final double item = 10.0; - final int weight = 108; - final double[] itemsArr = KllDoublesHelper.createItemsArray(item, weight); - assertEquals(itemsArr.length, 4); - Arrays.fill(itemsArr, item); - outputItems(itemsArr); - } - - private static void outputItems(final double[] itemsArr) { - final String[] hdr2 = {"Index", "Value"}; - final String hdr2fmt = "%6s %15s" + LS; - final String d2fmt = "%6d %15f" + LS; - println("ItemsArr"); - printf(hdr2fmt, (Object[]) hdr2); - for (int i = 0; i < itemsArr.length; i++) { - printf(d2fmt, i, itemsArr[i]); - } - println(""); - } - - @Test //set static enablePrinting = true for visual checking - public void checkCreateLevelsArray() { //used with weighted updates - final int weight = 108; - final int[] levelsArr = KllHelper.createLevelsArray(weight); - assertEquals(levelsArr.length, 8); - final int[] correct = {0,0,0,1,2,2,3,4}; - for (int i = 0; i < levelsArr.length; i++) { - assertEquals(levelsArr[i], correct[i]); - } - outputLevels(weight, levelsArr); - } - - private static void outputLevels(final int weight, final int[] levelsArr) { - final String[] hdr = {"Lvl", "StartAdr", "BitPattern", "Weight"}; - final String hdrfmt = "%3s %9s %10s %s" + LS; - final String dfmt = "%3d %9d %10d %d" + LS; - final String dfmt_2 = "%3d %9d %s" + LS; - println("Count = " + weight + " => " + (Integer.toBinaryString(weight))); - println("LevelsArr"); - printf(hdrfmt, (Object[]) hdr); - for (int i = 0; i < levelsArr.length; i++) { - if (i == (levelsArr.length - 1)) { printf(dfmt_2, i, levelsArr[i], "ItemsArr.length"); } - else { - final int j = bitAt(weight, i); - printf(dfmt, i, levelsArr[i], j, 1 << (i)); - } - } - println(""); - } - - @Test - public void viewMemorySketchData() { - final int k = 20; - final int n = 109; - final boolean withLevels = true; - final boolean withLevelsAndItems = true; - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { sk.update(i); } - final byte[] byteArr = sk.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - final KllDoublesSketch ddSk = KllDoublesSketch.wrap(seg); - println(ddSk.toString(withLevels, withLevelsAndItems)); - assertEquals(ddSk.getN(), n); - } - - @Test //set static enablePrinting = true for visual checking - public void checkIntCapAux() { - final String[] hdr = {"level", "depth", "wt", "cap", "(end)", "MaxN"}; - final String hdrFmt = "%6s %6s %28s %10s %10s %34s" + LS; - final String dataFmt = "%6d %6d %,28d %,10d %,10d %,34.0f" + LS; - final int k = 1000; - final int m = 8; - final int numLevels = 20; - println("k=" + k + ", m=" + m + ", numLevels=" + numLevels); - printf(hdrFmt, (Object[]) hdr); - double maxN = 0; - final double[] correct = {0,1,1,2,2,3,5,8,12,17,26,39,59,88,132,198,296,444,667,1000}; - for (int i = 0; i < numLevels; i++) { - final int depth = numLevels - i - 1; - final long cap = KllHelper.intCapAux(k, depth); - final long end = Math.max(m, cap); - final long wt = 1L << i; - maxN += (double)wt * (double)end; - printf(dataFmt, i, depth, wt, cap, end, maxN); - assertEquals(cap, correct[i]); - } - } - - @Test //set static enablePrinting = true for visual checking - public void checkIntCapAuxAux() { - final String[] hdr = {"d","twoK","2k*2^d","3^d","tmp=2k*2^d/3^d","(tmp + 1)/2", "(end)"}; - final String hdrFmt = "%6s %10s %20s %20s %15s %12s %10s" + LS; - final String dataFmt = "%6d %10d %,20d %,20d %15d %12d %10d" + LS; - final long k = (1L << 16) - 1L; - final long m = 8; - println("k = " + k + ", m = " + m); - printf(hdrFmt, (Object[]) hdr); - final long[] correct = - {65535,43690,29127,19418,12945,8630,5753,3836,2557,1705,1136,758,505,337,224,150,100,67,44,30,20,13,9,6,4,3,2,1,1,1,0}; - for (int i = 0; i < 31; i++) { - final long twoK = k << 1; - final long twoKxtwoD = twoK << i; - final long threeToD = KllHelper.powersOfThree[i]; - final long tmp = twoKxtwoD / threeToD; - final long result = (tmp + 1L) >>> 1; - final long end = Math.max(m, result); //performed later - printf(dataFmt, i, twoK, twoKxtwoD, threeToD, tmp, result, end); - assertEquals(result,correct[i]); - assertEquals(result, KllHelper.intCapAuxAux(k, i)); - } - } - - @Test - public void checkGrowLevels() { - final KllDoublesSketch sk = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - assertEquals(sk.getNumLevels(), 2); - assertEquals(sk.getDoubleItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure)[2], 33); - } - - @Test //set static enablePrinting = true for visual checking - public void checkSketchInitializeDoubleHeap() { - final int k = 20; //don't change this - KllDoublesSketch sk; - - println("#### CASE: DOUBLE FULL HEAP"); - sk = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: DOUBLE HEAP EMPTY"); - sk = KllDoublesSketch.newHeapInstance(k); - println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: DOUBLE HEAP SINGLE"); - sk = KllDoublesSketch.newHeapInstance(k); - sk.update(1); - println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test // set static enablePrinting = true for visual checking - public void checkSketchInitializeDoubleHeapifyCompactMemorySegment() { - final int k = 20; // don't change this - KllDoublesSketch sk; - KllDoublesSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - println("#### CASE: DOUBLE FULL HEAPIFIED FROM COMPACT"); - sk2 = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - // println(sk2.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true)); - sk = KllDoublesSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: DOUBLE EMPTY HEAPIFIED FROM COMPACT"); - sk2 = KllDoublesSketch.newHeapInstance(k); - // println(sk.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg, DOUBLES_SKETCH, true)); - sk = KllDoublesSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: DOUBLE SINGLE HEAPIFIED FROM COMPACT"); - sk2 = KllDoublesSketch.newHeapInstance(k); - sk2.update(1); - //println(sk2.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg, DOUBLES_SKETCH, true)); - sk = KllDoublesSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test // set static enablePrinting = true for visual checking - public void checkSketchInitializeDoubleHeapifyUpdatableMemorySegment() { - final int k = 20; // don't change this - KllDoublesSketch sk; - KllDoublesSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - println("#### CASE: DOUBLE FULL HEAPIFIED FROM UPDATABLE"); - sk2 = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk2.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true)); - sk = KllHeapDoublesSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: DOUBLE EMPTY HEAPIFIED FROM UPDATABLE"); - sk2 = KllDoublesSketch.newHeapInstance(k); - // println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg, DOUBLES_SKETCH, true)); - sk = KllHeapDoublesSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: DOUBLE SINGLE HEAPIFIED FROM UPDATABLE"); - sk2 = KllDoublesSketch.newHeapInstance(k); - sk2.update(1); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg, DOUBLES_SKETCH, true)); - sk = KllHeapDoublesSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getDoubleItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0); - assertEquals(sk.getMinItem(), 1.0); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test //set static enablePrinting = true for visual checking - public void checkMemoryToStringDoubleCompact() { - final int k = 20; //don't change this - KllDoublesSketch sk; - KllDoublesSketch sk2; - byte[] compBytes; - byte[] compBytes2; - MemorySegment wseg; - String s; - - println("#### CASE: DOUBLE FULL COMPACT"); - sk = KllDoublesSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - compBytes = sk.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllDoublesSketch.heapify(wseg); - compBytes2 = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes2); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 2: segorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(compBytes, compBytes2); - - println("#### CASE: DOUBLE EMPTY COMPACT"); - sk = KllDoublesSketch.newHeapInstance(20); - compBytes = sk.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllDoublesSketch.heapify(wseg); - compBytes2 = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes2); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(compBytes, compBytes2); - - println("#### CASE: DOUBLE SINGLE COMPACT"); - sk = KllDoublesSketch.newHeapInstance(20); - sk.update(1); - compBytes = sk.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllDoublesSketch.heapify(wseg); - compBytes2 = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes2); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(compBytes, compBytes2); - } - - @Test //set static enablePrinting = true for visual checking - public void checkMemoryToStringDoubleUpdatable() { - final int k = 20; //don't change this - KllDoublesSketch sk; - KllDoublesSketch sk2; - byte[] upBytes; - byte[] upBytes2; - MemorySegment wseg; - String s; - - println("#### CASE: DOUBLE FULL UPDATABLE"); - sk = KllDoublesSketch.newHeapInstance(20); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllHeapDoublesSketch.heapifyImpl(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); //note: heapify does not copy free space, while toUpdatableByteArray does - assertEquals(sk.getN(), sk2.getN()); - assertEquals(sk.getMinItem(), sk2.getMinItem()); - assertEquals(sk.getMaxItem(), sk2.getMaxItem()); - assertEquals(sk.getNumRetained(), sk2.getNumRetained()); - - println("#### CASE: DOUBLE EMPTY UPDATABLE"); - sk = KllDoublesSketch.newHeapInstance(k); - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllHeapDoublesSketch.heapifyImpl(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - - println("#### CASE: DOUBLE SINGLE UPDATABL"); - sk = KllDoublesSketch.newHeapInstance(k); - sk.update(1); - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllHeapDoublesSketch.heapifyImpl(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_DOUBLES_SKETCH, true); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - } - - @Test - public void checkSimpleMerge() { - final int k = 20; - final int m = 8; - final int n1 = 21; - final int n2 = 43; - final MemorySegment wseg = MemorySegment.ofArray(new byte[3000]); - final MemorySegment wseg2 = MemorySegment.ofArray(new byte[3000]); - - final KllDoublesSketch sk1 = KllDirectDoublesSketch.newDirectUpdatableInstance(k, m, wseg, null); - final KllDoublesSketch sk2 = KllDirectDoublesSketch.newDirectUpdatableInstance(k, m, wseg2, null); - for (int i = 1; i <= n1; i++) { - sk1.update(i); - } - for (int i = 1; i <= n2; i++) { - sk2.update(i + 100); - } - sk1.merge(sk2); - assertEquals(sk1.getMinItem(), 1.0); - assertEquals(sk1.getMaxItem(), 143.0); - } - - @Test - public void checkGetSingleItem() { - final int k = 20; - final KllDoublesSketch skHeap = KllDoublesSketch.newHeapInstance(k); - skHeap.update(1); - assertTrue(skHeap instanceof KllHeapDoublesSketch); - assertEquals(skHeap.getDoubleSingleItem(), 1.0); - - final MemorySegment srcSeg = MemorySegment.ofArray(KllHelper.toByteArray(skHeap, true)); - final KllDoublesSketch skDirect = KllDoublesSketch.wrap(srcSeg); - assertTrue(skDirect instanceof KllDirectDoublesSketch); - assertEquals(skDirect.getDoubleSingleItem(), 1.0); - - final MemorySegment srcSeg2 = MemorySegment.ofArray(skHeap.toByteArray()); - final KllDoublesSketch skCompact = KllDoublesSketch.wrap(srcSeg2); - assertEquals(skCompact.getDoubleSingleItem(), 1.0); - } - - @Test - public void printlnTest() { - final String s = "PRINTING: printf in " + this.getClass().getName(); - println(s); - printf("%s" + LS, s); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ... args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllMiscFloatsTest.java b/src/test/java/org/apache/datasketches/kll/KllMiscFloatsTest.java deleted file mode 100644 index 8a380b28c..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllMiscFloatsTest.java +++ /dev/null @@ -1,796 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.bitAt; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_FLOATS_SKETCH; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDirectFloatsSketch; -import org.apache.datasketches.kll.KllFloatsHelper; -import org.apache.datasketches.kll.KllFloatsSketch; -import org.apache.datasketches.kll.KllHeapFloatsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllPreambleUtil; -import org.apache.datasketches.kll.KllSketch; -import org.apache.datasketches.quantilescommon.FloatsSortedView; -import org.apache.datasketches.quantilescommon.FloatsSortedViewIterator; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class KllMiscFloatsTest { - - @Test - public void checkSortedViewConstruction() { - final KllFloatsSketch kll = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= 20; i++) { kll.update(i); } - final FloatsSortedView fsv = kll.getSortedView(); - final long[] cumWeights = fsv.getCumulativeWeights(); - final float[] values = fsv.getQuantiles(); - assertEquals(cumWeights.length, 20); - assertEquals(values.length, 20); - for (int i = 0; i < 20; i++) { - assertEquals(cumWeights[i], i + 1); - assertEquals(values[i], i + 1); - } - } - - @Test //set static enablePrinting = true for visual checking - public void checkBounds() { - final KllFloatsSketch kll = KllFloatsSketch.newHeapInstance(); //default k = 200 - for (int i = 0; i < 1000; i++) { - kll.update(i); - } - final double eps = kll.getNormalizedRankError(false); - final float est = kll.getQuantile(0.5); - final float ub = kll.getQuantileUpperBound(0.5); - final float lb = kll.getQuantileLowerBound(0.5); - assertEquals(ub, kll.getQuantile(.5 + eps)); - assertEquals(lb, kll.getQuantile(0.5 - eps)); - println("Ext : " + est); - println("UB : " + ub); - println("LB : " + lb); - final double rest = kll.getRank(est); - final double restUB = kll.getRankUpperBound(rest); - final double restLB = kll.getRankLowerBound(rest); - assertTrue((restUB - rest) < (2 * eps)); - assertTrue((rest - restLB) < (2 * eps)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions1() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 6, (byte) 3); //corrupt with odd M - KllFloatsSketch.heapify(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions2() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 0, (byte) 1); //corrupt preamble ints, should be 2 - KllFloatsSketch.heapify(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions3() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - sk.update(1.0f); - sk.update(2.0f); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 0, (byte) 1); //corrupt preamble ints, should be 5 - KllFloatsSketch.heapify(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions4() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 1, (byte) 0); //corrupt SerVer, should be 1 or 2 - KllFloatsSketch.heapify(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions5() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 2, (byte) 0); //corrupt FamilyID, should be 15 - KllFloatsSketch.heapify(wseg); - } - - @Test //set static enablePrinting = true for visual checking - public void checkMisc() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(8); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} //empty - println(sk.toString(true, true)); - for (int i = 0; i < 20; i++) { sk.update(i); } - println(sk.toString(true, true)); - sk.toByteArray(); - final float[] items = sk.getFloatItemsArray(); - assertEquals(items.length, 16); - final int[] levels = sk.getLevelsArray(sk.sketchStructure); - assertEquals(levels.length, 3); - assertEquals(sk.getNumLevels(), 2); - } - - @Test //set static enablePrinting = true for visual checking - public void visualCheckToString() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20); - int n = 21; - for (int i = 1; i <= n; i++) { sk.update(i); } - println(sk.toString(true, true)); - assertEquals(sk.getNumLevels(), 2); - assertEquals(sk.getMinItem(), 1); - assertEquals(sk.getMaxItem(), 21); - assertEquals(sk.getNumRetained(), 11); - - final KllFloatsSketch sk2 = KllFloatsSketch.newHeapInstance(20); - n = 400; - for (int i = 101; i <= (n + 100); i++) { sk2.update(i); } - println(LS + sk2.toString(true, true)); - assertEquals(sk2.getNumLevels(), 5); - assertEquals(sk2.getMinItem(), 101); - assertEquals(sk2.getMaxItem(), 500); - assertEquals(sk2.getNumRetained(), 52); - - sk2.merge(sk); - println(LS + sk2.toString(true, true)); - assertEquals(sk2.getNumLevels(), 5); - assertEquals(sk2.getMinItem(), 1); - assertEquals(sk2.getMaxItem(), 500); - assertEquals(sk2.getNumRetained(), 56); - } - - @Test //set static enablePrinting = true for visual checking - public void viewHeapCompactions() { - final int k = 20; - final int n = 108; - final boolean withLevels = false; - final boolean withLevelsAndItems = true; - int compaction = 0; - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { - sk.update(i); - if (sk.levelsArr[0] == 0) { - println(LS + "#<<< BEFORE COMPACTION # " + (++compaction) + " >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - sk.update(++i); - println(LS + "#<<< AFTER COMPACTION # " + (compaction) + " >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - assertEquals(sk.getFloatItemsArray()[sk.levelsArr[0]], i); - } - } - println(LS + "#<<< END STATE # >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - println(""); - } - - @Test //set static enablePrinting = true for visual checking - public void viewDirectCompactions() { - final int k = 20; - final int n = 108; - final boolean withLevels = false; - final boolean withLevelsAndItems = true; - int compaction = 0; - final int sizeBytes = KllSketch.getMaxSerializedSizeBytes(k, n, KLL_FLOATS_SKETCH, true); - final MemorySegment wseg = MemorySegment.ofArray(new byte[sizeBytes]); - final KllFloatsSketch sk = KllFloatsSketch.newDirectInstance(k, wseg, null); - for (int i = 1; i <= n; i++) { - sk.update(i); - if (sk.levelsArr[0] == 0) { - println(LS + "#<<< BEFORE COMPACTION # " + (++compaction) + " >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - sk.update(++i); - println(LS + "#<<< AFTER COMPACTION # " + (compaction) + " >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - assertEquals(sk.getFloatItemsArray()[sk.levelsArr[0]], i); - } - } - println(LS + "#<<< END STATE # >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - println(""); - } - - @Test //set static enablePrinting = true for visual checking - public void viewCompactionAndSortedView() { - final int n = 43; - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= n; i++) { sk.update(i); } - println(sk.toString(true, true)); - final FloatsSortedView sv = sk.getSortedView(); - final FloatsSortedViewIterator itr = sv.iterator(); - println("### SORTED VIEW"); - printf("%6s %12s %12s" + LS, "Idx", "Value", "Weight"); - int i = 0; - while (itr.next()) { - final float v = itr.getQuantile(); - final long wt = itr.getWeight(); - printf("%6d %12.1f %12d" + LS, i, v, wt); - i++; - } - assertEquals(sv.getMinItem(), 1.0F); - assertEquals(sv.getMaxItem(), n * 1.0F); - } - - @Test //set static enablePrinting = true for visual checking - public void checkWeightedUpdates1() { - final int k = 20; - final int weight = 127; - final float item = 10.0F; - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - println(sk.toString(true, true)); - sk.update(item, weight); - println(sk.toString(true, true)); - assertEquals(sk.getNumRetained(), 7); - assertEquals(sk.getN(), weight); - sk.update(item, weight); - println(sk.toString(true, true)); - assertEquals(sk.getNumRetained(), 14); - assertEquals(sk.getN(), 254); - } - - @Test //set static enablePrinting = true for visual checking - public void checkWeightedUpdates2() { - final int k = 20; - final int initial = 1000; - final int weight = 127; - final float item = 10.0F; - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= initial; i++) { sk.update(i + 1000); } - println(sk.toString(true, true)); - sk.update(item, weight); - println(sk.toString(true, true)); - assertEquals(sk.getNumRetained(), 65); - assertEquals(sk.getN(), 1127); - - final FloatsSortedViewIterator itr = sk.getSortedView().iterator(); - println("### SORTED VIEW"); - printf("%12s %12s %12s" + LS, "Value", "Weight", "NaturalRank"); - long cumWt = 0; - while (itr.next()) { - final double v = itr.getQuantile(); - final long wt = itr.getWeight(); - final long natRank = itr.getNaturalRank(INCLUSIVE); - cumWt += wt; - assertEquals(cumWt, natRank); - printf("%12.1f %12d %12d" + LS, v, wt, natRank); - } - assertEquals(cumWt, sk.getN()); - } - - @Test //set static enablePrinting = true for visual checking - public void checkCreateItemsArray() { //used with weighted updates - final float item = 10.0F; - final int weight = 108; - final float[] itemsArr = KllFloatsHelper.createItemsArray(item, weight); - assertEquals(itemsArr.length, 4); - Arrays.fill(itemsArr, item); - outputItems(itemsArr); - } - - private static void outputItems(final float[] itemsArr) { - final String[] hdr2 = {"Index", "Value"}; - final String hdr2fmt = "%6s %15s" + LS; - final String d2fmt = "%6d %15f" + LS; - println("ItemsArr"); - printf(hdr2fmt, (Object[]) hdr2); - for (int i = 0; i < itemsArr.length; i++) { - printf(d2fmt, i, itemsArr[i]); - } - println(""); - } - - @Test //set static enablePrinting = true for visual checking - public void checkCreateLevelsArray() { //used with weighted updates - final int weight = 108; - final int[] levelsArr = KllHelper.createLevelsArray(weight); - assertEquals(levelsArr.length, 8); - final int[] correct = {0,0,0,1,2,2,3,4}; - for (int i = 0; i < levelsArr.length; i++) { - assertEquals(levelsArr[i], correct[i]); - } - outputLevels(weight, levelsArr); - } - - private static void outputLevels(final int weight, final int[] levelsArr) { - final String[] hdr = {"Lvl", "StartAdr", "BitPattern", "Weight"}; - final String hdrfmt = "%3s %9s %10s %s" + LS; - final String dfmt = "%3d %9d %10d %d" + LS; - final String dfmt_2 = "%3d %9d %s" + LS; - println("Count = " + weight + " => " + (Integer.toBinaryString(weight))); - println("LevelsArr"); - printf(hdrfmt, (Object[]) hdr); - for (int i = 0; i < levelsArr.length; i++) { - if (i == (levelsArr.length - 1)) { printf(dfmt_2, i, levelsArr[i], "ItemsArr.length"); } - else { - final int j = bitAt(weight, i); - printf(dfmt, i, levelsArr[i], j, 1 << (i)); - } - } - println(""); - } - - @Test - public void viewMemorySketchData() { - final int k = 20; - final int n = 109; - final boolean withLevels = true; - final boolean withLevelsAndItems = true; - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { sk.update(i); } - final byte[] byteArr = sk.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - final KllFloatsSketch fltSk = KllFloatsSketch.wrap(seg); - println(fltSk.toString(withLevels, withLevelsAndItems)); - assertEquals(fltSk.getN(), n); - } - - @Test //set static enablePrinting = true for visual checking - public void checkIntCapAux() { - final String[] hdr = {"level", "depth", "wt", "cap", "(end)", "MaxN"}; - final String hdrFmt = "%6s %6s %28s %10s %10s %34s" + LS; - final String dataFmt = "%6d %6d %,28d %,10d %,10d %,34.0f" + LS; - final int k = 1000; - final int m = 8; - final int numLevels = 20; - println("k=" + k + ", m=" + m + ", numLevels=" + numLevels); - printf(hdrFmt, (Object[]) hdr); - double maxN = 0; - final double[] correct = {0,1,1,2,2,3,5,8,12,17,26,39,59,88,132,198,296,444,667,1000}; - for (int i = 0; i < numLevels; i++) { - final int depth = numLevels - i - 1; - final long cap = KllHelper.intCapAux(k, depth); - final long end = Math.max(m, cap); - final long wt = 1L << i; - maxN += (double)wt * (double)end; - printf(dataFmt, i, depth, wt, cap, end, maxN); - assertEquals(cap, correct[i]); - } - } - - @Test //set static enablePrinting = true for visual checking - public void checkIntCapAuxAux() { - final String[] hdr = {"d","twoK","2k*2^d","3^d","tmp=2k*2^d/3^d","(tmp + 1)/2", "(end)"}; - final String hdrFmt = "%6s %10s %20s %20s %15s %12s %10s" + LS; - final String dataFmt = "%6d %10d %,20d %,20d %15d %12d %10d" + LS; - final long k = (1L << 16) - 1L; - final long m = 8; - println("k = " + k + ", m = " + m); - printf(hdrFmt, (Object[]) hdr); - final long[] correct = - {65535,43690,29127,19418,12945,8630,5753,3836,2557,1705,1136,758,505,337,224,150,100,67,44,30,20,13,9,6,4,3,2,1,1,1,0}; - for (int i = 0; i < 31; i++) { - final long twoK = k << 1; - final long twoKxtwoD = twoK << i; - final long threeToD = KllHelper.powersOfThree[i]; - final long tmp = twoKxtwoD / threeToD; - final long result = (tmp + 1L) >>> 1; - final long end = Math.max(m, result); //performed later - printf(dataFmt, i, twoK, twoKxtwoD, threeToD, tmp, result, end); - assertEquals(result,correct[i]); - assertEquals(result, KllHelper.intCapAuxAux(k, i)); - } - } - - @Test - public void checkGrowLevels() { - final KllFloatsSketch sk = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - assertEquals(sk.getNumLevels(), 2); - assertEquals(sk.getFloatItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure)[2], 33); - } - - @Test //set static enablePrinting = true for visual checking - public void checkSketchInitializeFloatHeap() { - final int k = 20; //don't change this - KllFloatsSketch sk; - - println("#### CASE: FLOAT FULL HEAP"); - sk = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0F); - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: FLOAT HEAP EMPTY"); - sk = KllFloatsSketch.newHeapInstance(k); - println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: FLOAT HEAP SINGLE"); - sk = KllFloatsSketch.newHeapInstance(k); - sk.update(1); - println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0F); - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test //set static enablePrinting = true for visual checking - public void checkSketchInitializeFloatHeapifyCompactMemorySegment() { - final int k = 20; //don't change this - KllFloatsSketch sk; - KllFloatsSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - println("#### CASE: FLOAT FULL HEAPIFIED FROM COMPACT"); - sk2 = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk2.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true)); - sk = KllFloatsSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0F); - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: FLOAT EMPTY HEAPIFIED FROM COMPACT"); - sk2 = KllFloatsSketch.newHeapInstance(k); - //println(sk.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg, FLOATS_SKETCH, true)); - sk = KllFloatsSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: FLOAT SINGLE HEAPIFIED FROM COMPACT"); - sk2 = KllFloatsSketch.newHeapInstance(k); - sk2.update(1); - //println(sk2.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg, FLOATS_SKETCH, true)); - sk = KllFloatsSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0F); - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test //set static enablePrinting = true for visual checking - public void checkSketchInitializeFloatHeapifyUpdatableMemorySegment() { - final int k = 20; //don't change this - KllFloatsSketch sk; - KllFloatsSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - println("#### CASE: FLOAT FULL HEAPIFIED FROM UPDATABLE"); - sk2 = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk2.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true)); - sk = KllHeapFloatsSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21.0F); - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: FLOAT EMPTY HEAPIFIED FROM UPDATABLE"); - sk2 = KllFloatsSketch.newHeapInstance(k); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg, FLOATS_SKETCH, true)); - sk = KllHeapFloatsSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: FLOAT SINGLE HEAPIFIED FROM UPDATABLE"); - sk2 = KllFloatsSketch.newHeapInstance(k); - sk2.update(1); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg, FLOATS_SKETCH, true)); - sk = KllHeapFloatsSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getFloatItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1.0F); - assertEquals(sk.getMinItem(), 1.0F); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test //set static enablePrinting = true for visual checking - public void checkMemoryToStringFloatCompact() { - final int k = 20; //don't change this - KllFloatsSketch sk; - KllFloatsSketch sk2; - byte[] compBytes; - byte[] compBytes2; - MemorySegment wseg; - String s; - - println("#### CASE: FLOAT FULL COMPACT"); - sk = KllFloatsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - compBytes = sk.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllFloatsSketch.heapify(wseg); - compBytes2 = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes2); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 2: segory to heap sketch, to byte[]/segory & analyze segory. Should match above"); - println(s); - assertEquals(compBytes, compBytes2); - - println("#### CASE: FLOAT EMPTY COMPACT"); - sk = KllFloatsSketch.newHeapInstance(k); - compBytes = sk.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllFloatsSketch.heapify(wseg); - compBytes2 = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes2); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 2: segory to heap sketch, to byte[]/segory & analyze segory. Should match above"); - println(s); - assertEquals(compBytes, compBytes2); - - println("#### CASE: FLOAT SINGLE COMPACT"); - sk = KllFloatsSketch.newHeapInstance(k); - sk.update(1); - compBytes = sk.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllFloatsSketch.heapify(wseg); - compBytes2 = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes2); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 2: segory to heap sketch, to byte[]/segory & analyze segory. Should match above"); - println(s); - assertEquals(compBytes, compBytes2); - } - - @Test //set static enablePrinting = true for visual checking - public void checkMemoryToStringFloatUpdatable() { - final int k = 20; //don't change this - KllFloatsSketch sk; - KllFloatsSketch sk2; - byte[] upBytes; - byte[] upBytes2; - MemorySegment wseg; - String s; - - println("#### CASE: FLOAT FULL UPDATABLE"); - sk = KllFloatsSketch.newHeapInstance(20); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllHeapFloatsSketch.heapifyImpl(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 2: segory to heap sketch, to byte[]/segory & analyze segory. Should match above"); - println(s); //note: heapify does not copy free space, while toUpdatableByteArray does - assertEquals(sk.getN(), sk2.getN()); - assertEquals(sk.getMinItem(), sk2.getMinItem()); - assertEquals(sk.getMaxItem(), sk2.getMaxItem()); - assertEquals(sk.getNumRetained(), sk2.getNumRetained()); - - println("#### CASE: FLOAT EMPTY UPDATABLE"); - sk = KllFloatsSketch.newHeapInstance(k); - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllHeapFloatsSketch.heapifyImpl(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 2: segory to heap sketch, to byte[]/segory & analyze segory. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - - println("#### CASE: FLOAT SINGLE UPDATABLE"); - sk = KllFloatsSketch.newHeapInstance(k); - sk.update(1); - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllHeapFloatsSketch.heapifyImpl(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_FLOATS_SKETCH, true); - println("step 2: segory to heap sketch, to byte[]/segory & analyze segory. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - } - - @Test - public void checkSimpleMerge() { - final int k = 20; - final int m = 8; - final int n1 = 21; - final int n2 = 43; - final MemorySegment wseg = MemorySegment.ofArray(new byte[3000]); - final MemorySegment wseg2 = MemorySegment.ofArray(new byte[3000]); - - final KllFloatsSketch sk1 = KllDirectFloatsSketch.newDirectUpdatableInstance(k, m, wseg, null); - final KllFloatsSketch sk2 = KllDirectFloatsSketch.newDirectUpdatableInstance(k, m, wseg2, null); - for (int i = 1; i <= n1; i++) { - sk1.update(i); - } - for (int i = 1; i <= n2; i++) { - sk2.update(i + 100); - } - sk1.merge(sk2); - assertEquals(sk1.getMinItem(), 1.0); - assertEquals(sk1.getMaxItem(), 143.0); - } - - @Test - public void checkGetSingleItem() { - final int k = 20; - final KllFloatsSketch skHeap = KllFloatsSketch.newHeapInstance(k); - skHeap.update(1); - assertTrue(skHeap instanceof KllHeapFloatsSketch); - assertEquals(skHeap.getFloatSingleItem(), 1.0F); - - final MemorySegment srcSeg = MemorySegment.ofArray(KllHelper.toByteArray(skHeap, true)); - final KllFloatsSketch skDirect = KllFloatsSketch.wrap(srcSeg); - assertTrue(skDirect instanceof KllDirectFloatsSketch); - assertEquals(skDirect.getFloatSingleItem(), 1.0F); - - final MemorySegment srcSeg2 = MemorySegment.ofArray(skHeap.toByteArray()); - final KllFloatsSketch skCompact = KllFloatsSketch.wrap(srcSeg2); - assertTrue(skCompact.isCompactMemorySegmentFormat()); - assertEquals(skCompact.getFloatSingleItem(), 1.0F); - } - - @Test - public void printlnTest() { - final String s = "PRINTING: printf in " + this.getClass().getName(); - println(s); - printf("%s" + LS, s); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ... args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllMiscItemsTest.java b/src/test/java/org/apache/datasketches/kll/KllMiscItemsTest.java deleted file mode 100644 index 72a4acf47..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllMiscItemsTest.java +++ /dev/null @@ -1,607 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.bitAt; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_ITEMS_SKETCH; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfBooleansSerDe; -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.kll.KllDirectCompactItemsSketch; -import org.apache.datasketches.kll.KllHeapItemsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllItemsHelper; -import org.apache.datasketches.kll.KllItemsSketch; -import org.apache.datasketches.kll.KllPreambleUtil; -import org.apache.datasketches.quantilescommon.GenericSortedViewIterator; -import org.apache.datasketches.quantilescommon.ItemsSketchSortedView; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class KllMiscItemsTest { - public ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - - @Test - public void checkSortedViewConstruction() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - final int n = 20; - final int digits = Util.numDigits(n); - for (int i = 1; i <= n; i++) { - sk.update(Util.longToFixedLengthString(i, digits)); - } - final ItemsSketchSortedView sv = sk.getSortedView(); - final long[] cumWeights = sv.getCumulativeWeights(); - final String[] values = sv.getQuantiles(); - assertEquals(cumWeights.length, 20); - assertEquals(values.length, 20); - for (int i = 0; i < 20; i++) { - assertEquals(cumWeights[i], i + 1); - assertEquals(values[i], Util.longToFixedLengthString(i + 1, digits)); - } - } - - @Test //set static enablePrinting = true for visual checking - public void checkBounds() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final int n = 1000; - final int digits = Util.numDigits(n); - for (int i = 1; i <= n; i++) { - sk.update(Util.longToFixedLengthString(i, digits)); - } - final double eps = sk.getNormalizedRankError(false); - final String est = sk.getQuantile(0.5); - final String ub = sk.getQuantileUpperBound(0.5); - final String lb = sk.getQuantileLowerBound(0.5); - assertEquals(ub, sk.getQuantile(.5 + eps)); - assertEquals(lb, sk.getQuantile(0.5 - eps)); - println("Ext : " + est); - println("UB : " + ub); - println("LB : " + lb); - final double rest = sk.getRank(est); - final double restUB = sk.getRankUpperBound(rest); - final double restLB = sk.getRankLowerBound(rest); - assertTrue((restUB - rest) < (2 * eps)); - assertTrue((rest - restLB) < (2 * eps)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions1() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 6, (byte)3); //corrupt with odd M - KllItemsSketch.heapify(wseg, Comparator.naturalOrder(), serDe); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions2() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 0, (byte)1); //corrupt preamble ints, should be 2 - KllItemsSketch.heapify(wseg, Comparator.naturalOrder(), serDe); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions3() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sk.update("1"); - sk.update("2"); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 0, (byte)1); //corrupt preamble ints, should be 5 - KllItemsSketch.heapify(wseg, Comparator.naturalOrder(), serDe); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions4() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 1, (byte)0); //corrupt SerVer, should be 1 or 2 - KllItemsSketch.heapify(wseg, Comparator.naturalOrder(), serDe); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions5() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 2, (byte)0); //corrupt FamilyID, should be 15 - KllItemsSketch.heapify(wseg, Comparator.naturalOrder(), serDe); - } - - @Test //set static enablePrinting = true for visual checking - public void checkMisc() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} //empty - println(sk.toString(true, true)); - final int n = 21; - final int digits = Util.numDigits(n); - for (int i = 1; i <= n; i++) { - sk.update(Util.longToFixedLengthString(i, digits)); - } - println(sk.toString(true, true)); - sk.toByteArray(); - final String[] items = sk.getTotalItemsArray(); - assertEquals(items.length, 33); - final int[] levels = sk.getLevelsArray(sk.sketchStructure); - assertEquals(levels.length, 3); - assertEquals(sk.getNumLevels(), 2); - } - - //@Test //set static enablePrinting = true for visual checking - public void visualCheckToString() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - int n = 21; - int digits = 3; - for (int i = 1; i <= n; i++) { sk.update(Util.longToFixedLengthString(i, digits)); } - println(sk.toString(true, true)); - assertEquals(sk.getNumLevels(), 2); - assertEquals(sk.getMinItem()," 1"); - assertEquals(sk.getMaxItem()," 21"); - assertEquals(sk.getNumRetained(), 11); - - final KllItemsSketch sk2 = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - n = 400; - digits = 3; - for (int i = 101; i <= (n + 100); i++) { sk2.update(Util.longToFixedLengthString(i, digits)); } - println(LS + sk2.toString(true, true)); - assertEquals(sk2.getNumLevels(), 5); - assertEquals(sk2.getMinItem(), "101"); - assertEquals(sk2.getMaxItem(), "500"); - assertEquals(sk2.getNumRetained(), 52); - - sk2.merge(sk); - println(LS + sk2.toString(true, true)); - assertEquals(sk2.getNumLevels(), 5); - assertEquals(sk2.getMinItem()," 1"); - assertEquals(sk2.getMaxItem(), "500"); - assertEquals(sk2.getNumRetained(), 56); - } - - @Test //set static enablePrinting = true for visual checking - public void viewHeapCompactions() { - final int k = 20; - final int n = 108; - final boolean withLevels = false; - final boolean withLevelsAndItems = true; - final int digits = Util.numDigits(n); - int compaction = 0; - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - for (int i = 1; i <= n; i++) { - sk.update(Util.longToFixedLengthString(i, digits)); - if (sk.levelsArr[0] == 0) { - println(LS + "#<<< BEFORE COMPACTION # " + (++compaction) + " >>>"); - println(sk.toString(true, true)); - sk.update(Util.longToFixedLengthString(++i, digits)); - println(LS + "#<<< AFTER COMPACTION # " + (compaction) + " >>>"); - println(sk.toString(true, true)); - assertEquals(sk.getTotalItemsArray()[sk.levelsArr[0]], Util.longToFixedLengthString(i, digits)); - } - } - println(LS + "#<<< END STATE # >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - println(""); - } - - @Test //set static enablePrinting = true for visual checking - public void viewCompactionAndSortedView() { - final int n = 43; - final int digits = Util.numDigits(n); - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - for (int i = 1; i <= n; i++) { sk.update(Util.longToFixedLengthString(i, digits)); } - println(sk.toString(true, true)); - final ItemsSketchSortedView sv = sk.getSortedView(); - final GenericSortedViewIterator itr = sv.iterator(); - println("### SORTED VIEW"); - printf("%6s %12s %12s" + LS, "Idx", "Value", "CumWeight"); - int i = 0; - while (itr.next()) { - final String v = itr.getQuantile(); - final long wt = itr.getWeight(); - printf("%6d %12s %12d" + LS,i, v, wt); - i++; - } - assertEquals(sv.getMinItem(), " 1"); - assertEquals(sv.getMaxItem(), Integer.toString(n)); - } - - @Test //set static enablePrinting = true for visual checking - public void checkWeightedUpdates1() { - final int k = 20; - final int weight = 127; - final String item = "10"; - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - println(sk.toString(true, true)); - sk.update(item, weight); - println(sk.toString(true, true)); - assertEquals(sk.getNumRetained(), 7); - assertEquals(sk.getN(), weight); - sk.update(item, weight); - println(sk.toString(true, true)); - assertEquals(sk.getNumRetained(), 14); - assertEquals(sk.getN(), 254); - } - - @Test //set static enablePrinting = true for visual checking - public void checkWeightedUpdates2() { - final int k = 20; - final int initial = 1000; - final int digits = 4; - final int weight = 127; - final String item = " 10"; - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - for (int i = 1; i <= initial; i++) { sk.update(Util.longToFixedLengthString(i + 1000, digits)); } - println(sk.toString(true, true)); - sk.update(item, weight); - println(sk.toString(true, true)); - assertEquals(sk.getNumRetained(), 65); - assertEquals(sk.getN(), 1127); - - final GenericSortedViewIterator itr = sk.getSortedView().iterator(); - println("### SORTED VIEW"); - printf("%12s %12s %12s" + LS, "Value", "Weight", "NaturalRank"); - long cumWt = 0; - while (itr.next()) { - final String v = itr.getQuantile(); - final long wt = itr.getWeight(); - final long natRank = itr.getNaturalRank(INCLUSIVE); - cumWt += wt; - assertEquals(cumWt, natRank); - printf("%12s %12d %12d" + LS, v, wt, natRank); - } - assertEquals(cumWt, sk.getN()); - } - - - @Test - public void checkGrowLevels() { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(20, Comparator.naturalOrder(), serDe); - final int n = 21; - final int digits = Util.numDigits(n); - for (int i = 1; i <= n; i++) { sk.update(Util.longToFixedLengthString(i, digits)); } - assertEquals(sk.getNumLevels(), 2); - assertEquals(sk.getTotalItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure)[2], 33); - } - - @Test //set static enablePrinting = true for visual checking - public void checkSketchInitializeItemsHeap() { - final int k = 20; //don't change this - final int n = 21; - final int digits = Util.numDigits(n); - KllItemsSketch sk; - - println("#### CASE: ITEM FULL HEAP"); - sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - for (int i = 1; i <= n; i++) { sk.update(Util.longToFixedLengthString(i, digits)); } - println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), n); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getTotalItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), "21"); - assertEquals(sk.getMinItem(), " 1"); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: ITEM HEAP EMPTY"); - sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getTotalItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: ITEM HEAP SINGLE"); - sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - sk.update("1"); - println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getTotalItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), "1"); - assertEquals(sk.getMinItem(), "1"); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test //set static enablePrinting = true for visual checking - public void checkSketchInitializeItemsHeapifyCompactMemorySegment() { - final int k = 20; //don't change this - final int n = 21; - final int digits = Util.numDigits(n); - KllItemsSketch sk; - KllItemsSketch sk2; - byte[] compBytes; - MemorySegment seg; - - println("#### CASE: ITEM FULL HEAPIFIED FROM COMPACT"); - sk2 = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - for (int i = 1; i <= n; i++) { sk2.update(Util.longToFixedLengthString(i, digits)); } - println(sk2.toString(true, true)); - compBytes = sk2.toByteArray(); - seg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe)); - sk = KllItemsSketch.heapify(seg, Comparator.naturalOrder(), serDe); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getTotalItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), "21"); - assertEquals(sk.getMinItem(), " 1"); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: ITEM EMPTY HEAPIFIED FROM COMPACT"); - sk2 = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - //println(sk.toString(true, true)); - compBytes = sk2.toByteArray(); - seg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe)); - sk = KllItemsSketch.heapify(seg, Comparator.naturalOrder(), serDe); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getTotalItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: ITEM SINGLE HEAPIFIED FROM COMPACT"); - sk2 = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - sk2.update("1"); - //println(sk2.toString(true, true)); - compBytes = sk2.toByteArray(); - seg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe)); - sk = KllItemsSketch.heapify(seg, Comparator.naturalOrder(), serDe); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getTotalItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), "1"); - assertEquals(sk.getMinItem(), "1"); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - //public void checkSketchInitializeItemHeapifyUpdatableMemorySegment() Not Supported - - @Test //set static enablePrinting = true for visual checking - public void checkMemoryToStringItemsCompact() { - final int k = 20; //don't change this - final int n = 21; - final int digits = Util.numDigits(n); - KllItemsSketch sk; - KllItemsSketch sk2; - byte[] compBytes; - byte[] compBytes2; - MemorySegment seg; - String s; - - println("#### CASE: ITEM FULL COMPACT"); - sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - for (int i = 1; i <= n; i++) { sk.update(Util.longToFixedLengthString(i, digits)); } - compBytes = sk.toByteArray(); - seg = MemorySegment.ofArray(compBytes); - s = KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllItemsSketch.heapify(seg, Comparator.naturalOrder(), serDe); - compBytes2 = sk2.toByteArray(); - seg = MemorySegment.ofArray(compBytes2); - s = KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(compBytes, compBytes2); - - println("#### CASE: ITEM EMPTY COMPACT"); - sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - compBytes = sk.toByteArray(); - seg = MemorySegment.ofArray(compBytes); - s = KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllItemsSketch.heapify(seg, Comparator.naturalOrder(), serDe); - compBytes2 = sk2.toByteArray(); - seg = MemorySegment.ofArray(compBytes2); - s = KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(compBytes, compBytes2); - - println("#### CASE: ITEM SINGLE COMPACT"); - sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - sk.update("1"); - compBytes = sk.toByteArray(); - seg = MemorySegment.ofArray(compBytes); - s = KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe); - println("step 1: sketch to byte[]/MemorySegment & analyze MemorySegment"); - println(s); - sk2 = KllItemsSketch.heapify(seg, Comparator.naturalOrder(), serDe); - compBytes2 = sk2.toByteArray(); - seg = MemorySegment.ofArray(compBytes2); - s = KllPreambleUtil.toString(seg, KLL_ITEMS_SKETCH, true, serDe); - println("step 2: MemorySegment to heap sketch, to byte[]/MemorySegment & analyze MemorySegment. Should match above"); - println(s); - assertEquals(compBytes, compBytes2); - } - - @Test //set static enablePrinting = true for visual checking - public void checkCreateItemsArray() { //used with weighted updates - final String item = "10"; - final int weight = 108; - final String[] itemsArr = KllItemsHelper.createItemsArray(String.class, item, weight); - assertEquals(itemsArr.length, 4); - Arrays.fill(itemsArr, item); - outputItems(itemsArr); - } - - private static void outputItems(final String[] itemsArr) { - final String[] hdr2 = {"Index", "Value"}; - final String hdr2fmt = "%6s %15s" + LS; - final String d2fmt = "%6d %15s" + LS; - println("ItemsArr"); - printf(hdr2fmt, (Object[]) hdr2); - for (int i = 0; i < itemsArr.length; i++) { - printf(d2fmt, i, itemsArr[i]); - } - println(""); - } - - @Test //set static enablePrinting = true for visual checking - public void checkCreateLevelsArray() { //used with weighted updates - final int weight = 108; - final int[] levelsArr = KllHelper.createLevelsArray(weight); - assertEquals(levelsArr.length, 8); - final int[] correct = {0,0,0,1,2,2,3,4}; - for (int i = 0; i < levelsArr.length; i++) { - assertEquals(levelsArr[i], correct[i]); - } - outputLevels(weight, levelsArr); - } - - private static void outputLevels(final int weight, final int[] levelsArr) { - final String[] hdr = {"Lvl", "StartAdr", "BitPattern", "Weight"}; - final String hdrfmt = "%3s %9s %10s %s" + LS; - final String dfmt = "%3d %9d %10d %d" + LS; - final String dfmt_2 = "%3d %9d %s" + LS; - println("Count = " + weight + " => " + (Integer.toBinaryString(weight))); - println("LevelsArr"); - printf(hdrfmt, (Object[]) hdr); - for (int i = 0; i < levelsArr.length; i++) { - if (i == (levelsArr.length - 1)) { printf(dfmt_2, i, levelsArr[i], "ItemsArr.length"); } - else { - final int j = bitAt(weight, i); - printf(dfmt, i, levelsArr[i], j, 1 << (i)); - } - } - println(""); - } - - @Test - public void checkGetSingleItem() { - final int k = 20; - final KllItemsSketch skHeap = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - skHeap.update("1"); - assertTrue(skHeap instanceof KllHeapItemsSketch); - assertEquals(skHeap.getSingleItem(), "1"); - - final MemorySegment srcSeg = MemorySegment.ofArray(KllHelper.toByteArray(skHeap, true)); //true is ignored - final KllItemsSketch skDirect = KllItemsSketch.wrap(srcSeg, Comparator.naturalOrder(), serDe); - assertTrue(skDirect instanceof KllDirectCompactItemsSketch); - assertEquals(skDirect.getSingleItem(), "1"); - - final MemorySegment srcSeg2 = MemorySegment.ofArray(skHeap.toByteArray()); - final KllItemsSketch skCompact = KllItemsSketch.wrap(srcSeg2, Comparator.naturalOrder(), serDe); - assertTrue(skCompact instanceof KllDirectCompactItemsSketch); - assertEquals(skCompact.getSingleItem(), "1"); - } - - @Test - public void checkIssue484() { - final int k = 20; - final Boolean[] items = { true,false,true,false,true,false,true,false,true,false }; - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(k, Boolean::compareTo, new ArrayOfBooleansSerDe()); - for (int i = 0; i < items.length; i++) { sketch.update(items[i]); } - final byte[] serialized = sketch.toByteArray(); - final KllItemsSketch deserialized = - KllItemsSketch.wrap(MemorySegment.ofArray(serialized), Boolean::compareTo, new ArrayOfBooleansSerDe()); - checkSketchesEqual(sketch, deserialized); - } - - private static void checkSketchesEqual(final KllItemsSketch expected, final KllItemsSketch actual) { - final ItemsSketchSortedView expSV = expected.getSortedView(); - final ItemsSketchSortedView actSV = actual.getSortedView(); - final int N = (int)actSV.getN(); - final long[] expCumWts = expSV.getCumulativeWeights(); - final Boolean[] expItemsArr = (Boolean[])expSV.getQuantiles(); - final long[] actCumWts = actSV.getCumulativeWeights(); - final Boolean[] actItemsArr = (Boolean[])actSV.getQuantiles(); - printf("%3s %8s %8s" + LS, "i","Actual", "Expected"); - for (int i = 0; i < N; i++) { - printf("%3d %8s %8s" + LS, i, actItemsArr[i].toString(), expItemsArr[i].toString()); - } - assertEquals(actCumWts, expCumWts); - assertEquals(actItemsArr, expItemsArr); - assertEquals(actual.getMinItem(), expected.getMinItem()); - assertEquals(actual.getMaxItem(), expected.getMaxItem()); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllMiscLongsTest.java b/src/test/java/org/apache/datasketches/kll/KllMiscLongsTest.java deleted file mode 100644 index 0bf770445..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllMiscLongsTest.java +++ /dev/null @@ -1,796 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.bitAt; -import static org.apache.datasketches.kll.KllSketch.SketchType.KLL_LONGS_SKETCH; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDirectLongsSketch; -import org.apache.datasketches.kll.KllHeapLongsSketch; -import org.apache.datasketches.kll.KllHelper; -import org.apache.datasketches.kll.KllLongsHelper; -import org.apache.datasketches.kll.KllLongsSketch; -import org.apache.datasketches.kll.KllPreambleUtil; -import org.apache.datasketches.kll.KllSketch; -import org.apache.datasketches.kll.KllSketch.SketchStructure; -import org.apache.datasketches.quantilescommon.LongsSortedView; -import org.apache.datasketches.quantilescommon.LongsSortedViewIterator; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class KllMiscLongsTest { - - @Test - public void checkSortedViewConstruction() { - final KllLongsSketch kll = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= 20; i++) { kll.update(i); } - final LongsSortedView fsv = kll.getSortedView(); - final long[] cumWeights = fsv.getCumulativeWeights(); - final long[] values = fsv.getQuantiles(); - assertEquals(cumWeights.length, 20); - assertEquals(values.length, 20); - for (int i = 0; i < 20; i++) { - assertEquals(cumWeights[i], i + 1); - assertEquals(values[i], i + 1); - } - } - - @Test //set static enablePrinting = true for visual checking - public void checkBounds() { - final KllLongsSketch kll = KllLongsSketch.newHeapInstance(); //default k = 200 - for (int i = 0; i < 1000; i++) { - kll.update(i); - } - final double eps = kll.getNormalizedRankError(false); - final long est = kll.getQuantile(0.5); - final long ub = kll.getQuantileUpperBound(0.5); - final long lb = kll.getQuantileLowerBound(0.5); - assertEquals(ub, kll.getQuantile(.5 + eps)); - assertEquals(lb, kll.getQuantile(0.5 - eps)); - println("Ext : " + est); - println("UB : " + ub); - println("LB : " + lb); - final double rest = kll.getRank(est); - final double restUB = kll.getRankUpperBound(rest); - final double restLB = kll.getRankLowerBound(rest); - assertTrue((restUB - rest) < (2 * eps)); - assertTrue((rest - restLB) < (2 * eps)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions1() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 6, (byte) 3); //corrupt with odd M - KllLongsSketch.heapify(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions2() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 0, (byte) 1); //corrupt preamble ints, should be 2 - KllLongsSketch.heapify(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions3() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(); - sk.update(1); - sk.update(2); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 0, (byte) 1); //corrupt preamble ints, should be 5 - KllLongsSketch.heapify(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions4() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 1, (byte) 0); //corrupt SerVer, should be 1 or 2 - KllLongsSketch.heapify(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyExceptions5() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(); - final MemorySegment wseg = MemorySegment.ofArray(sk.toByteArray()); - wseg.set(JAVA_BYTE, 2, (byte) 0); //corrupt FamilyID, should be 15 - KllLongsSketch.heapify(wseg); - } - - @Test //set static enablePrinting = true for visual checking - public void checkMisc() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(8); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) {} //empty - println(sk.toString(true, true)); - for (int i = 0; i < 20; i++) { sk.update(i); } - println(sk.toString(true, true)); - sk.toByteArray(); - final long[] items = sk.getLongItemsArray(); - assertEquals(items.length, 16); - final int[] levels = sk.getLevelsArray(sk.sketchStructure); - assertEquals(levels.length, 3); - assertEquals(sk.getNumLevels(), 2); - } - - @Test //set static enablePrinting = true for visual checking - public void visualCheckToString() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(20); - int n = 21; - for (int i = 1; i <= n; i++) { sk.update(i); } - println(sk.toString(true, true)); - assertEquals(sk.getNumLevels(), 2); - assertEquals(sk.getMinItem(), 1); - assertEquals(sk.getMaxItem(), 21); - assertEquals(sk.getNumRetained(), 11); - - final KllLongsSketch sk2 = KllLongsSketch.newHeapInstance(20); - n = 400; - for (int i = 101; i <= (n + 100); i++) { sk2.update(i); } - println(LS + sk2.toString(true, true)); - assertEquals(sk2.getNumLevels(), 5); - assertEquals(sk2.getMinItem(), 101); - assertEquals(sk2.getMaxItem(), 500); - assertEquals(sk2.getNumRetained(), 52); - - sk2.merge(sk); - println(LS + sk2.toString(true, true)); - assertEquals(sk2.getNumLevels(), 5); - assertEquals(sk2.getMinItem(), 1); - assertEquals(sk2.getMaxItem(), 500); - assertEquals(sk2.getNumRetained(), 56); - } - - @Test //set static enablePrinting = true for visual checking - public void viewHeapCompactions() { - final int k = 20; - final int n = 108; - final boolean withLevels = false; - final boolean withLevelsAndItems = true; - int compaction = 0; - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { - sk.update(i); - if (sk.levelsArr[0] == 0) { - println(LS + "#<<< BEFORE COMPACTION # " + (++compaction) + " >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - sk.update(++i); - println(LS + "#<<< AFTER COMPACTION # " + (compaction) + " >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - assertEquals(sk.getLongItemsArray()[sk.levelsArr[0]], i); - } - } - println(LS + "#<<< END STATE # >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - println(""); - } - - @Test //set static enablePrinting = true for visual checking - public void viewDirectCompactions() { - final int k = 20; - final int n = 108; - final boolean withLevels = false; - final boolean withLevelsAndItems = true; - int compaction = 0; - final int sizeBytes = KllSketch.getMaxSerializedSizeBytes(k, n, KLL_LONGS_SKETCH, true); - final MemorySegment wseg = MemorySegment.ofArray(new byte[sizeBytes]); - final KllLongsSketch sk = KllLongsSketch.newDirectInstance(k, wseg, null); - for (int i = 1; i <= n; i++) { - sk.update(i); - if (sk.levelsArr[0] == 0) { - println(LS + "#<<< BEFORE COMPACTION # " + (++compaction) + " >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - sk.update(++i); - println(LS + "#<<< AFTER COMPACTION # " + (compaction) + " >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - assertEquals(sk.getLongItemsArray()[sk.levelsArr[0]], i); - } - } - println(LS + "#<<< END STATE # >>>"); - println(sk.toString(withLevels, withLevelsAndItems)); - println(""); - } - - @Test //set static enablePrinting = true for visual checking - public void viewCompactionAndSortedView() { - final int n = 43; - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= n; i++) { sk.update(i); } - println(sk.toString(true, true)); - final LongsSortedView sv = sk.getSortedView(); - final LongsSortedViewIterator itr = sv.iterator(); - println("### SORTED VIEW"); - printf("%6s %12s %12s" + LS, "Idx", "Value", "Weight"); - int i = 0; - while (itr.next()) { - final long v = itr.getQuantile(); - final long wt = itr.getWeight(); - printf("%6d %12d %12d" + LS, i, v, wt); - i++; - } - assertEquals(sv.getMinItem(), 1L); - assertEquals(sv.getMaxItem(), n); - } - - @Test //set static enablePrinting = true for visual checking - public void checkWeightedUpdates1() { - final int k = 20; - final int weight = 127; - final long item = 10; - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - println(sk.toString(true, true)); - sk.update(item, weight); - println(sk.toString(true, true)); - assertEquals(sk.getNumRetained(), 7); - assertEquals(sk.getN(), weight); - sk.update(item, weight); - println(sk.toString(true, true)); - assertEquals(sk.getNumRetained(), 14); - assertEquals(sk.getN(), 254); - } - - @Test //set static enablePrinting = true for visual checking - public void checkWeightedUpdates2() { - final int k = 20; - final int initial = 1000; - final int weight = 127; - final long item = 10; - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= initial; i++) { sk.update(i + 1000); } - println(sk.toString(true, true)); - sk.update(item, weight); - println(sk.toString(true, true)); - assertEquals(sk.getNumRetained(), 65); - assertEquals(sk.getN(), 1127); - - final LongsSortedViewIterator itr = sk.getSortedView().iterator(); - println("### SORTED VIEW"); - printf("%12s %12s %12s" + LS, "Value", "Weight", "NaturalRank"); - long cumWt = 0; - while (itr.next()) { - final long v = itr.getQuantile(); - final long wt = itr.getWeight(); - final long natRank = itr.getNaturalRank(INCLUSIVE); - cumWt += wt; - assertEquals(cumWt, natRank); - printf("%12d %12d %12d" + LS, v, wt, natRank); - } - assertEquals(cumWt, sk.getN()); - } - - @Test //set static enablePrinting = true for visual checking - public void checkCreateItemsArray() { //used with weighted updates - final long item = 10; - final int weight = 108; - final long[] itemsArr = KllLongsHelper.createItemsArray(item, weight); - assertEquals(itemsArr.length, 4); - Arrays.fill(itemsArr, item); - outputItems(itemsArr); - } - - private static void outputItems(final long[] itemsArr) { - final String[] hdr2 = {"Index", "Value"}; - final String hdr2fmt = "%6s %15s" + LS; - final String d2fmt = "%6d %15d" + LS; - println("ItemsArr"); - printf(hdr2fmt, (Object[]) hdr2); - for (int i = 0; i < itemsArr.length; i++) { - printf(d2fmt, i, itemsArr[i]); - } - println(""); - } - - @Test //set static enablePrinting = true for visual checking - public void checkCreateLevelsArray() { //used with weighted updates - final int weight = 108; - final int[] levelsArr = KllHelper.createLevelsArray(weight); - assertEquals(levelsArr.length, 8); - final int[] correct = {0,0,0,1,2,2,3,4}; - for (int i = 0; i < levelsArr.length; i++) { - assertEquals(levelsArr[i], correct[i]); - } - outputLevels(weight, levelsArr); - } - - private static void outputLevels(final int weight, final int[] levelsArr) { - final String[] hdr = {"Lvl", "StartAdr", "BitPattern", "Weight"}; - final String hdrfmt = "%3s %9s %10s %s" + LS; - final String dfmt = "%3d %9d %10d %d" + LS; - final String dfmt_2 = "%3d %9d %s" + LS; - println("Count = " + weight + " => " + (Integer.toBinaryString(weight))); - println("LevelsArr"); - printf(hdrfmt, (Object[]) hdr); - for (int i = 0; i < levelsArr.length; i++) { - if (i == (levelsArr.length - 1)) { printf(dfmt_2, i, levelsArr[i], "ItemsArr.length"); } - else { - final int j = bitAt(weight, i); - printf(dfmt, i, levelsArr[i], j, 1 << (i)); - } - } - println(""); - } - - @Test - public void viewMemorySketchData() { - final int k = 20; - final int n = 109; - final boolean withLevels = true; - final boolean withLevelsAndItems = true; - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= n; i++) { sk.update(i); } - final byte[] byteArr = sk.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - final KllLongsSketch fltSk = KllLongsSketch.wrap(seg); - println(fltSk.toString(withLevels, withLevelsAndItems)); - assertEquals(fltSk.getN(), n); - } - - @Test //set static enablePrinting = true for visual checking - public void checkIntCapAux() { - final String[] hdr = {"level", "depth", "wt", "cap", "(end)", "MaxN"}; - final String hdrFmt = "%6s %6s %28s %10s %10s %34s" + LS; - final String dataFmt = "%6d %6d %,28d %,10d %,10d %,34d" + LS; - final int k = 1000; - final int m = 8; - final int numLevels = 20; - println("k=" + k + ", m=" + m + ", numLevels=" + numLevels); - printf(hdrFmt, (Object[]) hdr); - long maxN = 0; - final long[] correct = {0,1,1,2,2,3,5,8,12,17,26,39,59,88,132,198,296,444,667,1000}; - for (int i = 0; i < numLevels; i++) { - final int depth = numLevels - i - 1; - final long cap = KllHelper.intCapAux(k, depth); - final long end = Math.max(m, cap); - final long wt = 1L << i; - maxN += wt * end; - printf(dataFmt, i, depth, wt, cap, end, maxN); - assertEquals(cap, correct[i]); - } - } - - @Test //set static enablePrinting = true for visual checking - public void checkIntCapAuxAux() { - final String[] hdr = {"d","twoK","2k*2^d","3^d","tmp=2k*2^d/3^d","(tmp + 1)/2", "(end)"}; - final String hdrFmt = "%6s %10s %20s %20s %15s %12s %10s" + LS; - final String dataFmt = "%6d %10d %,20d %,20d %15d %12d %10d" + LS; - final long k = (1L << 16) - 1L; - final long m = 8; - println("k = " + k + ", m = " + m); - printf(hdrFmt, (Object[]) hdr); - final long[] correct = - {65535,43690,29127,19418,12945,8630,5753,3836,2557,1705,1136,758,505,337,224,150,100,67,44,30,20,13,9,6,4,3,2,1,1,1,0}; - for (int i = 0; i < 31; i++) { - final long twoK = k << 1; - final long twoKxtwoD = twoK << i; - final long threeToD = KllHelper.powersOfThree[i]; - final long tmp = twoKxtwoD / threeToD; - final long result = (tmp + 1L) >>> 1; - final long end = Math.max(m, result); //performed later - printf(dataFmt, i, twoK, twoKxtwoD, threeToD, tmp, result, end); - assertEquals(result,correct[i]); - assertEquals(result, KllHelper.intCapAuxAux(k, i)); - } - } - - @Test - public void checkGrowLevels() { - final KllLongsSketch sk = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= 21; i++) { sk.update(i); } - assertEquals(sk.getNumLevels(), 2); - assertEquals(sk.getLongItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure)[2], 33); - } - - @Test //set static enablePrinting = true for visual checking - public void checkSketchInitializeLongHeap() { - final int k = 20; //don't change this - KllLongsSketch sk; - - println("#### CASE: LONG FULL HEAP"); - sk = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21L); - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: LONG HEAP EMPTY"); - sk = KllLongsSketch.newHeapInstance(k); - println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: LONG HEAP SINGLE"); - sk = KllLongsSketch.newHeapInstance(k); - sk.update(1); - println(sk.toString(true, true)); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1L); - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test //set static enablePrinting = true for visual checking - public void checkSketchInitializeLongHeapifyCompactMemorySegment() { - final int k = 20; //don't change this - KllLongsSketch sk; - KllLongsSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - println("#### CASE: LONG FULL HEAPIFIED FROM COMPACT"); - sk2 = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - //println(sk2.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true)); - sk = KllLongsSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21); - assertEquals(sk.getMinItem(), 1); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: LONG EMPTY HEAPIFIED FROM COMPACT"); - sk2 = KllLongsSketch.newHeapInstance(k); - //println(sk.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg, LONGS_SKETCH, true)); - sk = KllLongsSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: LONG SINGLE HEAPIFIED FROM COMPACT"); - sk2 = KllLongsSketch.newHeapInstance(k); - sk2.update(1); - //println(sk2.toString(true, true)); - compBytes = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg, LONGS_SKETCH, true)); - sk = KllLongsSketch.heapify(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1L); - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test //set static enablePrinting = true for visual checking - public void checkSketchInitializeLongHeapifyUpdatableMemorySegment() { - final int k = 20; //don't change this - KllLongsSketch sk; - KllLongsSketch sk2; - byte[] compBytes; - MemorySegment wseg; - - println("#### CASE: LONG FULL HEAPIFIED FROM UPDATABLE"); - sk2 = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk2.update(i); } - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - println(KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true)); - sk = KllHeapLongsSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), k + 1); - assertEquals(sk.getNumRetained(), 11); - assertFalse(sk.isEmpty()); - assertTrue(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 33); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 3); - assertEquals(sk.getMaxItem(), 21); - assertEquals(sk.getMinItem(), 1); - assertEquals(sk.getNumLevels(), 2); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: LONG EMPTY HEAPIFIED FROM UPDATABLE"); - sk2 = KllLongsSketch.newHeapInstance(k); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg, LONGS_SKETCH, true)); - sk = KllHeapLongsSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getNumRetained(), 0); - assertTrue(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - try { sk.getMaxItem(); fail(); } catch (final SketchesArgumentException e) { } - try { sk.getMinItem(); fail(); } catch (final SketchesArgumentException e) { } - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - - println("#### CASE: LONG SINGLE HEAPIFIED FROM UPDATABLE"); - sk2 = KllLongsSketch.newHeapInstance(k); - sk2.update(1); - //println(sk.toString(true, true)); - compBytes = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(compBytes); - //println(KllPreambleUtil.toString(wseg, LONGS_SKETCH, true)); - sk = KllHeapLongsSketch.heapifyImpl(wseg); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 1); - assertEquals(sk.getNumRetained(), 1); - assertFalse(sk.isEmpty()); - assertFalse(sk.isEstimationMode()); - assertEquals(sk.getMinK(), k); - assertEquals(sk.getLongItemsArray().length, 20); - assertEquals(sk.getLevelsArray(sk.sketchStructure).length, 2); - assertEquals(sk.getMaxItem(), 1L); - assertEquals(sk.getMinItem(), 1L); - assertEquals(sk.getNumLevels(), 1); - assertFalse(sk.isLevelZeroSorted()); - } - - @Test //set static enablePrinting = true for visual checking - public void checkMemoryToStringLongCompact() { - final int k = 20; //don't change this - KllLongsSketch sk; - KllLongsSketch sk2; - byte[] compBytes; - byte[] compBytes2; - MemorySegment wseg; - String s; - - println("#### CASE: LONG FULL COMPACT"); - sk = KllLongsSketch.newHeapInstance(k); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - compBytes = sk.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllLongsSketch.heapify(wseg); - compBytes2 = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes2); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 2: segory to heap sketch, to byte[]/segory & analyze segory. Should match above"); - println(s); - assertEquals(compBytes, compBytes2); - - println("#### CASE: LONG EMPTY COMPACT"); - sk = KllLongsSketch.newHeapInstance(k); - compBytes = sk.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllLongsSketch.heapify(wseg); - compBytes2 = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes2); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 2: segory to heap sketch, to byte[]/segory & analyze segory. Should match above"); - println(s); - assertEquals(compBytes, compBytes2); - - println("#### CASE: LONG SINGLE COMPACT"); - sk = KllLongsSketch.newHeapInstance(k); - sk.update(1); - compBytes = sk.toByteArray(); - wseg = MemorySegment.ofArray(compBytes); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllLongsSketch.heapify(wseg); - compBytes2 = sk2.toByteArray(); - wseg = MemorySegment.ofArray(compBytes2); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 2: segory to heap sketch, to byte[]/segory & analyze segory. Should match above"); - println(s); - assertEquals(compBytes, compBytes2); - } - - @Test //set static enablePrinting = true for visual checking - public void checkMemoryToStringLongUpdatable() { - final int k = 20; //don't change this - KllLongsSketch sk; - KllLongsSketch sk2; - byte[] upBytes; - byte[] upBytes2; - MemorySegment wseg; - String s; - - println("#### CASE: LONG FULL UPDATABLE"); - sk = KllLongsSketch.newHeapInstance(20); - for (int i = 1; i <= (k + 1); i++) { sk.update(i); } - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllHeapLongsSketch.heapifyImpl(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 2: segory to heap sketch, to byte[]/segory & analyze segory. Should match above"); - println(s); //note: heapify does not copy free space, while toUpdatableByteArray does - assertEquals(sk.getN(), sk2.getN()); - assertEquals(sk.getMinItem(), sk2.getMinItem()); - assertEquals(sk.getMaxItem(), sk2.getMaxItem()); - assertEquals(sk.getNumRetained(), sk2.getNumRetained()); - - println("#### CASE: LONG EMPTY UPDATABLE"); - sk = KllLongsSketch.newHeapInstance(k); - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllHeapLongsSketch.heapifyImpl(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 2: segory to heap sketch, to byte[]/segory & analyze segory. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - - println("#### CASE: LONG SINGLE UPDATABLE"); - sk = KllLongsSketch.newHeapInstance(k); - sk.update(1); - upBytes = KllHelper.toByteArray(sk, true); - wseg = MemorySegment.ofArray(upBytes); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 1: sketch to byte[]/segory & analyze segory"); - println(s); - sk2 = KllHeapLongsSketch.heapifyImpl(wseg); - upBytes2 = KllHelper.toByteArray(sk2, true); - wseg = MemorySegment.ofArray(upBytes2); - s = KllPreambleUtil.toString(wseg, KLL_LONGS_SKETCH, true); - println("step 2: segory to heap sketch, to byte[]/segory & analyze segory. Should match above"); - println(s); - assertEquals(upBytes, upBytes2); - } - - @Test - public void checkSimpleMerge() { - final int k = 20; - final int m = 8; - final int n1 = 21; - final int n2 = 43; - final MemorySegment wseg = MemorySegment.ofArray(new byte[3000]); - final MemorySegment wseg2 = MemorySegment.ofArray(new byte[3000]); - - final KllLongsSketch sk1 = KllDirectLongsSketch.newDirectUpdatableInstance(k, m, wseg, null); - final KllLongsSketch sk2 = KllDirectLongsSketch.newDirectUpdatableInstance(k, m, wseg2, null); - for (int i = 1; i <= n1; i++) { - sk1.update(i); - } - for (int i = 1; i <= n2; i++) { - sk2.update(i + 100); - } - sk1.merge(sk2); - assertEquals(sk1.getMinItem(), 1L); - assertEquals(sk1.getMaxItem(), 143L); - } - - @Test - public void checkGetSingleItem() { - final int k = 20; - final KllLongsSketch skHeap = KllLongsSketch.newHeapInstance(k); - skHeap.update(1); - assertTrue(skHeap instanceof KllHeapLongsSketch); - assertEquals(skHeap.getLongSingleItem(), 1L); - - final MemorySegment srcSeg = MemorySegment.ofArray(KllHelper.toByteArray(skHeap, true)); - final KllLongsSketch skDirect = KllLongsSketch.wrap(srcSeg); - assertTrue(skDirect instanceof KllDirectLongsSketch); - assertEquals(skDirect.getLongSingleItem(), 1L); - - final MemorySegment srcSeg2 = MemorySegment.ofArray(skHeap.toByteArray()); - final KllLongsSketch skCompact = KllLongsSketch.wrap(srcSeg2); - assertTrue(skCompact.sketchStructure == SketchStructure.COMPACT_SINGLE); - assertEquals(skCompact.getLongSingleItem(), 1L); - } - - @Test - public void printlnTest() { - final String s = "PRINTING: printf in " + this.getClass().getName(); - println(s); - printf("%s" + LS, s); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ... args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/kll/KllSketchTest.java b/src/test/java/org/apache/datasketches/kll/KllSketchTest.java deleted file mode 100644 index 131d080b5..000000000 --- a/src/test/java/org/apache/datasketches/kll/KllSketchTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.kll; - -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_EMPTY; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_FULL; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.COMPACT_SINGLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.UPDATABLE; -import static org.apache.datasketches.kll.KllSketch.SketchStructure.getSketchStructure; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.Test; - -public class KllSketchTest { - - @Test - public void checkSketchStructureEnum() { - assertEquals(getSketchStructure(2,1), COMPACT_EMPTY); - assertEquals(getSketchStructure(2,2), COMPACT_SINGLE); - assertEquals(getSketchStructure(5,1), COMPACT_FULL); - assertEquals(getSketchStructure(5,3), UPDATABLE); - try { getSketchStructure(5,2); fail(); } catch (final SketchesArgumentException e) { } - try { getSketchStructure(2,3); fail(); } catch (final SketchesArgumentException e) { } - } - - private final static boolean enablePrinting = false; - - /** - * @param o the Object to println - */ - static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} - diff --git a/src/test/java/org/apache/datasketches/partitions/ClassicPartitionsTest.java b/src/test/java/org/apache/datasketches/partitions/ClassicPartitionsTest.java deleted file mode 100644 index 5175ecab0..000000000 --- a/src/test/java/org/apache/datasketches/partitions/ClassicPartitionsTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.partitions; - -import static org.apache.datasketches.partitions.BoundsRule.INCLUDE_BOTH; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -import java.util.List; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow; -import org.apache.datasketches.quantiles.QuantilesItemsSketch; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; -import org.testng.annotations.Test; - -/** - * This classic quantiles sketch partitioner example application uses Strings formatted as numbers. - * The length of each string is the number of characters required to display the decimal digits of N, - * the number of elements of the entire set of data to be partitioned. - * As a result, there is a lot of overhead in string processing. - * Nevertheless, real applications of the approach outlined here, would have a lot of IO overhead that this simple - * test example does not have. - */ -@SuppressWarnings("unused") -public class ClassicPartitionsTest { - - /** - * Launch the partitioner as an application with the following arguments as strings: - *
    - *
  • arg[0]: int k, the size of the sketch
  • - *
  • arg[1]: String INCLUSIVE or EXCLUSIVE, the search criteria.
  • - *
  • arg[2]: long totalN, the total size, in elements, of the data set to parse.
  • - *
  • arg[3]: long tgtPartitionSize, the target number of elements per resulting partition.
  • - *
  • arg[4]: int maxPartsPerSk, the maximum number of partitions to be handled by any one sketch
  • - *
- * @param args input arguments as defined above. - */ - public void main(String[] args) { - final int k, maxPartsPerSk; - final long totalN, tgtPartitionSize; - final QuantileSearchCriteria searchCrit; - try { - k = Integer.parseInt(args[0].trim()); - searchCrit = args[1].trim().equalsIgnoreCase("INCLUSIVE") ? INCLUSIVE : EXCLUSIVE; - totalN = Long.parseLong(args[2].trim()); - tgtPartitionSize = Long.parseLong(args[3].trim()); - maxPartsPerSk = Integer.parseInt(args[4].trim()); - } catch (NumberFormatException e) { throw new SketchesArgumentException(e.toString()); } - classicPartitioner(k, searchCrit, totalN, tgtPartitionSize, maxPartsPerSk); - } - - //@Test //launch from TestNG - public void checkClassicPartitioner() { - final int k = 1 << 15; - final QuantileSearchCriteria searchCrit = INCLUSIVE; - final long totalN = 30_000_000L; //artificially set low so it will execute fast as a simple test - final long tgtPartitionSize = 3_000_000L; - final int maxPartsPerSk = 100; - classicPartitioner(k, searchCrit, totalN, tgtPartitionSize, maxPartsPerSk); - } - - /** - * Programmatic call to classic Partitioner - * @param k the size of the sketch. - * @param searchCrit the QuantileSearchCriteria: either INCLUSIVE or EXCLUSIVE. - * @param totalN the total size, in elements, of the data set to parse. - * @param tgtPartitionSize the target number of elements per resulting partition. - * @param maxPartsPerSk the maximum number of partitions to be handled by any one sketch. - */ - public void classicPartitioner( - final int k, - final QuantileSearchCriteria searchCrit, - final long totalN, - final long tgtPartitionSize, - final int maxPartsPerSk) { - - final long startTime_mS = System.currentTimeMillis(); - final ItemsSketchFillRequestLongAsString fillReq = new ItemsSketchFillRequestLongAsString(k, totalN); - final QuantilesItemsSketch sk = fillReq.getRange(1L, totalN, INCLUDE_BOTH); - final long endFillInitialSketchTime_mS = System.currentTimeMillis(); - final Partitioner> partitioner = new Partitioner<>( - tgtPartitionSize, - maxPartsPerSk, - fillReq, - searchCrit); - final List> list = partitioner.partition(sk); - final long endTime_mS = System.currentTimeMillis(); - final long fillInitialSketchTime_mS = endFillInitialSketchTime_mS - startTime_mS; - final long partitioningTime_mS = endTime_mS - endFillInitialSketchTime_mS; - final long totalTime_mS = endTime_mS - startTime_mS; - PartitionResults.output( - "Classic", - list, - k, - searchCrit, - totalN, - tgtPartitionSize, - maxPartsPerSk, - fillInitialSketchTime_mS, - partitioningTime_mS, - totalTime_mS); - } - -} diff --git a/src/test/java/org/apache/datasketches/partitions/ItemsSketchFillRequestLongAsString.java b/src/test/java/org/apache/datasketches/partitions/ItemsSketchFillRequestLongAsString.java deleted file mode 100644 index 8e39ba55f..000000000 --- a/src/test/java/org/apache/datasketches/partitions/ItemsSketchFillRequestLongAsString.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.partitions; - -import static org.apache.datasketches.partitions.BoundsRule.INCLUDE_BOTH; -import static org.apache.datasketches.partitions.BoundsRule.INCLUDE_UPPER; -import static org.apache.datasketches.quantilescommon.LongsAsOrderableStrings.digits; -import static org.apache.datasketches.quantilescommon.LongsAsOrderableStrings.getString; - -import java.util.Comparator; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantiles.QuantilesItemsSketch; - -/** - * This is an simulated data set with a given N used for testing. - * @author Lee Rhodes - */ -public class ItemsSketchFillRequestLongAsString implements SketchFillRequest> { - private int k; - private int numDigits; - - public ItemsSketchFillRequestLongAsString() { - k = 1 << 10; - numDigits = 3; - } - - public ItemsSketchFillRequestLongAsString(final int k, final long totalN) { - this.k = k; - this.numDigits = digits(totalN); - } - - @Override - public QuantilesItemsSketch getRange(final String lowerQuantile, final String upperQuantile, - final BoundsRule bounds) { - final QuantilesItemsSketch sk = QuantilesItemsSketch.getInstance(String.class, k, Comparator.naturalOrder()); - long upper, lower; - try { - lower = Long.parseLong(lowerQuantile.trim()); - upper = Long.parseLong(upperQuantile.trim()); - } catch (NumberFormatException e) { throw new SketchesArgumentException(e.toString()); } - if (bounds == INCLUDE_BOTH) { - for (long i = lower; i <= upper; i++) { sk.update(getString(i, numDigits)); } - } else if (bounds == INCLUDE_UPPER) { - for (long i = lower + 1; i <= upper; i++) { sk.update(getString(i, numDigits)); } - } else { //INCLUDE_LOWER - for (long i = lower; i < upper; i++) { sk.update(getString(i, numDigits)); } - } - return sk; - } - - public QuantilesItemsSketch getRange(final long lowerQuantile, final long upperQuantile, final BoundsRule bounds) { - final QuantilesItemsSketch sk = QuantilesItemsSketch.getInstance(String.class, k, Comparator.naturalOrder()); - final long lower = lowerQuantile; - final long upper = upperQuantile; - if (bounds == INCLUDE_BOTH) { - for (long i = lower; i <= upper; i++) { sk.update(getString(i, numDigits)); } - } else if (bounds == INCLUDE_UPPER) { - for (long i = lower + 1; i <= upper; i++) { sk.update(getString(i, numDigits)); } - } else { //INCLUDE_LOWER - for (long i = lower; i < upper; i++) { sk.update(getString(i, numDigits)); } - } - return sk; - } - -} diff --git a/src/test/java/org/apache/datasketches/partitions/KllItemsSketchFillRequestLongAsString.java b/src/test/java/org/apache/datasketches/partitions/KllItemsSketchFillRequestLongAsString.java deleted file mode 100644 index 5acf3a31b..000000000 --- a/src/test/java/org/apache/datasketches/partitions/KllItemsSketchFillRequestLongAsString.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.partitions; - -import static org.apache.datasketches.partitions.BoundsRule.INCLUDE_BOTH; -import static org.apache.datasketches.partitions.BoundsRule.INCLUDE_UPPER; -import static org.apache.datasketches.quantilescommon.LongsAsOrderableStrings.digits; -import static org.apache.datasketches.quantilescommon.LongsAsOrderableStrings.getString; - -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllItemsSketch; - -/** - * This is an simulated data set with a given N used for testing. - * @author Lee Rhodes - */ -public class KllItemsSketchFillRequestLongAsString implements SketchFillRequest> { - private final int k; - private final int numDigits; - - public KllItemsSketchFillRequestLongAsString() { - k = 1 << 10; - numDigits = 3; - } - - public KllItemsSketchFillRequestLongAsString(final int k, final long totalN) { - this.k = k; - numDigits = digits(totalN); - } - - @Override - public KllItemsSketch getRange(final String lowerQuantile, final String upperQuantile, - final BoundsRule bounds) { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), new ArrayOfStringsSerDe()); - long upper, lower; - try { - lower = Long.parseLong(lowerQuantile.trim()); - upper = Long.parseLong(upperQuantile.trim()); - } catch (final NumberFormatException e) { throw new SketchesArgumentException(e.toString()); } - if (bounds == INCLUDE_BOTH) { - for (long i = lower; i <= upper; i++) { sk.update(getString(i, numDigits)); } - } else if (bounds == INCLUDE_UPPER) { - for (long i = lower + 1; i <= upper; i++) { sk.update(getString(i, numDigits)); } - } else { //INCLUDE_LOWER - for (long i = lower; i < upper; i++) { sk.update(getString(i, numDigits)); } - } - return sk; - } - - public KllItemsSketch getRange(final long lowerQuantile, final long upperQuantile, final BoundsRule bounds) { - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), new ArrayOfStringsSerDe()); - final long lower = lowerQuantile; - final long upper = upperQuantile; - if (bounds == INCLUDE_BOTH) { - for (long i = lower; i <= upper; i++) { sk.update(getString(i, numDigits)); } - } else if (bounds == INCLUDE_UPPER) { - for (long i = lower + 1; i <= upper; i++) { sk.update(getString(i, numDigits)); } - } else { //INCLUDE_LOWER - for (long i = lower; i < upper; i++) { sk.update(getString(i, numDigits)); } - } - return sk; - } - -} diff --git a/src/test/java/org/apache/datasketches/partitions/KllPartitionsTest.java b/src/test/java/org/apache/datasketches/partitions/KllPartitionsTest.java deleted file mode 100644 index 1833adddd..000000000 --- a/src/test/java/org/apache/datasketches/partitions/KllPartitionsTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.partitions; - -import static org.apache.datasketches.partitions.BoundsRule.INCLUDE_BOTH; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -import java.util.List; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllItemsSketch; -import org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; -import org.testng.annotations.Test; - -/** - * This KLL quantiles sketch partitioner example application uses Strings formatted as numbers. - * The length of each string is the number of characters required to display the decimal digits of N, - * the number of elements of the entire set of data to be partitioned. - * As a result, there is a lot of overhead in string processing. - * Nevertheless, real applications of the approach outlined here, would have a lot of IO overhead that this simple - * test example does not have. - */ -@SuppressWarnings("unused") -public class KllPartitionsTest { - - /** - * Launch the partitioner as an application with the following arguments as strings: - *
    - *
  • arg[0]: int k, the size of the sketch
  • - *
  • arg[1]: String INCLUSIVE or EXCLUSIVE, the search criteria.
  • - *
  • arg[2]: long totalN, the total size, in elements, of the data set to parse.
  • - *
  • arg[3]: long tgtPartitionSize, the target number of elements per resulting partition.
  • - *
  • arg[4]: int maxPartsPerSk, the maximum number of partitions to be handled by any one sketch
  • - *
- * @param args input arguments as defined above. - */ - public void main(final String[] args) { - final int k, maxPartsPerSk; - final long totalN, tgtPartitionSize; - final QuantileSearchCriteria searchCrit; - try { - k = Integer.parseInt(args[0].trim()); - searchCrit = args[1].trim().equalsIgnoreCase("INCLUSIVE") ? INCLUSIVE : EXCLUSIVE; - totalN = Long.parseLong(args[2].trim()); - tgtPartitionSize = Long.parseLong(args[3].trim()); - maxPartsPerSk = Integer.parseInt(args[4].trim()); - } catch (final NumberFormatException e) { throw new SketchesArgumentException(e.toString()); } - kllPartitioner(k, searchCrit, totalN, tgtPartitionSize, maxPartsPerSk); - } - - //@Test //launch from TestNG - public void checkKllPartitioner() { - final int k = 1 << 15; - final QuantileSearchCriteria searchCrit = INCLUSIVE; - final long totalN = 30_000_000L; //artificially set low so it will execute fast as a simple test - final long tgtPartitionSize = 3_000_000L; - final int maxPartsPerSk = 100; - kllPartitioner(k, searchCrit, totalN, tgtPartitionSize, maxPartsPerSk); - } - - /** - * Programmatic call to KLL Partitioner - * @param k the size of the sketch. - * @param searchCrit the QuantileSearchCriteria: either INCLUSIVE or EXCLUSIVE. - * @param totalN the total size, in elements, of the data set to parse. - * @param tgtPartitionSize the target number of elements per resulting partition. - * @param maxPartsPerSk the maximum number of partitions to be handled by any one sketch. - */ - public void kllPartitioner( - final int k, - final QuantileSearchCriteria searchCrit, - final long totalN, - final long tgtPartitionSize, - final int maxPartsPerSk) { - - final long startTime_mS = System.currentTimeMillis(); - final KllItemsSketchFillRequestLongAsString fillReq = new KllItemsSketchFillRequestLongAsString(k, totalN); - final KllItemsSketch sk = fillReq.getRange(1L, totalN, INCLUDE_BOTH); - final long endFillInitialSketchTime_mS = System.currentTimeMillis(); - final Partitioner> partitioner = new Partitioner<>( - tgtPartitionSize, - maxPartsPerSk, - fillReq, - searchCrit); - final List> list = partitioner.partition(sk); - final long endTime_mS = System.currentTimeMillis(); - final long fillInitialSketchTime_mS = endFillInitialSketchTime_mS - startTime_mS; - final long partitioningTime_mS = endTime_mS - endFillInitialSketchTime_mS; - final long totalTime_mS = endTime_mS - startTime_mS; - PartitionResults.output( - "KLL", - list, - k, - searchCrit, - totalN, - tgtPartitionSize, - maxPartsPerSk, - fillInitialSketchTime_mS, - partitioningTime_mS, - totalTime_mS); - } - -} diff --git a/src/test/java/org/apache/datasketches/partitions/PartitionResults.java b/src/test/java/org/apache/datasketches/partitions/PartitionResults.java deleted file mode 100644 index 65d8a2ba8..000000000 --- a/src/test/java/org/apache/datasketches/partitions/PartitionResults.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.partitions; - -import static java.lang.Math.abs; -import static java.lang.Math.max; -import static java.lang.Math.sqrt; -import static org.apache.datasketches.common.Util.milliSecToString; - -import java.util.List; - -import org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; - -/** - * Output partitioning results to console. - */ -public class PartitionResults { - private final static String LS = System.getProperty("line.separator"); - private static final String[] hdr = - { "Level.Part", "Partition", "LowerBound", "UpperBound", "ApproxNumItems", "Include Rule" }; - private static final String hdrFmt = "%15s %10s %15s %15s %15s %15s\n"; - private static final String dFmt = "%15s %10d %15s %15s %15d %15s\n"; - - public static void output( - final String sketchType, - final List> list, - final int k, - final QuantileSearchCriteria searchCrit, - final long totalN, - final long tgtPartitionSize, - final int maxPartsPerSk, - final long fillInitialSketchTime_mS, - final long partitioningTime_mS, - final long totalTime_mS) { - printf(hdrFmt, (Object[]) hdr); - final int numParts = list.size(); - final double meanPartSize = (double)totalN / numParts; - double size = 0; - double sumSizes = 0; - double sumAbsRelErr = 0; - double sumSqErr = 0; - double maxAbsErr = 0; - for (int i = 0; i < numParts; i++) { - final PartitionBoundsRow row = list.get(i); - printf(dFmt, row.levelPartId , (i + 1), row.lowerBound, row.upperBound, row.approxNumDeltaItems, row.rule.name()); - size = row.approxNumDeltaItems; - sumSizes += size; - sumAbsRelErr += abs(size / meanPartSize - 1.0); - final double absErr = abs(size - meanPartSize); - sumSqErr += absErr * absErr; - maxAbsErr= max(absErr, maxAbsErr); - } - final double meanAbsRelErr = sumAbsRelErr / numParts; - final double meanSqErr = sumSqErr / numParts; //intermediate value - final double normMeanSqErr = meanSqErr / (meanPartSize * meanPartSize); //intermediate value - final double rmsRelErr = sqrt(normMeanSqErr); //a.k.a. Normalized RMS Error or NRMSE - final double maxAbsErrFraction = maxAbsErr / meanPartSize; - - println(LS + sketchType + " Generic Quantiles Sketch Partitions Test"); - println(LS + "INPUT:"); - printf("Sketch K :%,20d\n", k); - printf("Search Criteria :%20s\n", searchCrit.name()); - printf("Total N :%,20d\n", totalN); - printf("Tgt Partition Size :%,20d\n", tgtPartitionSize); - printf("Max Parts Per Sketch :%20d\n", maxPartsPerSk); - - println(LS + "STATISTICS:"); - printf( "Total ApproxNumItems :%,20d\n", (long)sumSizes); - printf( "Mean Partition Size :%,20.1f\n", meanPartSize); - printf( "Mean Abs Rel Error :%20.3f%%\n", meanAbsRelErr * 100); - printf( "Norm RMS Error :%20.3f%%\n", rmsRelErr * 100); - printf( "Max Abs Error Percent :%20.3f%%\n", maxAbsErrFraction * 100); - - println(LS + "TIMINGS:"); - println("FillInitialSketchTime : " + milliSecToString(fillInitialSketchTime_mS)); - println("PartioningTime : " + milliSecToString(partitioningTime_mS)); - println("Total Time : " + milliSecToString(totalTime_mS) + LS); - } - - private final static boolean enablePrinting = true; - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } -} diff --git a/src/test/java/org/apache/datasketches/quantiles/AccuracyTest.java b/src/test/java/org/apache/datasketches/quantiles/AccuracyTest.java deleted file mode 100644 index 2fed90dc8..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/AccuracyTest.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import java.util.Random; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class AccuracyTest { - static Random rand = new Random(1); - - @Test - public void baseTest() { - int n = 1 << 20; - int k = 1 << 5; - - double[] seqArr = new double[n]; - //build sequential array - for (int i = 1; i <= n; i++) { - seqArr[i - 1] = i; - } - double[] randArr = seqArr.clone(); - shuffle(randArr); - UpdatableQuantilesDoublesSketch sketch = QuantilesDoublesSketch.builder().setK(k).build(); - for (int i = 0; i < n; i++) { - sketch.update(randArr[i]); - } - double[] ranks = sketch.getCDF(seqArr); - double maxDelta = 0; - for (int i = 0; i < n; i++) { - double actRank = (double)i/n; - double estRank = ranks[i]; - double delta = actRank - estRank; - maxDelta = Math.max(maxDelta, delta); - //println("Act: " + + " \tEst: " + ranks[i]); - } - println("Max delta: " + maxDelta); - println(sketch.toString()); - - } - - public static void shuffle(double[] arr) { - int n = arr.length; - for (int i = 0; i < n; i++) { - int j = i + rand.nextInt(n - i); - swap(arr, i, j); - } - } - - public static void swap(double[] arr, int i, int j) { - double t = arr[i]; - arr[i] = arr[j]; - arr[j] = t; - } - - - //@Test - public void getEpsilon() { - for (int lgK = 4; lgK < 15; lgK++) { - int k = 1 << lgK; - double eps = ClassicUtil.getNormalizedRankError(k, false); - println(k + "\t" + eps); - } - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/ClassicQuantilesMemorySegmentRequestApp.java b/src/test/java/org/apache/datasketches/quantiles/ClassicQuantilesMemorySegmentRequestApp.java deleted file mode 100644 index 6e96578ca..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/ClassicQuantilesMemorySegmentRequestApp.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentRequestExample; -import org.testng.annotations.Test; - -public class ClassicQuantilesMemorySegmentRequestApp { - - @Test - /** - * This method emulates an application using an off-heap QuantilesDoublesSketch that needs to expand off-heap. - * This demonstrates one example of how to manage a growing off-heap QuantilesDoublesSketch where the - * expanded MemorySegments are also off-heap. - */ - public void checkMemorySegmentRequestExample() { - final int k = 128; //The default is 128 - final int itemsIn = 40 * k; //will force requests for more space - - //Use the custom MemorySegmentRequestExample to do the allocations. - final MemorySegmentRequestExample mSegReqEx = new MemorySegmentRequestExample(); - - //The allocation of the original off-heap MemorySegment for the QuantilesDoublesSketch - //Note that this targets the size to only handle 2k values, which is quite small. - final int initalBytes = QuantilesDoublesSketch.getUpdatableStorageBytes(k, 2 * k); - - final MemorySegment seg = mSegReqEx.request(initalBytes); - - //Create a new KllLongsSketch and pass the mSegReqEx - final QuantilesDoublesSketch sk = QuantilesDoublesSketch.builder().setK(k).build(seg, mSegReqEx); - - //Update the sketch with way more data than the original MemorySegment can handle, forcing it to request larger MemorySegments. - for (int n = 1; n <= itemsIn; n++) { sk.update(n); } - - //Check to make sure the sketch got all the data: - assertEquals(sk.getMaxItem(), itemsIn); - assertEquals(sk.getMinItem(), 1); - assertEquals(sk.getN(), itemsIn); - - //Confirm that the last MemorySegment used by the sketch is, in fact, not the same as the original one that was allocated. - assertTrue(sk.getMemorySegment() != seg); - - //All done with the sketch. Cleanup any unclosed off-heap MemorySegments. - mSegReqEx.cleanup(); - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/CustomQuantilesTest.java b/src/test/java/org/apache/datasketches/quantiles/CustomQuantilesTest.java deleted file mode 100644 index d0816c4dc..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/CustomQuantilesTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueDoubleQuantile; -import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueDoubleRank; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantilesUtil.getNaturalRank; -import static org.testng.Assert.assertEquals; - -import org.apache.datasketches.quantilescommon.DoublesSketchSortedView; -import org.testng.annotations.Test; - -public class CustomQuantilesTest { - - /** - * Currently, this test only exercises the classic QuantilesDoublesSketch, but all the quantiles - * sketches use the same code for getQuantile() and getRank() anyway. - * This same pattern is also part of the CrossCheckQuantilesTest. - * This structure of this test allows more detailed analysis for troubleshooting. - */ - @Test - public void checkQuantilesV400() { - println("org.apache.datasketches.quantiles.CustomQuantilesTest:"); - println("Classic DoubleSketch, Version 4.0.0, k=4, N=12"); - println(""); - //The following for loop creates the following pattern for the sorted view: - // Quantiles: {10,10,20,20,30,30,40,40} - // Weights : { 2, 1, 2, 1, 2, 1, 2, 1} - //This is easy to create from the classic quantiles sketch directly, but for the other - //quantiles sketches it is easier to create by loading the sorted view directly via - //a package-private constructor. - int k = 4; - UpdatableQuantilesDoublesSketch sk = QuantilesDoublesSketch.builder().setK(k).build(); - for (int i = 1; i <= 3; i++) { - for (int q = 10; q <= k * 10; q += 10) { - sk.update(q); - } - } - long N = sk.getN(); - DoublesSketchSortedView sv = sk.getSortedView(); - double[] quantilesArr = sv.getQuantiles(); - long[] cumWtsArr = sv.getCumulativeWeights(); - int lenQ = quantilesArr.length; - println("Sorted View:"); - printf("%13s %13s %13s\n", "QuantilesArr", "CumWtsArr", "NormRanks"); - double normRank; - for (int i = 0; i < lenQ; i++) { - normRank = (double)cumWtsArr[i] / N; - printf("%12.1f%12d%12.4f\n", quantilesArr[i], cumWtsArr[i], normRank); - } - println(""); - - println("GetRanks, EXCLUSIVE:"); - println(" R of the largest Q at the highest index that is < q. If q <= smallest Q => 0"); - printf("%12s %12s\n", "Quantiles", "NormRanks"); - for (int q = 0; q <= (k * 10) + 5; q += 5) { //create a range of quantiles for input - double normRankEst = sk.getRank(q, EXCLUSIVE); - double normRankTrue = getTrueDoubleRank(cumWtsArr, quantilesArr, q, EXCLUSIVE); - assertEquals(normRankEst, normRankTrue); - printf("%12.1f %12.3f", (double)q, normRankEst); - if (normRankEst != normRankTrue) { println(" " + normRankEst + " != " + normRankTrue); } else { println(""); } - } - println(""); - - println("GetQuantiles, EXCLUSIVE (round down)"); - println(" Q of the smallest rank > r. If r = 1.0 => null or NaN"); - printf("%22s %22s %22s %13s\n", "NormRanksIn", "RawNaturalRank", "TrimmedNatRank", "QuantilesEst"); - long limit = 4 * N; - double inc = 1.0 / limit; - for (long j = 0; j <= limit; j++) { - double normRankIn = (j * inc); - double qEst = sk.getQuantile(normRankIn, EXCLUSIVE); - double qTrue = getTrueDoubleQuantile(cumWtsArr, quantilesArr, normRankIn, EXCLUSIVE); - assertEquals(qEst, qTrue); - double rawNatRank = normRankIn * N; - double trimNatRank = getNaturalRank(normRankIn, N, EXCLUSIVE); - printf("%22.18f %22.18f %22.18f %13.1f", normRankIn, rawNatRank, trimNatRank, qEst); - if (qEst != qTrue) { println(" " + qEst + " != " +qTrue); } else { println(""); } - } - println(""); - - println("GetRanks, INCLUSIVE:"); - println(" R of the largest Q at the highest index that is <= q. If q < smallest Q => 0"); - printf("%12s %12s\n", "Quantiles", "NormRanks"); - for (int q = 0; q <= (k * 10) + 5; q += 5) { - double nr = sk.getRank(q, INCLUSIVE); - double nrTrue = getTrueDoubleRank(cumWtsArr, quantilesArr, q, INCLUSIVE); - assertEquals(nr, nrTrue); - printf("%12.1f %12.3f", (double)q, nr); - if (nr != nrTrue) { println(" " + nr + " != " +nrTrue); } else { println(""); } - } - println(""); - - println("GetQuantiles, INCLUSIVE (round up)"); - println(" Q of the smallest rank >= r."); - printf("%22s %22s %22s %13s\n", "NormRanksIn", "RawNaturalRank", "TrimmedNatRank", "QuantilesEst"); - - inc = 1.0 / limit; - for (long j = 0; j <= limit; j++) { - double normRankIn = (j * inc); - double qEst = sk.getQuantile(normRankIn, INCLUSIVE); - double qTrue = getTrueDoubleQuantile(cumWtsArr, quantilesArr, normRankIn, INCLUSIVE); - assertEquals(qEst, qTrue); - double rawNatRank = normRankIn * N; - double trimNatRank = getNaturalRank(normRankIn, N, INCLUSIVE); - printf("%22.18f %22.18f %22.18f %13.1f", normRankIn, rawNatRank, trimNatRank, qEst); - if (qEst != qTrue) { println(" " + qEst + " != " +qTrue); } else { println(""); } - } - println(""); - } - - private final static boolean enablePrinting = false; - - /** - * @param o the Object to print - */ - static final void print(final Object o) { - if (enablePrinting) { System.out.print(o.toString()); } - } - - /** - * @param o the Object to println - */ - static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - - /** - * @param format the format - * @param args the args - */ - static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } -} - diff --git a/src/test/java/org/apache/datasketches/quantiles/DebugUnionTest.java b/src/test/java/org/apache/datasketches/quantiles/DebugUnionTest.java deleted file mode 100644 index cdc1f7a93..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/DebugUnionTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.Util.LS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; -import java.util.HashSet; - -import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIteratorAPI; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class DebugUnionTest { - - @Test - public void test() { - final int n = 70_000; - final int valueLimit = 1000; - final int numSketches = 3; - final int sketchK = 8; - final int unionK = 8; - final UpdatableQuantilesDoublesSketch[] sketchArr = new UpdatableQuantilesDoublesSketch[numSketches]; - - //builds the input sketches, all on heap - QuantilesDoublesSketch.setRandom(1); //make deterministic for test - final HashSet set = new HashSet<>(); //holds input values - for (int s = 0; s < numSketches; s++) { - sketchArr[s] = buildHeapSketch(sketchK, n, valueLimit, set); - } - - //loads the on heap union - QuantilesDoublesSketch.setRandom(1); //make deterministic for test - final QuantilesDoublesUnion hUnion = QuantilesDoublesUnion.builder().setMaxK(unionK).build(); - for (int s = 0; s < numSketches; s++) { hUnion.union(sketchArr[s]); } - final QuantilesDoublesSketch hSketch = hUnion.getResult(); - - //loads the direct union - QuantilesDoublesSketch.setRandom(1); //make deterministic for test - QuantilesDoublesUnion dUnion; - QuantilesDoublesSketch dSketch; - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = arena.allocate(10_000_000); - dUnion = QuantilesDoublesUnion.builder().setMaxK(8).build(wseg, null); - for (int s = 0; s < numSketches; s++) { dUnion.union(sketchArr[s]); } - dSketch = dUnion.getResult(); //result is on heap - } catch (final Exception e) { - throw new RuntimeException(e); - } - - //iterates and counts errors - final int hCount = hSketch.getNumRetained(); - final int dCount = dSketch.getNumRetained(); - - assertEquals(hCount, dCount); //Retained items must be the same - - int hErrors = 0; - int dErrors = 0; - - final QuantilesDoublesSketchIteratorAPI hit = hSketch.iterator(); - final QuantilesDoublesSketchIteratorAPI dit = dSketch.iterator(); - - while (hit.next() && dit.next()) { - final double v = hit.getQuantile(); - if (!set.contains(v)) { hErrors++; } - - final double w = dit.getQuantile(); - if (!set.contains(w)) { dErrors++; } - assertEquals(v, w, 0); //Items must be returned in same order and be equal - } - assertTrue(hErrors == 0); - assertTrue(dErrors == 0); - - println("HeapUnion : Values: " + hCount + ", errors: " + hErrors); - //println(hSketch.toString(true, true)); - - println("DirectUnion: Values: " + dCount + ", errors: " + dErrors); - //println(dSketch.toString(true, true)); - } - - private static UpdatableQuantilesDoublesSketch buildHeapSketch(final int k, final int n, final int valueLimit, - final HashSet set) { - final UpdatableQuantilesDoublesSketch uSk = QuantilesDoublesSketch.builder().setK(k).build(); - for (int i = 0; i < n; i++) { - final double value = QuantilesDoublesSketch.rand.nextInt(valueLimit) + 1; - uSk.update(value); - set.add(value); - } - return uSk; - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - print(s+LS); - } - - /** - * @param s value to print - */ - static void print(final String s) { - //System.out.print(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/DirectCompactDoublesSketchTest.java b/src/test/java/org/apache/datasketches/quantiles/DirectCompactDoublesSketchTest.java deleted file mode 100644 index 4e8d405c8..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/DirectCompactDoublesSketchTest.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.Util.LS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import org.apache.datasketches.common.MemorySegmentRequest; -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -public class DirectCompactDoublesSketchTest { - - @BeforeMethod - public void setUp() { - QuantilesDoublesSketch.rand.setSeed(32749); // make sketches deterministic for testing - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void wrapFromUpdateSketch() { - final int k = 4; - final int n = 27; - final UpdatableQuantilesDoublesSketch qs = HeapUpdateDoublesSketchTest.buildAndLoadQS(k, n); - - final byte[] qsBytes = qs.toByteArray(); - final MemorySegment qsSeg = MemorySegment.ofArray(qsBytes); - - DirectCompactDoublesSketch.wrapInstance(qsSeg); - fail(); - } - - @Test - public void createFromUnsortedUpdateSketch() { - final int k = 4; - final int n = 13; - final UpdatableQuantilesDoublesSketch qs = QuantilesDoublesSketch.builder().setK(k).build(); - for (int i = n; i > 0; --i) { - qs.update(i); - } - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[qs.getCurrentCompactSerializedSizeBytes()]); - final DirectCompactDoublesSketch compactQs - = DirectCompactDoublesSketch.createFromUpdateSketch(qs, dstSeg); - - // don't expect equal but new base buffer should be sorted - final double[] combinedBuffer = compactQs.getCombinedBuffer(); - final int bbCount = compactQs.getBaseBufferCount(); - - for (int i = 1; i < bbCount; ++i) { - assert combinedBuffer[i - 1] < combinedBuffer[i]; - } - } - - @Test - public void wrapFromCompactSketch() { - final int k = 8; - final int n = 177; - final DirectCompactDoublesSketch qs = buildAndLoadDCQS(k, n); // assuming ordered inserts - - final byte[] qsBytes = qs.toByteArray(); - final MemorySegment qsSeg = MemorySegment.ofArray(qsBytes); - - final DirectCompactDoublesSketch compactQs = DirectCompactDoublesSketch.wrapInstance(qsSeg); - DoublesSketchTest.testSketchEquality(qs, compactQs); - assertEquals(qsBytes.length, compactQs.getSerializedSizeBytes()); - - final double[] combinedBuffer = compactQs.getCombinedBuffer(); - assertEquals(combinedBuffer.length, compactQs.getCombinedBufferItemCapacity()); - } - - @Test - public void wrapEmptyCompactSketch() { - final CompactQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build().compact(); - final MemorySegment seg - = MemorySegment.ofBuffer(ByteBuffer.wrap(s1.toByteArray()).order(ByteOrder.nativeOrder())); - final QuantilesDoublesSketch s2 = QuantilesDoublesSketch.wrap(seg); - assertTrue(s2.isEmpty()); - assertEquals(s2.getN(), 0); - assertTrue(Double.isNaN(s2.isEmpty() ? Double.NaN : s2.getMinItem())); - assertTrue(Double.isNaN(s2.isEmpty() ? Double.NaN : s2.getMaxItem())); - } - - @Test - public void checkEmpty() { - final int k = PreambleUtil.DEFAULT_K; - final DirectCompactDoublesSketch qs1 = buildAndLoadDCQS(k, 0); - try { qs1.getQuantile(0.5); fail(); } catch (final IllegalArgumentException e) {} - try { qs1.getQuantiles(new double[] {0.0, 0.5, 1.0}); fail(); } catch (final IllegalArgumentException e) {} - final double[] combinedBuffer = qs1.getCombinedBuffer(); - assertEquals(combinedBuffer.length, 2 * k); - assertNotEquals(combinedBuffer.length, qs1.getCombinedBufferItemCapacity()); - } - - @Test - public void checkCheckDirectSegCapacity() { - final int k = 128; - DirectCompactDoublesSketch.checkDirectSegCapacity(k, (2 * k) - 1, (4 + (2 * k)) * 8); - DirectCompactDoublesSketch.checkDirectSegCapacity(k, (2 * k) + 1, (4 + (3 * k)) * 8); - DirectCompactDoublesSketch.checkDirectSegCapacity(k, 0, 8); - - try { - DirectCompactDoublesSketch.checkDirectSegCapacity(k, 10000, 64); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkSegTooSmall() { - final MemorySegment seg = MemorySegment.ofArray(new byte[7]); - HeapCompactDoublesSketch.heapifyInstance(seg); - } - - static DirectCompactDoublesSketch buildAndLoadDCQS(final int k, final int n) { - return buildAndLoadDCQS(k, n, 0); - } - - static DirectCompactDoublesSketch buildAndLoadDCQS(final int k, final int n, final int startV) { - final UpdatableQuantilesDoublesSketch qs = QuantilesDoublesSketch.builder().setK(k).build(); - for (int i = 1; i <= n; i++) { - qs.update(startV + i); - } - final byte[] byteArr = new byte[qs.getCurrentCompactSerializedSizeBytes()]; - final MemorySegment seg = MemorySegment.ofArray(byteArr); - return (DirectCompactDoublesSketch) qs.compact(seg); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - print("PRINTING: " + this.getClass().getName() + LS); - } - - static void println(final String s) { - print(s + LS); - } - - /** - * @param s value to print - */ - static void print(final String s) { - //System.err.print(s); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/quantiles/DirectQuantilesMemoryRequestTest.java b/src/test/java/org/apache/datasketches/quantiles/DirectQuantilesMemoryRequestTest.java deleted file mode 100644 index 2b37b00a4..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/DirectQuantilesMemoryRequestTest.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.MemorySegmentStatus.isSameResource; -import static org.apache.datasketches.quantiles.PreambleUtil.COMBINED_BUFFER; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -/** - * The concept for these tests is that the "MemorySegment Manager" classes below are proxies for the - * implementation that owns the native MemorySegment allocations, thus is responsible for - * allocating larger MemorySegment when requested and the actual freeing of the old MemorySegment allocations. - */ -public class DirectQuantilesMemoryRequestTest { - - @Test - public void checkLimitedMemoryScenarios() { //Requesting application - final int k = 128; - final int u = 40 * k; - final int initBytes = ((2 * k) + 4) << 3; //just the BaseBuffer - - //########## Owning Implementation - // This part would actually be part of the application owning the MemorySegment so it is faked here - MemorySegment wseg; - try (Arena arena = Arena.ofConfined()) { - wseg = arena.allocate(initBytes); - println("Initial seg size: " + wseg.byteSize()); - - //########## Receiving Application - // The receiving application has been given wseg to use for a sketch, - // but alas, it is not ultimately large enough. - final UpdatableQuantilesDoublesSketch usk = QuantilesDoublesSketch.builder().setK(k).build(wseg); - assertTrue(usk.isEmpty()); - - //Load the sketch - for (int i = 0; i < u; i++) { - // The sketch uses The MemorySegmentRequestto acquire more MemorySegment as needed, - // which, for the default, the new MemorySegments will be on-heap. - usk.update(i); - } - final double result = usk.getQuantile(0.5); - println("Result: " + result); - assertEquals(result, u / 2.0, 0.05 * u); //Success - - //########## Owning Implementation - //The actual MemorySegment has been re-allocated several times, - // so the sketch is using a different object. - final MemorySegment wseg2 = usk.getMemorySegment(); - println("\nFinal seg size: " + wseg2.byteSize()); - } - assertFalse(wseg.scope().isAlive()); - } - - @Test - public void checkGrowBaseBuf() { - final int k = 128; - final int u = 32; // don't need the BB to fill here - final int initBytes = (4 + (u / 2)) << 3; // not enough to hold everything - MemorySegment wseg; - try (Arena arena = Arena.ofConfined()) { - wseg = arena.allocate(initBytes); - println("Initial seg size: " + wseg.byteSize()); - final UpdatableQuantilesDoublesSketch usk1 = QuantilesDoublesSketch.builder().setK(k).build(wseg); - for (int i = 1; i <= u; i++) { - usk1.update(i); - } - final int currentSpace = usk1.getCombinedBufferItemCapacity(); - println("curCombBufItemCap: " + currentSpace); - assertEquals(currentSpace, 2 * k); - assertTrue(wseg.scope().isAlive()); - } - assertFalse(wseg.scope().isAlive()); - } - - @Test - public void checkGrowCombBuf() { - final int k = 128; - final int u = (2 * k) - 1; //just to fill the BB - final int initBytes = ((2 * k) + 4) << 3; //just room for BB - MemorySegment wseg; - try (Arena arena = Arena.ofConfined()) { - wseg = arena.allocate(initBytes); - println("Initial seg size: " + wseg.byteSize()); - final UpdatableQuantilesDoublesSketch usk1 = QuantilesDoublesSketch.builder().setK(k).build(wseg); - for (int i = 1; i <= u; i++) { - usk1.update(i); - } - final int currentSpace = usk1.getCombinedBufferItemCapacity(); - println("curCombBufItemCap: " + currentSpace); - final double[] newCB = usk1.growCombinedBuffer(currentSpace, 3 * k); - final int newSpace = usk1.getCombinedBufferItemCapacity(); - println("newCombBurItemCap: " + newSpace); - assertEquals(newCB.length, 3 * k); - assertTrue(wseg.scope().isAlive()); - } - assertFalse(wseg.scope().isAlive()); - } - - @Test - public void checkUpdatableStorageBytes() { - final int k = 16; - final int initBytes = QuantilesDoublesSketch.getUpdatableStorageBytes(k, 1); - println("Predicted Updatable Storage Bytes: " + initBytes); - final UpdatableQuantilesDoublesSketch usk1 = QuantilesDoublesSketch.builder().setK(k).build(); - usk1.update(1.0); - final byte[] uarr = usk1.toByteArray(); - println("Actual Storage Bytes " + uarr.length); - assertEquals(initBytes, uarr.length); - assertEquals(initBytes, 64); - } - - - @Test - public void checkGrowFromWrappedEmptySketch() { - final int k = 16; - final int n = 0; - final int initBytes = QuantilesDoublesSketch.getUpdatableStorageBytes(k, n); //empty: 8 bytes - final UpdatableQuantilesDoublesSketch usk1 = QuantilesDoublesSketch.builder().setK(k).build(); - final MemorySegment origSketchSeg = MemorySegment.ofArray(usk1.toByteArray()); //on heap - MemorySegment wseg; - try (Arena arena = Arena.ofConfined()) { - wseg = arena.allocate(initBytes); //off heap - MemorySegment.copy(origSketchSeg, 0, wseg, 0, initBytes); - final UpdatableQuantilesDoublesSketch usk2 = DirectUpdateDoublesSketch.wrapInstance(wseg, null); - assertTrue(isSameResource(wseg, usk2.getMemorySegment())); - assertEquals(wseg.byteSize(), initBytes); - assertTrue(wseg.isNative()); - assertTrue(usk2.isEmpty()); - - //update the sketch forcing it to grow on-heap - usk2.update(1.0); - assertEquals(usk2.getN(), 1); - final MemorySegment seg2 = usk2.getMemorySegment(); - assertFalse(isSameResource(wseg, seg2)); - assertFalse(seg2.isNative()); //should now be on-heap - - final int expectedSize = COMBINED_BUFFER + ((2 * k) << 3); - assertEquals(seg2.byteSize(), expectedSize); - assertTrue(wseg.scope().isAlive()); - } - assertFalse(wseg.scope().isAlive()); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/DirectUpdateDoublesSketchTest.java b/src/test/java/org/apache/datasketches/quantiles/DirectUpdateDoublesSketchTest.java deleted file mode 100644 index 088b4462c..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/DirectUpdateDoublesSketchTest.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.ceilingPowerOf2; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -public class DirectUpdateDoublesSketchTest { - - - @BeforeMethod - public void setUp() { - QuantilesDoublesSketch.rand.setSeed(32749); // make sketches deterministic for testing - } - - @Test - public void checkSmallMinMax () { - final int k = 32; - final int n = 8; - final UpdatableQuantilesDoublesSketch qs1 = buildDQS(k, n); - final UpdatableQuantilesDoublesSketch qs2 = buildDQS(k, n); - final UpdatableQuantilesDoublesSketch qs3 = buildDQS(k, n); - - for (int i = n; i >= 1; i--) { - qs1.update(i); - qs2.update(10+i); - qs3.update(i); - } - assertEquals(qs1.getQuantile (0.0, EXCLUSIVE), 1.0); - assertEquals(qs1.getQuantile (0.5, EXCLUSIVE), 5.0); - assertEquals(qs1.getQuantile (1.0, EXCLUSIVE), 8.0); - - assertEquals(qs2.getQuantile (0.0, EXCLUSIVE), 11.0); - assertEquals(qs2.getQuantile (0.5, EXCLUSIVE), 15.0); - assertEquals(qs2.getQuantile (1.0, EXCLUSIVE), 18.0); - - assertEquals(qs3.getQuantile (0.0, EXCLUSIVE), 1.0); - assertEquals(qs3.getQuantile (0.5, EXCLUSIVE), 5.0); - assertEquals(qs3.getQuantile (1.0, EXCLUSIVE), 8.0); - - final double[] queries = {0.0, 0.5, 1.0}; - - final double[] resultsA = qs1.getQuantiles(queries, EXCLUSIVE); - assertEquals(resultsA[0], 1.0); - assertEquals(resultsA[1], 5.0); - assertEquals(resultsA[2], 8.0); - - final QuantilesDoublesUnion union1 = QuantilesDoublesUnion.heapify(qs1); - union1.union(qs2); - final QuantilesDoublesSketch result1 = union1.getResult(); - - final QuantilesDoublesUnion union2 = QuantilesDoublesUnion.heapify(qs2); - union2.union(qs3); - final QuantilesDoublesSketch result2 = union2.getResult(); - - final double[] resultsB = result1.getQuantiles(queries, EXCLUSIVE); - printResults(resultsB); - assertEquals(resultsB[0], 1.0); - assertEquals(resultsB[1], 11.0); - assertEquals(resultsB[2], 18.0); - - final double[] resultsC = result2.getQuantiles(queries, EXCLUSIVE); - assertEquals(resultsC[0], 1.0); - assertEquals(resultsC[1], 11.0); - assertEquals(resultsC[2], 18.0); - } - - static void printResults(final double[] results) { - println(results[0] + ", " + results[1] + ", " + results[2]); - } - - @Test - public void wrapEmptyUpdateSketch() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - final MemorySegment seg = MemorySegment.ofBuffer(ByteBuffer.wrap(s1.toByteArray()).order(ByteOrder.nativeOrder())); - final UpdatableQuantilesDoublesSketch s2 = DirectUpdateDoublesSketch.wrapInstance(seg, null); - assertTrue(s2.isEmpty()); - - assertEquals(s2.getN(), 0); - assertTrue(Double.isNaN(s2.isEmpty() ? Double.NaN : s2.getMinItem())); - assertTrue(Double.isNaN(s2.isEmpty() ? Double.NaN : s2.getMaxItem())); - - s2.reset(); // empty: a no-op - assertEquals(s2.getN(), 0); - } - - @Test - public void checkPutCombinedBuffer() { - final int k = PreambleUtil.DEFAULT_K; - final int cap = 32 + ((2 * k) << 3); - MemorySegment seg = MemorySegment.ofArray(new byte[cap]); - final UpdatableQuantilesDoublesSketch qs = QuantilesDoublesSketch.builder().setK(k).build(seg); - seg = qs.getMemorySegment(); - assertEquals(seg.byteSize(), cap); - assertTrue(qs.isEmpty()); - - final int n = 16; - final double[] data = new double[n]; - for (int i = 0; i < n; ++i) { - data[i] = i + 1; - } - qs.putBaseBufferCount(n); - qs.putN(n); - qs.putCombinedBuffer(data); - - final double[] combBuf = qs.getCombinedBuffer(); - assertEquals(combBuf, data); - - // shouldn't have changed min/max values - assertTrue(Double.isNaN(qs.getMinItem())); - assertTrue(Double.isNaN(qs.getMaxItem())); - } - - @Test - public void checkMisc() { - final int k = PreambleUtil.DEFAULT_K; - final int n = 48; - final int cap = 32 + ((2 * k) << 3); - MemorySegment seg = MemorySegment.ofArray(new byte[cap]); - UpdatableQuantilesDoublesSketch qs = QuantilesDoublesSketch.builder().setK(k).build(seg); - seg = qs.getMemorySegment(); - assertEquals(seg.byteSize(), cap); - double[] combBuf = qs.getCombinedBuffer(); - assertEquals(combBuf.length, 2 * k); - qs = buildAndLoadDQS(k, n); - qs.update(Double.NaN); - final int n2 = (int)qs.getN(); - assertEquals(n2, n); - combBuf = qs.getCombinedBuffer(); - assertEquals(combBuf.length, ceilingPowerOf2(n)); // since n < k - println(qs.toString(true, true)); - qs.reset(); - assertEquals(qs.getN(), 0); - qs.putBaseBufferCount(0); - } - - @SuppressWarnings("unused") - @Test - public void variousExceptions() { - final MemorySegment seg = MemorySegment.ofArray(new byte[8]); - try { - final int flags = PreambleUtil.COMPACT_FLAG_MASK; - DirectUpdateDoublesSketch.checkCompact(2, 0); - fail(); - } catch (final SketchesArgumentException e) {} //OK - try { - final int flags = PreambleUtil.COMPACT_FLAG_MASK; - DirectUpdateDoublesSketch.checkCompact(3, flags); - fail(); - } catch (final SketchesArgumentException e) {} //OK - try { - DirectUpdateDoublesSketch.checkPreLongs(3); - fail(); - } catch (final SketchesArgumentException e) {} //OK - try { - DirectUpdateDoublesSketch.checkPreLongs(0); - fail(); - } catch (final SketchesArgumentException e) {} //OK - try { - DirectUpdateDoublesSketch.checkDirectFlags(PreambleUtil.COMPACT_FLAG_MASK); - fail(); - } catch (final SketchesArgumentException e) {} //OK - try { - DirectUpdateDoublesSketch.checkEmptyAndN(true, 1); - fail(); - } catch (final SketchesArgumentException e) {} //OK - } - - @Test - public void checkCheckDirectSegCapacity() { - final int k = 128; - DirectUpdateDoublesSketch.checkDirectSegCapacity(k, (2 * k) - 1, (4 + (2 * k)) * 8); - DirectUpdateDoublesSketch.checkDirectSegCapacity(k, (2 * k) + 1, (4 + (3 * k)) * 8); - DirectUpdateDoublesSketch.checkDirectSegCapacity(k, 0, 8); - - try { - DirectUpdateDoublesSketch.checkDirectSegCapacity(k, 10000, 64); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - } - - @Test - public void serializeDeserialize() { - final int sizeBytes = QuantilesDoublesSketch.getUpdatableStorageBytes(128, 2000); - final MemorySegment seg = MemorySegment.ofArray(new byte[sizeBytes]); - final UpdatableQuantilesDoublesSketch sketch1 = QuantilesDoublesSketch.builder().build(seg); - for (int i = 0; i < 1000; i++) { - sketch1.update(i); - } - - final UpdatableQuantilesDoublesSketch sketch2 = UpdatableQuantilesDoublesSketch.wrap(seg, null); - for (int i = 0; i < 1000; i++) { - sketch2.update(i + 1000); - } - assertEquals(sketch2.getMinItem(), 0.0); - assertEquals(sketch2.getMaxItem(), 1999.0); - assertEquals(sketch2.getQuantile(0.5), 1000.0, 10.0); - - final byte[] arr2 = sketch2.toByteArray(false); - assertEquals(arr2.length, sketch2.getSerializedSizeBytes()); - final QuantilesDoublesSketch sketch3 = QuantilesDoublesSketch.writableWrap(MemorySegment.ofArray(arr2), null); - assertEquals(sketch3.getMinItem(), 0.0); - assertEquals(sketch3.getMaxItem(), 1999.0); - assertEquals(sketch3.getQuantile(0.5), 1000.0, 10.0); - } - - @Test - public void mergeTest() { - final QuantilesDoublesSketch dqs1 = buildAndLoadDQS(128, 256); - final QuantilesDoublesSketch dqs2 = buildAndLoadDQS(128, 256, 256); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(128).build(); - union.union(dqs1); - union.union(dqs2); - final QuantilesDoublesSketch result = union.getResult(); - final double median = result.getQuantile(0.5); - println("Median: " + median); - assertEquals(median, 258.0, .05 * 258); - } - - @Test - public void checkSimplePropagateCarryDirect() { - final int k = 16; - final int n = k * 2; - - final int segBytes = QuantilesDoublesSketch.getUpdatableStorageBytes(k, n); - final MemorySegment seg = MemorySegment.ofArray(new byte[segBytes]); - final QuantilesDoublesSketchBuilder bldr = QuantilesDoublesSketch.builder(); - final UpdatableQuantilesDoublesSketch ds = bldr.setK(k).build(seg); - for (int i = 1; i <= n; i++) { // 1 ... n - ds.update(i); - } - double last = 0.0; - for (int i = 0; i < k; i++) { //check the level 0 - final double d = seg.get(JAVA_DOUBLE_UNALIGNED, (4 + (2 * k) + i) << 3); - assertTrue(d > 0); - assertTrue(d > last); - last = d; - } - //println(ds.toString(true, true)); - } - - @Test - public void getRankAndGetCdfConsistency() { - final int k = 128; - final int n = 1_000_000; - final int segBytes = QuantilesDoublesSketch.getUpdatableStorageBytes(k, n); - final MemorySegment seg = MemorySegment.ofArray(new byte[segBytes]); - final UpdatableQuantilesDoublesSketch sketch = QuantilesDoublesSketch.builder().build(seg); - final double[] values = new double[n]; - for (int i = 0; i < n; i++) { - sketch.update(i); - values[i] = i; - } - final double[] ranks = sketch.getCDF(values); - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i])); - } - } - - static UpdatableQuantilesDoublesSketch buildAndLoadDQS(final int k, final int n) { - return buildAndLoadDQS(k, n, 0); - } - - static UpdatableQuantilesDoublesSketch buildAndLoadDQS(final int k, final long n, final int startV) { - final UpdatableQuantilesDoublesSketch qs = buildDQS(k, n); - for (long i = 1; i <= n; i++) { - qs.update(startV + i); - } - return qs; - } - - static UpdatableQuantilesDoublesSketch buildDQS(final int k, final long n) { - int cap = QuantilesDoublesSketch.getUpdatableStorageBytes(k, n); - if (cap < (2 * k)) { cap = 2 * k; } - final QuantilesDoublesSketchBuilder bldr = new QuantilesDoublesSketchBuilder(); - bldr.setK(k); - return bldr.build(MemorySegment.ofArray(new byte[cap])); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - print(s+LS); - } - - /** - * @param s value to print - */ - static void print(final String s) { - //System.err.print(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/DoublesMiscTest.java b/src/test/java/org/apache/datasketches/quantiles/DoublesMiscTest.java deleted file mode 100644 index 51d062564..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/DoublesMiscTest.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.MemorySegmentStatus.isSameResource; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesReadOnlyException; -import org.apache.datasketches.common.SketchesStateException; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class DoublesMiscTest { - - @Test - public void wrapAndUpdating() { - final UpdatableQuantilesDoublesSketch sk1 = QuantilesDoublesSketch.builder().build(); - sk1.update(1); - sk1.update(2); - final byte[] bytes = sk1.toByteArray(false); - final int curBytes = sk1.getCurrentUpdatableSerializedSizeBytes(); - Assert.assertEquals(bytes.length, curBytes); - //convert to MemorySegment - final MemorySegment seg = MemorySegment.ofArray(bytes); - final UpdatableQuantilesDoublesSketch sk2 = (UpdatableQuantilesDoublesSketch) QuantilesDoublesSketch.writableWrap(seg, null); - assertEquals(seg.byteSize(), curBytes); - sk2.update(3); - sk2.update(4); - assertEquals(sk2.getMinItem(), 1.0); - assertEquals(sk2.getMaxItem(), 4.0); - //check the size for just 4 elements - final MemorySegment seg2 = sk2.getMemorySegment(); - assertEquals(seg2.byteSize(), QuantilesDoublesSketch.getUpdatableStorageBytes(sk2.getK(), sk2.getN())); - } - - @Test - public void wrapCompactSketch() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - s1.update(1); - s1.update(2); - final MemorySegment seg = MemorySegment.ofArray(s1.compact().toByteArray()); - final QuantilesDoublesSketch s2 = QuantilesDoublesSketch.wrap(seg); // compact, so this is ok - assertEquals(s2.getMinItem(), 1.0); - assertEquals(s2.getMaxItem(), 2.0); - assertEquals(s2.getN(), 2); - } - - @Test - public void heapifySparseSketch() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - s1.update(1); - s1.update(2); - final MemorySegment seg = MemorySegment.ofArray(s1.toByteArray(false)); - final QuantilesDoublesSketch s2 = QuantilesDoublesSketch.heapify(seg); - assertEquals(s2.getMinItem(), 1.0); - assertEquals(s2.getMaxItem(), 2.0); - } - - @Test - public void heapifyAndUpdateSparseSketch() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - s1.update(1); - s1.update(2); - final MemorySegment seg = MemorySegment.ofArray(s1.toByteArray(false)); - final UpdatableQuantilesDoublesSketch s2 = (UpdatableQuantilesDoublesSketch) QuantilesDoublesSketch.heapify(seg); - s2.update(3); - assertEquals(s2.getMinItem(), 1.0); - assertEquals(s2.getMaxItem(), 3.0); - } - - @Test - public void heapifyCompactSketch() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - s1.update(1); - s1.update(2); - final MemorySegment seg = MemorySegment.ofArray(s1.toByteArray(true)); - final QuantilesDoublesSketch s2 = QuantilesDoublesSketch.heapify(seg); - assertEquals(s2.getMinItem(), 1.0); - assertEquals(s2.getMaxItem(), 2.0); - } - - @Test - public void heapifyEmptyUpdateSketch() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - final MemorySegment seg = MemorySegment.ofArray(s1.toByteArray()); - final QuantilesDoublesSketch s2 = QuantilesDoublesSketch.heapify(seg); - assertTrue(s2.isEmpty()); - } - - @Test - public void heapifyEmptyCompactSketch() { - final CompactQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build().compact(); - final MemorySegment seg = MemorySegment.ofArray(s1.toByteArray()); - final QuantilesDoublesSketch s2 = QuantilesDoublesSketch.heapify(seg); - assertTrue(s2.isEmpty()); - } - - @Test - public void wrapEmptyUpdateSketch() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - final MemorySegment seg = MemorySegment.ofArray(s1.toByteArray()).asReadOnly(); - final UpdatableQuantilesDoublesSketch s2 = (UpdatableQuantilesDoublesSketch) QuantilesDoublesSketch.writableWrap(seg, null); - assertTrue(s2.isEmpty()); - - // ensure the various put calls fail - try { - s2.putMinItem(-1.0); - fail(); - } catch (final SketchesReadOnlyException e) { - // expected - } - - try { - s2.putMaxItem(1.0); - fail(); - } catch (final SketchesReadOnlyException e) { - // expected - } - - try { - s2.putN(1); - fail(); - } catch (final SketchesReadOnlyException e) { - // expected - } - - try { - s2.putBitPattern(1); - fail(); - } catch (final SketchesReadOnlyException e) { - // expected - } - - try { - s2.reset(); - fail(); - } catch (final SketchesReadOnlyException e) { - // expected - } - - try { - s2.putBaseBufferCount(5); - fail(); - } catch (final SketchesReadOnlyException e) { - // expected - } - - try { - s2.putCombinedBuffer(new double[16]); - fail(); - } catch (final SketchesReadOnlyException e) { - // expected - } - - try { - final int currCap = s2.getCombinedBufferItemCapacity(); - s2.growCombinedBuffer(currCap, 2 * currCap); - fail(); - } catch (final SketchesReadOnlyException e) { - // expected - } - } - - @Test - public void wrapEmptyCompactSketch() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - final MemorySegment seg = MemorySegment.ofArray(s1.compact().toByteArray()); - final QuantilesDoublesSketch s2 = QuantilesDoublesSketch.wrap(seg); // compact, so this is ok - Assert.assertTrue(s2.isEmpty()); - } - - @Test - public void heapifyUnionFromSparse() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - s1.update(1); - s1.update(2); - final MemorySegment seg = MemorySegment.ofArray(s1.toByteArray(false)); - final QuantilesDoublesUnion u = QuantilesDoublesUnion.heapify(seg); - u.update(3); - final QuantilesDoublesSketch s2 = u.getResult(); - Assert.assertEquals(s2.getMinItem(), 1.0); - Assert.assertEquals(s2.getMaxItem(), 3.0); - } - - @Test - public void initializeUnionFromCompactSegment() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - s1.update(1); - s1.update(2); - final MemorySegment seg = MemorySegment.ofArray(s1.toByteArray(true)); - final QuantilesDoublesUnion u = QuantilesDoublesUnion.heapify(seg); - u.update(3); - final QuantilesDoublesSketch s2 = u.getResult(); - Assert.assertEquals(s2.getMinItem(), 1.0); - Assert.assertEquals(s2.getMaxItem(), 3.0); - } - - @Test - public void unionFromUpdatableSegment() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - s1.update(1); - s1.update(2); - final MemorySegment seg = MemorySegment.ofArray(s1.toByteArray(false)); - final QuantilesDoublesUnion u = QuantilesDoublesUnion.wrap(seg); - u.update(3); - final QuantilesDoublesSketch s2 = u.getResult(); - Assert.assertEquals(s2.getMinItem(), 1.0); - Assert.assertEquals(s2.getMaxItem(), 3.0); - } - - @Test - public void wrapUnionFromHeap() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - s1.update(1); - s1.update(2); - final MemorySegment seg = MemorySegment.ofArray(s1.toByteArray(false)).asReadOnly(); - try { - final QuantilesDoublesUnion u = QuantilesDoublesUnion.wrap(seg, null); - } catch (final SketchesReadOnlyException e) { - //expected - } - - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void wrapUnionFromCompact() { - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().build(); - s1.update(1); - s1.update(2); - final MemorySegment seg = MemorySegment.ofArray(s1.toByteArray(true)); - QuantilesDoublesUnion.wrap(seg, null); //compact seg - fail(); - } - - /** - * println - * @param o object to print - */ - private static void println(final Object o) { - //System.out.println(o.toString()); - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/DoublesSketchBuilderTest.java b/src/test/java/org/apache/datasketches/quantiles/DoublesSketchBuilderTest.java deleted file mode 100644 index c6759ac03..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/DoublesSketchBuilderTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -public class DoublesSketchBuilderTest { - - @Test - public void checkBuilder() { - final int k = 256; //default is 128 - QuantilesDoublesSketchBuilder bldr = QuantilesDoublesSketch.builder(); - bldr.setK(k); - assertEquals(bldr.getK(), k); //confirms new k - println(bldr.toString()); - final int bytes = QuantilesDoublesSketch.getUpdatableStorageBytes(k, 0); - final byte[] byteArr = new byte[bytes]; - final MemorySegment seg = MemorySegment.ofArray(byteArr); - final QuantilesDoublesSketch ds = bldr.build(seg); - assertTrue(ds.hasMemorySegment()); - assertFalse(ds.isOffHeap()); - println(bldr.toString()); - - bldr = QuantilesDoublesSketch.builder(); - assertEquals(bldr.getK(), PreambleUtil.DEFAULT_K); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/DoublesSketchIteratorTest.java b/src/test/java/org/apache/datasketches/quantiles/DoublesSketchIteratorTest.java deleted file mode 100644 index a84c0f068..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/DoublesSketchIteratorTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIteratorAPI; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class DoublesSketchIteratorTest { - - @Test - public void emptySketch() { - QuantilesDoublesSketch sketch = QuantilesDoublesSketch.builder().build(); - QuantilesDoublesSketchIteratorAPI it = sketch.iterator(); - Assert.assertFalse(it.next()); - } - - @Test - public void oneItemSketch() { - UpdatableQuantilesDoublesSketch sketch = QuantilesDoublesSketch.builder().build(); - sketch.update(0); - QuantilesDoublesSketchIteratorAPI it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getQuantile(), 0.0); - Assert.assertEquals(it.getWeight(), 1); - Assert.assertFalse(it.next()); - } - - @Test - public void bigSketches() { - for (int n = 1000; n < 100000; n += 2000) { - UpdatableQuantilesDoublesSketch sketch = QuantilesDoublesSketch.builder().build(); - for (int i = 0; i < n; i++) { - sketch.update(i); - } - QuantilesDoublesSketchIteratorAPI it = sketch.iterator(); - int count = 0; - int weight = 0; - while (it.next()) { - count++; - weight += (int)it.getWeight(); - } - Assert.assertEquals(count, sketch.getNumRetained()); - Assert.assertEquals(weight, n); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/DoublesSketchTest.java b/src/test/java/org/apache/datasketches/quantiles/DoublesSketchTest.java deleted file mode 100644 index 48d361ed8..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/DoublesSketchTest.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.quantilescommon.DoublesSortedView; -import org.apache.datasketches.quantilescommon.DoublesSortedViewIterator; -import org.testng.Assert; -import org.testng.annotations.Test; - - - -public class DoublesSketchTest { - - @Test - public void heapToDirect() { - final UpdatableQuantilesDoublesSketch heapSketch = QuantilesDoublesSketch.builder().build(); - for (int i = 0; i < 1000; i++) { - heapSketch.update(i); - } - final QuantilesDoublesSketch directSketch = QuantilesDoublesSketch.writableWrap(MemorySegment.ofArray(heapSketch.toByteArray(false)), null); - - assertEquals(directSketch.getMinItem(), 0.0); - assertEquals(directSketch.getMaxItem(), 999.0); - assertEquals(directSketch.getQuantile(0.5), 500.0, 4.0); - } - - @Test - public void directToHeap() { - final int sizeBytes = 10000; - final UpdatableQuantilesDoublesSketch directSketch = QuantilesDoublesSketch.builder().build(MemorySegment.ofArray(new byte[sizeBytes])); - for (int i = 0; i < 1000; i++) { - directSketch.update(i); - } - UpdatableQuantilesDoublesSketch heapSketch; - heapSketch = (UpdatableQuantilesDoublesSketch) QuantilesDoublesSketch.heapify(MemorySegment.ofArray(directSketch.toByteArray())); - for (int i = 0; i < 1000; i++) { - heapSketch.update(i + 1000); - } - assertEquals(heapSketch.getMinItem(), 0.0); - assertEquals(heapSketch.getMaxItem(), 1999.0); - assertEquals(heapSketch.getQuantile(0.5), 1000.0, 10.0); - } - - @Test - public void checkToByteArray() { - final UpdatableQuantilesDoublesSketch ds = QuantilesDoublesSketch.builder().build(); //k = 128 - ds.update(1); - ds.update(2); - final byte[] arr = ds.toByteArray(false); - assertEquals(arr.length, ds.getCurrentUpdatableSerializedSizeBytes()); - } - - /** - * Checks 2 DoublesSketches for equality, triggering an assert if unequal. Handles all - * input sketches and compares only values on valid levels, allowing it to be used to compare - * Update and Compact sketches. - * @param sketch1 input sketch 1 - * @param sketch2 input sketch 2 - */ - static void testSketchEquality(final QuantilesDoublesSketch sketch1, - final QuantilesDoublesSketch sketch2) { - assertEquals(sketch1.getK(), sketch2.getK()); - assertEquals(sketch1.getN(), sketch2.getN()); - assertEquals(sketch1.getBitPattern(), sketch2.getBitPattern()); - assertEquals(sketch1.getMinItem(), sketch2.getMinItem()); - assertEquals(sketch1.getMaxItem(), sketch2.getMaxItem()); - - final DoublesSketchAccessor accessor1 = DoublesSketchAccessor.wrap(sketch1, false); - final DoublesSketchAccessor accessor2 = DoublesSketchAccessor.wrap(sketch2, false); - - // Compare base buffers. Already confirmed n and k match. - for (int i = 0; i < accessor1.numItems(); ++i) { - assertEquals(accessor1.get(i), accessor2.get(i)); - } - - // Iterate over levels comparing items - long bitPattern = sketch1.getBitPattern(); - for (int lvl = 0; bitPattern != 0; ++lvl, bitPattern >>>= 1) { - if ((bitPattern & 1) > 0) { - accessor1.setLevel(lvl); - accessor2.setLevel(lvl); - for (int i = 0; i < accessor1.numItems(); ++i) { - assertEquals(accessor1.get(i), accessor2.get(i)); - } - } - } - } - - @Test - public void checkIsSameResource() { - final int k = 16; - final MemorySegment seg = MemorySegment.ofArray(new byte[(k*16) +24]); - final MemorySegment cseg = MemorySegment.ofArray(new byte[8]); - final DirectUpdateDoublesSketch duds = - (DirectUpdateDoublesSketch) QuantilesDoublesSketch.builder().setK(k).build(seg); - assertTrue(duds.isSameResource(seg)); - final DirectCompactDoublesSketch dcds = (DirectCompactDoublesSketch) duds.compact(cseg); - assertTrue(dcds.isSameResource(cseg)); - - final UpdatableQuantilesDoublesSketch uds = QuantilesDoublesSketch.builder().setK(k).build(); - assertFalse(uds.isSameResource(seg)); - } - - @Test - public void checkEmptyExceptions() { - final int k = 16; - final UpdatableQuantilesDoublesSketch uds = QuantilesDoublesSketch.builder().setK(k).build(); - try { uds.getMaxItem(); fail(); } catch (final IllegalArgumentException e) {} - try { uds.getMinItem(); fail(); } catch (final IllegalArgumentException e) {} - try { uds.getRank(1.0); fail(); } catch (final IllegalArgumentException e) {} - try { uds.getPMF(new double[] { 0, 0.5, 1.0 }); fail(); } catch (final IllegalArgumentException e) {} - try { uds.getCDF(new double[] { 0, 0.5, 1.0 }); fail(); } catch (final IllegalArgumentException e) {} - } - - @Test - public void directSketchShouldMoveOntoHeapEventually() { - final Arena arena = Arena.ofConfined(); - final MemorySegment wseg = arena.allocate(1000); - final UpdatableQuantilesDoublesSketch sketch = QuantilesDoublesSketch.builder().build(wseg); - Assert.assertTrue(sketch.isSameResource(wseg)); - for (int i = 0; i < 1000; i++) { - sketch.update(i); - } - Assert.assertFalse(sketch.isSameResource(wseg)); - arena.close(); - Assert.assertFalse(wseg.scope().isAlive()); - } - - @Test - public void directSketchShouldMoveOntoHeapEventually2() { - final Arena arena = Arena.ofConfined(); - int i = 0; - final MemorySegment wseg = arena.allocate(50); - final UpdatableQuantilesDoublesSketch sketch = QuantilesDoublesSketch.builder().build(wseg); - Assert.assertTrue(sketch.isSameResource(wseg)); - for (; i < 1000; i++) { - if (sketch.isSameResource(wseg)) { - sketch.update(i); - } else { - //println("MOVED OUT at i = " + i); - break; - } - } - arena.close(); - Assert.assertFalse(wseg.scope().isAlive()); - } - - @Test - public void checkEmptyDirect() { - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = arena.allocate(1000); - final UpdatableQuantilesDoublesSketch sketch = QuantilesDoublesSketch.builder().build(wseg); - sketch.toByteArray(); //exercises a specific path - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Test - public void sortedView() { - final UpdatableQuantilesDoublesSketch sketch = QuantilesDoublesSketch.builder().build(); - sketch.update(3); - sketch.update(1); - sketch.update(2); - { // cumulative inclusive - final DoublesSortedView view = sketch.getSortedView(); - final DoublesSortedViewIterator it = view.iterator(); - Assert.assertEquals(it.next(), true); - Assert.assertEquals(it.getQuantile(), 1); - Assert.assertEquals(it.getWeight(), 1); - Assert.assertEquals(it.getNaturalRank(INCLUSIVE), 1); - Assert.assertEquals(it.next(), true); - Assert.assertEquals(it.getQuantile(), 2); - Assert.assertEquals(it.getWeight(), 1); - Assert.assertEquals(it.getNaturalRank(INCLUSIVE), 2); - Assert.assertEquals(it.next(), true); - Assert.assertEquals(it.getQuantile(), 3); - Assert.assertEquals(it.getWeight(), 1); - Assert.assertEquals(it.getNaturalRank(INCLUSIVE), 3); - Assert.assertEquals(it.next(), false); - } - } - - @Test - public void checkRankLBError() { - final UpdatableQuantilesDoublesSketch sk = QuantilesDoublesSketch.builder().build(); - final double eps = sk.getNormalizedRankError(false); - println("" + (2 * eps)); - for (int i = 1; i <= 10000; i++) { sk.update(i); } - final double rlb = sk.getRankLowerBound(.5); - println(.5 - rlb); - assertTrue((.5 - rlb) <= (2* eps)); - } - - @Test - public void checkRankUBError() { - final UpdatableQuantilesDoublesSketch sk = QuantilesDoublesSketch.builder().build(); - final double eps = sk.getNormalizedRankError(false); - println(""+ (2 * eps)); - for (int i = 1; i <= 10000; i++) { sk.update(i); } - final double rub = sk.getRankUpperBound(.5); - println(rub -.5); - assertTrue((rub -.5) <= (2 * eps)); - } - - @Test - public void checkGetRanks() { - final UpdatableQuantilesDoublesSketch sk = QuantilesDoublesSketch.builder().build(); - for (int i = 1; i <= 10000; i++) { sk.update(i); } - final double[] qArr = {1000,2000,3000,4000,5000,6000,7000,8000,9000,10000}; - final double[] ranks = sk.getRanks(qArr, INCLUSIVE); - for (int i = 0; i < qArr.length; i++) { - final double rLB = sk.getRankLowerBound(ranks[i]); - final double rUB = sk.getRankUpperBound(ranks[i]); - assertTrue(rLB <= ranks[i]); - assertTrue(rUB >= ranks[i]); - println(rLB + ", " + ranks[i] + ", " + rUB); - } - } - - @Test - public void checkToStringHeap() { - final QuantilesDoublesSketch sk = QuantilesDoublesSketch.builder().setK(8).build(); - final int n = 32; - for (int i = 1; i <= n; i++) { - final double item = i; - sk.update(item); - } - println(sk.toString(true, false)); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - private final static boolean enablePrinting = false; - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/DoublesUnionBuilderTest.java b/src/test/java/org/apache/datasketches/quantiles/DoublesUnionBuilderTest.java deleted file mode 100644 index d41d79051..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/DoublesUnionBuilderTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; - -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -public class DoublesUnionBuilderTest { - - @Test - public void checkBuilds() { - final UpdatableQuantilesDoublesSketch qs1 = QuantilesDoublesSketch.builder().build(); - for (int i=0; i<1000; i++) { qs1.update(i); } - - final int bytes = qs1.getCurrentCompactSerializedSizeBytes(); - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[bytes]); - qs1.putIntoMemorySegment(dstSeg); - final MemorySegment srcSeg = dstSeg; - - final QuantilesDoublesUnionBuilder bldr = new QuantilesDoublesUnionBuilder(); - bldr.setMaxK(128); - QuantilesDoublesUnion union = bldr.build(); //virgin union - - union = QuantilesDoublesUnion.heapify(srcSeg); - final QuantilesDoublesSketch qs2 = union.getResult(); - assertEquals(qs1.getCurrentCompactSerializedSizeBytes(), qs2.getCurrentCompactSerializedSizeBytes()); - - union = QuantilesDoublesUnion.heapify(qs2); - final QuantilesDoublesSketch qs3 = union.getResult(); - assertEquals(qs2.getCurrentCompactSerializedSizeBytes(), qs3.getCurrentCompactSerializedSizeBytes()); - assertFalse(qs2 == qs3); - } - - -@Test -public void checkDeprecated1() { - final UpdatableQuantilesDoublesSketch qs1 = QuantilesDoublesSketch.builder().build(); - for (int i=0; i<1000; i++) { - qs1.update(i); - } - - final int bytes = qs1.getCurrentCompactSerializedSizeBytes(); - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[bytes]); - qs1.putIntoMemorySegment(dstSeg); - final MemorySegment srcSeg = dstSeg; - - final QuantilesDoublesUnionBuilder bldr = new QuantilesDoublesUnionBuilder(); - bldr.setMaxK(128); - QuantilesDoublesUnion union = bldr.build(); //virgin union - - union = QuantilesDoublesUnion.heapify(srcSeg); //heapify - final QuantilesDoublesSketch qs2 = union.getResult(); - assertEquals(qs1.getCurrentCompactSerializedSizeBytes(), qs2.getCurrentCompactSerializedSizeBytes()); - assertEquals(qs1.getCurrentUpdatableSerializedSizeBytes(), qs2.getCurrentUpdatableSerializedSizeBytes()); - - union = QuantilesDoublesUnion.heapify(qs2); //heapify again - final QuantilesDoublesSketch qs3 = union.getResult(); - assertEquals(qs2.getCurrentCompactSerializedSizeBytes(), qs3.getCurrentCompactSerializedSizeBytes()); - assertEquals(qs2.getCurrentUpdatableSerializedSizeBytes(), qs3.getCurrentUpdatableSerializedSizeBytes()); - assertFalse(qs2 == qs3); //different objects -} - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param o value to print - */ - static void println(final Object o) { - //System.err.println(o.toString()); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/DoublesUnionImplTest.java b/src/test/java/org/apache/datasketches/quantiles/DoublesUnionImplTest.java deleted file mode 100644 index 3c64cd87a..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/DoublesUnionImplTest.java +++ /dev/null @@ -1,738 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.quantiles.DirectUpdateDoublesSketchTest.buildAndLoadDQS; -import static org.apache.datasketches.quantiles.HeapUpdateDoublesSketchTest.buildAndLoadQS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class DoublesUnionImplTest { - - @Test - public void checkUnion1() { - QuantilesDoublesSketch result; - final QuantilesDoublesSketch qs1; - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(256).build(); //virgin 256 - - final QuantilesDoublesSketch qs0 = buildAndLoadQS(256, 500); - union.union(qs0); //me = null, that = valid, exact - result = union.getResult(); - assertEquals(result.getN(), 500); - assertEquals(result.getK(), 256); - - union.reset(); - qs1 = buildAndLoadQS(256, 1000); //first 1000 - union.union(qs1); //me = null, that = valid, OK - - //check copy me = null, that = valid - result = union.getResult(); - assertEquals(result.getN(), 1000); - assertEquals(result.getK(), 256); - - //check merge me = valid, that = valid, both K's the same - final QuantilesDoublesSketch qs2 = buildAndLoadQS(256, 1000, 1000); //add 1000 - union.union(qs2); - result = union.getResult(); - assertEquals(result.getN(), 2000); - assertEquals(result.getK(), 256); - } - - @Test - public void checkUnion1Direct() { - QuantilesDoublesSketch result; - final QuantilesDoublesSketch qs1; - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(256).build(); //virgin 256 - - final QuantilesDoublesSketch qs0 = buildAndLoadDQS(256, 500); - union.union(qs0); //me = null, that = valid, exact - result = union.getResult(); - assertEquals(result.getN(), 500); - assertEquals(result.getK(), 256); - - union.reset(); - qs1 = buildAndLoadDQS(256, 1000); //first 1000 - union.union(qs1); //me = null, that = valid, OK - - //check copy me = null, that = valid - result = union.getResult(); - assertEquals(result.getN(), 1000); - assertEquals(result.getK(), 256); - - //check merge me = valid, that = valid, both K's the same - final QuantilesDoublesSketch qs2 = buildAndLoadDQS(256, 1000, 1000).compact(); //add 1000 - union.union(qs2); - result = union.getResult(); - assertEquals(result.getN(), 2000); - assertEquals(result.getK(), 256); - } - - @Test - public void checkUnion2() { - final QuantilesDoublesSketch qs1 = buildAndLoadQS(256, 1000).compact(); - final QuantilesDoublesSketch qs2 = buildAndLoadQS(128, 1000); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(256).build(); //virgin 256 - assertEquals(union.getEffectiveK(), 256); - - union.union(qs1); - final QuantilesDoublesSketch res1 = union.getResult(); - //println(res1.toString()); - assertEquals(res1.getN(), 1000); - assertEquals(res1.getK(), 256); - - union.union(qs2); - final QuantilesDoublesSketch res2 = union.getResult(); - assertEquals(res2.getN(), 2000); - assertEquals(res2.getK(), 128); - assertEquals(union.getEffectiveK(), 128); - println(union.toString()); - } - - @Test - public void checkUnion2Direct() { - final QuantilesDoublesSketch qs1 = buildAndLoadDQS(256, 1000); - final QuantilesDoublesSketch qs2 = buildAndLoadDQS(128, 1000); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(256).build(); //virgin 256 - assertEquals(union.getEffectiveK(), 256); - - union.union(qs1); - final QuantilesDoublesSketch res1 = union.getResult(); - //println(res1.toString()); - assertEquals(res1.getN(), 1000); - assertEquals(res1.getK(), 256); - - union.union(qs2); - final QuantilesDoublesSketch res2 = union.getResult(); - assertEquals(res2.getN(), 2000); - assertEquals(res2.getK(), 128); - assertEquals(union.getEffectiveK(), 128); - println(union.toString()); - } - - @Test - public void checkUnion3() { //Union is direct, empty and with larger K than valid input - final int k1 = 128; - final int n1 = 2 * k1; - final int k2 = 256; - final int n2 = 2000; - final QuantilesDoublesSketch sketchIn1 = buildAndLoadQS(k1, n1); - final int bytes = QuantilesDoublesSketch.getUpdatableStorageBytes(k2, n2);//just for size - final MemorySegment seg = MemorySegment.ofArray(new byte[bytes]); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(k2).build(seg, null); //virgin 256 - union.union(sketchIn1); - assertEquals(union.getMaxK(), k2); - assertEquals(union.getEffectiveK(), k1); - final QuantilesDoublesSketch result = union.getResult(); - assertEquals(result.getMaxItem(), n1, 0.0); - assertEquals(result.getMinItem(), 1.0, 0.0); - assertEquals(result.getK(), k1); - } - - @Test - public void checkUnion3Direct() { //Union is direct, empty and with larger K than valid input - final int k1 = 128; - final int n1 = 2 * k1; - final int k2 = 256; - final int n2 = 2000; - final QuantilesDoublesSketch sketchIn1 = buildAndLoadDQS(k1, n1); - final int bytes = QuantilesDoublesSketch.getUpdatableStorageBytes(k2, n2);//just for size - final MemorySegment seg = MemorySegment.ofArray(new byte[bytes]); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(k2).build(seg, null); //virgin 256 - union.union(sketchIn1); - assertEquals(union.getMaxK(), k2); - assertEquals(union.getEffectiveK(), k1); - final QuantilesDoublesSketch result = union.getResult(); - assertEquals(result.getMaxItem(), n1, 0.0); - assertEquals(result.getMinItem(), 1.0, 0.0); - assertEquals(result.getK(), k1); - } - - @Test - public void checkUnion4() { //Union is direct, valid and with larger K than valid input - final int k1 = 8; - final int n1 = 2 * k1; //16 - final int k2 = 4; - final int n2 = 2 * k2; //8 - final int bytes = QuantilesDoublesSketch.getUpdatableStorageBytes(256, 50);//just for size - final MemorySegment skSeg = MemorySegment.ofArray(new byte[bytes]); - final UpdatableQuantilesDoublesSketch sketchIn1 = QuantilesDoublesSketch.builder().setK(k1).build(skSeg); - for (int i = 0; i < n1; i++) { sketchIn1.update(i + 1); } - - final MemorySegment uSeg = MemorySegment.ofArray(new byte[bytes]); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(256).build(uSeg, null); //virgin 256 - //QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(256).build(); //virgin 256 - union.union(sketchIn1); - assertEquals(union.getResult().getN(), n1); - assertEquals(union.getMaxK(), 256); - assertEquals(union.getEffectiveK(), k1); - QuantilesDoublesSketch result = union.getResult(); - assertEquals(result.getN(), 16); - assertEquals(result.getMaxItem(), n1, 0.0); - assertEquals(result.getMinItem(), 1.0, 0.0); - assertEquals(result.getK(), k1); - - final QuantilesDoublesSketch sketchIn2 = buildAndLoadQS(k2, n2, 17); - union.reset(); - union.union(sketchIn2); - result = union.getResult(); - assertEquals(result.getMaxItem(), n2 + 17, 0.0); - assertEquals(result.getMinItem(), 1.0 + 17, 0.0); - println("\nFinal" + union.getResult().toString(true, true)); - } - - @Test - public void checkUnion4Direct() { //Union is direct, valid and with larger K than valid input - final int k1 = 8; - final int n1 = 2 * k1; //16 - final int k2 = 4; - final int n2 = 2 * k2; //8 - final int bytes = QuantilesDoublesSketch.getUpdatableStorageBytes(256, 50);//just for size - final MemorySegment skSeg = MemorySegment.ofArray(new byte[bytes]); - final UpdatableQuantilesDoublesSketch sketchIn1 = QuantilesDoublesSketch.builder().setK(k1).build(skSeg); - for (int i = 0; i < n1; i++) { sketchIn1.update(i + 1); } - - final MemorySegment uSeg = MemorySegment.ofArray(new byte[bytes]); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(256).build(uSeg, null); //virgin 256 - union.union(sketchIn1); - assertEquals(union.getResult().getN(), n1); - assertEquals(union.getMaxK(), 256); - assertEquals(union.getEffectiveK(), k1); - QuantilesDoublesSketch result = union.getResult(); - assertEquals(result.getN(), 16); - assertEquals(result.getMaxItem(), n1, 0.0); - assertEquals(result.getMinItem(), 1.0, 0.0); - assertEquals(result.getK(), k1); - - final QuantilesDoublesSketch sketchIn2 = buildAndLoadDQS(k2, n2, 17); - union.reset(); - union.union(sketchIn2); - result = union.getResult(); - assertEquals(result.getMaxItem(), n2 + 17, 0.0); - assertEquals(result.getMinItem(), 1.0 + 17, 0.0); - println("\nFinal" + union.getResult().toString(true, true)); - } - - @Test - public void checkUnion4DirectCompact() { - final int k1 = 8; - final int n1 = 2 * k1; //16 - final int k2 = 4; - final int n2 = 5 * k2; //8 - final int bytes = QuantilesDoublesSketch.getUpdatableStorageBytes(256, 50);//just for size - final MemorySegment skSeg = MemorySegment.ofArray(new byte[bytes]); - final UpdatableQuantilesDoublesSketch sketchIn0 = QuantilesDoublesSketch.builder().setK(k1).build(skSeg); - for (int i = 0; i < n1; i++) { sketchIn0.update(i + 1); } - final CompactQuantilesDoublesSketch sketchIn1 = sketchIn0.compact(); - - final MemorySegment uSeg = MemorySegment.ofArray(new byte[bytes]); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(256).build(uSeg, null); //virgin 256 - union.union(sketchIn1); - assertEquals(union.getResult().getN(), n1); - assertEquals(union.getMaxK(), 256); - assertEquals(union.getEffectiveK(), k1); - QuantilesDoublesSketch result = union.getResult(); - assertEquals(result.getN(), 16); - assertEquals(result.getMaxItem(), n1, 0.0); - assertEquals(result.getMinItem(), 1.0, 0.0); - assertEquals(result.getK(), k1); - - final CompactQuantilesDoublesSketch sketchIn2 = buildAndLoadDQS(k2, n2, 17).compact(); - union.reset(); - union.union(sketchIn2); - result = union.getResult(); - assertEquals(result.getMaxItem(), n2 + 17, 0.0); - assertEquals(result.getMinItem(), 1.0 + 17, 0.0); - println("\nFinal" + union.getResult().toString(true, true)); - } - - @Test - public void checkUnion5() { //Union is direct, valid and with larger K than valid input - final int k2 = 4; - final int n2 = 2 * k2; //8 - final int bytes = QuantilesDoublesSketch.getUpdatableStorageBytes(256, 50);//big enough - final MemorySegment skSeg = MemorySegment.ofArray(new byte[bytes]); - QuantilesDoublesSketch.builder().setK(256).build(skSeg); - - final QuantilesDoublesUnion union = QuantilesDoublesUnionImpl.heapifyInstance(skSeg); - assertEquals(union.getResult().getN(), 0); - assertEquals(union.getMaxK(), 256); - assertEquals(union.getEffectiveK(), 256); - final QuantilesDoublesSketch result = union.getResult(); - assertEquals(result.getK(), 256); - - final QuantilesDoublesSketch sketchIn2 = buildAndLoadQS(k2, n2, 17); - union.union(sketchIn2); - println("\nFinal" + union.getResult().toString(true, true)); - assertEquals(union.getResult().getN(), n2); - } - - @Test - public void checkUnion5Direct() { //Union is direct, valid and with larger K than valid input - final int k2 = 4; - final int n2 = 2 * k2; //8 - final int bytes = QuantilesDoublesSketch.getUpdatableStorageBytes(256, 50);//big enough - final MemorySegment skSeg = MemorySegment.ofArray(new byte[bytes]); - QuantilesDoublesSketch.builder().setK(256).build(skSeg); - - final QuantilesDoublesUnion union = QuantilesDoublesUnionImpl.heapifyInstance(skSeg); - assertEquals(union.getResult().getN(), 0); - assertEquals(union.getMaxK(), 256); - assertEquals(union.getEffectiveK(), 256); - final QuantilesDoublesSketch result = union.getResult(); - assertEquals(result.getK(), 256); - - final QuantilesDoublesSketch sketchIn2 = buildAndLoadDQS(k2, n2, 17); - union.union(sketchIn2); - println("\nFinal" + union.getResult().toString(true, true)); - assertEquals(union.getResult().getN(), n2); - } - - @Test - public void checkUnion6() { - final int k1 = 8; - final int n1 = 2 * k1; //16 - final int k2 = 16; - final int n2 = 2 * k2; //32 - final QuantilesDoublesSketch sk1 = buildAndLoadQS(k1, n1, 0); - final QuantilesDoublesSketch sk2 = buildAndLoadQS(k2, n2, n1); - final QuantilesDoublesUnion union = QuantilesDoublesUnionImpl.heapifyInstance(sk1); - union.union(sk2); - final QuantilesDoublesSketch result = union.getResult(); - assertEquals(result.getMaxItem(), n1 + n2, 0.0); - assertEquals(result.getMinItem(), 1.0, 0.0); - println("\nFinal" + union.getResult().toString(true, true)); - } - - @Test - public void checkUnion6Direct() { - final int k1 = 8; - final int n1 = 2 * k1; //16 - final int k2 = 16; - final int n2 = 2 * k2; //32 - final QuantilesDoublesSketch sk1 = buildAndLoadDQS(k1, n1, 0); - final QuantilesDoublesSketch sk2 = buildAndLoadDQS(k2, n2, n1); - final QuantilesDoublesUnion union = QuantilesDoublesUnionImpl.heapifyInstance(sk1); - union.union(sk2); - final QuantilesDoublesSketch result = union.getResult(); - assertEquals(result.getMaxItem(), n1 + n2, 0.0); - assertEquals(result.getMinItem(), 1.0, 0.0); - println("\nFinal" + union.getResult().toString(true, true)); - } - - @Test - public void checkUnion7() { - final QuantilesDoublesUnion union = QuantilesDoublesUnionImpl.heapInstance(16); - final QuantilesDoublesSketch skEst = buildAndLoadQS(32, 64); //other is bigger, est - union.union(skEst); - println(skEst.toString(true, true)); - println(union.toString(true, true)); - final QuantilesDoublesSketch result = union.getResult(); - assertEquals(result.getMaxItem(), 64, 0.0); - assertEquals(result.getMinItem(), 1.0, 0.0); - } - - @Test - public void checkUnionQuantiles() { - final int k = 128; - final int n1 = k * 13; - final int n2 = (k * 8) + (k / 2); - final int n = n1 + n2; - final double errorTolerance = 0.0175 * n; // assuming k = 128 - final UpdatableQuantilesDoublesSketch sketch1 = buildAndLoadQS(k, n1); - final CompactQuantilesDoublesSketch sketch2 = buildAndLoadQS(k, n2, n1).compact(); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(256).build(); //virgin 256 - union.union(sketch2); - union.union(sketch1); - final MemorySegment seg = MemorySegment.ofArray(union.getResult().toByteArray(true)); - final QuantilesDoublesSketch result = QuantilesDoublesSketch.wrap(seg); - assertEquals(result.getN(), n1 + n2); - assertEquals(result.getK(), k); - - for (double fraction = 0.05; fraction < 1.0; fraction += 0.05) { - assertEquals(result.getQuantile(fraction), fraction * n, errorTolerance); - } - } - - @Test - public void checkUnion7Direct() { - final QuantilesDoublesUnion union = QuantilesDoublesUnionImpl.heapInstance(16); - final QuantilesDoublesSketch skEst = buildAndLoadDQS(32, 64); //other is bigger, est - union.union(skEst); - final QuantilesDoublesSketch result = union.getResult(); - assertEquals(result.getMaxItem(), 64, 0.0); - assertEquals(result.getMinItem(), 1.0, 0.0); - // println(skEst.toString(true, true)); - // println(union.toString(true, true)); - } - - @Test - public void checkUpdateMemory() { - final QuantilesDoublesSketch qs1 = buildAndLoadQS(256, 1000); - final int bytes = qs1.getCurrentCompactSerializedSizeBytes(); - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[bytes]); - qs1.putIntoMemorySegment(dstSeg); - final MemorySegment srcSeg = dstSeg; - - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().build(); //virgin - union.union(srcSeg); - for (int i = 1000; i < 2000; i++) { union.update(i); } - final QuantilesDoublesSketch qs2 = union.getResult(); - assertEquals(qs2.getMaxItem(), 1999, 0.0); - final String s = union.toString(); - println(s); //enable printing to see - union.reset(); //sets to null - } - - @Test - public void checkUpdateMemoryDirect() { - final QuantilesDoublesSketch qs1 = buildAndLoadDQS(256, 1000); - final int bytes = qs1.getCurrentCompactSerializedSizeBytes(); - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[bytes]); - qs1.putIntoMemorySegment(dstSeg); - final MemorySegment srcSeg = dstSeg; - - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().build(); //virgin - union.union(srcSeg); - for (int i = 1000; i < 2000; i++) { union.update(i); } - final QuantilesDoublesSketch qs2 = union.getResult(); - assertEquals(qs2.getMaxItem(), 1999, 0.0); - final String s = union.toString(); - println(s); //enable printing to see - union.reset(); //sets to null - } - - @Test - public void checkUnionUpdateLogic() { - final HeapUpdateDoublesSketch qs1 = null; - final HeapUpdateDoublesSketch qs2 = (HeapUpdateDoublesSketch) buildAndLoadQS(256, 0); - QuantilesDoublesUnionImpl.updateLogic(256, qs1, qs2); //null, empty - QuantilesDoublesUnionImpl.updateLogic(256, qs2, qs1); //empty, null - qs2.update(1); //no longer empty - final QuantilesDoublesSketch result = QuantilesDoublesUnionImpl.updateLogic(256, qs2, qs1); //valid, null - assertEquals(result.getMaxItem(), result.getMinItem(), 0.0); - } - - @Test - public void checkUnionUpdateLogicDirect() { - final HeapUpdateDoublesSketch qs1 = null; - final DirectUpdateDoublesSketch qs2 = (DirectUpdateDoublesSketch) buildAndLoadDQS(256, 0); - QuantilesDoublesUnionImpl.updateLogic(256, qs1, qs2); //null, empty - QuantilesDoublesUnionImpl.updateLogic(256, qs2, qs1); //empty, null - qs2.update(1); //no longer empty - final QuantilesDoublesSketch result = QuantilesDoublesUnionImpl.updateLogic(256, qs2, qs1); //valid, null - assertEquals(result.getMaxItem(), result.getMinItem(), 0.0); - } - - @Test - public void checkUnionUpdateLogicDirectDownsampled() { - final DirectUpdateDoublesSketch qs1 = (DirectUpdateDoublesSketch) buildAndLoadDQS(256, 1000); - final DirectUpdateDoublesSketch qs2 = (DirectUpdateDoublesSketch) buildAndLoadDQS(128, 2000); - final QuantilesDoublesSketch result = QuantilesDoublesUnionImpl.updateLogic(128, qs1, qs2); - assertEquals(result.getMaxItem(), 2000.0, 0.0); - assertEquals(result.getMinItem(), 1.0, 0.0); - assertEquals(result.getN(), 3000); - assertEquals(result.getK(), 128); - } - - @Test - public void checkUnionUpdateLogic2() { - QuantilesDoublesSketch qs1 = QuantilesDoublesSketch.builder().build(); - final QuantilesDoublesSketch qs2 = QuantilesDoublesSketch.builder().build(); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().build(); - union.union(qs1); - union.union(qs2); //case 5 - qs1 = buildAndLoadQS(128, 1000); - union.union(qs1); - union.union(qs2); //case 9 - final QuantilesDoublesSketch result = union.getResult(); - //println(union.toString(true, true)); - assertEquals(result.getMaxItem(), 1000.0, 0.0); - assertEquals(result.getMinItem(), 1.0, 0.0); - - } - - @Test - public void checkUnionUpdateLogic2Direct() { - QuantilesDoublesSketch qs1 = QuantilesDoublesSketch.builder().build(); - final QuantilesDoublesSketch qs2 = QuantilesDoublesSketch.builder().build(); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().build(); - union.union(qs1); - union.union(qs2); //case 5 - qs1 = buildAndLoadDQS(128, 1000); - union.union(qs1); - union.union(qs2); //case 9 - final QuantilesDoublesSketch result = union.getResult(); - //println(union.toString(true, true)); - assertEquals(result.getMaxItem(), 1000.0, 0.0); - assertEquals(result.getMinItem(), 1.0, 0.0); - } - - @Test - public void checkResultAndReset() { - final QuantilesDoublesSketch qs1 = buildAndLoadQS(256, 0); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.heapify(qs1); - final QuantilesDoublesSketch qs2 = union.getResultAndReset(); - assertEquals(qs2.getK(), 256); - } - - @Test - public void checkResultAndResetDirect() { - final QuantilesDoublesSketch qs1 = buildAndLoadDQS(256, 0); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.heapify(qs1); - final QuantilesDoublesSketch qs2 = union.getResultAndReset(); - assertEquals(qs2.getK(), 256); - } - - @Test - public void checkResultViaMemory() { - // empty gadget - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().build(); - - // MemorySegment too small - MemorySegment seg = MemorySegment.ofArray(new byte[1]); - try { - union.getResult(seg, null); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - // sufficient MemorySegment - seg = MemorySegment.ofArray(new byte[8]); - QuantilesDoublesSketch result = union.getResult(seg, null); - assertTrue(result.isEmpty()); - - final int k = 128; - final int n = 1392; - seg = MemorySegment.ofArray(new byte[QuantilesDoublesSketch.getUpdatableStorageBytes(k, n)]); - final QuantilesDoublesSketch qs = buildAndLoadQS(k, n); - union.union(qs); - result = union.getResult(seg, null); - DoublesSketchTest.testSketchEquality(result, qs); - } - - @Test - public void updateWithDoubleValueOnly() { - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().build(); - union.update(123.456); - final QuantilesDoublesSketch qs = union.getResultAndReset(); - assertEquals(qs.getN(), 1); - } - - @Test - public void checkEmptyUnion() { - final QuantilesDoublesUnionImpl union = QuantilesDoublesUnionImpl.heapInstance(128); - final QuantilesDoublesSketch sk = union.getResult(); - assertNotNull(sk); - final byte[] bytes = union.toByteArray(); - assertEquals(bytes.length, 8); // - final String s = union.toString(); - assertNotNull(s); - } - - @Test - public void checkUnionNulls() { - final QuantilesDoublesUnion union = QuantilesDoublesUnionImpl.heapInstance(128); - final QuantilesDoublesSketch sk1 = union.getResultAndReset(); - final QuantilesDoublesSketch sk2 = union.getResultAndReset(); - assertNull(sk1); - assertNull(sk2); - try { union.union(sk2); fail(); } - catch (final NullPointerException e) { } - final QuantilesDoublesSketch sk3 = union.getResultAndReset(); - assertNull(sk3); - } - - @Test - public void differentLargerK() { - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(128).build(); - final UpdatableQuantilesDoublesSketch sketch1 = buildAndLoadQS(256, 0); - union.union(sketch1); - Assert.assertEquals(union.getResult().getK(), 128); - sketch1.update(1.0); - union.union(sketch1); - Assert.assertEquals(union.getResult().getK(), 128); - } - - @Test - public void differentLargerKDirect() { - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(128).build(); - final UpdatableQuantilesDoublesSketch sketch1 = buildAndLoadDQS(256, 0); - union.union(sketch1); - Assert.assertEquals(union.getResult().getK(), 128); - sketch1.update(1.0); - union.union(sketch1); - Assert.assertEquals(union.getResult().getK(), 128); - } - - @Test - public void differentEmptySmallerK() { - final int k128 = 128; - final int k64 = 64; - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(k128).build(); - assertTrue(union.isEmpty()); //gadget is null - assertFalse(union.hasMemorySegment()); - assertFalse(union.isOffHeap()); - - // byte[] unionByteArr = union.toByteArray(); - // Assert.assertEquals(unionByteArr.length, 32 + 32); //empty - - final UpdatableQuantilesDoublesSketch sketch1 = buildAndLoadQS(k64, 0); //build smaller empty sketch - union.union(sketch1); - assertTrue(union.isEmpty()); //gadget is valid - assertFalse(union.hasMemorySegment()); - assertFalse(union.isOffHeap()); - - // unionByteArr = union.toByteArray(); - // int udBytes = QuantilesDoublesSketch.getUpdatableStorageBytes(k64, 0); - // Assert.assertEquals(unionByteArr.length, udBytes); //empty - - assertEquals(union.getResult().getK(), 128); - sketch1.update(1.0); - union.union(sketch1); - assertEquals(union.getResult().getK(), 128); - } - - @Test - public void differentEmptySmallerKDirect() { - final int k128 = 128; - final int k64 = 64; - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().setMaxK(k128).build(); - assertTrue(union.isEmpty()); //gadget is null - assertFalse(union.hasMemorySegment()); - assertFalse(union.isOffHeap()); - - // byte[] unionByteArr = union.toByteArray(); - // Assert.assertEquals(unionByteArr.length, 32 + 32); //empty - - final UpdatableQuantilesDoublesSketch sketch1 = buildAndLoadDQS(k64, 0); //build smaller empty sketch - union.union(sketch1); - assertTrue(union.isEmpty()); //gadget is valid - assertFalse(union.hasMemorySegment()); - assertFalse(union.isOffHeap()); - - // unionByteArr = union.toByteArray(); - // int udBytes = QuantilesDoublesSketch.getUpdatableStorageBytes(k64, 0); - // Assert.assertEquals(unionByteArr.length, udBytes); //empty - - assertEquals(union.getResult().getK(), 128); - sketch1.update(1.0); - union.union(sketch1); - assertEquals(union.getResult().getK(), 128); - } - - @Test - public void checkDirectInstance() { - final int k = 128; - final int n = 1000; - final QuantilesDoublesUnionBuilder bldr = QuantilesDoublesUnion.builder(); - bldr.setMaxK(k); - assertEquals(bldr.getMaxK(), k); - final int bytes = QuantilesDoublesSketch.getUpdatableStorageBytes(k, n); - final byte[] byteArr = new byte[bytes]; - final MemorySegment seg = MemorySegment.ofArray(byteArr); - final QuantilesDoublesUnion union = bldr.build(seg, null); - assertTrue(union.isEmpty()); - assertTrue(union.hasMemorySegment()); - assertFalse(union.isOffHeap()); - for (int i = 1; i <= n; i++) { - union.update(i); - } - assertFalse(union.isEmpty()); - final QuantilesDoublesSketch res = union.getResult(); - final double median = res.getQuantile(.5); - assertEquals(median, 500, 10); - println(union.toString()); - } - - @Test - public void checkWrapInstance() { - final int k = 128; - final int n = 1000; - final UpdatableQuantilesDoublesSketch sketch = QuantilesDoublesSketch.builder().setK(k).build(); - for (int i = 1; i <= n; i++) { - sketch.update(i); - } - final double skMedian = sketch.getQuantile(.5); - Assert.assertEquals(skMedian, 500, 10); - - final byte[] byteArr = sketch.toByteArray(false); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.wrap(seg, null); - Assert.assertFalse(union.isEmpty()); - assertTrue(union.hasMemorySegment()); - assertFalse(union.isOffHeap()); - final QuantilesDoublesSketch sketch2 = union.getResult(); - final double uMedian = sketch2.getQuantile(0.5); - Assert.assertEquals(skMedian, uMedian, 0.0); - - // check serializing again - final byte[] bytesOut = union.toByteArray(); - assertEquals(bytesOut.length, byteArr.length); - assertEquals(bytesOut, byteArr); // wrapped, so should be exact - } - - @Test - public void isSameResourceHeap() { - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().build(); - Assert.assertFalse(union.isSameResource(null)); - } - - @Test - public void isSameResourceDirect() { - final MemorySegment seg1 = MemorySegment.ofArray(new byte[1000000]); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().build(seg1, null); - Assert.assertTrue(union.isSameResource(seg1)); - final MemorySegment seg2 = MemorySegment.ofArray(new byte[1000000]); - Assert.assertFalse(union.isSameResource(seg2)); - } - - @Test - public void emptyUnionSerDeIssue195() { - final QuantilesDoublesUnion union = QuantilesDoublesUnion.builder().build(); - final byte[] byteArr = union.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - final QuantilesDoublesUnion union2 = QuantilesDoublesUnion.heapify(seg); - Assert.assertEquals(seg.byteSize(), 8L); - Assert.assertTrue(union2.isEmpty()); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/quantiles/DoublesUtilTest.java b/src/test/java/org/apache/datasketches/quantiles/DoublesUtilTest.java deleted file mode 100644 index 24fb53a8e..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/DoublesUtilTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.quantiles.HeapUpdateDoublesSketchTest.buildAndLoadQS; - -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -public class DoublesUtilTest { - - @Test - public void checkPrintSegmentData() { - final int k = 16; - final int n = 1000; - final QuantilesDoublesSketch qs = buildAndLoadQS(k,n); - - byte[] byteArr = qs.toByteArray(false); - MemorySegment seg = MemorySegment.ofArray(byteArr); - println(segToString(true, true, seg)); - - byteArr = qs.toByteArray(true); - seg = MemorySegment.ofArray(byteArr); - println(segToString(true, true, seg)); - } - - @Test - public void checkPrintSegmentData2() { - final int k = PreambleUtil.DEFAULT_K; - final int n = 0; - final QuantilesDoublesSketch qs = buildAndLoadQS(k,n); - - final byte[] byteArr = qs.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - println(segToString(true, true, seg)); - } - - static String segToString(final boolean withLevels, final boolean withLevelsAndItems, - final MemorySegment seg) { - final QuantilesDoublesSketch ds = QuantilesDoublesSketch.heapify(seg); - return ds.toString(withLevels, withLevelsAndItems); - } - - @Test - public void checkCopyToHeap() { - final int k = 128; - final int n = 400; - - // HeapUpdateDoublesSketch - final HeapUpdateDoublesSketch huds = (HeapUpdateDoublesSketch) buildAndLoadQS(k, n); - final HeapUpdateDoublesSketch target1 = DoublesUtil.copyToHeap(huds); - DoublesSketchTest.testSketchEquality(huds, target1); - - // DirectUpdateDoublesSketch - final MemorySegment seg1 = MemorySegment.ofArray(huds.toByteArray()); - final DirectUpdateDoublesSketch duds = (DirectUpdateDoublesSketch) UpdatableQuantilesDoublesSketch.wrap(seg1, null); - final HeapUpdateDoublesSketch target2 = DoublesUtil.copyToHeap(duds); - DoublesSketchTest.testSketchEquality(huds, duds); - DoublesSketchTest.testSketchEquality(duds, target2); - - // HeapCompactDoublesSketch - final CompactQuantilesDoublesSketch hcds = huds.compact(); - final HeapUpdateDoublesSketch target3 = DoublesUtil.copyToHeap(hcds); - DoublesSketchTest.testSketchEquality(huds, hcds); - DoublesSketchTest.testSketchEquality(hcds, target3); - - // DirectCompactDoublesSketch - final MemorySegment seg2 = MemorySegment.ofArray(hcds.toByteArray()); - final DirectCompactDoublesSketch dcds = (DirectCompactDoublesSketch) QuantilesDoublesSketch.wrap(seg2); - final HeapUpdateDoublesSketch target4 = DoublesUtil.copyToHeap(dcds); - DoublesSketchTest.testSketchEquality(huds, dcds); - DoublesSketchTest.testSketchEquality(dcds, target4); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - print(s + LS); - } - - /** - * @param s value to print - */ - static void print(final String s) { - //System.out.print(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/HeapCompactDoublesSketchTest.java b/src/test/java/org/apache/datasketches/quantiles/HeapCompactDoublesSketchTest.java deleted file mode 100644 index 9fe37355c..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/HeapCompactDoublesSketchTest.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.quantiles.PreambleUtil.COMBINED_BUFFER; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -public class HeapCompactDoublesSketchTest { - - @BeforeMethod - public void setUp() { - QuantilesDoublesSketch.rand.setSeed(32749); // make sketches deterministic for testing - } - - @Test - public void heapifyFromUpdateSketch() { - final int k = 4; - final int n = 45; - final UpdatableQuantilesDoublesSketch qs = buildAndLoadQS(k, n); - final byte[] qsBytes = qs.toByteArray(); - final MemorySegment qsSeg = MemorySegment.ofArray(qsBytes); - - final HeapCompactDoublesSketch compactQs = HeapCompactDoublesSketch.heapifyInstance(qsSeg); - DoublesSketchTest.testSketchEquality(qs, compactQs); - - assertNull(compactQs.getMemorySegment()); - } - - @Test - public void createFromUnsortedUpdateSketch() { - final int k = 4; - final int n = 13; - final UpdatableQuantilesDoublesSketch qs = QuantilesDoublesSketch.builder().setK(k).build(); - for (int i = n; i > 0; --i) { - qs.update(i); - } - final HeapCompactDoublesSketch compactQs = HeapCompactDoublesSketch.createFromUpdateSketch(qs); - - // don't expect equal but new base buffer should be sorted - checkBaseBufferIsSorted(compactQs); - } - - @Test - public void heapifyFromCompactSketch() { - final int k = 8; - final int n = 177; - final UpdatableQuantilesDoublesSketch qs = buildAndLoadQS(k, n); // assuming reverse ordered inserts - - final byte[] qsBytes = qs.compact().toByteArray(); - final MemorySegment qsSeg = MemorySegment.ofArray(qsBytes); - - final HeapCompactDoublesSketch compactQs = HeapCompactDoublesSketch.heapifyInstance(qsSeg); - DoublesSketchTest.testSketchEquality(qs, compactQs); - } - - @Test - public void checkHeapifyUnsortedCompactV2() { - final int k = 64; - final UpdatableQuantilesDoublesSketch qs = QuantilesDoublesSketch.builder().setK(64).build(); - for (int i = 0; i < (3 * k); ++i) { - qs.update(i); - } - assertEquals(qs.getBaseBufferCount(), k); - final byte[] sketchBytes = qs.toByteArray(true); - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - - // modify to make v2, clear compact flag, and insert a -1 in the middle of the base buffer - PreambleUtil.insertSerVer(seg, 2); - PreambleUtil.insertFlags(seg, 0); - final long tgtAddr = COMBINED_BUFFER + ((Double.BYTES * (long)k) / 2); - seg.set(JAVA_DOUBLE_UNALIGNED, tgtAddr, -1.0); - assert seg.get(JAVA_DOUBLE_UNALIGNED, tgtAddr - Double.BYTES) > seg.get(JAVA_DOUBLE_UNALIGNED, tgtAddr); - - // ensure the heapified base buffer is sorted - final HeapCompactDoublesSketch qs2 = HeapCompactDoublesSketch.heapifyInstance(seg); - checkBaseBufferIsSorted(qs2); - } - - @Test - public void checkEmpty() { - final int k = PreambleUtil.DEFAULT_K; - final UpdatableQuantilesDoublesSketch qs1 = buildAndLoadQS(k, 0); - final byte[] byteArr = qs1.compact().toByteArray(); - final byte[] byteArr2 = qs1.toByteArray(true); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - final HeapCompactDoublesSketch qs2 = HeapCompactDoublesSketch.heapifyInstance(seg); - assertTrue(qs2.isEmpty()); - assertEquals(byteArr.length, qs1.getSerializedSizeBytes()); - assertEquals(byteArr, byteArr2); - try { qs2.getQuantile(0.5); fail(); } catch (final IllegalArgumentException e) { } - try { qs2.getQuantiles(new double[] {0.0, 0.5, 1.0}); fail(); } catch (final IllegalArgumentException e) { } - try { qs2.getRank(0); fail(); } catch (final IllegalArgumentException e) { } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkSegTooSmall1() { - final MemorySegment seg = MemorySegment.ofArray(new byte[7]); - HeapCompactDoublesSketch.heapifyInstance(seg); - } - - static void checkBaseBufferIsSorted(final HeapCompactDoublesSketch qs) { - final double[] combinedBuffer = qs.getCombinedBuffer(); - final int bbCount = qs.getBaseBufferCount(); - - for (int i = 1; i < bbCount; ++i) { - assert combinedBuffer[i - 1] <= combinedBuffer[i]; - } - } - - static UpdatableQuantilesDoublesSketch buildAndLoadQS(final int k, final int n) { - return buildAndLoadQS(k, n, 0); - } - - static UpdatableQuantilesDoublesSketch buildAndLoadQS(final int k, final int n, final int startV) { - final UpdatableQuantilesDoublesSketch qs = QuantilesDoublesSketch.builder().setK(k).build(); - for (int i = 1; i <= n; i++) { - qs.update(startV + i); - } - return qs; - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - print("PRINTING: " + this.getClass().getName() + LS); - } - - /** - * @param s value to print - */ - static void println(final String s) { - print(s + LS); - } - - /** - * @param s value to print - */ - static void print(final String s) { - //System.err.print(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/HeapUpdateDoublesSketchTest.java b/src/test/java/org/apache/datasketches/quantiles/HeapUpdateDoublesSketchTest.java deleted file mode 100644 index e9d72d1fa..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/HeapUpdateDoublesSketchTest.java +++ /dev/null @@ -1,1053 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static java.lang.Math.floor; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.common.Util.log2; -import static org.apache.datasketches.quantiles.ClassicUtil.computeCombinedBufferItemCapacity; -import static org.apache.datasketches.quantiles.ClassicUtil.computeNumLevelsNeeded; -import static org.apache.datasketches.quantiles.HeapUpdateDoublesSketch.checkPreLongsFlagsSerVer; -import static org.apache.datasketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK; -import static org.apache.datasketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantilesUtil.equallySpacedDoubles; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteOrder; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.QuantilesUtil; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -public class HeapUpdateDoublesSketchTest { - - @BeforeMethod - public void setUp() { - QuantilesDoublesSketch.rand.setSeed(32749); // make sketches deterministic for testing - } - - // Please note that this is a randomized test that could probabilistically fail - // if we didn't set the seed. (The probability of failure could be reduced by increasing k.) - // Setting the seed has now made it deterministic. - @Test - public void checkEndToEnd() { - final int k = 256; - final UpdatableQuantilesDoublesSketch qs = QuantilesDoublesSketch.builder().setK(k).build(); - final UpdatableQuantilesDoublesSketch qs2 = QuantilesDoublesSketch.builder().setK(k).build(); - final int n = 1000000; - for (int item = n; item >= 1; item--) { - if ((item % 4) == 0) { - qs.update(item); - } - else { - qs2.update(item); - } - } - assertEquals(qs.getN() + qs2.getN(), n); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.heapify(qs); - union.union(qs2); - final QuantilesDoublesSketch result = union.getResult(); - - final int numPhiValues = 99; - final double[] phiArr = new double[numPhiValues]; - for (int q = 1; q <= 99; q++) { - phiArr[q-1] = q / 100.0; - } - final double[] splitPoints = result.getQuantiles(phiArr); - -// for (int i = 0; i < 99; i++) { -// String s = String.format("%d\t%.6f\t%.6f", i, phiArr[i], splitPoints[i]); -// println(s); -// } - - for (int q = 1; q <= 99; q++) { - final double nominal = (1e6 * q) / 100.0; - final double reported = splitPoints[q-1]; - assertTrue(reported >= (nominal - 10000.0)); - assertTrue(reported <= (nominal + 10000.0)); - } - - final double[] pmfResult = result.getPMF(splitPoints); - double subtotal = 0.0; - for (int q = 1; q <= 100; q++) { - final double phi = q / 100.0; - subtotal += pmfResult[q-1]; - assertTrue(subtotal >= (phi - 0.01)); - assertTrue(subtotal <= (phi + 0.01)); - } - - final double[] cdfResult = result.getCDF(splitPoints); - for (int q = 1; q <= 100; q++) { - final double phi = q / 100.0; - subtotal = cdfResult[q-1]; - assertTrue(subtotal >= (phi - 0.01)); - assertTrue(subtotal <= (phi + 0.01)); - } - - assertEquals(result.getRank(500000), 0.5, 0.01); - } - - @Test - public void checkSmallMinMax () { - final int k = 32; - final int n = 8; - final UpdatableQuantilesDoublesSketch qs1 = QuantilesDoublesSketch.builder().setK(k).build(); - final UpdatableQuantilesDoublesSketch qs2 = QuantilesDoublesSketch.builder().setK(k).build(); - final UpdatableQuantilesDoublesSketch qs3 = QuantilesDoublesSketch.builder().setK(k).build(); - - for (int i = n; i >= 1; i--) { - qs1.update(i); - qs2.update(10+i); - qs3.update(i); - } - assertEquals(qs1.getQuantile (0.0, EXCLUSIVE), 1.0); - assertEquals(qs1.getQuantile (0.5, EXCLUSIVE), 5.0); - assertEquals(qs1.getQuantile (1.0, EXCLUSIVE), 8.0); - - assertEquals(qs2.getQuantile (0.0, EXCLUSIVE), 11.0); - assertEquals(qs2.getQuantile (0.5, EXCLUSIVE), 15.0); - assertEquals(qs2.getQuantile (1.0, EXCLUSIVE), 18.0); - - assertEquals(qs3.getQuantile (0.0, EXCLUSIVE), 1.0); - assertEquals(qs3.getQuantile (0.5, EXCLUSIVE), 5.0); - assertEquals(qs3.getQuantile (1.0, EXCLUSIVE), 8.0); - - final double[] queries = {0.0, 0.5, 1.0}; - - final double[] resultsA = qs1.getQuantiles(queries, EXCLUSIVE); - assertEquals(resultsA[0], 1.0); - assertEquals(resultsA[1], 5.0); - assertEquals(resultsA[2], 8.0); - - final QuantilesDoublesUnion union1 = QuantilesDoublesUnion.heapify(qs1); - union1.union(qs2); - final QuantilesDoublesSketch result1 = union1.getResult(); - - final QuantilesDoublesUnion union2 = QuantilesDoublesUnion.heapify(qs2); - union2.union(qs3); - final QuantilesDoublesSketch result2 = union2.getResult(); - - final double[] resultsB = result1.getQuantiles(queries, EXCLUSIVE); - assertEquals(resultsB[0], 1.0); - assertEquals(resultsB[1], 11.0); - assertEquals(resultsB[2], 18.0); - - final double[] resultsC = result2.getQuantiles(queries, EXCLUSIVE); - assertEquals(resultsC[0], 1.0); - assertEquals(resultsC[1], 11.0); - assertEquals(resultsC[2], 18.0); - } - - @Test - public void checkMisc() { - final int k = PreambleUtil.DEFAULT_K; - final int n = 10000; - final UpdatableQuantilesDoublesSketch qs = buildAndLoadQS(k, n); - qs.update(Double.NaN); //ignore - final int n2 = (int)qs.getN(); - assertEquals(n2, n); - - qs.reset(); - assertEquals(qs.getN(), 0); - } - - @SuppressWarnings("unused") - @Test - public void checkToStringDetail() { - final int k = PreambleUtil.DEFAULT_K; - final int n = 1000000; - UpdatableQuantilesDoublesSketch qs = buildAndLoadQS(k, 0); - String s = qs.toString(); - s = qs.toString(false, true); - //println(s); - qs = buildAndLoadQS(k, n); - s = qs.toString(); - //println(s); - s = qs.toString(false, true); - //println(qs.toString(false, true)); - - final int n2 = (int)qs.getN(); - assertEquals(n2, n); - qs.update(Double.NaN); //ignore - qs.reset(); - assertEquals(qs.getN(), 0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkConstructorException() { - QuantilesDoublesSketch.builder().setK(0).build(); - } - - @Test - public void checkPreLongsFlagsAndSize() { - byte[] byteArr; - final UpdatableQuantilesDoublesSketch ds = QuantilesDoublesSketch.builder().build(); //k = 128 - //empty - byteArr = ds.toByteArray(true); // compact - assertEquals(byteArr.length, 8); - - byteArr = ds.toByteArray(false); // not compact - assertEquals(byteArr.length, 8); - assertEquals(byteArr[3], EMPTY_FLAG_MASK); - - //not empty - ds.update(1); - byteArr = ds.toByteArray(true); // compact - assertEquals(byteArr.length, 40); //compact, 1 value - - byteArr = ds.toByteArray(false); // not compact - assertEquals(byteArr.length, 64); // 32 + MIN_K(=2) * 2 * 8 = 64 - } - - @Test - public void checkPreLongsFlagsSerVerB() { - checkPreLongsFlagsSerVer(EMPTY_FLAG_MASK, 1, 1); //38 - checkPreLongsFlagsSerVer(0, 1, 5); //164 - checkPreLongsFlagsSerVer(EMPTY_FLAG_MASK, 2, 1); //42 - checkPreLongsFlagsSerVer(0, 2, 2); //72 - checkPreLongsFlagsSerVer(EMPTY_FLAG_MASK | COMPACT_FLAG_MASK, 3, 1); //47 - checkPreLongsFlagsSerVer(EMPTY_FLAG_MASK | COMPACT_FLAG_MASK, 3, 2); //79 - checkPreLongsFlagsSerVer(EMPTY_FLAG_MASK, 3, 2); //78 - checkPreLongsFlagsSerVer(COMPACT_FLAG_MASK, 3, 2);//77 - checkPreLongsFlagsSerVer(0, 3, 2); //76 - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkPreLongsFlagsSerVer3() { - checkPreLongsFlagsSerVer(EMPTY_FLAG_MASK, 1, 2); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkGetQuantiles() { - final int k = PreambleUtil.DEFAULT_K; - final int n = 1000000; - final QuantilesDoublesSketch qs = buildAndLoadQS(k, n); - final double[] frac = {-0.5}; - qs.getQuantiles(frac); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkGetQuantile() { - final int k = PreambleUtil.DEFAULT_K; - final int n = 1000000; - final QuantilesDoublesSketch qs = buildAndLoadQS(k, n); - final double frac = -0.5; //negative not allowed - qs.getQuantile(frac); - } - - //@Test //visual only - public void summaryCheckViaMemory() { - final QuantilesDoublesSketch qs = buildAndLoadQS(256, 1000000); - String s = qs.toString(); - println(s); - println(""); - - final MemorySegment srcSeg = MemorySegment.ofArray(qs.toByteArray()); - - final HeapUpdateDoublesSketch qs2 = HeapUpdateDoublesSketch.heapifyInstance(srcSeg); - s = qs2.toString(); - println(s); - } - - @Test - public void checkComputeNumLevelsNeeded() { - final int n = 1 << 20; - final int k = PreambleUtil.DEFAULT_K; - final int lvls1 = computeNumLevelsNeeded(k, n); - final int lvls2 = (int)Math.max(floor(log2((double)n/k)),0); - assertEquals(lvls1, lvls2); - } - - @Test - public void checkComputeBitPattern() { - final int n = 1 << 20; - final int k = PreambleUtil.DEFAULT_K; - final long bitP = ClassicUtil.computeBitPattern(k, n); - assertEquals(bitP, n/(2L*k)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkValidateSplitPointsOrder() { - final double[] arr = {2, 1}; - QuantilesUtil.checkDoublesSplitPointsOrder(arr); - } - - @Test - public void checkGetStorageBytes() { - final int k = PreambleUtil.DEFAULT_K; //128 - QuantilesDoublesSketch qs = buildAndLoadQS(k, 0); //k, n - int stor = qs.getCurrentCompactSerializedSizeBytes(); - assertEquals(stor, 8); - - qs = buildAndLoadQS(k, 2*k); //forces one level - stor = qs.getCurrentCompactSerializedSizeBytes(); - - int retItems = ClassicUtil.computeRetainedItems(k, 2*k); - assertEquals(stor, 32 + (retItems << 3)); - - qs = buildAndLoadQS(k, (2*k)-1); //just Base Buffer - stor = qs.getCurrentCompactSerializedSizeBytes(); - retItems = ClassicUtil.computeRetainedItems(k, (2*k)-1); - assertEquals(stor, 32 + (retItems << 3)); - } - - @Test - public void checkGetStorageBytes2() { - final int k = PreambleUtil.DEFAULT_K; - long v = 1; - final UpdatableQuantilesDoublesSketch qs = QuantilesDoublesSketch.builder().setK(k).build(); - for (int i = 0; i< 1000; i++) { - qs.update(v++); -// for (int j = 0; j < 1000; j++) { -// qs.update(v++); -// } - final byte[] byteArr = qs.toByteArray(false); - assertEquals(byteArr.length, qs.getCurrentUpdatableSerializedSizeBytes()); - } - } - - @Test - public void checkMerge() { - final int k = PreambleUtil.DEFAULT_K; - final int n = 1000000; - final QuantilesDoublesSketch qs1 = buildAndLoadQS(k,n,0); - final QuantilesDoublesSketch qs2 = buildAndLoadQS(k,0,0); //empty - final QuantilesDoublesUnion union = QuantilesDoublesUnion.heapify(qs2); - union.union(qs1); - final QuantilesDoublesSketch result = union.getResult(); - final double med1 = qs1.getQuantile(0.5); - final double med2 = result.getQuantile(0.5); - assertEquals(med1, med2, 0.0); - //println(med1+","+med2); - } - - @Test - public void checkReverseMerge() { - final int k = PreambleUtil.DEFAULT_K; - final QuantilesDoublesSketch qs1 = buildAndLoadQS(k, 1000, 0); - final QuantilesDoublesSketch qs2 = buildAndLoadQS(2*k,1000, 1000); - final QuantilesDoublesUnion union = QuantilesDoublesUnion.heapify(qs2); - union.union(qs1); //attempt merge into larger k - final QuantilesDoublesSketch result = union.getResult(); - assertEquals(result.getK(), k); - } - - @Test - public void checkInternalBuildHistogram() { - final int k = PreambleUtil.DEFAULT_K; - final int n = 1000000; - final QuantilesDoublesSketch qs = buildAndLoadQS(k,n,0); - final double eps = qs.getNormalizedRankError(true); - //println("EPS:"+eps); - final double[] spts = {100000, 500000, 900000}; - final double[] fracArr = qs.getPMF(spts); -// println(fracArr[0]+", "+ (fracArr[0]-0.1)); -// println(fracArr[1]+", "+ (fracArr[1]-0.4)); -// println(fracArr[2]+", "+ (fracArr[2]-0.4)); -// println(fracArr[3]+", "+ (fracArr[3]-0.1)); - assertEquals(fracArr[0], .1, eps); - assertEquals(fracArr[1], .4, eps); - assertEquals(fracArr[2], .4, eps); - assertEquals(fracArr[3], .1, eps); - } - - @Test - public void checkComputeBaseBufferCount() { - final int n = 1 << 20; - final int k = PreambleUtil.DEFAULT_K; - final long bbCnt = ClassicUtil.computeBaseBufferItems(k, n); - assertEquals(bbCnt, n % (2L*k)); - } - - @Test - public void checkToFromByteArray() { - checkToFromByteArray2(128, 1300); //generates a pattern of 5 -> 101 - checkToFromByteArray2(4, 7); - checkToFromByteArray2(4, 8); - checkToFromByteArray2(4, 9); - } - - private static void checkToFromByteArray2(final int k, final int n) { - final QuantilesDoublesSketch qs = buildAndLoadQS(k, n); - byte[] byteArr; - MemorySegment seg; - QuantilesDoublesSketch qs2; - - // from compact - byteArr = qs.toByteArray(true); - seg = MemorySegment.ofArray(byteArr); - qs2 = UpdatableQuantilesDoublesSketch.heapify(seg); - for (double f = 0.1; f < 0.95; f += 0.1) { - assertEquals(qs.getQuantile(f), qs2.getQuantile(f), 0.0); - } - - // ordered, non-compact - byteArr = qs.toByteArray(false); - seg = MemorySegment.ofArray(byteArr); - qs2 = QuantilesDoublesSketch.heapify(seg); - final DoublesSketchAccessor dsa = DoublesSketchAccessor.wrap(qs2, false); - dsa.sort(); - for (double f = 0.1; f < 0.95; f += 0.1) { - assertEquals(qs.getQuantile(f), qs2.getQuantile(f), 0.0); - } - - // not ordered, not compact - byteArr = qs.toByteArray(false); - seg = MemorySegment.ofArray(byteArr); - qs2 = QuantilesDoublesSketch.heapify(seg); - for (double f = 0.1; f < 0.95; f += 0.1) { - assertEquals(qs.getQuantile(f), qs2.getQuantile(f), 0.0); - } - } - - @Test - public void checkEmpty() { - final int k = PreambleUtil.DEFAULT_K; - final QuantilesDoublesSketch qs1 = buildAndLoadQS(k, 0); - final byte[] byteArr = qs1.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - final QuantilesDoublesSketch qs2 = QuantilesDoublesSketch.heapify(seg); - assertTrue(qs2.isEmpty()); - final int expectedSizeBytes = 8; //COMBINED_BUFFER + ((2 * MIN_K) << 3); - assertEquals(byteArr.length, expectedSizeBytes); - try { qs2.getQuantile(0.5); fail(); } catch (final IllegalArgumentException e) { } - try { qs2.getQuantiles(new double[] {0.0, 0.5, 1.0}); fail(); } catch (final IllegalArgumentException e) { } - try { qs2.getRank(0); fail(); } catch (final IllegalArgumentException e) { } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkSegTooSmall1() { - final MemorySegment seg = MemorySegment.ofArray(new byte[7]); - HeapUpdateDoublesSketch.heapifyInstance(seg); - fail(); - //qs2.getQuantile(0.5); - } - - //Corruption tests - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkSerVer() { - DoublesUtil.checkDoublesSerVer(0, HeapUpdateDoublesSketch.MIN_HEAP_DOUBLES_SER_VER); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkFamilyID() { - ClassicUtil.checkFamilyID(3); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkSegCapacityException() { - final int k = PreambleUtil.DEFAULT_K; - final long n = 1000; - final int serVer = 3; - final int combBufItemCap = computeCombinedBufferItemCapacity(k, n); - final int segCapBytes = (combBufItemCap + 4) << 3; - final int badCapBytes = segCapBytes - 1; //corrupt - HeapUpdateDoublesSketch.checkHeapSegCapacity(k, n, false, serVer, badCapBytes); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBufAllocAndCap() { - final int k = PreambleUtil.DEFAULT_K; - final long n = 1000; - final int serVer = 3; - final int combBufItemCap = computeCombinedBufferItemCapacity(k, n); //non-compact cap - final int segCapBytes = (combBufItemCap + 4) << 3; - final int segCapBytesV1 = (combBufItemCap + 5) << 3; - HeapUpdateDoublesSketch.checkHeapSegCapacity(k, n, false, 1, segCapBytesV1); - HeapUpdateDoublesSketch.checkHeapSegCapacity(k, n, false, serVer, segCapBytes - 1); //corrupt - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkPreLongsFlagsCap() { - final int preLongs = 5; - final int flags = EMPTY_FLAG_MASK; - final int segCap = 8; - ClassicUtil.checkPreLongsFlagsCap(preLongs, flags, segCap); //corrupt - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkPreLongsFlagsCap2() { - final int preLongs = 5; - final int flags = 0; - final int segCap = 8; - ClassicUtil.checkPreLongsFlagsCap(preLongs, flags, segCap); //corrupt - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkFlags() { - final int flags = 1; - ClassicUtil.checkHeapFlags(flags); - } - - @Test - public void checkZeroPatternReturn() { - final int k = PreambleUtil.DEFAULT_K; - final QuantilesDoublesSketch qs1 = buildAndLoadQS(k, 64); - final byte[] byteArr = qs1.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - HeapUpdateDoublesSketch.heapifyInstance(seg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadDownSamplingRatio() { - final int k1 = 64; - final QuantilesDoublesSketch qs1 = buildAndLoadQS(k1, k1); - qs1.downSample(qs1, 2*k1, null, null);//should be smaller - } - - @Test - public void checkImproperKvalues() { - checksForImproperK(0); - checksForImproperK(1<<16); - } - - //Primarily visual only tests - static void testDownSampling(final int bigK, final int smallK) { - final HeapUpdateDoublesSketch sketch1 = HeapUpdateDoublesSketch.newInstance(bigK); - final HeapUpdateDoublesSketch sketch2 = HeapUpdateDoublesSketch.newInstance(smallK); - for (int i = 127; i >= 1; i--) { - sketch1.update (i); - sketch2.update (i); - } - final HeapUpdateDoublesSketch downSketch = - (HeapUpdateDoublesSketch)sketch1.downSample(sketch1, smallK, null, null); - println (LS+"Sk1"+LS); - String s1, s2, down; - s1 = sketch1.toString(true, true); - println(s1); - println (LS+"Down"+LS); - down = downSketch.toString(true, true); - println(down); - println(LS+"Sk2"+LS); - s2 = sketch2.toString(true, true); - println(s2); - assertEquals(downSketch.getNumRetained(), sketch2.getNumRetained()); - } - - @Test - public void checkDownSampling() { - testDownSampling(4,4); //no down sampling - testDownSampling(16,4); - //testDownSampling(12,3); - } - - @Test - public void testDownSampling2() { - final HeapUpdateDoublesSketch sketch1 = HeapUpdateDoublesSketch.newInstance(8); - final HeapUpdateDoublesSketch sketch2 = HeapUpdateDoublesSketch.newInstance(2); - QuantilesDoublesSketch downSketch; - downSketch = sketch1.downSample(sketch1, 2, null, null); - assertTrue(sameStructurePredicate(sketch2, downSketch)); - for (int i = 0; i < 50; i++) { - sketch1.update (i); - sketch2.update (i); - downSketch = sketch1.downSample(sketch1, 2, null, null); - assertTrue (sameStructurePredicate(sketch2, downSketch)); - } - } - - @Test - public void testDownSampling3() { - final int k1 = 8; - final int k2 = 2; - final int n = 50; - final UpdatableQuantilesDoublesSketch sketch1 = QuantilesDoublesSketch.builder().setK(k1).build(); - final UpdatableQuantilesDoublesSketch sketch2 = QuantilesDoublesSketch.builder().setK(k2).build(); - QuantilesDoublesSketch downSketch; - for (int i = 0; i < n; i++) { - sketch1.update (i); - sketch2.update (i); - downSketch = sketch1.downSample(sketch1, k2, null, null); - assertTrue (sameStructurePredicate(sketch2, downSketch)); - } - } - - @Test // - public void testDownSampling3withSeg() { - final int k1 = 8; - final int k2 = 2; - final int n = 50; - final UpdatableQuantilesDoublesSketch sketch1 = QuantilesDoublesSketch.builder().setK(k1).build(); - final UpdatableQuantilesDoublesSketch sketch2 = QuantilesDoublesSketch.builder().setK(k2).build(); - QuantilesDoublesSketch downSketch; - final int bytes = QuantilesDoublesSketch.getUpdatableStorageBytes(k2, n); - final MemorySegment seg = MemorySegment.ofArray(new byte[bytes]); - for (int i = 0; i < n; i++) { - sketch1.update (i); - sketch2.update (i); - - downSketch = sketch1.downSample(sketch1, k2, seg, null); - assertTrue (sameStructurePredicate(sketch2, downSketch)); - } - - } - - @Test - public void testDownSampling4() { - for (int n1 = 0; n1 < 50; n1++ ) { - final HeapUpdateDoublesSketch bigSketch = HeapUpdateDoublesSketch.newInstance(8); - for (int i1 = 1; i1 <= n1; i1++ ) { - bigSketch.update(i1); - } - for (int n2 = 0; n2 < 50; n2++ ) { - final HeapUpdateDoublesSketch directSketch = HeapUpdateDoublesSketch.newInstance(2); - for (int i1 = 1; i1 <= n1; i1++ ) { - directSketch.update(i1); - } - for (int i2 = 1; i2 <= n2; i2++ ) { - directSketch.update(i2); - } - final HeapUpdateDoublesSketch smlSketch = HeapUpdateDoublesSketch.newInstance(2); - for (int i2 = 1; i2 <= n2; i2++ ) { - smlSketch.update(i2); - } - DoublesMergeImpl.downSamplingMergeInto(bigSketch, smlSketch); - assertTrue (sameStructurePredicate(directSketch, smlSketch)); - } - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void testDownSamplingExceptions1() { - final UpdatableQuantilesDoublesSketch qs1 = QuantilesDoublesSketch.builder().setK(4).build(); // not smaller - final QuantilesDoublesSketch qs2 = QuantilesDoublesSketch.builder().setK(3).build(); - DoublesMergeImpl.mergeInto(qs2, qs1); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void testDownSamplingExceptions2() { - final UpdatableQuantilesDoublesSketch qs1 = QuantilesDoublesSketch.builder().setK(4).build(); - final QuantilesDoublesSketch qs2 = QuantilesDoublesSketch.builder().setK(7).build(); // 7/4 not pwr of 2 - DoublesMergeImpl.mergeInto(qs2, qs1); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void testDownSamplingExceptions3() { - final UpdatableQuantilesDoublesSketch qs1 = QuantilesDoublesSketch.builder().setK(4).build(); - final QuantilesDoublesSketch qs2 = QuantilesDoublesSketch.builder().setK(12).build(); // 12/4 not pwr of 2 - DoublesMergeImpl.mergeInto(qs2, qs1); - } - - //@Test //visual only - public void quantilesCheckViaMemory() { - final int k = 256; - final int n = 1000000; - final QuantilesDoublesSketch qs = buildAndLoadQS(k, n); - final double[] ranks = {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}; - final String s = getRanksTable(qs, ranks); - println(s); - println(""); - - final MemorySegment srcSeg = MemorySegment.ofArray(qs.toByteArray()); - - final HeapUpdateDoublesSketch qs2 = HeapUpdateDoublesSketch.heapifyInstance(srcSeg); - println(getRanksTable(qs2, ranks)); - } - - static String getRanksTable(final QuantilesDoublesSketch qs, final double[] ranks) { - final double rankError = qs.getNormalizedRankError(false); - final double[] values = qs.getQuantiles(ranks); - final double maxV = qs.getMaxItem(); - final double minV = qs.getMinItem(); - final double delta = maxV - minV; - println("Note: This prints the relative value errors for illustration."); - println("The quantiles sketch does not and can not guarantee relative value errors"); - - final StringBuilder sb = new StringBuilder(); - sb.append(LS); - sb.append("N = ").append(qs.getN()).append(LS); - sb.append("K = ").append(qs.getK()).append(LS); - final String formatStr1 = "%10s%15s%10s%15s%10s%10s"; - final String formatStr2 = "%10.1f%15.5f%10.0f%15.5f%10.5f%10.5f"; - final String hdr = String.format( - formatStr1, "Rank", "ValueLB", "<= Value", "<= ValueUB", "RelErrLB", "RelErrUB"); - sb.append(hdr).append(LS); - for (int i=0; i valueLB); - - final double valRelPctErrUB = (valueUB/ value) -1.0; - final double valRelPctErrLB = (valueLB/ value) -1.0; - final String row = String.format( - formatStr2,rank, valueLB, value, valueUB, valRelPctErrLB, valRelPctErrUB); - sb.append(row).append(LS); - } - } - return sb.toString(); - } - - @Test - public void checkKisTwo() { - final int k = 2; - final UpdatableQuantilesDoublesSketch qs1 = QuantilesDoublesSketch.builder().setK(k).build(); - final double err = qs1.getNormalizedRankError(false); - assertTrue(err < 1.0); - byte[] arr = qs1.toByteArray(true); //8 - assertEquals(arr.length, QuantilesDoublesSketch.getCompactSerialiedSizeBytes(k, 0)); - qs1.update(1.0); - arr = qs1.toByteArray(true); //40 - assertEquals(arr.length, QuantilesDoublesSketch.getCompactSerialiedSizeBytes(k, 1)); - } - - @Test - public void checkKisTwoDeprecated() { - final int k = 2; - final UpdatableQuantilesDoublesSketch qs1 = QuantilesDoublesSketch.builder().setK(k).build(); - final double err = qs1.getNormalizedRankError(false); - assertTrue(err < 1.0); - byte[] arr = qs1.toByteArray(true); //8 - assertEquals(arr.length, QuantilesDoublesSketch.getCompactSerialiedSizeBytes(k, 0)); - assertEquals(arr.length, qs1.getCurrentCompactSerializedSizeBytes()); - qs1.update(1.0); - arr = qs1.toByteArray(true); //40 - assertEquals(arr.length, QuantilesDoublesSketch.getCompactSerialiedSizeBytes(k, 1)); - assertEquals(arr.length, qs1.getCurrentCompactSerializedSizeBytes()); - } - - @Test - public void checkPutMemory() { - final UpdatableQuantilesDoublesSketch qs1 = QuantilesDoublesSketch.builder().build(); //k = 128 - for (int i=0; i<1000; i++) { - qs1.update(i); - } - final int bytes = qs1.getCurrentUpdatableSerializedSizeBytes(); - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[bytes]); - qs1.putIntoMemorySegment(dstSeg, false); - final MemorySegment srcSeg = dstSeg; - final QuantilesDoublesSketch qs2 = QuantilesDoublesSketch.heapify(srcSeg); - assertEquals(qs1.getMinItem(), qs2.getMinItem(), 0.0); - assertEquals(qs1.getMaxItem(), qs2.getMaxItem(), 0.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkPutMemoryTooSmall() { - final UpdatableQuantilesDoublesSketch qs1 = QuantilesDoublesSketch.builder().build(); //k = 128 - for (int i=0; i<1000; i++) { - qs1.update(i); - } - final int bytes = qs1.getCurrentCompactSerializedSizeBytes(); - final MemorySegment dstSeg = MemorySegment.ofArray(new byte[bytes-1]); //too small - qs1.putIntoMemorySegment(dstSeg); - } - - //Himanshu's case - @Test - public void testIt() { - final java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(1<<20).order(ByteOrder.nativeOrder()); - final MemorySegment seg = MemorySegment.ofBuffer(bb); - - final int k = 1024; - final QuantilesDoublesSketch qsk = new QuantilesDoublesSketchBuilder().setK(k).build(); - final QuantilesDoublesUnion u1 = QuantilesDoublesUnion.heapify(qsk); - u1.getResult().putIntoMemorySegment(seg); - final QuantilesDoublesUnion u2 = QuantilesDoublesUnion.heapify(seg); - final QuantilesDoublesSketch qsk2 = u2.getResult(); - assertTrue(qsk2.isEmpty()); - } - - @Test - public void checkEquallySpacedRanks() { - final int n = 10; - final double[] es = equallySpacedDoubles(n); - final int len = es.length; - for (int j=0; j= ClassicUtil.computeCombinedBufferItemCapacity(mq1.getK(), mq1.getN())) - && (mq2.getCombinedBufferItemCapacity() - >= ClassicUtil.computeCombinedBufferItemCapacity(mq2.getK(), mq2.getN())) - && (mq1.getBaseBufferCount() == mq2.getBaseBufferCount()) - && (mq1.getBitPattern() == mq2.getBitPattern()) ); - - final boolean b2; - if (mq1.isEmpty()) { - b2 = mq2.isEmpty(); - } else { - b2 = (mq1.getMinItem() == mq2.getMinItem()) && (mq1.getMaxItem() == mq2.getMaxItem()); - } - return b1 && b2; - } - - static UpdatableQuantilesDoublesSketch buildAndLoadQS(final int k, final int n) { - return buildAndLoadQS(k, n, 0); - } - - static UpdatableQuantilesDoublesSketch buildAndLoadQS(final int k, final int n, final int startV) { - final UpdatableQuantilesDoublesSketch qs = QuantilesDoublesSketch.builder().setK(k).build(); - for (int i=1; i<=n; i++) { - qs.update(startV + i); - } - return qs; - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - print("PRINTING: "+this.getClass().getName() + LS); - } - - /** - * @param s value to print - */ - static void println(final Object o) { - print(o.toString() + LS); - } - - /** - * @param s value to print - */ - static void print(final Object o) { - //System.out.print(o.toString()); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/ItemsSketchIteratorTest.java b/src/test/java/org/apache/datasketches/quantiles/ItemsSketchIteratorTest.java deleted file mode 100644 index 912d6237e..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/ItemsSketchIteratorTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import java.util.Comparator; - -import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class ItemsSketchIteratorTest { - - @Test - public void emptySketch() { - QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Integer.class, 128, Comparator.naturalOrder()); - QuantilesGenericSketchIteratorAPI it = sketch.iterator(); - Assert.assertFalse(it.next()); - } - - @Test - public void oneItemSketch() { - QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Integer.class, 128, Comparator.naturalOrder()); - sketch.update(0); - QuantilesGenericSketchIteratorAPI it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getQuantile(), Integer.valueOf(0)); - Assert.assertEquals(it.getWeight(), 1); - Assert.assertFalse(it.next()); - } - - @Test - public void bigSketches() { - for (int n = 1000; n < 100000; n += 2000) { - QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Integer.class, 128, Comparator.naturalOrder()); - for (int i = 0; i < n; i++) { - sketch.update(i); - } - QuantilesGenericSketchIteratorAPI it = sketch.iterator(); - int count = 0; - int weight = 0; - while (it.next()) { - count++; - weight += (int)it.getWeight(); - } - Assert.assertEquals(count, sketch.getNumRetained()); - Assert.assertEquals(weight, n); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/ItemsSketchTest.java b/src/test/java/org/apache/datasketches/quantiles/ItemsSketchTest.java deleted file mode 100644 index d557868b9..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/ItemsSketchTest.java +++ /dev/null @@ -1,704 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.Util.clearBits; -import static org.apache.datasketches.quantilescommon.LongsAsOrderableStrings.getString; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; -import java.util.Comparator; -import java.util.Random; - -import org.apache.datasketches.common.ArrayOfBooleansSerDe; -import org.apache.datasketches.common.ArrayOfDoublesSerDe; -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.ArrayOfLongsSerDe; -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.GenericSortedView; -import org.apache.datasketches.quantilescommon.GenericSortedViewIterator; -import org.apache.datasketches.quantilescommon.ItemsSketchSortedView; -import org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -public class ItemsSketchTest { - - @BeforeMethod - public void setUp() { - QuantilesItemsSketch.rand.setSeed(32749); // make sketches deterministic for testing - } - - @Test - public void empty() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(String.class, 128, Comparator.naturalOrder()); - assertNotNull(sketch); - sketch.update(null); - assertTrue(sketch.isEmpty()); - assertEquals(sketch.getN(), 0); - assertEquals(sketch.getNumRetained(), 0); - try { sketch.getMinItem(); fail(); } catch (final IllegalArgumentException e) {} - try { sketch.getMaxItem(); fail(); } catch (final IllegalArgumentException e) {} - - try { sketch.getQuantile(0.5); fail(); } catch (final IllegalArgumentException e) {} - try { sketch.getQuantiles(new double[] {0.0, 1.0}); fail(); } catch (final IllegalArgumentException e) {} - - final byte[] byteArr = sketch.toByteArray(new ArrayOfStringsSerDe()); - assertEquals(byteArr.length, 8); - try { sketch.getPMF(new String[0]); fail(); } catch (final IllegalArgumentException e) {} - try { sketch.getCDF(new String[0]); fail(); } catch (final IllegalArgumentException e) {} - try { sketch.getRank("a"); fail(); } catch (final IllegalArgumentException e) {} - } - - @Test - public void oneItem() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(String.class, 128, Comparator.naturalOrder()); - sketch.update("a"); - assertEquals(sketch.getN(), 1); - assertEquals(sketch.getNumRetained(), 1); - assertEquals(sketch.getMinItem(), "a"); - assertEquals(sketch.getMaxItem(), "a"); - assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), "a"); - assertEquals(sketch.getRank("a", EXCLUSIVE), 0.0); - - { - final double[] pmf = sketch.getPMF(new String[0], EXCLUSIVE); - assertEquals(pmf.length, 1); - assertEquals(pmf[0], 1.0); - } - - { - final double[] pmf = sketch.getPMF(new String[] {"a"}, EXCLUSIVE); - assertEquals(pmf.length, 2); - assertEquals(pmf[0], 0.0); - assertEquals(pmf[1], 1.0); - } - - { - final double[] cdf = sketch.getCDF(new String[0], EXCLUSIVE); - assertEquals(cdf.length, 1); - assertEquals(cdf[0], 1.0); - } - - { - final double[] cdf = sketch.getCDF(new String[] {"a"}, EXCLUSIVE); - assertEquals(cdf.length, 2); - assertEquals(cdf[0], 0.0); - assertEquals(cdf[1], 1.0); - } - - sketch.reset(); - assertTrue(sketch.isEmpty()); - assertEquals(sketch.getN(), 0); - assertEquals(sketch.getNumRetained(), 0); - try { sketch.getMinItem(); fail(); } catch (final IllegalArgumentException e) {} - try { sketch.getMaxItem(); fail(); } catch (final IllegalArgumentException e) {} - try { sketch.getQuantile(0.5); fail(); } catch (final IllegalArgumentException e) {} - } - - @Test - public void tenItems() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Integer.class, 128, Comparator.naturalOrder()); - for (int i = 1; i <= 10; i++) { sketch.update(i); } - assertFalse(sketch.isEmpty()); - assertFalse(sketch.isReadOnly()); - assertEquals(sketch.getN(), 10); - assertEquals(sketch.getNumRetained(), 10); - for (int i = 1; i <= 10; i++) { - assertEquals(sketch.getRank(i), (i) / 10.0); - assertEquals(sketch.getRank(i, EXCLUSIVE), (i - 1) / 10.0); - assertEquals(sketch.getRank(i, INCLUSIVE), i / 10.0); - } - final Integer[] qArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - double[] rOut = sketch.getRanks(qArr); //inclusive - for (int i = 0; i < qArr.length; i++) { - assertEquals(rOut[i], (i + 1) / 10.0); - } - rOut = sketch.getRanks(qArr, EXCLUSIVE); //exclusive - for (int i = 0; i < qArr.length; i++) { - assertEquals(rOut[i], i / 10.0); - } - // inclusive = (default) - assertEquals(sketch.getQuantile(0, EXCLUSIVE), 1); - assertEquals(sketch.getQuantile(0.1, EXCLUSIVE), 2); - assertEquals(sketch.getQuantile(0.2, EXCLUSIVE), 3); - assertEquals(sketch.getQuantile(0.3, EXCLUSIVE), 4); - assertEquals(sketch.getQuantile(0.4, EXCLUSIVE), 5); - assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 6); - assertEquals(sketch.getQuantile(0.6, EXCLUSIVE), 7); - assertEquals(sketch.getQuantile(0.7, EXCLUSIVE), 8); - assertEquals(sketch.getQuantile(0.8, EXCLUSIVE), 9); - assertEquals(sketch.getQuantile(0.9, EXCLUSIVE), 10); - assertEquals(sketch.getQuantile(1, EXCLUSIVE), 10); - // inclusive = true - assertEquals(sketch.getQuantile(0, INCLUSIVE), 1); - assertEquals(sketch.getQuantile(0.1, INCLUSIVE), 1); - assertEquals(sketch.getQuantile(0.2, INCLUSIVE), 2); - assertEquals(sketch.getQuantile(0.3, INCLUSIVE), 3); - assertEquals(sketch.getQuantile(0.4, INCLUSIVE), 4); - assertEquals(sketch.getQuantile(0.5, INCLUSIVE), 5); - assertEquals(sketch.getQuantile(0.6, INCLUSIVE), 6); - assertEquals(sketch.getQuantile(0.7, INCLUSIVE), 7); - assertEquals(sketch.getQuantile(0.8, INCLUSIVE), 8); - assertEquals(sketch.getQuantile(0.9, INCLUSIVE), 9); - assertEquals(sketch.getQuantile(1, INCLUSIVE), 10); - - // getQuantile() and getQuantiles() equivalence - { - // inclusive = (default) - final Integer[] quantiles = - sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1}); - for (int i = 0; i <= 10; i++) { - assertEquals(sketch.getQuantile(i / 10.0), quantiles[i]); - } - } - { - // inclusive = true - final Integer[] quantiles = - sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1}, INCLUSIVE); - for (int i = 0; i <= 10; i++) { - assertEquals(sketch.getQuantile(i / 10.0, INCLUSIVE), quantiles[i]); - } - } - } - - @Test - public void estimation() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Integer.class, 128, Comparator.naturalOrder()); - for (int i = 1; i <= 1000; i++) { - sketch.update(i); - } - assertEquals(sketch.getN(), 1000); - assertTrue(sketch.getNumRetained() < 1000); - assertEquals(sketch.getMinItem(), Integer.valueOf(1)); - assertEquals(sketch.getMaxItem(), Integer.valueOf(1000)); - // based on ~1.7% normalized rank error for this particular case - assertEquals(sketch.getQuantile(0.5), 500, 17); - - final double[] normRanks = {0.0, 0.5, 1.0}; - final Integer[] quantiles = sketch.getQuantiles(normRanks); - - assertEquals(quantiles[1], 500, 17); // median - - final double[] normRanks2 = {.25, 0.5, 0.75}; - final Integer[] quantiles2 = sketch.getQuantiles(normRanks2); - assertEquals(quantiles2[0], 250, 17); - assertEquals(quantiles2[1], 500, 17); - assertEquals(quantiles2[2], 750, 17); - - final double normErr = sketch.getNormalizedRankError(true); - assertEquals(normErr, .0172, .001); - println(""+normErr); - - { - final double[] pmf = sketch.getPMF(new Integer[0]); - assertEquals(pmf.length, 1); - assertEquals(pmf[0], 1.0); - } - - { - final double[] pmf = sketch.getPMF(new Integer[] {500}); - assertEquals(pmf.length, 2); - assertEquals(pmf[0], 0.5, 0.05); - assertEquals(pmf[1], 0.5, 0.05); - } - - { - final Integer[] intArr = new Integer[50]; - for (int i= 0; i<50; i++) { - intArr[i] = (20*i) +10; - } - final double[] pmf = sketch.getPMF(intArr); - assertEquals(pmf.length, 51); - } - - { - final double[] cdf = sketch.getCDF(new Integer[0]); - assertEquals(cdf.length, 1); - assertEquals(cdf[0], 1.0); - } - - { - final double[] cdf = sketch.getCDF(new Integer[] {500}); - assertEquals(cdf.length, 2); - assertEquals(cdf[0], 0.5, 0.05); - assertEquals(cdf[1], 1.0, 0.05); - } - - assertEquals(sketch.getRank(500), 0.5, 0.01); - } - - @Test - public void serializeDeserializeLong() { - final QuantilesItemsSketch sketch1 = QuantilesItemsSketch.getInstance(Long.class, 128, Comparator.naturalOrder()); - for (int i = 1; i <= 500; i++) { - sketch1.update((long) i); - } - - final ArrayOfItemsSerDe serDe = new ArrayOfLongsSerDe(); - final byte[] bytes = sketch1.toByteArray(serDe); - final QuantilesItemsSketch sketch2 = - QuantilesItemsSketch.heapify(Long.class, MemorySegment.ofArray(bytes), Comparator.naturalOrder(), serDe); - - for (int i = 501; i <= 1000; i++) { - sketch2.update((long) i); - } - assertEquals(sketch2.getN(), 1000); - assertTrue(sketch2.getNumRetained() < 1000); - assertEquals(sketch2.getMinItem(), Long.valueOf(1)); - assertEquals(sketch2.getMaxItem(), Long.valueOf(1000)); - // based on ~1.7% normalized rank error for this particular case - assertEquals(sketch2.getQuantile(0.5), 500, 17); - } - - @Test - public void serializeDeserializeDouble() { - final QuantilesItemsSketch sketch1 = QuantilesItemsSketch.getInstance(Double.class, 128, Comparator.naturalOrder()); - for (int i = 1; i <= 500; i++) { - sketch1.update((double) i); - } - - final ArrayOfItemsSerDe serDe = new ArrayOfDoublesSerDe(); - final byte[] bytes = sketch1.toByteArray(serDe); - final QuantilesItemsSketch sketch2 = - QuantilesItemsSketch.heapify(Double.class, MemorySegment.ofArray(bytes), Comparator.naturalOrder(), serDe); - - for (int i = 501; i <= 1000; i++) { - sketch2.update((double) i); - } - assertEquals(sketch2.getN(), 1000); - assertTrue(sketch2.getNumRetained() < 1000); - assertEquals(sketch2.getMinItem(), Double.valueOf(1)); - assertEquals(sketch2.getMaxItem(), Double.valueOf(1000)); - // based on ~1.7% normalized rank error for this particular case - assertEquals(sketch2.getQuantile(0.5), 500, 17); - } - - @Test - public void serializeDeserializeString() { - // numeric order to be able to make meaningful assertions - final Comparator numericOrder = new Comparator() { - @Override - public int compare(final String s1, final String s2) { - final Integer i1 = Integer.parseInt(s1, 2); - final Integer i2 = Integer.parseInt(s2, 2); - return i1.compareTo(i2); - } - }; - final QuantilesItemsSketch sketch1 = QuantilesItemsSketch.getInstance(String.class, 128, numericOrder); - for (int i = 1; i <= 500; i++) - { - sketch1.update(Integer.toBinaryString(i << 10)); // to make strings longer - } - - final ArrayOfItemsSerDe serDe = new ArrayOfStringsSerDe(); - final byte[] bytes = sketch1.toByteArray(serDe); - final QuantilesItemsSketch sketch2 = QuantilesItemsSketch.heapify(String.class, MemorySegment.ofArray(bytes), numericOrder, serDe); - - for (int i = 501; i <= 1000; i++) { - sketch2.update(Integer.toBinaryString(i << 10)); - } - assertEquals(sketch2.getN(), 1000); - assertTrue(sketch2.getNumRetained() < 1000); - assertEquals(sketch2.getMinItem(), Integer.toBinaryString(1 << 10)); - assertEquals(sketch2.getMaxItem(), Integer.toBinaryString(1000 << 10)); - // based on ~1.7% normalized rank error for this particular case - assertEquals(Integer.parseInt(sketch2.getQuantile(0.5), 2) >> 10, 500, 17); - } - - @Test - public void toStringCrudeCheck() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(String.class, Comparator.naturalOrder()); - String brief, full, part; - brief = sketch.toString(); - full = sketch.toString(true, true); - part = sketch.toString(false, true); - sketch.update("a"); - brief = sketch.toString(); - full = sketch.toString(true, true); - part = sketch.toString(false, true); - //println(full); - assertTrue(brief.length() < full.length()); - assertTrue(part.length() < full.length()); - final ArrayOfItemsSerDe serDe = new ArrayOfStringsSerDe(); - final byte[] bytes = sketch.toByteArray(serDe); - QuantilesItemsSketch.toString(bytes); - QuantilesItemsSketch.toString(MemorySegment.ofArray(bytes)); - //PreambleUtil.toString(bytes, true); // not a QuantilesDoublesSketch so this will fail - //QuantilesItemsSketch sketch2 = QuantilesItemsSketch.getInstance(MemorySegment.wrap(bytes), Comparator.naturalOrder(), serDe); - } - - @Test - public void toStringBiggerCheck() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(String.class, 16, Comparator.naturalOrder()); - for (int i=0; i<40; i++) { - sketch.update(Integer.toString(i)); - } - final String bigger = sketch.toString(); - final String full = sketch.toString(true, true); - //println(full); - assertTrue(bigger.length() < full.length()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkDownsampleException() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(String.class, 16, Comparator.naturalOrder()); - for (int i=0; i<40; i++) { - sketch.update(Integer.toString(i)); - } - sketch.downSample(32); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void negativeQuantileMustThrow() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(String.class, 16, Comparator.naturalOrder()); - sketch.update("ABC"); - sketch.getQuantile(-0.1); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkGetInstanceExcep1() { - final MemorySegment seg = MemorySegment.ofArray(new byte[4]); - QuantilesItemsSketch.heapify(String.class, seg, Comparator.naturalOrder(), new ArrayOfStringsSerDe()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkGetInstanceExcep2() { - final MemorySegment seg = MemorySegment.ofArray(new byte[8]); - QuantilesItemsSketch.heapify(String.class, seg, Comparator.naturalOrder(), new ArrayOfStringsSerDe()); - } - - @Test - public void checkGoodSerDeId() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(String.class, Comparator.naturalOrder()); - final byte[] byteArr = sketch.toByteArray(new ArrayOfStringsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - QuantilesItemsSketch.heapify(String.class, seg, Comparator.naturalOrder(), new ArrayOfStringsSerDe()); - } - - @Test - public void checkDownsample() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(String.class, 16, Comparator.naturalOrder()); - for (int i=0; i<40; i++) { - sketch.update(Integer.toString(i)); - } - final QuantilesItemsSketch out = sketch.downSample(8); - assertEquals(out.getK(), 8); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void unorderedSplitPoints() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Integer.class, Comparator.naturalOrder()); - sketch.update(1); - sketch.getPMF(new Integer[] {2, 1}); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void nonUniqueSplitPoints() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Integer.class, Comparator.naturalOrder()); - sketch.update(1); - sketch.getPMF(new Integer[] {1, 1}); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void nullInSplitPoints() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Integer.class, Comparator.naturalOrder()); - sketch.update(1); - sketch.getPMF(new Integer[] {1, null}); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void compactNotSupported() { - final ArrayOfDoublesSerDe serDe = new ArrayOfDoublesSerDe(); - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Double.class, Comparator.naturalOrder()); - final byte[] byteArr = sketch.toByteArray(serDe); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - clearBits(seg, PreambleUtil.FLAGS_BYTE, (byte) PreambleUtil.COMPACT_FLAG_MASK); - println(PreambleUtil.toString(seg, false)); - QuantilesItemsSketch.heapify(Double.class, seg, Comparator.naturalOrder(), serDe); - } - - @Test - public void checkPutMemory() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(String.class, 16, Comparator.naturalOrder()); - for (int i=0; i<40; i++) { - sketch.update(Integer.toString(i)); - } - final byte[] byteArr = new byte[200]; - final MemorySegment seg = MemorySegment.ofArray(byteArr); - sketch.putIntoMemorySegment(seg, new ArrayOfStringsSerDe()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkPutMemoryException() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(String.class, 16, Comparator.naturalOrder()); - for (int i=0; i<40; i++) { - sketch.update(Integer.toString(i)); - } - final byte[] byteArr = new byte[100]; - final MemorySegment seg = MemorySegment.ofArray(byteArr); - sketch.putIntoMemorySegment(seg, new ArrayOfStringsSerDe()); - } - - @Test - public void checkPMFonEmpty() { - final QuantilesItemsSketch iss = buildStringIS(32, 32); - final double[] ranks = {}; - final String[] qOut = iss.getQuantiles(ranks); - println("qOut: "+qOut.length); - assertEquals(qOut.length, 0); - final double[] cdfOut = iss.getCDF(new String[0]); - println("cdfOut: "+cdfOut.length); - assertEquals(cdfOut[0], 1.0, 0.0); - } - - @Test - public void checkToFromByteArray() { - checkToFromByteArray2(128, 1300); //generates a pattern of 5 -> 101 - checkToFromByteArray2(4, 7); - checkToFromByteArray2(4, 8); - checkToFromByteArray2(4, 9); - } - - @Test - public void getRankAndGetCdfConsistency() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Integer.class, Comparator.naturalOrder()); - final int n = 1_000_000; - final Integer[] values = new Integer[n]; - for (int i = 0; i < n; i++) { - sketch.update(i); - values[i] = i; - } - { // inclusive = false (default) - final double[] ranks = sketch.getCDF(values); - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i]), 0.00001, "CDF vs rank for value " + i); - } - } - { // inclusive = true - final double[] ranks = sketch.getCDF(values, INCLUSIVE); - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i], INCLUSIVE), 0.00001, "CDF vs rank for value " + i); - } - } - } - - @Test - public void getRankAndGetCdfConsistencyReverseComparator() { - final QuantilesItemsSketch sketch = - QuantilesItemsSketch.getInstance(Integer.class, Comparator.naturalOrder().reversed()); - final int n = 1_000_000; - final Integer[] values = new Integer[n]; - for (int i = 0; i < n; i++) { - sketch.update(i); - values[i] = i; - } - Arrays.sort(values, sketch.getComparator()); - final double[] ranks = sketch.getCDF(values); - for (int i = 0; i < n; i++) { - assertEquals(ranks[i], sketch.getRank(values[i]), 0.00001, "CDF vs rank for value " + i); - } - } - - @Test - public void checkBounds() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Double.class, Comparator.naturalOrder()); - for (int i = 0; i < 1000; i++) { - sketch.update((double)i); - } - final double eps = sketch.getNormalizedRankError(false); - final double est = sketch.getQuantile(0.5); - final double ub = sketch.getQuantileUpperBound(0.5); - final double lb = sketch.getQuantileLowerBound(0.5); - assertEquals(ub, (double)sketch.getQuantile(.5 + eps)); - assertEquals(lb, (double)sketch.getQuantile(0.5 - eps)); - println("Ext : " + est); - println("UB : " + ub); - println("LB : " + lb); - } - - @Test - public void checkGetKFromEqs() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Double.class, Comparator.naturalOrder()); - final int k = sketch.getK(); - final double eps = QuantilesItemsSketch.getNormalizedRankError(k, false); - final double epsPmf = QuantilesItemsSketch.getNormalizedRankError(k, true); - final int kEps = QuantilesItemsSketch.getKFromEpsilon(eps, false); - final int kEpsPmf = QuantilesItemsSketch.getKFromEpsilon(epsPmf, true); - assertEquals(kEps, k); - assertEquals(kEpsPmf, k); - } - - private static void checkToFromByteArray2(final int k, final int n) { - final QuantilesItemsSketch is = buildStringIS(k, n); - byte[] byteArr; - MemorySegment seg; - QuantilesItemsSketch is2; - final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - - //ordered - byteArr = is.toByteArray(true, serDe); - seg = MemorySegment.ofArray(byteArr); - is2 = QuantilesItemsSketch.heapify(String.class, seg, Comparator.naturalOrder(), serDe); - for (double f = 0.1; f < 0.95; f += 0.1) { - assertEquals(is.getQuantile(f), is2.getQuantile(f)); - } - - //Not-ordered - byteArr = is.toByteArray(false, serDe); - seg = MemorySegment.ofArray(byteArr); - is2 = QuantilesItemsSketch.heapify(String.class, seg, Comparator.naturalOrder(), serDe); - for (double f = 0.1; f < 0.95; f += 0.1) { - assertEquals(is.getQuantile(f), is2.getQuantile(f)); - } - } - - static QuantilesItemsSketch buildStringIS(final int k, final int n) { - return buildStringIS(k, n, 0); - } - - static QuantilesItemsSketch buildStringIS(final int k, final int n, final int start) { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(String.class, k, Comparator.naturalOrder()); - for (int i = 0; i < n; i++) { - sketch.update(Integer.toString(i + start)); - } - return sketch; - } - - @Test - public void sortedView() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Integer.class, Comparator.naturalOrder()); - sketch.update(3); - sketch.update(1); - sketch.update(2); - { // cumulative inclusive - final GenericSortedView view = sketch.getSortedView(); - final GenericSortedViewIterator it = view.iterator(); - assertEquals(it.next(), true); - assertEquals(it.getQuantile(), 1); - assertEquals(it.getWeight(), 1); - assertEquals(it.getNaturalRank(INCLUSIVE), 1); - assertEquals(it.next(), true); - assertEquals(it.getQuantile(), 2); - assertEquals(it.getWeight(), 1); - assertEquals(it.getNaturalRank(INCLUSIVE), 2); - assertEquals(it.next(), true); - assertEquals(it.getQuantile(), 3); - assertEquals(it.getWeight(), 1); - assertEquals(it.getNaturalRank(INCLUSIVE), 3); - assertEquals(it.next(), false); - } - } - - @Test - public void checkIssue484() { - final Boolean[] items = { true,false,true,false,true,false,true,false,true,false }; - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Boolean.class, Boolean::compareTo); - for (int i = 0; i < items.length; i++) { sketch.update(items[i]); } - final byte[] serialized = sketch.toByteArray(new ArrayOfBooleansSerDe()); - final QuantilesItemsSketch deserialized = - QuantilesItemsSketch.heapify(Boolean.class, MemorySegment.ofArray(serialized), Boolean::compareTo, new ArrayOfBooleansSerDe()); - checkSketchesEqual(sketch, deserialized); - } - - private static void checkSketchesEqual(final QuantilesItemsSketch expected, final QuantilesItemsSketch actual) { - final ItemsSketchSortedView expSV = expected.getSortedView(); - final ItemsSketchSortedView actSV = actual.getSortedView(); - final int N = (int)actSV.getN(); - final long[] expCumWts = expSV.getCumulativeWeights(); - final Boolean[] expItemsArr = (Boolean[])expSV.getQuantiles(); - final long[] actCumWts = actSV.getCumulativeWeights(); - final Boolean[] actItemsArr = (Boolean[])actSV.getQuantiles(); - printf("%3s %8s %8s\n", "i","Actual", "Expected"); - for (int i = 0; i < N; i++) { - printf("%3d %8s %8s\n", i, actItemsArr[i].toString(), expItemsArr[i].toString()); - } - assertEquals(actCumWts, expCumWts); - assertEquals(actItemsArr, expItemsArr); - } - - @Test - //There is no guarantee that BaseBuffer is sorted after a merge. - //The issue is, during a merge, BB must be sorted prior to a compaction to a higher level. - //Otherwise the higher levels would not be sorted properly. - public void checkL0SortDuringMergeIssue527() throws NumberFormatException { - final Random rand = new Random(); - final QuantilesItemsSketch sk1 = QuantilesItemsSketch.getInstance(String.class, 8, Comparator.reverseOrder()); - final QuantilesItemsSketch sk2 = QuantilesItemsSketch.getInstance(String.class, 8, Comparator.reverseOrder()); - final int n = 24; //don't change this - for (int i = 1; i <= n; i++ ) { - final int j = rand.nextInt(n) + 1; - sk1.update(getString(j, 3)); - sk2.update(getString(j +100, 3)); - } - final int k = 8; - final QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(String.class, k, Comparator.reverseOrder()); - union.union(sk1); - union.union(sk2); - final QuantilesItemsSketch sk3 = union.getResult(); - println(sk3.toString(true, true)); //L0 and above should be sorted in reverse. Ignore BB. - - final QuantilesGenericSketchIteratorAPI itr = sk3.iterator(); - itr.next(); - int prev = Integer.parseInt(itr.getQuantile().trim()); - for (int i = 1; i < (2 * k); i++) { - if (itr.next()) { - final int v = Integer.parseInt(itr.getQuantile().trim()); - if (i == k) { - prev = Integer.parseInt(itr.getQuantile().trim()); - continue; - } - assertTrue(v <= prev); - prev = v; - } - } - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/ItemsUnionTest.java b/src/test/java/org/apache/datasketches/quantiles/ItemsUnionTest.java deleted file mode 100644 index 27b3f7083..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/ItemsUnionTest.java +++ /dev/null @@ -1,403 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.quantiles.PreambleUtil.DEFAULT_K; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.apache.datasketches.common.ArrayOfLongsSerDe; -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class ItemsUnionTest { - - @Test - public void nullAndEmpty() { - final QuantilesItemsSketch emptySk = QuantilesItemsSketch.getInstance(Integer.class, Comparator.naturalOrder()); - final QuantilesItemsSketch validSk = QuantilesItemsSketch.getInstance(Integer.class, Comparator.naturalOrder()); - QuantilesItemsSketch result; - validSk.update(1); - QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(Integer.class, Comparator.naturalOrder()); - union.union(validSk); - - union = QuantilesItemsUnion.initialize(emptySk); - // internal sketch is empty at this point - union.union((QuantilesItemsSketch) null); - union.union(emptySk); - Assert.assertTrue(union.isEmpty()); - Assert.assertEquals(union.getMaxK(), DEFAULT_K); - Assert.assertEquals(union.getEffectiveK(), DEFAULT_K); - result = union.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getN(), 0); - try { result.getMinItem(); fail(); } catch (final IllegalArgumentException e) {} - try { result.getMaxItem(); fail(); } catch (final IllegalArgumentException e) {} - union.union(validSk); - - union.reset(); - // internal sketch is null again - union.union((QuantilesItemsSketch) null); - result = union.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getN(), 0); - try { result.getMinItem(); fail(); } catch (final IllegalArgumentException e) {} - try { result.getMaxItem(); fail(); } catch (final IllegalArgumentException e) {} - - // internal sketch is not null again because getResult() instantiated it - union.union(QuantilesItemsSketch.getInstance(Integer.class, Comparator.naturalOrder())); - result = union.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getN(), 0); - try { result.getMinItem(); fail(); } catch (final IllegalArgumentException e) {} - try { result.getMaxItem(); fail(); } catch (final IllegalArgumentException e) {} - - union.reset(); - // internal sketch is null again - union.union(QuantilesItemsSketch.getInstance(Integer.class, Comparator.naturalOrder())); - result = union.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getN(), 0); - try { result.getMinItem(); fail(); } catch (final IllegalArgumentException e) {} - try { result.getMaxItem(); fail(); } catch (final IllegalArgumentException e) {} - } - - @Test - public void nullAndEmptyInputsToNonEmptyUnion() { - final QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(Integer.class, 128, Comparator.naturalOrder()); - union.update(1); - QuantilesItemsSketch result = union.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getN(), 1); - Assert.assertEquals(result.getMinItem(), Integer.valueOf(1)); - Assert.assertEquals(result.getMaxItem(), Integer.valueOf(1)); - - union.union((QuantilesItemsSketch) null); - result = union.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getN(), 1); - Assert.assertEquals(result.getMinItem(), Integer.valueOf(1)); - Assert.assertEquals(result.getMaxItem(), Integer.valueOf(1)); - - union.union(QuantilesItemsSketch.getInstance(Integer.class, Comparator.naturalOrder())); - result = union.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getN(), 1); - Assert.assertEquals(result.getMinItem(), Integer.valueOf(1)); - Assert.assertEquals(result.getMaxItem(), Integer.valueOf(1)); - } - - @Test - public void basedOnSketch() { - final Comparator comp = Comparator.naturalOrder(); - final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(String.class, comp); - QuantilesItemsUnion union = QuantilesItemsUnion.initialize(sketch); - union.reset(); - final byte[] byteArr = sketch.toByteArray(serDe); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - union = QuantilesItemsUnion.initializeWithMemorySegment(String.class, seg, comp, serDe); - Assert.assertEquals(byteArr.length, 8); - union.reset(); - } - - @Test - public void sameK() { - final QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(Long.class, 128, Comparator.naturalOrder()); - QuantilesItemsSketch result = union.getResult(); - Assert.assertEquals(result.getN(), 0); - try { result.getMinItem(); fail(); } catch (final IllegalArgumentException e) { } - try { result.getMaxItem(); fail(); } catch (final IllegalArgumentException e) { } - - for (int i = 1; i <= 1000; i++) { union.update((long) i); } - result = union.getResult(); - Assert.assertEquals(result.getN(), 1000); - Assert.assertEquals(result.getMinItem(), Long.valueOf(1)); - Assert.assertEquals(result.getMaxItem(), Long.valueOf(1000)); - Assert.assertEquals(result.getQuantile(0.5), 500, 17); // ~1.7% normalized rank error - - final QuantilesItemsSketch sketch1 = QuantilesItemsSketch.getInstance(Long.class, Comparator.naturalOrder()); - for (int i = 1001; i <= 2000; i++) { sketch1.update((long) i); } - union.union(sketch1); - result = union.getResult(); - Assert.assertEquals(result.getN(), 2000); - Assert.assertEquals(result.getMinItem(), Long.valueOf(1)); - Assert.assertEquals(result.getMaxItem(), Long.valueOf(2000)); - Assert.assertEquals(result.getQuantile(0.5), 1000, 34); // ~1.7% normalized rank error - - final QuantilesItemsSketch sketch2 = QuantilesItemsSketch.getInstance(Long.class, Comparator.naturalOrder()); - for (int i = 2001; i <= 3000; i++) { sketch2.update((long) i); } - final ArrayOfItemsSerDe serDe = new ArrayOfLongsSerDe(); - union.union(MemorySegment.ofArray(sketch2.toByteArray(serDe)), serDe); - result = union.getResultAndReset(); - Assert.assertNotNull(result); - Assert.assertEquals(result.getN(), 3000); - Assert.assertEquals(result.getMinItem(), Long.valueOf(1)); - Assert.assertEquals(result.getMaxItem(), Long.valueOf(3000)); - Assert.assertEquals(result.getQuantile(0.5), 1500, 51); // ~1.7% normalized rank error - - result = union.getResult(); - Assert.assertEquals(result.getN(), 0); - try { result.getMinItem(); fail(); } catch (final IllegalArgumentException e) { } - try { result.getMaxItem(); fail(); } catch (final IllegalArgumentException e) { } - } - - @Test - public void differentK() { - final QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(Long.class, 512, Comparator.naturalOrder()); - QuantilesItemsSketch result = union.getResult(); - Assert.assertEquals(result.getN(), 0); - try { result.getMinItem(); fail(); } catch (final IllegalArgumentException e) {} - try { result.getMaxItem(); fail(); } catch (final IllegalArgumentException e) {} - - for (int i = 1; i <= 10000; i++) { union.update((long) i); } - result = union.getResult(); - Assert.assertEquals(result.getK(), 512); - Assert.assertEquals(result.getN(), 10000); - Assert.assertEquals(result.getMinItem(), Long.valueOf(1)); - Assert.assertEquals(result.getMaxItem(), Long.valueOf(10000)); - Assert.assertEquals(result.getQuantile(0.5), 5000, 50); // ~0.5% normalized rank error - - final QuantilesItemsSketch sketch1 = QuantilesItemsSketch.getInstance(Long.class, 256, Comparator.naturalOrder()); - for (int i = 10001; i <= 20000; i++) { sketch1.update((long) i); } - union.union(sketch1); - result = union.getResult(); - Assert.assertEquals(result.getK(), 256); - Assert.assertEquals(result.getN(), 20000); - Assert.assertEquals(result.getMinItem(), Long.valueOf(1)); - Assert.assertEquals(result.getMaxItem(), Long.valueOf(20000)); - Assert.assertEquals(result.getQuantile(0.5), 10000, 180); // ~0.9% normalized rank error - - final QuantilesItemsSketch sketch2 = QuantilesItemsSketch.getInstance(Long.class,128, Comparator.naturalOrder()); - for (int i = 20001; i <= 30000; i++) { sketch2.update((long) i); } - final ArrayOfItemsSerDe serDe = new ArrayOfLongsSerDe(); - union.union(MemorySegment.ofArray(sketch2.toByteArray(serDe)), serDe); - result = union.getResultAndReset(); - Assert.assertNotNull(result); - Assert.assertEquals(result.getK(), 128); - Assert.assertEquals(result.getN(), 30000); - Assert.assertEquals(result.getMinItem(), Long.valueOf(1)); - Assert.assertEquals(result.getMaxItem(), Long.valueOf(30000)); - Assert.assertEquals(result.getQuantile(0.5), 15000, 510); // ~1.7% normalized rank error - - result = union.getResult(); - Assert.assertEquals(result.getN(), 0); - try { result.getMinItem(); fail(); } catch (final IllegalArgumentException e) {} - try { result.getMaxItem(); fail(); } catch (final IllegalArgumentException e) {} - } - - @Test - public void differentLargerK() { - final QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(Long.class, 128, Comparator.naturalOrder()); - final QuantilesItemsSketch sketch1 = QuantilesItemsSketch.getInstance(Long.class, 256, Comparator.naturalOrder()); - union.union(sketch1); - Assert.assertEquals(union.getResult().getK(), 128); - sketch1.update(1L); - union.union(sketch1); - Assert.assertEquals(union.getResult().getK(), 128); - } - - @Test - public void differentSmallerK() { - final QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(Long.class, 128, Comparator.naturalOrder()); - final QuantilesItemsSketch sketch1 = QuantilesItemsSketch.getInstance(Long.class, 64, Comparator.naturalOrder()); - union.union(sketch1); //union empty, sketch1: empty - Assert.assertEquals(union.getResult().getK(), 128); //union: empty, k=128 - sketch1.update(1L); //union: empty, k=128; sketch: valid, k=64 - union.union(sketch1); - Assert.assertEquals(union.getResult().getK(), 128); - } - - @Test - public void toStringCrudeCheck() { - final QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(String.class, 128, Comparator.naturalOrder()); - union.update("a"); - final String brief = union.toString(); - final String full = union.toString(true, true); - Assert.assertTrue(brief.length() < full.length()); - } - - @Test - public void meNullOtherExactBiggerSmaller() { - final QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(Long.class, 16, Comparator.naturalOrder()); //me null - QuantilesItemsSketch skExact = buildIS(32, 31); //other is bigger, exact - union.union(skExact); - println(skExact.toString(true, true)); - println(union.toString(true, true)); - Assert.assertEquals(skExact.getQuantile(0.5), union.getResult().getQuantile(0.5), 0.0); - - union.reset(); - skExact = buildIS(8, 15); //other is smaller exact, - union.union(skExact); - println(skExact.toString(true, true)); - println(union.toString(true, true)); - Assert.assertEquals(skExact.getQuantile(0.5), union.getResult().getQuantile(0.5), 0.0); - } - - @Test - public void meNullOtherEstBiggerSmaller() { - final QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(Long.class, 16, Comparator.naturalOrder()); //me null - QuantilesItemsSketch skEst = buildIS(32, 64); //other is bigger, est - union.union(skEst); - Assert.assertEquals(union.getResult().getMinItem(), skEst.getMinItem(), 0.0); - Assert.assertEquals(union.getResult().getMaxItem(), skEst.getMaxItem(), 0.0); - - union.reset(); - skEst = buildIS(8, 64); //other is smaller est, - union.union(skEst); - Assert.assertEquals(union.getResult().getMinItem(), skEst.getMinItem(), 0.0); - Assert.assertEquals(union.getResult().getMaxItem(), skEst.getMaxItem(), 0.0); - } - - @Test - public void meEmptyOtherExactBiggerSmaller() { - final QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(Long.class, 16, Comparator.naturalOrder()); //me null - final QuantilesItemsSketch skEmpty = QuantilesItemsSketch.getInstance(Long.class, 64, Comparator.naturalOrder()); - union.union(skEmpty); //empty at k = 16 - QuantilesItemsSketch skExact = buildIS(32, 63); //bigger, exact - union.union(skExact); - Assert.assertEquals(union.getResult().getMinItem(), skExact.getMinItem(), 0.0); - Assert.assertEquals(union.getResult().getMaxItem(), skExact.getMaxItem(), 0.0); - - union.reset(); - union.union(skEmpty); //empty at k = 16 - skExact = buildIS(8, 15); //smaller, exact - union.union(skExact); - Assert.assertEquals(union.getResult().getMinItem(), skExact.getMinItem(), 0.0); - Assert.assertEquals(union.getResult().getMaxItem(), skExact.getMaxItem(), 0.0); - } - - @Test - public void meEmptyOtherEstBiggerSmaller() { - final QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(Long.class, 16, Comparator.naturalOrder()); //me null - final QuantilesItemsSketch skEmpty = QuantilesItemsSketch.getInstance(Long.class, 64, Comparator.naturalOrder()); - union.union(skEmpty); //empty at k = 16 - QuantilesItemsSketch skExact = buildIS(32, 64); //bigger, est - union.union(skExact); - Assert.assertEquals(union.getResult().getMinItem(), skExact.getMinItem(), 0.0); - Assert.assertEquals(union.getResult().getMaxItem(), skExact.getMaxItem(), 0.0); - - union.reset(); - union.union(skEmpty); //empty at k = 16 - skExact = buildIS(8, 16); //smaller, est - union.union(skExact); - Assert.assertEquals(union.getResult().getMinItem(), skExact.getMinItem(), 0.0); - Assert.assertEquals(union.getResult().getMaxItem(), skExact.getMaxItem(), 0.0); - } - - @Test - public void checkMergeIntoEqualKs() { - final QuantilesItemsSketch skEmpty1 = buildIS(32, 0); - final QuantilesItemsSketch skEmpty2 = buildIS(32, 0); - ItemsMergeImpl.mergeInto(skEmpty1, skEmpty2); - try { skEmpty2.getMinItem(); fail(); } catch (final IllegalArgumentException e) {} - try { skEmpty2.getMaxItem(); fail(); } catch (final IllegalArgumentException e) {} - - QuantilesItemsSketch skValid1, skValid2; - int n = 64; - skValid1 = buildIS(32, n, 0); - skValid2 = buildIS(32, 0, 0); //empty - ItemsMergeImpl.mergeInto(skValid1, skValid2); - Assert.assertEquals(skValid2.getMinItem(), 0.0, 0.0); - Assert.assertEquals(skValid2.getMaxItem(), n - 1.0, 0.0); - - skValid1 = buildIS(32, 0, 0); //empty - skValid2 = buildIS(32, n, 0); - ItemsMergeImpl.mergeInto(skValid1, skValid2); - Assert.assertEquals(skValid2.getMinItem(), 0.0, 0.0); - Assert.assertEquals(skValid2.getMaxItem(), n - 1.0, 0.0); - - skValid1 = buildIS(32, n, 0); - skValid2 = buildIS(32, n, n); - ItemsMergeImpl.mergeInto(skValid1, skValid2); - Assert.assertEquals(skValid2.getMinItem(), 0.0, 0.0); - Assert.assertEquals(skValid2.getMaxItem(), (2 * n) - 1.0, 0.0); - - n = 512; - skValid1 = buildIS(32, n, 0); - skValid2 = buildIS(32, n, n); - ItemsMergeImpl.mergeInto(skValid1, skValid2); - Assert.assertEquals(skValid2.getMinItem(), 0.0, 0.0); - Assert.assertEquals(skValid2.getMaxItem(), (2 * n) - 1.0, 0.0); - - skValid1 = buildIS(32, n, 0); - skValid2 = buildIS(32, n, n); - ItemsMergeImpl.mergeInto(skValid2, skValid1); - Assert.assertEquals(skValid1.getMinItem(), 0.0, 0.0); - Assert.assertEquals(skValid1.getMaxItem(), (2 * n) - 1.0, 0.0); - } - - @Test - public void checkDownSamplingMergeIntoUnequalKs() { - QuantilesItemsSketch sk1, sk2; - final int n = 128; - sk1 = buildIS(64, n, 0); - sk2 = buildIS(32, n, 128); - ItemsMergeImpl.downSamplingMergeInto(sk1, sk2); - - sk1 = buildIS(64, n, 128); - sk2 = buildIS(32, n, 0); - ItemsMergeImpl.downSamplingMergeInto(sk1, sk2); - } - - @Test - public void checkToByteArray() { - final int k = 32; - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - QuantilesItemsUnion union = QuantilesItemsUnion.getInstance(Long.class, k, Comparator.naturalOrder()); - byte[] bytesOut = union.toByteArray(serDe); - Assert.assertEquals(bytesOut.length, 8); - Assert.assertTrue(union.isEmpty()); - - final byte[] byteArr = buildIS(k, (2 * k) + 5).toByteArray(serDe); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - union = QuantilesItemsUnion.initializeWithMemorySegment(Long.class, seg, Comparator.naturalOrder(), serDe); - bytesOut = union.toByteArray(serDe); - Assert.assertEquals(bytesOut.length, byteArr.length); - Assert.assertEquals(bytesOut, byteArr); // assumes consistent internal use of toByteArray() - } - - private static QuantilesItemsSketch buildIS(final int k, final int n) { - return buildIS(k, n, 0); - } - - private static QuantilesItemsSketch buildIS(final int k, final int n, final int startV) { - final QuantilesItemsSketch is = QuantilesItemsSketch.getInstance(Long.class, k, Comparator.naturalOrder()); - for (long i = 0; i < n; i++) { is.update(i + startV); } - return is; - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param o value to print - */ - static void println(final Object o) { - //System.out.println(o.toString()); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/PreambleUtilTest.java b/src/test/java/org/apache/datasketches/quantiles/PreambleUtilTest.java deleted file mode 100644 index 4ea915c75..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/PreambleUtilTest.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.common.Util.clear; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFamilyID; -import static org.apache.datasketches.quantiles.PreambleUtil.extractFlags; -import static org.apache.datasketches.quantiles.PreambleUtil.extractK; -import static org.apache.datasketches.quantiles.PreambleUtil.extractMaxDouble; -import static org.apache.datasketches.quantiles.PreambleUtil.extractMinDouble; -import static org.apache.datasketches.quantiles.PreambleUtil.extractN; -import static org.apache.datasketches.quantiles.PreambleUtil.extractPreLongs; -import static org.apache.datasketches.quantiles.PreambleUtil.extractSerVer; -import static org.apache.datasketches.quantiles.PreambleUtil.insertFamilyID; -import static org.apache.datasketches.quantiles.PreambleUtil.insertFlags; -import static org.apache.datasketches.quantiles.PreambleUtil.insertK; -import static org.apache.datasketches.quantiles.PreambleUtil.insertMaxDouble; -import static org.apache.datasketches.quantiles.PreambleUtil.insertMinDouble; -import static org.apache.datasketches.quantiles.PreambleUtil.insertN; -import static org.apache.datasketches.quantiles.PreambleUtil.insertPreLongs; -import static org.apache.datasketches.quantiles.PreambleUtil.insertSerVer; -import static org.testng.Assert.assertEquals; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -public class PreambleUtilTest { - - @Test - public void checkInsertsAndExtracts() { - final int bytes = 32; - try (Arena arena = Arena.ofConfined()) { - final MemorySegment offHeapSeg = arena.allocate(bytes); - final MemorySegment onHeapSeg = MemorySegment.ofArray(new byte[bytes]); - - clear(onHeapSeg); - clear(offHeapSeg); - - //BYTES - int v = 0XFF; - int onH, offH; - - //PREAMBLE_LONGS_BYTE; - insertPreLongs(onHeapSeg, v); - onH = extractPreLongs(onHeapSeg); - assertEquals(onH, v); - - insertPreLongs(offHeapSeg, v); - offH = extractPreLongs(offHeapSeg); - assertEquals(offH, v); - clear(onHeapSeg); - clear(offHeapSeg); - - //SER_VER_BYTE; - insertSerVer(onHeapSeg, v); - onH = extractSerVer(onHeapSeg); - assertEquals(onH, v); - - insertSerVer(offHeapSeg, v); - offH = extractSerVer(offHeapSeg); - assertEquals(offH, v); - clear(onHeapSeg); - clear(offHeapSeg); - - //FAMILY_BYTE; - insertFamilyID(onHeapSeg, v); - onH = extractFamilyID(onHeapSeg); - assertEquals(onH, v); - - insertFamilyID(offHeapSeg, v); - offH = extractFamilyID(offHeapSeg); - assertEquals(offH, v); - clear(onHeapSeg); - clear(offHeapSeg); - - //FLAGS_BYTE; - insertFlags(onHeapSeg, v); - onH = extractFlags(onHeapSeg); - assertEquals(onH, v); - - insertFlags(offHeapSeg, v); - offH = extractFlags(offHeapSeg); - assertEquals(offH, v); - clear(onHeapSeg); - clear(offHeapSeg); - - //SHORTS - v = 0XFFFF; - - //K_SHORT; - insertK(onHeapSeg, v); - onH = extractK(onHeapSeg); - assertEquals(onH, v); - - insertK(offHeapSeg, v); - offH = extractK(offHeapSeg); - assertEquals(offH, v); - clear(onHeapSeg); - clear(offHeapSeg); - - //LONGS - - //N_LONG; - long onHL, offHL; - final long vL = 1L << 30; - insertN(onHeapSeg, vL); - onHL = extractN(onHeapSeg); - assertEquals(onHL, vL); - - insertN(offHeapSeg, vL); - offHL = extractN(offHeapSeg); - assertEquals(offHL, vL); - clear(onHeapSeg); - clear(offHeapSeg); - - //DOUBLES - - //MIN_DOUBLE; - double onHD, offHD; - final double vD = 1L << 40; - - insertMinDouble(onHeapSeg, vD); - onHD = extractMinDouble(onHeapSeg); - assertEquals(onHD, vD); - - insertMinDouble(offHeapSeg, vD); - offHD = extractMinDouble(offHeapSeg); - assertEquals(offHD, vD); - clear(onHeapSeg); - clear(offHeapSeg); - - //MAX_DOUBLE; - insertMaxDouble(onHeapSeg, vD); - onHD = extractMaxDouble(onHeapSeg); - assertEquals(onHD, vD); - - insertMaxDouble(offHeapSeg, vD); - offHD = extractMaxDouble(offHeapSeg); - assertEquals(offHD, vD); - clear(onHeapSeg); - clear(offHeapSeg); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Test - public void checkToString() { - final int k = PreambleUtil.DEFAULT_K; - final int n = 1000000; - final UpdatableQuantilesDoublesSketch qs = QuantilesDoublesSketch.builder().setK(k).build(); - for (int i=0; i sk = QuantilesItemsSketch.getInstance(String.class, new Comparator() { - @Override - public int compare(final String s1, final String s2) { - try { - final int i1 = Integer.parseInt(s1); - final int i2 = Integer.parseInt(s2); - return Integer.compare(i1,i2); - } catch (final NumberFormatException e) { - throw new RuntimeException(e); - } - } - }); - for (int i = 1; i <= n; i++) { - sk.update(Integer.toString(i)); - } - if (n > 0) { - assertEquals(sk.getMinItem(), "1"); - assertEquals(sk.getMaxItem(), Integer.toString(n)); - } - putBytesToJavaPath("quantiles_string_n" + n + "_java.sk", sk.toByteArray(new ArrayOfStringsSerDe())); - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void checkDoublesSketch() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] byteArr = getFileBytes(cppPath, "quantiles_double_n" + n + "_cpp.sk"); - final QuantilesDoublesSketch sk = QuantilesDoublesSketch.wrap(MemorySegment.ofArray(byteArr)); - assertTrue(n == 0 ? sk.isEmpty() : !sk.isEmpty()); - assertTrue(n > 128 ? sk.isEstimationMode() : !sk.isEstimationMode()); - assertEquals(sk.getN(), n); - if (n > 0) { - assertEquals(sk.getMinItem(), 1); - assertEquals(sk.getMaxItem(), n); - final QuantilesDoublesSketchIteratorAPI it = sk.iterator(); - long weight = 0; - while(it.next()) { - assertTrue(it.getQuantile() >= sk.getMinItem()); - assertTrue(it.getQuantile() <= sk.getMaxItem()); - weight += it.getWeight(); - } - assertEquals(weight, n); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void checkItemsSketchWithStrings() throws IOException { - // sketch contains numbers in strings to make meaningful assertions - final Comparator numericOrder = new Comparator() { - @Override - public int compare(final String s1, final String s2) { - try { - final int i1 = Integer.parseInt(s1); - final int i2 = Integer.parseInt(s2); - return Integer.compare(i1, i2); - } catch (final NumberFormatException e) { - throw new RuntimeException(e); - } - } - }; - final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] byteArr = getFileBytes(cppPath, "quantiles_string_n" + n + "_cpp.sk"); - final QuantilesItemsSketch sk = QuantilesItemsSketch.heapify( - String.class, - MemorySegment.ofArray(byteArr), - numericOrder, - new ArrayOfStringsSerDe() - ); - assertTrue(n == 0 ? sk.isEmpty() : !sk.isEmpty()); - assertTrue(n > 128 ? sk.isEstimationMode() : !sk.isEstimationMode()); - assertEquals(sk.getN(), n); - if (n > 0) { - assertEquals(sk.getMinItem(), "1"); - assertEquals(sk.getMaxItem(), Integer.toString(n)); - final QuantilesGenericSketchIteratorAPI it = sk.iterator(); - long weight = 0; - while(it.next()) { - assertTrue(numericOrder.compare(it.getQuantile(), sk.getMinItem()) >= 0); - assertTrue(numericOrder.compare(it.getQuantile(), sk.getMaxItem()) <= 0); - weight += it.getWeight(); - } - assertEquals(weight, n); - } - } - } - - @Test(groups = {CHECK_CPP_HISTORICAL_FILES}) - //fullPath: sketches/src/test/resources/Qk128_n50_v0.3.0.sk - //Median2: 26.0 - public void check030_50() { - final int n = 50; - final String ver = "0.3.0"; - final double expected = 26; - getAndCheck(ver, n, expected); - } - - @Test(groups = {CHECK_CPP_HISTORICAL_FILES}) - //fullPath: sketches/src/test/resources/Qk128_n1000_v0.3.0.sk - //Median2: 501.0 - public void check030_1000() { - final int n = 1000; - final String ver = "0.3.0"; - final double expected = 501; - getAndCheck(ver, n, expected); - } - - @Test(groups = {CHECK_CPP_HISTORICAL_FILES}) - //fullPath: sketches/src/test/resources/Qk128_n50_v0.6.0.sk - //Median2: 26.0 - public void check060_50() { - final int n = 50; - final String ver = "0.6.0"; - final double expected = 26; - getAndCheck(ver, n, expected); - } - - @Test(groups = {CHECK_CPP_HISTORICAL_FILES}) - //fullPath: sketches/src/test/resources/Qk128_n1000_v0.6.0.sk - //Median2: 501.0 - public void check060_1000() { - final int n = 1000; - final String ver = "0.6.0"; - final double expected = 501; - getAndCheck(ver, n, expected); - } - - @Test(groups = {CHECK_CPP_HISTORICAL_FILES}) - //fullPath: sketches/src/test/resources/Qk128_n50_v0.8.0.sk - //Median2: 26.0 - public void check080_50() { - final int n = 50; - final String ver = "0.8.0"; - final double expected = 26; - getAndCheck(ver, n, expected); - } - - @Test(groups = {CHECK_CPP_HISTORICAL_FILES}) - //fullPath: sketches/src/test/resources/Qk128_n1000_v0.8.0.sk - //Median2: 501.0 - public void check080_1000() { - final int n = 1000; - final String ver = "0.8.0"; - final double expected = 501; - getAndCheck(ver, n, expected); - } - - @Test(groups = {CHECK_CPP_HISTORICAL_FILES}) - //fullPath: sketches/src/test/resources/Qk128_n50_v0.8.3.sk - //Median2: 26.0 - public void check083_50() { - final int n = 50; - final String ver = "0.8.3"; - final double expected = 26; - getAndCheck(ver, n, expected); - } - - @Test(groups = {CHECK_CPP_HISTORICAL_FILES}) - //fullPath: sketches/src/test/resources/Qk128_n1000_v0.8.0.sk - //Median2: 501.0 - public void check083_1000() { - final int n = 1000; - final String ver = "0.8.3"; - final double expected = 501; - getAndCheck(ver, n, expected); - } - - private static void getAndCheck(final String ver, final int n, final double quantile) { - QuantilesDoublesSketch.rand.setSeed(131); //make deterministic - //create fileName - final int k = 128; - final double nf = 0.5; - final String fileName = String.format("Qk%d_n%d_v%s.sk", k, n, ver); - println("fullName: "+ fileName); - println("Old Median: " + quantile); - //Read File bytes - final byte[] byteArr = TestUtil.getFileBytes(resPath, fileName); - final MemorySegment srcSeg = MemorySegment.ofArray(byteArr); - - // heapify as update sketch - QuantilesDoublesSketch qs2 = UpdatableQuantilesDoublesSketch.heapify(srcSeg); - //Test the quantile - double q2 = qs2.getQuantile(nf, EXCLUSIVE); - println("New Median: " + q2); - Assert.assertEquals(q2, quantile, 0.0); - - // same thing with compact sketch - qs2 = HeapCompactDoublesSketch.heapifyInstance(srcSeg); - //Test the quantile - q2 = qs2.getQuantile(nf, EXCLUSIVE); - println("New Median: " + q2); - Assert.assertEquals(q2, quantile, 0.0); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - static void println(final Object o) { - if (o == null) { print(LS); } - else { print(o.toString() + LS); } - } - - /** - * @param o value to print - */ - static void print(final Object o) { - if (o != null) { - //System.out.print(o.toString()); //disable here - } - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/SerDeCompatibilityTest.java b/src/test/java/org/apache/datasketches/quantiles/SerDeCompatibilityTest.java deleted file mode 100644 index 7788c1a7b..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/SerDeCompatibilityTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import java.lang.foreign.MemorySegment; -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfDoublesSerDe; -import org.apache.datasketches.common.ArrayOfItemsSerDe; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class SerDeCompatibilityTest { - - private static final ArrayOfItemsSerDe serDe = new ArrayOfDoublesSerDe(); - - @Test - public void itemsToDoubles() { - final QuantilesItemsSketch sketch1 = QuantilesItemsSketch.getInstance(Double.class, Comparator.naturalOrder()); - for (int i = 1; i <= 500; i++) { sketch1.update((double) i); } - - final byte[] bytes = sketch1.toByteArray(serDe); - final UpdatableQuantilesDoublesSketch sketch2; - sketch2 = UpdatableQuantilesDoublesSketch.heapify(MemorySegment.ofArray(bytes)); - - for (int i = 501; i <= 1000; i++) { sketch2.update(i); } - Assert.assertEquals(sketch2.getN(), 1000); - Assert.assertTrue(sketch2.getNumRetained() < 1000); - Assert.assertEquals(sketch2.getMinItem(), 1.0); - Assert.assertEquals(sketch2.getMaxItem(), 1000.0); - // based on ~1.7% normalized rank error for this particular case - Assert.assertEquals(sketch2.getQuantile(0.5), 500.0, 17); - } - - @Test - public void doublesToItems() { - final UpdatableQuantilesDoublesSketch sketch1 = QuantilesDoublesSketch.builder().build(); //SerVer = 3 - for (int i = 1; i <= 500; i++) { sketch1.update(i); } - - final CompactQuantilesDoublesSketch cs = sketch1.compact(); - DoublesSketchTest.testSketchEquality(sketch1, cs); - //final byte[] bytes = sketch1.compact().toByteArray(); // must be compact - final byte[] bytes = cs.toByteArray(); // must be compact - - //reconstruct with QuantilesItemsSketch - final QuantilesItemsSketch sketch2 = QuantilesItemsSketch.heapify(Double.class, MemorySegment.ofArray(bytes), - Comparator.naturalOrder(), serDe); - - for (int i = 501; i <= 1000; i++) { sketch2.update((double) i); } - Assert.assertEquals(sketch2.getN(), 1000); - Assert.assertTrue(sketch2.getNumRetained() < 1000); - Assert.assertEquals((double)sketch2.getMinItem(), 1.0); - Assert.assertEquals((double)sketch2.getMaxItem(), 1000.0); - // based on ~1.7% normalized rank error for this particular case - Assert.assertEquals(sketch2.getQuantile(0.5), 500.0, 17); - } - -} diff --git a/src/test/java/org/apache/datasketches/quantiles/UtilTest.java b/src/test/java/org/apache/datasketches/quantiles/UtilTest.java deleted file mode 100644 index 3181a2619..000000000 --- a/src/test/java/org/apache/datasketches/quantiles/UtilTest.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantiles; - -import static org.apache.datasketches.quantiles.ClassicUtil.MIN_K; -import static org.apache.datasketches.quantiles.ClassicUtil.checkPreLongsFlagsCap; -import static org.apache.datasketches.quantiles.ClassicUtil.computeCombinedBufferItemCapacity; -import static org.apache.datasketches.quantiles.ClassicUtil.computeValidLevels; -import static org.apache.datasketches.quantiles.ClassicUtil.hiBitPos; -import static org.apache.datasketches.quantiles.ClassicUtil.lowestZeroBitStartingAt; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.Test; - -public class UtilTest { - - @Test - public void checkCombBufItemCapacity() { - final int k = 227; - final int capEl = computeCombinedBufferItemCapacity(k, 0); - assertEquals(capEl, 2 * MIN_K); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkThePreLongsFlagsCap() { - checkPreLongsFlagsCap(2, 0, 15L); - } - - @Test - public void checkHiBitPos() { - final int bitPos = hiBitPos(4096); - assertEquals(bitPos, 12); - } - - @Test - public void checkNumValidLevels() { - final long v = (1L << 32)-1L; - final int ones = computeValidLevels(v); - assertEquals(ones, 32); - } - - @Test - public void testPositionOfLowestZeroBitStartingAt() { - final int [] answers = {9, 8, 7, 7, 7, 4, 4, 4, 1, 1}; - final long v = 109L; - //println("IN: " + Long.toBinaryString(v)); - for (int i = 0, j = 9; i < 10; i++, j--) { - final int result = lowestZeroBitStartingAt(v, i); - //System.out.printf ("%d %d %d%n", i, result, answers[j]); - assertTrue (answers[j] == result); - } - } - - @Test - public void testPositionOfLowestZeroBitStartingAt2() { - final long bits = -1L; - final int startingBit = 70; //only low 6 bits are used - final int result = lowestZeroBitStartingAt(bits, startingBit); - assertEquals(result, 64); - } - -//The remainder of this file is a brute force test of corner cases - // for blockyTandemMergeSort. - - private static void assertMergeTestPrecondition(final double [] arr, final long [] brr, final int arrLen, final int blkSize) { - int violationsCount = 0; - for (int i = 0; i < (arrLen-1); i++) { - if (((i+1) % blkSize) == 0) { - continue; - } - if (arr[i] > arr[i+1]) { violationsCount++; } - } - - for (int i = 0; i < arrLen; i++) { - if (brr[i] != (long) (1e12 * (1.0 - arr[i]))) { - violationsCount++; - } - } - if (brr[arrLen] != 0) { violationsCount++; } - - assertEquals(violationsCount, 0); - } - - private static void assertMergeTestPostcondition(final double [] arr, final long [] brr, final int arrLen) { - int violationsCount = 0; - for (int i = 0; i < (arrLen-1); i++) { - if (arr[i] > arr[i+1]) { violationsCount++; } - } - - for (int i = 0; i < arrLen; i++) { - if (brr[i] != (long) (1e12 * (1.0 - arr[i]))) { - violationsCount++; - } - } - if (brr[arrLen] != 0) { violationsCount++; } - - assertEquals(violationsCount, 0); - } - - - private static double[] makeMergeTestInput(final int arrLen, final int blkSize) { - final double[] arr = new double[arrLen]; - - final double pick = Math.random (); - - for (int i = 0; i < arrLen; i++) { - if (pick < 0.01) { // every value the same - arr[i] = 0.3; - } - else if (pick < 0.02) { // ascending values - final int j = i+1; - final int denom = arrLen+1; - arr[i] = ((double) j) / ((double) denom); - } - else if (pick < 0.03) { // descending values - final int j = i+1; - final int denom = arrLen+1; - arr[i] = 1.0 - (((double) j) / ((double) denom)); - } - else { // random values - arr[i] = Math.random (); - } - } - - for (int start = 0; start < arrLen; start += blkSize) { - Arrays.sort (arr, start, Math.min (arrLen, start + blkSize)); - } - - return arr; - } - - private static long [] makeTheTandemArray(final double [] arr) { - final long [] brr = new long [arr.length + 1]; /* make it one longer, just like in the sketches */ - for (int i = 0; i < arr.length; i++) { - brr[i] = (long) (1e12 * (1.0 - arr[i])); /* it's a better test with the order reversed */ - } - brr[arr.length] = 0; - return brr; - } - - @Test - public void checkBlockyTandemMergeSort() { - testBlockyTandemMergeSort(10, 50); - } - - /** - * @param numTries number of tries - * @param maxArrLen maximum length of array size - */ - private static void testBlockyTandemMergeSort(final int numTries, final int maxArrLen) { - int arrLen = 0; - double[] arr = null; - for (arrLen = 0; arrLen <= maxArrLen; arrLen++) { - for (int blkSize = 1; blkSize <= (arrLen + 100); blkSize++) { - for (int tryno = 1; tryno <= numTries; tryno++) { - arr = makeMergeTestInput(arrLen, blkSize); - final long [] brr = makeTheTandemArray(arr); - assertMergeTestPrecondition(arr, brr, arrLen, blkSize); - QuantilesDoublesSketch.blockyTandemMergeSort(arr, brr, arrLen, blkSize); - /* verify sorted order */ - for (int i = 0; i < (arrLen-1); i++) { - assert arr[i] <= arr[i+1]; - } - assertMergeTestPostcondition(arr, brr, arrLen); - } - } - } - //System.out.printf ("Passed: testBlockyTandemMergeSort%n"); - } - -// we are retaining this stand-alone test because it can be more exhaustive - -// @SuppressWarnings("unused") -// private static void exhaustiveMain(String[] args) { -// assert (args.length == 2); -// int numTries = Integer.parseInt(args[0]); -// int maxArrLen = Integer.parseInt(args[1]); -// System.out.printf("Testing blockyTandemMergeSort%n"); -// for (int arrLen = 0; arrLen < maxArrLen; arrLen++) { -// for (int blkSize = 1; blkSize <= arrLen + 100; blkSize++) { -// System.out.printf ( -// "Testing %d times with arrLen = %d and blkSize = %d%n", numTries, arrLen, blkSize); -// for (int tryno = 1; tryno <= numTries; tryno++) { -// double[] arr = makeMergeTestInput(arrLen, blkSize); -// long[] brr = makeTheTandemArray(arr); -// assertMergeTestPrecondition(arr, brr, arrLen, blkSize); -// DoublesAuxiliary.blockyTandemMergeSort(arr, brr, arrLen, blkSize); -// assertMergeTestPostcondition(arr, brr, arrLen); -// } -// } -// } -// } -// -// public static void main(String[] args) { -// exhaustiveMain(new String[] {"10", "100"}); -// } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/quantilescommon/CrossCheckQuantilesTest.java b/src/test/java/org/apache/datasketches/quantilescommon/CrossCheckQuantilesTest.java deleted file mode 100644 index 06b011ea3..000000000 --- a/src/test/java/org/apache/datasketches/quantilescommon/CrossCheckQuantilesTest.java +++ /dev/null @@ -1,422 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.common.Util.longToFixedLengthString; -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueDoubleQuantile; -import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueDoubleRank; -import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueFloatQuantile; -import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueFloatRank; -import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueItemQuantile; -import static org.apache.datasketches.quantilescommon.LinearRanksAndQuantiles.getTrueItemRank; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -import static org.testng.Assert.assertEquals; - -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllDoublesSketch; -import org.apache.datasketches.kll.KllFloatsSketch; -import org.apache.datasketches.kll.KllItemsSketch; -import org.apache.datasketches.quantiles.QuantilesDoublesSketch; -import org.apache.datasketches.quantiles.QuantilesItemsSketch; -import org.apache.datasketches.quantiles.UpdatableQuantilesDoublesSketch; -import org.apache.datasketches.req.ReqSketch; -import org.testng.annotations.Test; - -/** - * This test suite runs a common set of tests against all of the quantiles-type sketches in the library. - * Although the unit tests for each of the sketches is quite extensive, the purpose of this test is to make - * sure that key corner cases are in fact handled the same way by all of the sketches. - * - *

These tests are not about estimation accuracy, per se, as each of the different quantile sketches have very - * different algorithms for selecting the data to be retained in the sketch and thus will have very different error - * properties. These tests are primarily interested in making sure that the internal search and comparison algorithms - * used within the sketches are producing the correct results for exact queries based on a chosen search - * criteria. The search criteria are selected from the enum {@link QuantileSearchCriteria}. The corner cases of - * interest here are to make sure that each of the search criteria behave correctly for the following.

- *
    - *
  • A sketch with a single value.
  • - *
  • A sketch with two identical values
  • - *
  • A sketch with multiple duplicates and where the duplicates have weights greater than one. - * Note that the case with weights greater than one is only tested via the Sorted Views. The data loaded into the - * sketches will all have weights of one.
  • - *
- * - * @author Lee Rhodes - */ -public class CrossCheckQuantilesTest { - private final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - private final Comparator comparator = Comparator.naturalOrder(); - private final static int k = 32; //all sketches are in exact mode - - //These test sets are specifically designed for the corner cases mentioned in the class javadoc. - // Please don't mess with them unless you know what you are doing. - //These sets must start with 10 and be multiples of 10. - final float[][] svFValues = - { - {10}, //set 0 - {10,10}, //set 1 - {10,20,30,40}, //set 2 - {10,20,20,30,30,30,40,50}, //set 3 - {10,10,20,20,30,30,40,40} //set 4 - }; - - final double[][] svDValues = - { - {10}, - {10,10}, - {10,20,30,40}, - {10,20,20,30,30,30,40,50}, - {10,10,20,20,30,30,40,40} - }; - - final String[][] svIValues = - { - {"10"}, - {"10","10"}, - {"10","20","30","40"}, - {"10","20","20","30","30","30","40","50"}, - {"10","10","20","20","30","30","40","40"} - }; - - //these are value weights and will be converted to cumulative. - final long[][] svWeights = - { - {1}, - {1,1}, - {2,2,2,2}, - {2,2,2,2,2,2,2,2}, - {2,1,2,1,2,1,2,1} - }; - - final float[] svMaxFValues = { 10, 10, 40, 50, 40 }; - final float[] svMinFValues = { 10, 10, 10, 10, 10 }; - final double[] svMaxDValues = { 10, 10, 40, 50, 40 }; - final double[] svMinDValues = { 10, 10, 10, 10, 10 }; - final String[] svMaxIValues = { "10", "10", "40", "50", "40" }; - final String[] svMinIValues = { "10", "10", "10", "10", "10" }; - - - int numSets; - - long[][] svCumWeights; - - long[] totalN; - - float[][] skFStreamValues; - double[][] skDStreamValues; - String[][] skIStreamValues; - - ReqSketch reqFloatsSk = null; - KllFloatsSketch kllFloatsSk = null; - KllDoublesSketch kllDoublesSk = null; - UpdatableQuantilesDoublesSketch classicDoublesSk = null; - KllItemsSketch kllItemsSk = null; - QuantilesItemsSketch itemsSk = null; - - FloatsSketchSortedView floatsSV = null; - DoublesSketchSortedView doublesSV = null; - ItemsSketchSortedView classicItemsSV = null; - ItemsSketchSortedView kllItemsSV = null; - - public CrossCheckQuantilesTest() {} - - @Test - public void runTests() throws Exception { - buildDataSets(); - for (int set = 0; set < numSets; set++) { - buildSVs(set); - buildSketches(set); - println(""); - println("TEST getRank, Set " + set + ", all Criteria, across all sketches and their Sorted Views:"); - checkGetRank(set, INCLUSIVE); - checkGetRank(set, EXCLUSIVE); - println(""); - println("TEST getQuantile, Set " + set + ", all Criteria, across all sketches and their Sorted Views:"); - checkGetQuantile(set, INCLUSIVE); - checkGetQuantile(set, EXCLUSIVE); - } - } - - private void checkGetRank(final int set, final QuantileSearchCriteria crit) { - double trueRank; - double testRank; - - println(LS + "FLOATS getRank Test SV vs Sk"); - final float maxFloatvalue = getMaxFloatValue(set); - for (float v = 5f; v <= (maxFloatvalue + 5f); v += 5f) { - trueRank = getTrueFloatRank(svCumWeights[set], svFValues[set],v, crit); - - testRank = floatsSV.getRank(v, crit); - assertEquals(testRank, trueRank); - testRank = reqFloatsSk.getRank(v, crit); - assertEquals(testRank, trueRank); - testRank = kllFloatsSk.getRank(v, crit); - assertEquals(testRank, trueRank); - - println("Floats set: " + set + ", value: " + v + ", rank: " + trueRank + ", crit: " + crit.toString()); - } - - println(LS + "DOUBLES getRank Test SV vs Sk"); - final double maxDoubleValue = getMaxDoubleValue(set); - for (double v = 5; v <= (maxDoubleValue + 5); v += 5) { - trueRank = getTrueDoubleRank(svCumWeights[set], svDValues[set],v, crit); - - testRank = doublesSV.getRank(v, crit); - assertEquals(testRank, trueRank); - testRank = kllDoublesSk.getRank(v, crit); - assertEquals(testRank, trueRank); - testRank = classicDoublesSk.getRank(v, crit); - assertEquals(testRank, trueRank); - - println("Doubles set: " + set + ", value: " + v + ", rank: " + trueRank + ", crit: " + crit.toString()); - } - - println(LS + "ITEMS getRank Test SV vs Sk"); - int maxItemValue; - try { maxItemValue = Integer.parseInt(getMaxItemValue(set)); } - catch (final NumberFormatException e) { throw new SketchesArgumentException(e.toString()); } - for (int v = 5; v <= (maxItemValue + 5); v += 5) { - final String s = longToFixedLengthString(v, 2); - trueRank = getTrueItemRank(svCumWeights[set], svIValues[set], s, crit, comparator); - - testRank = kllItemsSV.getRank(s, crit); - assertEquals(testRank, trueRank); - testRank = kllItemsSk.getRank(s, crit); - assertEquals(testRank, trueRank); - testRank = classicItemsSV.getRank(s, crit); - assertEquals(testRank, trueRank); - testRank = itemsSk.getRank(s, crit); - assertEquals(testRank, trueRank); - - println("Items set: " + set + ", value: " + s + ", rank: " + trueRank + ", crit: " + crit.toString()); - } - } - - private void checkGetQuantile(final int set, final QuantileSearchCriteria crit) { - final int twoN = (int)totalN[set] * 2; - final double dTwoN = twoN; - float trueFQ; - float testFQ; - - println(LS + "FLOATS getQuantile Test SV vs Sk"); - for (int i = 0; i <= twoN; i++) { - final double normRank = i / dTwoN; - trueFQ = getTrueFloatQuantile(svCumWeights[set], svFValues[set], normRank, crit); - - testFQ = floatsSV.getQuantile(normRank, crit); - assertEquals(testFQ, trueFQ); - testFQ = reqFloatsSk.getQuantile(normRank, crit); - assertEquals(testFQ, trueFQ); - testFQ = kllFloatsSk.getQuantile(normRank, crit); - assertEquals(testFQ, trueFQ); - - println("Floats set: " + set + ", rank: " + normRank + ", Q: " + trueFQ + ", crit: " + crit.toString()); - } - - println(LS + "DOUBLES getQuantile Test SV vs Sk"); - double trueDQ; - double testDQ; - for (int i = 0; i <= twoN; i++) { - final double normRank = i / dTwoN; - trueDQ = getTrueDoubleQuantile(svCumWeights[set], svDValues[set], normRank, crit); - - testDQ = doublesSV.getQuantile(normRank, crit); - assertEquals(testDQ, trueDQ); - testDQ = kllDoublesSk.getQuantile(normRank, crit); - assertEquals(testDQ, trueDQ); - testDQ = classicDoublesSk.getQuantile(normRank, crit); - assertEquals(testDQ, trueDQ); - - println("Doubles set: " + set + ", rank: " + normRank + ", Q: " + trueDQ + ", crit: " + crit.toString()); - } - - println(LS + "ITEMS getQuantile Test SV vs Sk"); - String trueIQ; - String testIQ; - for (int i = 0; i <= twoN; i++) { - final double normRank = i / dTwoN; - trueIQ = getTrueItemQuantile(svCumWeights[set], svIValues[set], normRank, crit); - - testIQ = kllItemsSV.getQuantile(normRank, crit); - assertEquals(testIQ, trueIQ); - testIQ = kllItemsSk.getQuantile(normRank, crit); - assertEquals(testIQ, trueIQ); - testIQ = classicItemsSV.getQuantile(normRank, crit); - assertEquals(testIQ, trueIQ); - testIQ = itemsSk.getQuantile(normRank, crit); - assertEquals(testIQ, trueIQ); - - println("Items set: " + set + ", rank: " + normRank + ", Q: " + trueIQ + ", crit: " + crit.toString()); - } - } - - private double getMaxDoubleValue(final int set) { - final int streamLen = skDStreamValues[set].length; - return skDStreamValues[set][streamLen -1]; - } - - private float getMaxFloatValue(final int set) { - final int streamLen = skFStreamValues[set].length; - return skFStreamValues[set][streamLen -1]; - } - - private String getMaxItemValue(final int set) { - final int streamLen = skIStreamValues[set].length; - return skIStreamValues[set][streamLen -1]; - } - - /*******BUILD & LOAD SKETCHES***********/ - - private void buildSketches(final int set) { - reqFloatsSk = ReqSketch.builder().setK(k).build(); - kllFloatsSk = KllFloatsSketch.newHeapInstance(k); - kllDoublesSk = KllDoublesSketch.newHeapInstance(k); - classicDoublesSk = QuantilesDoublesSketch.builder().setK(k).build(); - kllItemsSk = KllItemsSketch.newHeapInstance(k, comparator, serDe); - itemsSk = QuantilesItemsSketch.getInstance(String.class, k, comparator); - - final int count = skFStreamValues[set].length; - for (int i = 0; i < count; i++) { - reqFloatsSk.update(skFStreamValues[set][i]); - kllFloatsSk.update(skFStreamValues[set][i]); - kllDoublesSk.update(skDStreamValues[set][i]); - classicDoublesSk.update(skDStreamValues[set][i]); - kllItemsSk.update(skIStreamValues[set][i]); - itemsSk.update(skIStreamValues[set][i]); - } - } - - /*******BUILD & LOAD SVs***********/ - - private void buildSVs(final int set) throws Exception { - floatsSV = new FloatsSketchSortedView(svFValues[set], svCumWeights[set], totalN[set], - svMaxFValues[set], svMinFValues[set]); - doublesSV = new DoublesSketchSortedView(svDValues[set], svCumWeights[set], totalN[set], - svMaxDValues[set], svMinDValues[set]); - final String svImax = svIValues[set][svIValues[set].length - 1]; - final String svImin = svIValues[set][0]; - - kllItemsSV = new ItemsSketchSortedView<>(svIValues[set], svCumWeights[set], totalN[set], - comparator, svImax, svImin, String.class, .01, svCumWeights[set].length); - - classicItemsSV = new ItemsSketchSortedView<>(svIValues[set], svCumWeights[set], totalN[set], - comparator, svImax, svImin, String.class, .01, svCumWeights[set].length); - } - - /********BUILD DATA SETS**********/ - - private void buildDataSets() { - numSets = svWeights.length; - svCumWeights = new long[numSets][]; - totalN = new long[numSets]; - skFStreamValues = new float[numSets][]; - skDStreamValues = new double[numSets][]; - skIStreamValues = new String[numSets][]; - for (int i = 0; i < numSets; i++) { - svCumWeights[i] = convertToCumWeights(svWeights[i]); - final int len = svCumWeights[i].length; - final int totalCount = (int)svCumWeights[i][len -1]; - totalN[i] = totalCount; - skFStreamValues[i] = convertToFloatStream(svFValues[i], svWeights[i], totalCount); - skDStreamValues[i] = convertToDoubleStream(svDValues[i], svWeights[i], totalCount); - skIStreamValues[i] = convertToItemStream(svIValues[i], svWeights[i], totalCount); - } - println(""); - } - - private static float[] convertToFloatStream( - final float[] svFValueArr, - final long[] svWeightsArr, - final int totalCount) { - final float[] out = new float[totalCount]; - final int len = svWeightsArr.length; - int i = 0; - for (int j = 0; j < len; j++) { - final float f = svFValueArr[j]; - final int wt = (int)svWeightsArr[j]; - for (int w = 0; w < wt; w++) { - out[i++] = f; - } - } - return out; - } - - private static double[] convertToDoubleStream( - final double[] svDValueArr, - final long[] svWeightsArr, - final int totalCount) { - final double[] out = new double[totalCount]; - final int len = svWeightsArr.length; - int i = 0; - for (int j = 0; j < len; j++) { - final double d = svDValueArr[j]; - final int wt = (int)svWeightsArr[j]; - for (int w = 0; w < wt; w++) { - out[i++] = d; - } - } - return out; - } - - private static String[] convertToItemStream( - final String[] svIValueArr, - final long[] svWeightsArr, - final int totalCount) { - final String[] out = new String[totalCount]; - final int len = svWeightsArr.length; - int i = 0; - for (int j = 0; j < len; j++) { - final String s = svIValueArr[j]; - final int wt = (int)svWeightsArr[j]; - for (int w = 0; w < wt; w++) { - out[i++] = s; - } - } - return out; - } - - private static long[] convertToCumWeights(final long[] weights) { - final int len = weights.length; - final long[] out = new long[len]; - out[0] = weights[0]; - for (int i = 1; i < len; i++) { - out[i] = weights[i] + out[i - 1]; - } - return out; - } - - /*******************/ - - private final static boolean enablePrinting = false; - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/quantilescommon/GenericInequalitySearchTest.java b/src/test/java/org/apache/datasketches/quantilescommon/GenericInequalitySearchTest.java deleted file mode 100644 index 6d6cdd409..000000000 --- a/src/test/java/org/apache/datasketches/quantilescommon/GenericInequalitySearchTest.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.find; -import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality.EQ; -import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality.GE; -import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality.GT; -import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality.LE; -import static org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality.LT; -import static org.testng.Assert.assertEquals; - -import java.util.Comparator; -import java.util.Random; - -import org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class GenericInequalitySearchTest { - static Random rand = new Random(1); - private static final String LS = System.getProperty("line.separator"); - private static int randDelta() { return rand.nextDouble() < 0.4 ? 0 : 1; } - - private final Comparator comparator = Comparator.naturalOrder(); - - //CodeQL may complain about boxed values, but Java Generics require objects. - private static Float[] buildRandFloatArr(final int len) { - final Float[] arr = new Float[len]; - float v = 1.0f; - for (int i = 0; i < len; i++) { - arr[i] = v; - v += randDelta(); - } - return arr; - } - -// @Test //visual testing only -// //@SuppressWarnings("unused") -// private static void viewBuildRandArr() { -// final int len = 10; -// for (int i = 0; i < 10; i++) { -// final Float[] tarr = buildRandFloatArr(len); -// for (int j = 0; j < len; j++) { -// printf("%4.1f,", tarr[j]); -// } -// println(""); -// } -// } - - @Test - public void checkBinSearchFltLimits() { - for (int len = 10; len <= 13; len++) { - final Float[] tarr = buildRandFloatArr(len); - final int low = 2; - final int high = len - 2; - println(listFltArray(tarr, low, high)); - checkBinarySearchFloatLimits(tarr, low, high); - } - } - - private static String listFltArray(final Float[] arr, final int low, final int high) { - final StringBuilder sb = new StringBuilder(); - sb.append(LS); - sb.append("The values in parentheses are the low and high values of the sub-array to search"); - sb.append(LS); - sb.append("arr: "); - for (int i = 0; i < arr.length; i++) { - if (i == low || i == high) { sb.append(String.format("(%.0f) ", arr[i])); } - else { sb.append(String.format("%.0f ", arr[i])); } - } - return sb.toString(); - } - - private void checkBinarySearchFloatLimits(final Float[] arr, final int low, final int high) { - final Float lowV = arr[low]; - final Float highV = arr[high]; - Float v; - int res; - v = lowV - 1f; - res = find(arr, low, high, v, LT, comparator); - println(desc(arr, low, high, v, res, LT, comparator)); - assertEquals(res, -1); - - v = lowV; - res = find(arr, low, high, v, LT, comparator); - println(desc(arr, low, high, v, res, LT, comparator)); - assertEquals(res, -1); - - v = highV + 1; - res = find(arr, low, high, v, LT, comparator); - println(desc(arr, low, high, v, res, LT, comparator)); - assertEquals(res, high); - - v = lowV -1; - res = find(arr, low, high, v, LE, comparator); - println(desc(arr, low, high, v, res, LE, comparator)); - assertEquals(res, -1); - - v = highV; - res = find(arr, low, high, v, LE, comparator); - println(desc(arr, low, high, v, res, LE, comparator)); - assertEquals(res, high); - - v = highV + 1; - res = find(arr, low, high, v, LE, comparator); - println(desc(arr, low, high, v, res, LE, comparator)); - assertEquals(res, high); - - v = lowV - 1; - res = find(arr, low, high, v, EQ, comparator); - println(desc(arr, low, high, v, res, EQ, comparator)); - assertEquals(res, -1); - - v = highV; - res = find(arr, low, high, v, EQ, comparator); - println(desc(arr, low, high, v, res, EQ, comparator)); - assertEquals(arr[res], v); - - v = highV + 1; - res = find(arr, low, high, v, EQ, comparator); - println(desc(arr, low, high, v, res, EQ, comparator)); - assertEquals(res, -1); - - v = lowV - 1; - res = find(arr, low, high, v, GT, comparator); - println(desc(arr, low, high, v, res, GT, comparator)); - assertEquals(res, low); - - v = highV; - res = find(arr, low, high, v, GT, comparator); - println(desc(arr, low, high, v, res, GT, comparator)); - assertEquals(res, -1); - - v = highV + 1; - res = find(arr, low, high, v, GT, comparator); - println(desc(arr, low, high, v, res, GT, comparator)); - assertEquals(res, -1); - - v = lowV - 1; - res = find(arr, low, high, v, GE, comparator); - println(desc(arr, low, high, v, res, GE, comparator)); - assertEquals(res, low); - - v = lowV; - res = find(arr, low, high, v, GE, comparator); - println(desc(arr, low, high, v, res, GE, comparator)); - assertEquals(res, low); - - v = highV + 1; - res = find(arr, low, high, v, GE, comparator); - println(desc(arr, low, high, v, res, GE, comparator)); - assertEquals(res, -1); - } - - @Test // visual only - public void exerciseFltBinSearch() { - checkFindFloat(LT); - checkFindFloat(LE); - checkFindFloat(GE); - checkFindFloat(GT); - } - - private void checkFindFloat(final GenericInequalitySearch.Inequality inequality) { - final String ie = inequality.name(); - println("Inequality: " + ie); - // 0 1 2 3 4 5 6 7 8 9 - final Float[] arr = {5f,5f,5f,6f,6f,6f,7f,8f,8f,8f}; - final int len = arr.length; - print("Index: "); - for (int i = 0; i < len; i++) { printf("%d, ", i); } - print(LS + "Value: "); - for (int i = 0; i < len; i++) { printf("%.1f, ", arr[i]); } - println(""); - for (float v = 0.5f; v <= arr[len - 1] + 0.5f; v += .5f) { - final int low = 0; - final int high = len - 1; - final int idx = find(arr, low, high, v, inequality, comparator); - if (idx == -1) { - println(ie +": " + v + " Not resolved, return -1."); - } - else { - println(desc(arr, low, high, v, idx, inequality, comparator)); - } - } - println(""); - } - - /** - * Optional call that describes the details of the results of the search. - * Used primarily for debugging. - * @param arr The underlying sorted array of generic values - * @param low the low index of the range - * @param high the high index of the range - * @param v the generic value to search for - * @param idx the resolved index from the search - * @param inequality one of LT, LE, EQ, GE, GT. - * @param comparator for the type T - * @param The generic type of value to be used in the search process. - * @return the descriptive string. - */ - public static String desc(final T[] arr, final int low, final int high, final T v, final int idx, - final Inequality inequality, final Comparator comparator) { - switch (inequality) { - case LT: { - if (idx == -1) { - return "LT: " + v + " <= arr[" + low + "]=" + arr[low] + "; return -1"; - } - if (idx == high) { - return "LT: " + v + " > arr[" + high + "]=" + arr[high] - + "; return arr[" + high + "]=" + arr[high]; - } //idx < high - return "LT: " + v - + ": arr[" + idx + "]=" + arr[idx] + " < " + v - + " <= arr[" + (idx + 1) + "]=" + arr[idx + 1] - + "; return arr[" + idx + "]=" + arr[idx]; - } - case LE: { - if (idx == -1) { - return "LE: " + v + " < arr[" + low + "]=" + arr[low] + "; return -1"; - } - if (idx == high) { - return "LE: " + v + " >= arr[" + high + "]=" + arr[high] - + "; return arr[" + high + "]=" + arr[high]; - } - return "LE: " + v - + ": arr[" + idx + "]=" + arr[idx] + " <= " + v - + " < arr[" + (idx + 1) + "]=" + arr[idx + 1] - + "; return arr[" + idx + "]=" + arr[idx]; - } - case EQ: { - if (idx == -1) { - if (comparator.compare(v, arr[high]) > 0) { - return "EQ: " + v + " > arr[" + high + "]; return -1"; - } - if (comparator.compare(v, arr[low]) < 0) { - return "EQ: " + v + " < arr[" + low + "]; return -1"; - } - return "EQ: " + v + " Cannot be found within arr[" + low + "], arr[" + high + "]; return -1"; - } - return "EQ: " + v + " == arr[" + idx + "]; return arr[" + idx + "]=" + arr[idx]; - } - case GE: { - if (idx == -1) { - return "GE: " + v + " > arr[" + high + "]=" + arr[high] + "; return -1"; - } - if (idx == low) { - return "GE: " + v + " <= arr[" + low + "]=" + arr[low] - + "; return arr[" + low + "]=" + arr[low]; - } //idx > low - return "GE: " + v - + ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " < " + v + " <= arr[" + idx + "]=" + arr[idx] - + "; return arr[" + idx + "]=" + arr[idx]; - } - case GT: { - if (idx == -1) { - return "GT: " + v + " >= arr[" + high + "]=" + arr[high] + "; return -1"; - } - if (idx == low) { - return "GT: " + v + " < arr[" + low + "]=" + arr[low] - + "; return arr[" + low + "]=" + arr[low]; - } //idx > low - return "GT: " + v - + ": arr[" + (idx - 1) + "]=" + arr[idx - 1] + " <= " + v + " < arr[" + idx + "]=" + arr[idx] - + "; return arr[" + idx + "]=" + arr[idx]; - } - } - return ""; - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - - /** - * @param o the Object to print - */ - static final void print(final Object o) { - if (enablePrinting) { System.out.print(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/quantilescommon/IncludeMinMaxTest.java b/src/test/java/org/apache/datasketches/quantilescommon/IncludeMinMaxTest.java deleted file mode 100644 index cfcebce10..000000000 --- a/src/test/java/org/apache/datasketches/quantilescommon/IncludeMinMaxTest.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.quantilescommon.IncludeMinMax.DoublesPair; -import static org.apache.datasketches.quantilescommon.IncludeMinMax.FloatsPair; -import static org.apache.datasketches.quantilescommon.IncludeMinMax.ItemsPair; -import static org.testng.Assert.assertEquals; - -import java.util.Comparator; - -import org.testng.annotations.Test; - -/** - * Checks the IncludeMinMax process - */ -public final class IncludeMinMaxTest { - - @Test - public static void checkDoublesEndsAdjustment() { - final double[] quantiles = {2, 4, 6, 7}; - final long[] cumWeights = {2, 4, 6, 8}; - - final double maxItem = 8; - final double minItem = 1; - final DoublesPair dPair = IncludeMinMax.includeDoublesMinMax(quantiles, cumWeights, maxItem, minItem); - final double[] adjQuantiles = dPair.quantiles; - final long[] adjCumWeights = dPair.cumWeights; - int len = adjCumWeights.length; - printf("%10s %10s" + LS, "Quantiles", "CumWeights"); - for (int i = 0; i < len; i++) { - printf("%10.1f %10d" + LS, adjQuantiles[i], adjCumWeights[i]); - } - final int topIn = quantiles.length - 1; - final int topAdj = adjQuantiles.length - 1; - assertEquals(adjQuantiles[topAdj], maxItem); - assertEquals(adjQuantiles[0], minItem); - assertEquals(adjCumWeights[topAdj], cumWeights[topIn]); - assertEquals(adjCumWeights[0], 1); - assertEquals(adjQuantiles.length - quantiles.length, 2); - assertEquals(adjCumWeights.length - cumWeights.length, 2); - } - - @Test - public static void checkDoublesEndsAdjustment2() { - final double[] quantiles = {2, 4, 6, 7}; - final long[] cumWeights = {2, 4, 6, 8}; - - final double maxItem = 7; - final double minItem = 2; - final DoublesPair dPair = IncludeMinMax.includeDoublesMinMax(quantiles, cumWeights, maxItem, minItem); - final double[] adjQuantiles = dPair.quantiles; - final long[] adjCumWeights = dPair.cumWeights; - int len = adjCumWeights.length; - printf("%10s %10s" + LS, "Quantiles", "CumWeights"); - for (int i = 0; i < len; i++) { - printf("%10.1f %10d" + LS, adjQuantiles[i], adjCumWeights[i]); - } - final int topIn = quantiles.length - 1; - final int topAdj = adjQuantiles.length - 1; - assertEquals(adjQuantiles[topAdj], maxItem); - assertEquals(adjQuantiles[0], minItem); - assertEquals(adjCumWeights[topAdj], cumWeights[topIn]); - assertEquals(adjCumWeights[0], cumWeights[0]); - assertEquals(adjQuantiles.length - quantiles.length, 0); - assertEquals(adjCumWeights.length - cumWeights.length, 0); - } - - @Test - public static void checkFloatsEndsAdjustment() { - final float[] quantiles = {2, 4, 6, 7}; - final long[] cumWeights = {2, 4, 6, 8}; - - final float maxItem = 8; - final float minItem = 1; - final FloatsPair dPair = IncludeMinMax.includeFloatsMinMax(quantiles, cumWeights, maxItem, minItem); - final float[] adjQuantiles = dPair.quantiles; - final long[] adjCumWeights = dPair.cumWeights; - int len = adjCumWeights.length; - printf("%10s %10s" + LS, "Quantiles", "CumWeights"); - for (int i = 0; i < len; i++) { - printf("%10.1f %10d" + LS, adjQuantiles[i], adjCumWeights[i]); - } - final int topIn = quantiles.length - 1; - final int topAdj = adjQuantiles.length - 1; - assertEquals(adjQuantiles[topAdj], maxItem); - assertEquals(adjQuantiles[0], minItem); - assertEquals(adjCumWeights[topAdj], cumWeights[topIn]); - assertEquals(adjCumWeights[0], 1); - assertEquals(adjQuantiles.length - quantiles.length, 2); - assertEquals(adjCumWeights.length - cumWeights.length, 2); - } - - @Test - public static void checkFloatsEndsAdjustment2() { - final float[] quantiles = {2, 4, 6, 7}; - final long[] cumWeights = {2, 4, 6, 8}; - - final float maxItem = 7; - final float minItem = 2; - final FloatsPair dPair = IncludeMinMax.includeFloatsMinMax(quantiles, cumWeights, maxItem, minItem); - final float[] adjQuantiles = dPair.quantiles; - final long[] adjCumWeights = dPair.cumWeights; - int len = adjCumWeights.length; - printf("%10s %10s" + LS, "Quantiles", "CumWeights"); - for (int i = 0; i < len; i++) { - printf("%10.1f %10d" + LS, adjQuantiles[i], adjCumWeights[i]); - } - final int topIn = quantiles.length - 1; - final int topAdj = adjQuantiles.length - 1; - assertEquals(adjQuantiles[topAdj], maxItem); - assertEquals(adjQuantiles[0], minItem); - assertEquals(adjCumWeights[topAdj], cumWeights[topIn]); - assertEquals(adjCumWeights[0], cumWeights[0]); - assertEquals(adjQuantiles.length - quantiles.length, 0); - assertEquals(adjCumWeights.length - cumWeights.length, 0); - } - - @Test - public static void checkItemsEndsAdjustment() { - final String[] quantiles = {"2", "4", "6", "7"}; - final long[] cumWeights = {2, 4, 6, 8}; - - final String maxItem = "8"; - final String minItem = "1"; - final ItemsPair dPair = - IncludeMinMax.includeItemsMinMax(quantiles, cumWeights, maxItem, minItem, Comparator.naturalOrder()); - final String[] adjQuantiles = dPair.quantiles; - final long[] adjCumWeights = dPair.cumWeights; - int len = adjCumWeights.length; - printf("%10s %10s" + LS, "Quantiles", "CumWeights"); - for (int i = 0; i < len; i++) { - printf("%10s %10d" + LS, adjQuantiles[i], adjCumWeights[i]); - } - final int topIn = quantiles.length - 1; - final int topAdj = adjQuantiles.length - 1; - assertEquals(adjQuantiles[topAdj], maxItem); - assertEquals(adjQuantiles[0], minItem); - assertEquals(adjCumWeights[topAdj], cumWeights[topIn]); - assertEquals(adjCumWeights[0], 1); - assertEquals(adjQuantiles.length - quantiles.length, 2); - assertEquals(adjCumWeights.length - cumWeights.length, 2); - } - - @Test - public static void checkItemsEndsAdjustment2() { - final String[] quantiles = {"2", "4", "6", "7"}; - final long[] cumWeights = {2, 4, 6, 8}; - - final String maxItem = "7"; - final String minItem = "2"; - final ItemsPair dPair = - IncludeMinMax.includeItemsMinMax(quantiles, cumWeights, maxItem, minItem, Comparator.naturalOrder()); - final String[] adjQuantiles = dPair.quantiles; - final long[] adjCumWeights = dPair.cumWeights; - int len = adjCumWeights.length; - printf("%10s %10s" + LS, "Quantiles", "CumWeights"); - for (int i = 0; i < len; i++) { - printf("%10s %10d" + LS, adjQuantiles[i], adjCumWeights[i]); - } - final int topIn = quantiles.length - 1; - final int topAdj = adjQuantiles.length - 1; - assertEquals(adjQuantiles[topAdj], maxItem); - assertEquals(adjQuantiles[0], minItem); - assertEquals(adjCumWeights[topAdj], cumWeights[topIn]); - assertEquals(adjCumWeights[0], cumWeights[0]); - assertEquals(adjQuantiles.length - quantiles.length, 0); - assertEquals(adjCumWeights.length - cumWeights.length, 0); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/quantilescommon/InequalitySearchTest.java b/src/test/java/org/apache/datasketches/quantilescommon/InequalitySearchTest.java deleted file mode 100644 index 640d7d59c..000000000 --- a/src/test/java/org/apache/datasketches/quantilescommon/InequalitySearchTest.java +++ /dev/null @@ -1,581 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.quantilescommon.InequalitySearch.EQ; -import static org.apache.datasketches.quantilescommon.InequalitySearch.GE; -import static org.apache.datasketches.quantilescommon.InequalitySearch.GT; -import static org.apache.datasketches.quantilescommon.InequalitySearch.LE; -import static org.apache.datasketches.quantilescommon.InequalitySearch.LT; -import static org.testng.Assert.assertEquals; - -import java.util.Random; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class InequalitySearchTest { - static Random rand = new Random(1); - private static final String LS = System.getProperty("line.separator"); - - private static int randDelta() { return rand.nextDouble() < 0.4 ? 0 : 1; } - - private static float[] buildRandFloatArr(final int len) { - final float[] arr = new float[len]; - float v = 1.0f; - for (int i = 0; i < len; i++) { - arr[i] = v; - v += randDelta(); - } - return arr; - } - - private static double[] buildRandDoubleArr(final int len) { - final double[] arr = new double[len]; - double v = 1.0; - for (int i = 0; i < len; i++) { - arr[i] = v; - v += randDelta(); - } - return arr; - } - - private static long[] buildRandLongArr(final int len) { - final long[] arr = new long[len]; - long v = 1L; - for (int i = 0; i < len; i++) { - arr[i] = v; - v += 2L * randDelta(); - } - return arr; - } - - //double array - - @Test - public void checkBinSearchDblLimits() { - for (int len = 10; len <= 13; len++) { - final double[] tarr = buildRandDoubleArr(len); - final int low = 2; - final int high = len - 2; - println(listDblArray(tarr, low, high)); - checkBinarySearchDoubleLimits(tarr, low, high); - } - } - - private static String listDblArray(final double[] arr, final int low, final int high) { - final StringBuilder sb = new StringBuilder(); - sb.append(LS); - final int len = arr.length; - sb.append("double[" + len + "]: "); - for (int i = 0; i < len; i++) { - if (i == low || i == high) { sb.append(String.format("(%.0f) ", arr[i])); } - else { sb.append(String.format("%.0f ", arr[i])); } - } - return sb.toString(); - } - - private static void checkBinarySearchDoubleLimits(final double[] arr, final int low, final int high) { - final double lowV = arr[low]; - final double highV = arr[high]; - double v; - int res; - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, LT); - println(LT.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = lowV; - res = InequalitySearch.find(arr, low, high, v, LT); - println(LT.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, LT); - println(LT.desc(arr, low, high, v, res)); - assertEquals(res, high); - - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, LE); - println(LE.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = highV; - res = InequalitySearch.find(arr, low, high, v, LE); - println(LE.desc(arr, low, high, v, res)); - assertEquals(res, high); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, LE); - println(LE.desc(arr, low, high, v, res)); - assertEquals(res, high); - - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, EQ); - println(EQ.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = highV; - res = InequalitySearch.find(arr, low, high, v, EQ); - println(EQ.desc(arr, low, high, v, res)); - assertEquals(arr[res], v); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, EQ); - println(EQ.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, GT); - println(GT.desc(arr, low, high, v, res)); - assertEquals(res, low); - - v = highV; - res = InequalitySearch.find(arr, low, high, v, GT); - println(GT.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, GT); - println(GT.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, GE); - println(GE.desc(arr, low, high, v, res)); - assertEquals(res, low); - - v = lowV; - res = InequalitySearch.find(arr, low, high, v, GE); - println(GE.desc(arr, low, high, v, res)); - assertEquals(res, low); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, GE); - println(GE.desc(arr, low, high, v, res)); - assertEquals(res, -1); - } - - //float array - - @Test - public void checkBinSearchFltLimits() { - for (int len = 10; len <= 13; len++) { - final float[] tarr = buildRandFloatArr(len); - final int low = 2; - final int high = len - 2; - println(listFltArray(tarr, low, high)); - checkBinarySearchFloatLimits(tarr, low, high); - } - } - - private static String listFltArray(final float[] arr, final int low, final int high) { - final StringBuilder sb = new StringBuilder(); - sb.append(LS); - final int len = arr.length; - sb.append("float[" + len + "]: "); - for (int i = 0; i < len; i++) { - if (i == low || i == high) { sb.append(String.format("(%.0f) ", arr[i])); } - else { sb.append(String.format("%.0f ", arr[i])); } - } - return sb.toString(); - } - - private static void checkBinarySearchFloatLimits(final float[] arr, final int low, final int high) { - final float lowV = arr[low]; - final float highV = arr[high]; - float v; - int res; - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, LT); - println(LT.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = lowV; - res = InequalitySearch.find(arr, low, high, v, LT); - println(LT.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, LT); - println(LT.desc(arr, low, high, v, res)); - assertEquals(res, high); - - v = lowV -1; - res = InequalitySearch.find(arr, low, high, v, LE); - println(LE.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = highV; - res = InequalitySearch.find(arr, low, high, v, LE); - println(LE.desc(arr, low, high, v, res)); - assertEquals(res, high); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, LE); - println(LE.desc(arr, low, high, v, res)); - assertEquals(res, high); - - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, EQ); - println(EQ.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = highV; - res = InequalitySearch.find(arr, low, high, v, EQ); - println(EQ.desc(arr, low, high, v, res)); - assertEquals(arr[res], v); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, EQ); - println(EQ.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, GT); - println(GT.desc(arr, low, high, v, res)); - assertEquals(res, low); - - v = highV; - res = InequalitySearch.find(arr, low, high, v, GT); - println(GT.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, GT); - println(GT.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, GE); - println(GE.desc(arr, low, high, v, res)); - assertEquals(res, low); - - v = lowV; - res = InequalitySearch.find(arr, low, high, v, GE); - println(GE.desc(arr, low, high, v, res)); - assertEquals(res, low); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, GE); - println(GE.desc(arr, low, high, v, res)); - assertEquals(res, -1); - } - - //long array - - @Test - public void checkBinSearchLongLimits() { - for (int len = 10; len <= 13; len++) { - final long[] tarr = buildRandLongArr(len); - final int low = 2; - final int high = len - 2; - println(listLongArray(tarr, low, high)); - checkBinarySearchLongLimits(tarr, low, high); - } - } - - private static String listLongArray(final long[] arr, final int low, final int high) { - final StringBuilder sb = new StringBuilder(); - sb.append(LS); - final int len = arr.length; - sb.append("long[" + len + "]: "); - for (int i = 0; i < len; i++) { - if (i == low || i == high) { sb.append(String.format("(%d) ", arr[i])); } - else { sb.append(String.format("%d ", arr[i])); } - } - return sb.toString(); - } - - private static void checkBinarySearchLongLimits(final long[] arr, final int low, final int high) { - final long lowV = arr[low]; - final long highV = arr[high]; - long v; - int res; - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, LT); - println(LT.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = lowV; - res = InequalitySearch.find(arr, low, high, v, LT); - println(LT.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, LT); - println(LT.desc(arr, low, high, v, res)); - assertEquals(res, high); - - v = lowV -1; - res = InequalitySearch.find(arr, low, high, v, LE); - println(LE.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = highV; - res = InequalitySearch.find(arr, low, high, v, LE); - println(LE.desc(arr, low, high, v, res)); - assertEquals(res, high); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, LE); - println(LE.desc(arr, low, high, v, res)); - assertEquals(res, high); - - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, EQ); - println(EQ.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = highV; - res = InequalitySearch.find(arr, low, high, v, EQ); - println(EQ.desc(arr, low, high, v, res)); - assertEquals(arr[res], v); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, EQ); - println(EQ.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, GT); - println(GT.desc(arr, low, high, v, res)); - assertEquals(res, low); - - v = highV; - res = InequalitySearch.find(arr, low, high, v, GT); - println(GT.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, GT); - println(GT.desc(arr, low, high, v, res)); - assertEquals(res, -1); - - v = lowV - 1; - res = InequalitySearch.find(arr, low, high, v, GE); - println(GE.desc(arr, low, high, v, res)); - assertEquals(res, low); - - v = lowV; - res = InequalitySearch.find(arr, low, high, v, GE); - println(GE.desc(arr, low, high, v, res)); - assertEquals(res, low); - - v = highV + 1; - res = InequalitySearch.find(arr, low, high, v, GE); - println(GE.desc(arr, low, high, v, res)); - assertEquals(res, -1); - } - - /****************/ - - @Test // visual only for doubles inequality - public void exerciseDoublesSearch() { - println("--------{1f}--------"); - double[] arr = {1}; - exerciseDoubles(arr); - println("------{1f, 1f}------"); - arr = new double[] {1f, 1f}; - exerciseDoubles(arr); - println("---------{1,1,1,2,2,2,3,4,4,4}--------"); - // 0 1 2 3 4 5 6 7 8 9 - arr = new double[] {1,1,1,2,2,2,3,4,4,4}; - exerciseDoubles(arr); - } - - private static void exerciseDoubles(final double[] arr) { - checkFindDouble(arr, LT); - checkFindDouble(arr, LE); - checkFindDouble(arr, EQ); - checkFindDouble(arr, GE); - checkFindDouble(arr, GT); - } - - private static void checkFindDouble(final double[] arr, final InequalitySearch crit) { - println("InequalitySearch: " + crit.name()); - final int len = arr.length; - for (double v = 0.5; v <= arr[len - 1] + 0.5; v += .5) { - final int low = 0; - final int high = len - 1; - final int idx = InequalitySearch.find(arr, low, high, v, crit); - println(crit.desc(arr, low, high, v, idx)); - } - println(""); - } - - /****************/ - - @Test // visual only for floats inequality - public void exerciseFloatsSearch() { - println("--------{1f}--------"); - float[] arr = {1f}; - exerciseFloats(arr); - println("------{1f, 1f}------"); - arr = new float[] {1f, 1f}; - exerciseFloats(arr); - println("---------{1,1,1,2,2,2,3,4,4,4}--------"); - // 0 1 2 3 4 5 6 7 8 9 - arr = new float[] {1,1,1,2,2,2,3,4,4,4}; - exerciseFloats(arr); - } - - private static void exerciseFloats(final float[] arr) { - checkFindFloat(arr, LT); - checkFindFloat(arr, LE); - checkFindFloat(arr, EQ); - checkFindFloat(arr, GE); - checkFindFloat(arr, GT); - } - - private static void checkFindFloat(final float[] arr, final InequalitySearch crit) { - println("InequalitySearch: " + crit.name()); - final int len = arr.length; - for (float v = 0.5f; v <= arr[len - 1] + 0.5f; v += 0.5f) { - final int low = 0; - final int high = len - 1; - final int idx = InequalitySearch.find(arr, low, high, v, crit); - println(crit.desc(arr, low, high, v, idx)); - } - println(""); - } - - /****************/ - - @Test // visual only for longs inequality - public void exerciseLongsSearch() { - println("--------{1}--------"); - long[] arr = {1}; - exerciseLongs(arr); - println("------{1, 1}------"); - arr = new long[] {1, 1}; - exerciseLongs(arr); - println("--------{1,1,1,2,2,2,3,4,4,4}--------"); - // 0 1 2 3 4 5 6 7 8 9 - arr = new long[] {1,1,1,2,2,2,3,4,4,4}; - exerciseLongs(arr); - } - - private static void exerciseLongs(final long[] arr) { - checkFindLong(arr, LT); - checkFindLong(arr, LE); - checkFindLong(arr, EQ); - checkFindLong(arr, GE); - checkFindLong(arr, GT); - } - - private static void checkFindLong(final long[] arr, final InequalitySearch crit) { - println("InequalitySearch: " + crit.name()); - final int len = arr.length; - for (long v = 0L; v <= arr[len - 1] + 1L; v++) { - final int low = 0; - final int high = len - 1; - final int idx = InequalitySearch.find(arr, low, high, v, crit); - println(crit.desc(arr, low, high, v, idx)); - } - println(""); - } - - /****************/ - - //test equality binary searches - - @Test - public void checkSimpleFindFloat() { - final int len = 10; - final float[] arr = new float[len]; - for (int i = 0; i < len; i++) { arr[i] = i; } - int idx; - for (int i = 0; i < len; i++) { - idx = BinarySearch.find(arr, 0, len - 1, i); - assertEquals(idx, i); - } - idx = BinarySearch.find(arr, 0, len - 1, -1); - assertEquals(idx, -1); - idx = BinarySearch.find(arr, 0, len - 1, len); - assertEquals(idx, -1); - } - - @Test - public void checkSimpleFindDouble() { - final int len = 11; - final double[] arr = new double[len]; - for (int i = 0; i < len; i++) { arr[i] = i; } - int idx; - for (int i = 0; i < len; i++) { - idx = BinarySearch.find(arr, 0, len - 1, i); - assertEquals(idx, i); - } - idx = BinarySearch.find(arr, 0, len - 1, -1); - assertEquals(idx, -1); - idx = BinarySearch.find(arr, 0, len - 1, len); - assertEquals(idx, -1); - } - - @Test - public void checkSimpleFindLong() { - final int len = 11; - final long[] arr = new long[len]; - for (int i = 0; i < len; i++) { arr[i] = i; } - int idx; - for (int i = 0; i < len; i++) { - idx = BinarySearch.find(arr, 0, len - 1, i); - assertEquals(idx, i); - } - idx = BinarySearch.find(arr, 0, len - 1, -1); - assertEquals(idx, -1); - idx = BinarySearch.find(arr, 0, len - 1, len); - assertEquals(idx, -1); - } - - /****************/ - - @Test //visual testing only - //@SuppressWarnings("unused") - private static void checkBuildRandFloatArr() { - final int len = 10; - for (int i = 0; i < 10; i++) { - final float[] tarr = buildRandFloatArr(len); - for (int j = 0; j < len; j++) { - printf("%4.1f,", tarr[j]); - } - println(""); - } - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } -} diff --git a/src/test/java/org/apache/datasketches/quantilescommon/KolmogorovSmirnovTest.java b/src/test/java/org/apache/datasketches/quantilescommon/KolmogorovSmirnovTest.java deleted file mode 100644 index e80d61cd0..000000000 --- a/src/test/java/org/apache/datasketches/quantilescommon/KolmogorovSmirnovTest.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.util.Random; - -import org.apache.datasketches.kll.KllDoublesSketch; -import org.apache.datasketches.kll.KllFloatsSketch; -import org.apache.datasketches.kll.KllSketch; -import org.apache.datasketches.quantiles.QuantilesDoublesSketch; -import org.apache.datasketches.quantiles.UpdatableQuantilesDoublesSketch; -import org.testng.annotations.Test; - -public class KolmogorovSmirnovTest { - private static final String LS = System.getProperty("line.separator"); - - @Test - public void checkDisjointDistributionClassicDoubles() { - final int k = 256; - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().setK(k).build(); - final UpdatableQuantilesDoublesSketch s2 = QuantilesDoublesSketch.builder().setK(k).build(); - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final double x = rand.nextGaussian(); - s1.update(x + 500); - s2.update(x); - } - final double eps = QuantilesDoublesSketch.getNormalizedRankError(k, false); - println("Disjoint Classic Doubles"); - println("D = " + KolmogorovSmirnov.computeKSDelta(s1, s2)); - println("2*eps = " + (2 * eps) + LS); - assertEquals(KolmogorovSmirnov.computeKSDelta(s1, s2), 1.0, 2 * eps); - } - - @Test - public void checkDisjointDistributionKllDoubles() { - final int k = 256; - final KllDoublesSketch s1 = KllDoublesSketch.newHeapInstance(k); - final KllDoublesSketch s2 = KllDoublesSketch.newHeapInstance(k); - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final double x = rand.nextGaussian(); - s1.update(x + 500); - s2.update(x); - } - final double eps = KllSketch.getNormalizedRankError(k, false); - println("Disjoint KLL Doubles"); - println("D = " + KolmogorovSmirnov.computeKSDelta(s1, s2)); - println("2*eps = " + (2 * eps)); - println(""); - assertEquals(KolmogorovSmirnov.computeKSDelta(s1, s2), 1.0, 2 * eps); - } - - @Test - public void checkDisjointDistributionKllFloats() { - final int k = 256; - final KllFloatsSketch s1 = KllFloatsSketch.newHeapInstance(k); - final KllFloatsSketch s2 = KllFloatsSketch.newHeapInstance(k); - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final float x = (float)rand.nextGaussian(); - s1.update(x + 500); - s2.update(x); - } - final double eps = KllSketch.getNormalizedRankError(k, false); - println("Disjoint KLL Floats"); - println("D = " + KolmogorovSmirnov.computeKSDelta(s1, s2)); - println("2*eps = " + (2 * eps) + LS); - assertEquals(KolmogorovSmirnov.computeKSDelta(s1, s2), 1.0, 2 * eps); - } - - @Test - public void checkIdenticalDistributionClassicDoubles() { - final int k = 256; - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().setK(k).build(); - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final double x = rand.nextGaussian(); - s1.update(x); - } - println("Identical Classic Doubles"); - println("D = " + KolmogorovSmirnov.computeKSDelta(s1, s1)); - println("2*eps = 0.0" + LS); - assertEquals(KolmogorovSmirnov.computeKSDelta(s1, s1), 0.0, 0.0); - } - - @Test - public void checkIdenticalDistributionKllDoubles() { - final int k = 256; - final KllDoublesSketch s1 = KllDoublesSketch.newHeapInstance(k); - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final double x = rand.nextGaussian(); - s1.update(x); - } - println("Identical KLL Doubles"); - println("D = " + KolmogorovSmirnov.computeKSDelta(s1, s1)); - println("2*eps = 0.0" + LS); - assertEquals(KolmogorovSmirnov.computeKSDelta(s1, s1), 0.0, 0.0); - } - - @Test - public void checkIdenticalDistributionKllFloats() { - final int k = 256; - final KllFloatsSketch s1 = KllFloatsSketch.newHeapInstance(k); - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final float x = (float)rand.nextGaussian(); - s1.update(x); - } - println("Identical KLL Floats"); - println("D = " + KolmogorovSmirnov.computeKSDelta(s1, s1)); - println("2*eps = 0.0" + LS); - assertEquals(KolmogorovSmirnov.computeKSDelta(s1, s1), 0.0, 0.0); - } - - @Test - public void checkSameDistributionDifferentClassicDoublesSketches() { - final int k = 256; - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().setK(k).build(); - final UpdatableQuantilesDoublesSketch s2 = QuantilesDoublesSketch.builder().setK(k).build(); - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final double x = rand.nextGaussian(); - s1.update(x); - s2.update(x); - } - final double eps = QuantilesDoublesSketch.getNormalizedRankError(k, false); - println("Same Classic Doubles"); - println("D = " + KolmogorovSmirnov.computeKSDelta(s1, s2)); - println("2*eps = " + (2 * eps) + LS); - assertEquals(KolmogorovSmirnov.computeKSDelta(s1, s2), 0, 2 * eps); - } - - @Test - public void checkSameDistributionDifferentKllDoublesSketches() { - final int k = 256; - final KllDoublesSketch s1 = KllDoublesSketch.newHeapInstance(k); - final KllDoublesSketch s2 = KllDoublesSketch.newHeapInstance(k); - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final double x = rand.nextGaussian(); - s1.update(x); - s2.update(x); - } - final double eps = KllSketch.getNormalizedRankError(k, false); - println("Same KLL Doubles"); - println("D = " + KolmogorovSmirnov.computeKSDelta(s1, s2)); - println("2*eps = " + (2 * eps) + LS); - assertEquals(KolmogorovSmirnov.computeKSDelta(s1, s2), 0, 2 * eps); - } - - @Test - public void checkSameDistributionDifferentKllFloatsSketches() { - final int k = 256; - final KllFloatsSketch s1 = KllFloatsSketch.newHeapInstance(k); - final KllFloatsSketch s2 = KllFloatsSketch.newHeapInstance(k); - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final float x = (float)rand.nextGaussian(); - s1.update(x); - s2.update(x); - } - final double eps = KllSketch.getNormalizedRankError(k, false); - println("Same KLL Floats"); - println("D = " + KolmogorovSmirnov.computeKSDelta(s1, s2)); - println("2*eps = " + (2 * eps) + LS); - assertEquals(KolmogorovSmirnov.computeKSDelta(s1, s2), 0, 2 * eps); - } - - @Test - public void mediumResolutionClassicDoubles() { - final int k = 2048; - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().setK(k).build(); - final UpdatableQuantilesDoublesSketch s2 = QuantilesDoublesSketch.builder().setK(k).build(); - final double tgtPvalue = .05; - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final double x = rand.nextGaussian(); - s1.update(x + .05); - s2.update(x); - } - - final double D = KolmogorovSmirnov.computeKSDelta(s1, s2); - final double thresh = KolmogorovSmirnov.computeKSThreshold(s1, s2, tgtPvalue); - final boolean reject = KolmogorovSmirnov.kolmogorovSmirnovTest(s1, s2, tgtPvalue); - println("MedRes Classic Doubles"); - println("pVal = " + tgtPvalue + "\nK = " + k + "\nD = " + D + "\nTh = " + thresh - + "\nNull Hypoth Rejected = " + reject + LS); - assertFalse(reject); - } - - @Test - public void mediumResolutionKllDoubles() { - final int k = 2048; - final KllDoublesSketch s1 = KllDoublesSketch.newHeapInstance(k); - final KllDoublesSketch s2 = KllDoublesSketch.newHeapInstance(k); - final double tgtPvalue = .05; - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final double x = rand.nextGaussian(); - s1.update(x + .05); - s2.update(x); - } - - final double D = KolmogorovSmirnov.computeKSDelta(s1, s2); - final double thresh = KolmogorovSmirnov.computeKSThreshold(s1, s2, tgtPvalue); - final boolean reject = KolmogorovSmirnov.kolmogorovSmirnovTest(s1, s2, tgtPvalue); - println("MedRes KLL Doubles"); - println("pVal = " + tgtPvalue + "\nK = " + k + "\nD = " + D + "\nTh = " + thresh - + "\nNull Hypoth Rejected = " + reject + LS); - assertFalse(reject); - } - - @Test - public void mediumResolutionKllFloats() { - final int k = 2048; - final KllFloatsSketch s1 = KllFloatsSketch.newHeapInstance(k); - final KllFloatsSketch s2 = KllFloatsSketch.newHeapInstance(k); - final double tgtPvalue = .05; - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final float x = (float)rand.nextGaussian(); - s1.update(x + .05F); - s2.update(x); - } - - final double D = KolmogorovSmirnov.computeKSDelta(s1, s2); - final double thresh = KolmogorovSmirnov.computeKSThreshold(s1, s2, tgtPvalue); - final boolean reject = KolmogorovSmirnov.kolmogorovSmirnovTest(s1, s2, tgtPvalue); - println("MedRes KLL Floats"); - println("pVal = " + tgtPvalue + "\nK = " + k + "\nD = " + D + "\nTh = " + thresh - + "\nNull Hypoth Rejected = " + reject + LS); - assertFalse(reject); - } - - @Test - public void highResolutionClassicDoubles() { - final int k = 8192; - final UpdatableQuantilesDoublesSketch s1 = QuantilesDoublesSketch.builder().setK(k).build(); - final UpdatableQuantilesDoublesSketch s2 = QuantilesDoublesSketch.builder().setK(k).build(); - final double tgtPvalue = .05; - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final double x = rand.nextGaussian(); - s1.update(x + .05); - s2.update(x); - } - - final double D = KolmogorovSmirnov.computeKSDelta(s1, s2); - final double thresh = KolmogorovSmirnov.computeKSThreshold(s1, s2, tgtPvalue); - final boolean reject = KolmogorovSmirnov.kolmogorovSmirnovTest(s1, s2, tgtPvalue); - println("HiRes Classic Doubles"); - println("pVal = " + tgtPvalue + "\nK = " + k + "\nD = " + D + "\nTh = " + thresh - + "\nNull Hypoth Rejected = " + reject + LS); - assertTrue(reject); - } - - @Test - public void highResolutionKllDoubles() { - final int k = 8192; - final KllDoublesSketch s1 = KllDoublesSketch.newHeapInstance(k); - final KllDoublesSketch s2 = KllDoublesSketch.newHeapInstance(k); - final double tgtPvalue = .05; - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final double x = rand.nextGaussian(); - s1.update(x + .05); - s2.update(x); - } - - final double D = KolmogorovSmirnov.computeKSDelta(s1, s2); - final double thresh = KolmogorovSmirnov.computeKSThreshold(s1, s2, tgtPvalue); - final boolean reject = KolmogorovSmirnov.kolmogorovSmirnovTest(s1, s2, tgtPvalue); - println("HiRes KLL Doubles"); - println("pVal = " + tgtPvalue + "\nK = " + k + "\nD = " + D + "\nTh = " + thresh - + "\nNull Hypoth Rejected = " + reject + LS); - assertTrue(reject); - } - - @Test - public void highResolutionKllFloats() { - final int k = 8192; - final KllFloatsSketch s1 = KllFloatsSketch.newHeapInstance(k); - final KllFloatsSketch s2 = KllFloatsSketch.newHeapInstance(k); - final double tgtPvalue = .05; - - final Random rand = new Random(1); - - final int n = (3 * k) - 1; - for (int i = 0; i < n; ++i) { - final float x = (float)rand.nextGaussian(); - s1.update(x + .05F); - s2.update(x); - } - - final double D = KolmogorovSmirnov.computeKSDelta(s1, s2); - final double thresh = KolmogorovSmirnov.computeKSThreshold(s1, s2, tgtPvalue); - final boolean reject = KolmogorovSmirnov.kolmogorovSmirnovTest(s1, s2, tgtPvalue); - println("HiRes KLL Floats"); - println("pVal = " + tgtPvalue + "\nK = " + k + "\nD = " + D + "\nTh = " + thresh - + "\nNull Hypoth Rejected = " + reject + LS); - assertTrue(reject); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - private final static boolean enablePrinting = false; - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/quantilescommon/LinearRanksAndQuantiles.java b/src/test/java/org/apache/datasketches/quantilescommon/LinearRanksAndQuantiles.java deleted file mode 100644 index fd8885c6f..000000000 --- a/src/test/java/org/apache/datasketches/quantilescommon/LinearRanksAndQuantiles.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.common.Util.le; -import static org.apache.datasketches.common.Util.lt; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.fail; - -import java.util.Comparator; - -public class LinearRanksAndQuantiles { - - /** - * Gets the quantile based on the given normalized rank. - *
  • getQuantile(rank, INCLUSIVE) or q(r, GE)
    - * := Given r, return the quantile, q, of the smallest rank that is strictly Greater than or Equal to r.
  • - *

  • getQuantile(rank, EXCLUSIVE) or q(r, GT)
    - * := Given r, return the quantile, q, of the smallest rank that is strictly Greater Than r.
  • - *
- * - * @param cumWeights the given natural cumulative weights. The last value must be N. - * @param quantiles the given quantile array - * @param givenNormR the given normalized rank, which must be in the range [0.0, 1.0], inclusive. - * @param inclusive determines the search criterion used. - * @return the quantile - */ - public static float getTrueFloatQuantile( - final long[] cumWeights, - final float[] quantiles, - final double givenNormR, - final QuantileSearchCriteria inclusive) { - final int len = cumWeights.length; - final long N = cumWeights[len - 1]; - float result = Float.NaN; - - for (int i = 0; i < len; i++) { - if (i == len - 1) { //at top or single element array - double topR = (double)cumWeights[i] / N; - float topQ = quantiles[i]; - if (inclusive == INCLUSIVE) { - if (givenNormR <= topR) { result = topQ; break; } - fail("normRank > 1.0"); - } - //EXCLUSIVE - if (givenNormR < topR ) { result = topQ; break; } - if (givenNormR > 1.0) { fail("normRank > 1.0"); } - result =topQ; // R == 1.0 - break; - } - else { //always at least two valid entries - double loR = (double)cumWeights[i] / N; - double hiR = (double)cumWeights[i + 1] / N; - float loQ = quantiles[i]; - float hiQ = quantiles[i + 1]; - if (inclusive == INCLUSIVE) { - if (i == 0) { //at bottom, starting up - if (givenNormR <= loR) { result = loQ; break; } - } - if (loR < givenNormR && givenNormR <= hiR) { result = hiQ; break; } - continue; - } - //EXCLUSIVE - if (i == 0) { //at bottom, starting up - if (givenNormR < loR) { result = loQ; break; } - } - if (loR <= givenNormR && givenNormR < hiR) { result = hiQ; break; } - continue; - } - } - return result; - } - - /** - * Gets the quantile based on the given normalized rank. - *
  • getQuantile(rank, INCLUSIVE) or q(r, GE)
    - * := Given r, return the quantile, q, of the smallest rank that is strictly Greater than or Equal to r.
  • - *

  • getQuantile(rank, EXCLUSIVE) or q(r, GT)
    - * := Given r, return the quantile, q, of the smallest rank that is strictly Greater Than r.
  • - *
- * - * @param cumWeights the given natural cumulative weights. The last value must be N. - * @param quantiles the given quantile array - * @param givenNormR the given normalized rank, which must be in the range [0.0, 1.0], inclusive. - * @param inclusive determines the search criterion used. - * @return the quantile - */ - public static double getTrueDoubleQuantile( - final long[] cumWeights, - final double[] quantiles, - final double givenNormR, - final QuantileSearchCriteria inclusive) { - final int len = cumWeights.length; - final long N = cumWeights[len - 1]; - double result = Double.NaN; - - for (int i = 0; i < len; i++) { - if (i == len - 1) { //at top or single element array - double topR = (double)cumWeights[i] / N; - double topQ = quantiles[i]; - if (inclusive == INCLUSIVE) { - if (givenNormR <= topR) { result = topQ; break; } - fail("normRank > 1.0"); - } - //EXCLUSIVE - if (givenNormR < topR ) { result = topQ; break; } - if (givenNormR > 1.0) { fail("normRank > 1.0"); } - result = topQ; // R == 1.0 - break; - } - else { //always at least two valid entries - double loR = (double)cumWeights[i] / N; - double hiR = (double)cumWeights[i + 1] / N; - double loQ = quantiles[i]; - double hiQ = quantiles[i + 1]; - if (inclusive == INCLUSIVE) { - if (i == 0) { //at bottom, starting up - if (givenNormR <= loR) { result = loQ; break; } - } - if (loR < givenNormR && givenNormR <= hiR) { result = hiQ; break; } - continue; - } - //EXCLUSIVE) { - if (i == 0) { //at bottom, starting up - if (givenNormR < loR) { result = loQ; break; } - } - if (loR <= givenNormR && givenNormR < hiR) { result = hiQ; break; } - continue; - } - } - return result; - } - - /** - * Gets the quantile based on the given normalized rank. - *
  • getQuantile(rank, INCLUSIVE) or q(r, GE)
    - * := Given r, return the quantile, q, of the smallest rank that is strictly Greater than or Equal to r.
  • - *

  • getQuantile(rank, EXCLUSIVE) or q(r, GT)
    - * := Given r, return the quantile, q, of the smallest rank that is strictly Greater Than r.
  • - *
- * - * @param cumWeights the given natural cumulative weights. The last value must be N. - * @param quantiles the given quantile array - * @param givenNormR the given normalized rank, which must be in the range [0.0, 1.0], inclusive. - * @param inclusive determines the search criterion used. - * @return the quantile - */ - public static T getTrueItemQuantile( - final long[] cumWeights, - final T[] quantiles, - final double givenNormR, - final QuantileSearchCriteria inclusive) { - final int len = cumWeights.length; - final long N = cumWeights[len - 1]; - T result = null; - - for (int i = 0; i < len; i++) { - if (i == len - 1) { //at top or single element array - double topR = (double)cumWeights[i] / N; - T topQ = quantiles[i]; - if (inclusive == INCLUSIVE) { - if (givenNormR <= topR) { result = topQ; break; } - fail("normRank > 1.0"); - } - //EXCLUSIVE - if (givenNormR < topR ) { result = topQ; break; } - if (givenNormR > 1.0) { fail("normRank > 1.0"); } - result = topQ; // R == 1.0 - break; - } - else { //always at least two valid entries - double loR = (double)cumWeights[i] / N; - double hiR = (double)cumWeights[i + 1] / N; - T loQ = quantiles[i]; - T hiQ = quantiles[i + 1]; - if (inclusive == INCLUSIVE) { - if (i == 0) { //at bottom, starting up - if (givenNormR <= loR) { result = loQ; break; } - } - if (loR < givenNormR && givenNormR <= hiR) { result = hiQ; break; } - continue; - } - //EXCLUSIVE) { - if (i == 0) { //at bottom, starting up - if (givenNormR < loR) { result = loQ; break; } - } - if (loR <= givenNormR && givenNormR < hiR) { result = hiQ; break; } - continue; - } - } - return result; - } - - - /** - * Gets the normalized rank based on the given value. - *
  • getRank(quantile, INCLUSIVE) or r(q, LE)
    - * := Given q, return the rank, r, of the largest quantile that is less than or equal to q.
  • - *
  • getRank(quantile, EXCLUSIVE) or r(q, LT) - * := Given q, return the rank, r, of the largest quantile that is strictly Less Than q.
  • - *
- * - * @param cumWeights the given cumulative weights - * @param quantiles the given quantile array - * @param givenQ the given quantile - * @param inclusive determines the search criterion used. - * @return the normalized rank - */ - public static double getTrueFloatRank( - final long[] cumWeights, - final float[] quantiles, - final float givenQ, - final QuantileSearchCriteria inclusive) { - final int len = quantiles.length; - final long N = cumWeights[len -1]; - double result = Double.NaN; - - for (int i = len; i-- > 0; ) { - if (i == 0) { //at bottom of single element array - double bottomR = (double)cumWeights[i] / N; - float bottomQ = quantiles[i]; - if (inclusive == INCLUSIVE) { - if (givenQ < bottomQ) { result = 0; break; } - result = bottomR; - break; - } - //EXCLUSIVE - if (givenQ <= bottomQ) { result = 0; break; } - if (bottomQ < givenQ) { result = bottomR; break; } - } - else { //always at least two valid entries - double loR = (double)cumWeights[i - 1] / N; - //double hiR = (double)cumWeights[i] / N; - float loQ = quantiles[i - 1]; - float hiQ = quantiles[i]; - if (inclusive == INCLUSIVE) { - if (i == len - 1) { //at top, starting down - if (hiQ <= givenQ) { result = 1.0; break; } - } - if (loQ <= givenQ && givenQ < hiQ) { result = loR; break; } - continue; - } - //EXCLUSIVE - if (i == len - 1) { //at top, starting down - if (hiQ < givenQ) { result = 1.0; break; } - } - if (loQ < givenQ && givenQ <= hiQ) { result = loR; break; } - continue; - } - } - return result; - } - - /** - * Gets the normalized rank based on the given value. - *
  • getRank(quantile, INCLUSIVE) or r(q, LE)
    - * := Given q, return the rank, r, of the largest quantile that is less than or equal to q.
  • - *
  • getRank(quantile, EXCLUSIVE) or r(q, LT) - * := Given q, return the rank, r, of the largest quantile that is strictly Less Than q.
  • - *
- * - * @param cumWeights the given cumulative weights - * @param quantiles the given quantile array - * @param givenQ the given quantile - * @param inclusive determines the search criterion used. - * @return the normalized rank - */ - public static double getTrueDoubleRank( - final long[] cumWeights, - final double[] quantiles, - final double givenQ, - final QuantileSearchCriteria inclusive) { - final int len = quantiles.length; - final long N = cumWeights[len -1]; - double result = Double.NaN; - - for (int i = len; i-- > 0; ) { - if (i == 0) { //at bottom of single element array - double bottomR = (double)cumWeights[i] / N; - double bottomQ = quantiles[i]; - if (inclusive == INCLUSIVE) { - if (givenQ < bottomQ) { result = 0; break; } - result = bottomR; - break; - } - //EXCLUSIVE - if (givenQ <= bottomQ) { result = 0; break; } - if (bottomQ < givenQ) { result = bottomR; break; } - } - else { //always at least two valid entries - double loR = (double)cumWeights[i - 1] / N; - //double hiR = (double)cumWeights[i] / N; - double loQ = quantiles[i - 1]; - double hiQ = quantiles[i]; - if (inclusive == INCLUSIVE) { - if (i == len - 1) { //at top, starting down - if (hiQ <= givenQ) { result = 1.0; break; } - } - if (loQ <= givenQ && givenQ < hiQ) { result = loR; break; } - continue; - } - //EXCLUSIVE - if (i == len - 1) { //at top, starting down - if (hiQ < givenQ) { result = 1.0; break; } - } - if (loQ < givenQ && givenQ <= hiQ) { result = loR; break; } - continue; - } - } - return result; - } - - /** - * Gets the normalized rank based on the given value. - *
  • getRank(quantile, INCLUSIVE) or r(q, LE)
    - * := Given q, return the rank, r, of the largest quantile that is less than or equal to q.
  • - *
  • getRank(quantile, EXCLUSIVE) or r(q, LT) - * := Given q, return the rank, r, of the largest quantile that is strictly Less Than q.
  • - *
- * - * @param cumWeights the given cumulative weights - * @param quantiles the given quantile array - * @param givenQ the given quantile - * @param inclusive determines the search criterion used. - * @return the normalized rank - */ - public static double getTrueItemRank( - final long[] cumWeights, - final T[] quantiles, - final T givenQ, - final QuantileSearchCriteria inclusive, - final Comparator comp) { - final int len = quantiles.length; - final long N = cumWeights[len -1]; - double result = Double.NaN; - - for (int i = len; i-- > 0; ) { - if (i == 0) { //at bottom of single element array - double bottomR = (double)cumWeights[i] / N; - T bottomQ = quantiles[i]; - if (inclusive == INCLUSIVE) { - if (lt(givenQ, bottomQ, comp)) { result = 0; break; } - result = bottomR; - break; - } - //EXCLUSIVE - if (le(givenQ, bottomQ, comp)) { result = 0; break; } - if (lt(bottomQ, givenQ, comp)) { result = bottomR; break; } - } - else { //always at least two valid entries - double loR = (double)cumWeights[i - 1] / N; - //double hiR = (double)cumWeights[i] / N; - T loQ = quantiles[i - 1]; - T hiQ = quantiles[i]; - if (inclusive == INCLUSIVE) { - if (i == len - 1) { //at top, starting down - if (le(hiQ, givenQ, comp)) { result = 1.0; break; } - } - if (le(loQ, givenQ,comp) && lt(givenQ, hiQ, comp)) { result = loR; break; } - continue; - } - //EXCLUSIVE - if (i == len - 1) { //at top, starting down - if (lt(hiQ, givenQ, comp)) { result = 1.0; break; } - } - if (lt(loQ, givenQ, comp) && le(givenQ, hiQ, comp)) { result = loR; break; } - continue; - } - } - return result; - } - -} - diff --git a/src/test/java/org/apache/datasketches/quantilescommon/LongsAsOrderableStrings.java b/src/test/java/org/apache/datasketches/quantilescommon/LongsAsOrderableStrings.java deleted file mode 100644 index 10d5c9073..000000000 --- a/src/test/java/org/apache/datasketches/quantilescommon/LongsAsOrderableStrings.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static java.lang.Math.ceil; -import static java.lang.Math.log; -import static org.apache.datasketches.common.Util.characterPad; - -import org.apache.datasketches.common.SketchesArgumentException; - -/** - * Creates a string from a positive long value that is orderable in the - * same order as its long value. - */ -public final class LongsAsOrderableStrings { - - /** - * Converts the given long into a string with leading spaces based on the given numDigits. - * This allows the stings to be ordered as if they were longs. - * @param value the value to convert - * @param numDigits the maximum required number of total spaces for digits. - * @return the given long into a string with leading spaces - */ - public static String getString(final long value, final int numDigits) { - return characterPad(Long.toString(value), numDigits, ' ', false); - } - - /** - * Converts the given String back to a long by trimming any leading or trailing spaces. - * @param value the given string to convert - * @return the given String back to a long - */ - public static long getLong(final String value) { - long out; - try { out = Long.parseLong(value.trim()); } catch (NumberFormatException e) { - throw new SketchesArgumentException(e.toString()); - } - return out; - } - - /** - * Computes the number of digits required to display the given positive long value. - * This does not include commas or other digit separators. - * This works with longs less than 1E15. - * @param maxValue the maximum anticipated long value. - * @return the number of required display digits - */ - public static int digits(final long maxValue) { - if (maxValue <= 0) { return 1; } - return (int) ceil(log(maxValue + 1) / log(10.0)); - } - -} diff --git a/src/test/java/org/apache/datasketches/quantilescommon/PartitionBoundariesTest.java b/src/test/java/org/apache/datasketches/quantilescommon/PartitionBoundariesTest.java deleted file mode 100644 index 7ff4596d5..000000000 --- a/src/test/java/org/apache/datasketches/quantilescommon/PartitionBoundariesTest.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.apache.datasketches.common.Util.LS; -import static org.apache.datasketches.quantilescommon.LongsAsOrderableStrings.digits; -import static org.apache.datasketches.quantilescommon.LongsAsOrderableStrings.getString; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - -import java.util.Comparator; - -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.kll.KllItemsSketch; -import org.apache.datasketches.quantiles.QuantilesItemsSketch; -import org.testng.annotations.Test; - -/** - * This tests partition boundaries with both KllItemsSketch and classic QuantilesItemsSketch - */ -public class PartitionBoundariesTest { - private final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - private static String[] hdr = {"N", "MaxItem", "MinItem", "NumParts", "SearchCriteria"}; - private static String hdrfmt = "%6s %10s %10s %10s %15s" + LS; - private static String hdrdfmt = "%6d %10s %10s %10d %15s" + LS; - - private static String[] rowhdr = {"Row", "NormRanks", "NatRanks", "Boundaries", "DeltaItems"}; - private static String rowhdrfmt = "%5s %12s %12s %12s %12s" + LS; - private static String rowdfmt = "%5d %12.8f %12d %12s %12d" + LS; - - private static String[] rowhdr2 = {"Row", "NormRanks", "NatRanks", "Boundaries"}; - private static String rowhdrfmt2= "%5s %12s %12s %12s" + LS; - private static String rowdfmt2 = "%5d %12.8f %12d %12s" + LS; - - //@Test //visual check only. set enablePrinting = true to view. - public void checkSkewWithClassic() { - final int n = 2050; //1000000; - final int k = 1 << 15; - final int n2 = 200; - final int totalN = n + n2; - final int numDigits = digits(totalN); - final long v2 = 1000L; - final QuantileSearchCriteria searchCrit = QuantileSearchCriteria.INCLUSIVE; - final QuantilesItemsSketch sk = QuantilesItemsSketch.getInstance(String.class,k, Comparator.naturalOrder()); - - for (long i = 1; i <= n; i++) { sk.update(getString(i, numDigits)); } - for (long i = 1; i <= n2; i++) { sk.update(getString(v2, numDigits)); } - final int numParts = sk.getMaxPartitions(); //22 - final ItemsSketchSortedView sv = sk.getSortedView(); - final GenericSortedViewIterator itr = sv.iterator(); - println("SORTED VIEW:"); - printf(rowhdrfmt2, (Object[])rowhdr2); - int j = 0; - while (itr.next()) { - printf(rowdfmt2, j++, itr.getNormalizedRank(searchCrit), itr.getNaturalRank(searchCrit), itr.getQuantile()); - } - - final GenericPartitionBoundaries gpb = sv.getPartitionBoundariesFromNumParts(numParts, searchCrit); - final int arrLen = gpb.getBoundaries().length; - final double[] normRanks = gpb.getNormalizedRanks(); - final long[] natRanks = gpb.getNaturalRanks(); - final String[] boundaries = gpb.getBoundaries(); - final long[] numDeltaItems = gpb.getNumDeltaItems(); - println(""); - println("GET PARTITION BOUNDARIES:"); - printf(hdrfmt, (Object[]) hdr); - printf(hdrdfmt, totalN, gpb.getMaxItem(), gpb.getMinItem(), numParts, searchCrit.toString()); - println(""); - printf(rowhdrfmt, (Object[]) rowhdr); - for (int i = 0; i < arrLen; i++) { - printf(rowdfmt, i, normRanks[i], natRanks[i], boundaries[i], numDeltaItems[i]); - } - } - - //@Test //visual check only. set enablePrinting = true to view. - public void checkSkewWithKll() { - final int n = 2050; //1_000_000; - final int k = 1 << 15; - final int n2 = 200; - final int totalN = n + n2; - final int numDigits = digits(totalN); - final long v2 = 1000L; - final QuantileSearchCriteria searchCrit = QuantileSearchCriteria.INCLUSIVE; - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, Comparator.naturalOrder(), serDe); - - for (long i = 1; i <= n; i++) { sk.update(getString(i, numDigits)); } - for (long i = 1; i <= n2; i++) { sk.update(getString(v2, numDigits)); } - final int numParts = sk.getMaxPartitions(); //22 - final ItemsSketchSortedView sv = sk.getSortedView(); - final GenericSortedViewIterator itr = sv.iterator(); - println("SORTED VIEW:"); - printf(rowhdrfmt2, (Object[])rowhdr2); - int j = 0; - while (itr.next()) { - printf(rowdfmt2, j++, itr.getNormalizedRank(searchCrit), itr.getNaturalRank(searchCrit), itr.getQuantile()); - } - - final GenericPartitionBoundaries gpb = sv.getPartitionBoundariesFromNumParts(numParts, searchCrit); - final int arrLen = gpb.getBoundaries().length; - final double[] normRanks = gpb.getNormalizedRanks(); - final long[] natRanks = gpb.getNaturalRanks(); - final String[] boundaries = gpb.getBoundaries(); - final long[] numDeltaItems = gpb.getNumDeltaItems(); - println(""); - println("GET PARTITION BOUNDARIES:"); - printf(hdrfmt, (Object[]) hdr); - printf(hdrdfmt, totalN, gpb.getMaxItem(), gpb.getMinItem(), numParts, searchCrit.toString()); - println(""); - printf(rowhdrfmt, (Object[]) rowhdr); - for (int i = 0; i < arrLen; i++) { - printf(rowdfmt, i, normRanks[i], natRanks[i], boundaries[i], numDeltaItems[i]); - } - } - - @Test - public void getQuantilesVsPartitionBoundariesKll() { - final KllItemsSketch sketch = KllItemsSketch.newHeapInstance(Comparator.naturalOrder(), serDe); - sketch.update("A"); - sketch.update("B"); - sketch.update("C"); - sketch.update("D"); - String[] quantiles1 = sketch.getQuantiles(new double[] {0.0, 0.5, 1.0}, EXCLUSIVE); - String[] quantiles2 = sketch.getPartitionBoundariesFromNumParts(2, EXCLUSIVE).getBoundaries(); - assertEquals(quantiles1, quantiles2); - quantiles1 = sketch.getQuantiles(new double[] {0.0, 0.5, 1.0}, INCLUSIVE); - quantiles2 = sketch.getPartitionBoundariesFromNumParts(2, INCLUSIVE).getBoundaries(); - assertEquals(quantiles1, quantiles2); - } - - @Test - public void getQuantilesVsPartitionBoundariesClassic() { - final QuantilesItemsSketch sketch = QuantilesItemsSketch.getInstance(Integer.class, Comparator.naturalOrder()); - sketch.update(1); - sketch.update(2); - sketch.update(3); - sketch.update(4); - Integer[] quantiles1 = sketch.getQuantiles(new double[] {0.0, 0.5, 1.0}, EXCLUSIVE); - Integer[] quantiles2 = sketch.getPartitionBoundariesFromNumParts(2, EXCLUSIVE).getBoundaries(); - assertEquals(quantiles1, quantiles2); - quantiles1 = sketch.getQuantiles(new double[] {0.0, 0.5, 1.0}, INCLUSIVE); - quantiles2 = sketch.getPartitionBoundariesFromNumParts(2, INCLUSIVE).getBoundaries(); - assertEquals(quantiles1, quantiles2); - } - - /** - * Because both Kll and Classic items sketches use the same Sorted View class. - * This test applies to both. - */ - @Test - public void checkSimpleEndsAdjustment() { - final String[] quantiles = {"2","4","6","7"}; - final long[] cumWeights = {2, 4, 6, 8}; - final long totalN = 8; - final Comparator comparator = Comparator.naturalOrder(); - final String maxItem = "8"; - final String minItem = "1"; - final ItemsSketchSortedView sv = new ItemsSketchSortedView<>( - quantiles, cumWeights, totalN, comparator, maxItem, minItem, - String.class, .01, 4); - - final GenericSortedViewIterator itr = sv.iterator(); - while (itr.next()) { - println(itr.getNaturalRank(INCLUSIVE) + ", " + itr.getQuantile(INCLUSIVE)); - } - final GenericPartitionBoundaries gpb = sv.getPartitionBoundariesFromNumParts(2); - final String[] boundaries = gpb.getBoundaries(); - final long[] natRanks = gpb.getNaturalRanks(); - final double[] normRanks = gpb.getNormalizedRanks(); - final long[] deltaItems = gpb.getNumDeltaItems(); - final int numParts = gpb.getNumPartitions(); - final String maxItm = gpb.getMaxItem(); - final String minItm = gpb.getMinItem(); - assertEquals(boundaries, new String[] {"1","4","8"}); - assertEquals(natRanks, new long[] {1,4,8}); - assertEquals(normRanks, new double[] {.125,.5,1.0}); - assertEquals(deltaItems, new long[] {0,4,4}); - assertEquals(numParts, 2); - assertEquals(maxItm, "8"); - assertEquals(minItm, "1"); - } - - @SuppressWarnings("unused") - @Test //For visual check, set enablePrinting = true to view. - public void checkSketchPartitionLimits() { - final long totalN = 2000; //1_000_000; - final Comparator comparator = Comparator.naturalOrder(); - final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - final int k = 1 << 15; - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, comparator, serDe); - final int d = digits(totalN); - for (int i = 1; i <= totalN; i++) { - sk.update(getString(i, d)); - } - //*** - final int numRet = sk.getNumRetained(); - println("NumRetained: " + numRet + " /2: " + (numRet / 2)); - final double eps = sk.getNormalizedRankError(true); - printf("NormRankErr: %10.6f 1/eps: %10.3f" + LS, eps, 1/eps); - //*** - //this should pass - final int goodNumPartsRequest = sk.getMaxPartitions(); - println("Good numPartsRequest " + goodNumPartsRequest); - GenericPartitionBoundaries gpb = sk.getPartitionBoundariesFromNumParts(goodNumPartsRequest); - //this should fail - try { - final int badNumPartsRequest = goodNumPartsRequest + 1; - println("Bad numPartsRequest " + badNumPartsRequest); - gpb = sk.getPartitionBoundariesFromNumParts(badNumPartsRequest); - fail("Bad numPartsRequest should have failed. " + badNumPartsRequest); - } catch (final SketchesArgumentException e) { } //OK - } - - @SuppressWarnings("unused") - @Test //For visual check, set enablePrinting = true to view. - public void checkSketchPartitionLimits2() { - final long totalN = 2000; //1_000_000; - final Comparator comparator = Comparator.naturalOrder(); - final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - final int k = 1 << 15; - final KllItemsSketch sk = KllItemsSketch.newHeapInstance(k, comparator, serDe); - final int d = digits(totalN); - for (int i = 1; i <= totalN; i++) { - sk.update(getString(i, d)); - } - final double eps = sk.getNormalizedRankError(true); - printf("NormRankErr: %10.6f 1/eps: %10.3f" + LS, eps, 1/eps); - println("N: " + sk.getN()); - println("Max Parts: " + sk.getMaxPartitions()); - - //this should pass - final long goodPartSizeRequest= sk.getMinPartitionSizeItems(); - println("Good partSizeRequest " + goodPartSizeRequest); - final GenericPartitionBoundaries gpb = sk.getPartitionBoundariesFromPartSize(goodPartSizeRequest); - //this should fail - try { - final long badPartSizeRequest = goodPartSizeRequest - 1; - println("Bad partSizeRequest " + badPartSizeRequest); - } catch (final SketchesArgumentException e) { } //OK - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } -} diff --git a/src/test/java/org/apache/datasketches/quantilescommon/QuantilesUtilTest.java b/src/test/java/org/apache/datasketches/quantilescommon/QuantilesUtilTest.java deleted file mode 100644 index 24c653203..000000000 --- a/src/test/java/org/apache/datasketches/quantilescommon/QuantilesUtilTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.Test; - -public class QuantilesUtilTest { - - @Test - public void checkEquallySpacedDoubles() { - double[] arr = QuantilesUtil.equallySpacedDoubles(2); - assertEquals(arr[1], 0.5); - arr = QuantilesUtil.equallySpacedDoubles(4); - assertEquals(arr[0], 0.0); - assertEquals(arr[1], 0.25); - assertEquals(arr[2], 0.5); - assertEquals(arr[3], 0.75); - assertEquals(arr[4], 1.0); - } - - @Test - public void checkEquallySpacedLongs() { - long[] arr = QuantilesUtil.equallySpacedLongs(1, 5, 4); - assertEquals(arr[0], 1); - assertEquals(arr[1], 2); - assertEquals(arr[2], 3); - assertEquals(arr[3], 4); - assertEquals(arr[4], 5); - } - - @Test - public void checkEvenlySpacedFloats() { - float[] arr = QuantilesUtil.evenlySpacedFloats(0, 1, 3); - assertEquals(arr[0], 0.0f); - assertEquals(arr[1], 0.5f); - assertEquals(arr[2], 1.0f); - arr = QuantilesUtil.evenlySpacedFloats(3, 7, 3); - assertEquals(arr[0], 3.0f); - assertEquals(arr[1], 5.0f); - assertEquals(arr[2], 7.0f); - arr = QuantilesUtil.evenlySpacedFloats(0f, 1.0f, 2); - assertEquals(arr[0], 0f); - assertEquals(arr[1], 1f); - try { QuantilesUtil.evenlySpacedFloats(0f, 1f, 1); fail(); } catch (SketchesArgumentException e) {} - } - - @Test - public void checkEvenlySpacedDoubles() { - double[] arr = QuantilesUtil.evenlySpacedDoubles(0, 1, 3); - assertEquals(arr[0], 0.0); - assertEquals(arr[1], 0.5); - assertEquals(arr[2], 1.0); - arr = QuantilesUtil.evenlySpacedDoubles(3, 7, 3); - assertEquals(arr[0], 3.0); - assertEquals(arr[1], 5.0); - assertEquals(arr[2], 7.0); - arr = QuantilesUtil.evenlySpacedDoubles(0, 1.0, 2); - assertEquals(arr[0], 0); - assertEquals(arr[1], 1.0); - try { QuantilesUtil.evenlySpacedDoubles(0, 1.0, 1); fail(); } catch (SketchesArgumentException e) {} - } - - - - @Test - public void checkEvenlyLogSpaced() { - final double[] arr = QuantilesUtil.evenlyLogSpaced(1, 8, 4); - assertEquals(arr[0], 1.0); - assertEquals(arr[1], 2.0); - assertEquals(arr[2], 4.0); - assertEquals(arr[3], 8.0); - try { QuantilesUtil.evenlyLogSpaced(-1.0, 1.0, 2); fail(); } catch (SketchesArgumentException e) {} - try { QuantilesUtil.evenlyLogSpaced(1.0, -1.0, 2); fail(); } catch (SketchesArgumentException e) {} - try { QuantilesUtil.evenlyLogSpaced(-1.0, -1.0, 2); fail(); } catch (SketchesArgumentException e) {} - try { QuantilesUtil.evenlyLogSpaced(1.0, 1.0, 1); fail(); } catch (SketchesArgumentException e) {} - } - - private final static boolean enablePrinting = true; - - /** - * @param o the Object to println - */ - static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} - diff --git a/src/test/java/org/apache/datasketches/quantilescommon/SortedViewEmptyAccessorTest.java b/src/test/java/org/apache/datasketches/quantilescommon/SortedViewEmptyAccessorTest.java deleted file mode 100644 index e983272d3..000000000 --- a/src/test/java/org/apache/datasketches/quantilescommon/SortedViewEmptyAccessorTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.quantilescommon; - -import static org.testng.Assert.fail; - -import java.util.Comparator; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.Test; - -public final class SortedViewEmptyAccessorTest { - - @Test - public void checkFloatsSortedViewEmptyAccessors() { - final FloatsSketchSortedView sv = new FloatsSketchSortedView( - new float[] {1F}, - new long[] {1}, - 0, - 1F, - 1F); - - assertEmptyAccessorThrows(() -> sv.getMaxItem()); - assertEmptyAccessorThrows(() -> sv.getMinItem()); - } - - @Test - public void checkDoublesSortedViewEmptyAccessors() { - final DoublesSketchSortedView sv = new DoublesSketchSortedView( - new double[] {1.0}, - new long[] {1}, - 0, - 1.0, - 1.0); - - assertEmptyAccessorThrows(() -> sv.getMaxItem()); - assertEmptyAccessorThrows(() -> sv.getMinItem()); - } - - @Test - public void checkLongsSortedViewEmptyAccessors() { - final LongsSketchSortedView sv = new LongsSketchSortedView( - new long[] {1}, - new long[] {1}, - 0, - 1, - 1); - - assertEmptyAccessorThrows(() -> sv.getMaxItem()); - assertEmptyAccessorThrows(() -> sv.getMinItem()); - } - - @Test - public void checkItemsSortedViewEmptyAccessors() { - final ItemsSketchSortedView sv = new ItemsSketchSortedView<>( - new String[] {"1"}, - new long[] {1}, - 0, - Comparator.naturalOrder(), - "1", - "1", - String.class, - .01, - 1); - - assertEmptyAccessorThrows(() -> sv.getMaxItem()); - assertEmptyAccessorThrows(() -> sv.getMinItem()); - } - - private static void assertEmptyAccessorThrows(final Runnable accessor) { - try { - accessor.run(); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - } -} diff --git a/src/test/java/org/apache/datasketches/req/ReqCompactorTest.java b/src/test/java/org/apache/datasketches/req/ReqCompactorTest.java deleted file mode 100644 index 6c0ec20da..000000000 --- a/src/test/java/org/apache/datasketches/req/ReqCompactorTest.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.positional.PositionalSegment; -import org.apache.datasketches.req.FloatBuffer; -import org.apache.datasketches.req.ReqCompactor; -import org.apache.datasketches.req.ReqSerDe; -import org.apache.datasketches.req.ReqSketch; -import org.apache.datasketches.req.ReqSerDe.Compactor; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class ReqCompactorTest { - final ReqSketchTest reqSketchTest = new ReqSketchTest(); - - @Test - public void checkNearestEven() { - assertEquals(ReqCompactor.nearestEven(-0.9f), 0); - } - - @Test - public void checkGetters() { - final boolean up = true; - final boolean hra = true; - final ReqSketch sk = reqSketchTest.loadSketch( 20, 1, 120, up, hra, 0); - final ReqCompactor c = sk.getCompactors().get(0); - - c.getCoin(); - final long state = c.getState(); - assertEquals(state, 1L); - assertEquals(c.getNumSections(), 3); - assertEquals(c.getSectionSize(), 20); - } - - @Test - public void checkSerDe() { - checkSerDeImpl(12, false); - checkSerDeImpl(12, true); - } - - private static void checkSerDeImpl(final int k, final boolean hra) { - final ReqCompactor c1 = new ReqCompactor((byte)0, hra, k, null); - final int nomCap = 2 * 3 * k; - final int cap = 2 * nomCap; - final int delta = nomCap; - final FloatBuffer fbuf = c1.getBuffer(); - - for (int i = 1; i <= nomCap; i++) { - fbuf.append(i); //compactor doesn't have a direct update() method - } - final float minV = 1; - final float maxV = nomCap; - final float sectionSizeFlt = c1.getSectionSizeFlt(); - final int sectionSize = c1.getSectionSize(); - final int numSections = c1.getNumSections(); - final long state = c1.getState(); - final int lgWeight = c1.getLgWeight(); - final boolean c1hra = c1.isHighRankAccuracy(); - final boolean sorted = fbuf.isSorted(); - final byte[] c1ser = c1.toByteArray(); - //now deserialize - final PositionalSegment posSeg = PositionalSegment.wrap(MemorySegment.ofArray(c1ser)); - final Compactor compactor = ReqSerDe.extractCompactor(posSeg, sorted, c1hra); - final ReqCompactor c2 = compactor.reqCompactor; - assertEquals(compactor.minItem, minV); - assertEquals(compactor.maxItem, maxV); - assertEquals(compactor.count, nomCap); - assertEquals(c2.getSectionSizeFlt(), sectionSizeFlt); - assertEquals(c2.getSectionSize(), sectionSize); - assertEquals(c2.getNumSections(), numSections); - assertEquals(c2.getState(), state); - assertEquals(c2.getLgWeight(), lgWeight); - assertEquals(c2.isHighRankAccuracy(), c1hra); - final FloatBuffer fbuf2 = c2.getBuffer(); - assertEquals(fbuf2.getCapacity(), cap); - assertEquals(fbuf2.getDelta(), delta); - assertTrue(fbuf.isEqualTo(fbuf2)); - } - - @Test - public void checkSerDeWithNegativeValues() { - checkSerDeNegativeImpl(12, false); - checkSerDeNegativeImpl(12, true); - } - - private static void checkSerDeNegativeImpl(final int k, final boolean hra) { - final ReqCompactor c1 = new ReqCompactor((byte)0, hra, k, null); - final int nomCap = 2 * 3 * k; - final FloatBuffer fbuf = c1.getBuffer(); - - for (int i = 1; i <= nomCap; i++) { - fbuf.append(-i); //all negative values - } - final byte[] c1ser = c1.toByteArray(); - final PositionalSegment posSeg = PositionalSegment.wrap(MemorySegment.ofArray(c1ser)); - final Compactor compactor = ReqSerDe.extractCompactor(posSeg, fbuf.isSorted(), hra); - assertEquals(compactor.minItem, -nomCap); - assertEquals(compactor.maxItem, -1f); - } - - @Test - public void checkSerDeWithMixedValues() { - checkSerDeMixedImpl(12, false); - checkSerDeMixedImpl(12, true); - } - - private static void checkSerDeMixedImpl(final int k, final boolean hra) { - final ReqCompactor c1 = new ReqCompactor((byte)0, hra, k, null); - final int nomCap = 2 * 3 * k; - final int half = nomCap / 2; - final FloatBuffer fbuf = c1.getBuffer(); - - for (int i = 0; i < nomCap; i++) { - fbuf.append(i - half); // range: -half to half-1 - } - final byte[] c1ser = c1.toByteArray(); - final PositionalSegment posSeg = PositionalSegment.wrap(MemorySegment.ofArray(c1ser)); - final Compactor compactor = ReqSerDe.extractCompactor(posSeg, fbuf.isSorted(), hra); - assertEquals(compactor.minItem, (float) -half); - assertEquals(compactor.maxItem, (float) (half - 1)); - } - - @Test - public void checkSerDeWithInfiniteValues() { - checkSerDeInfiniteImpl(12, false); - checkSerDeInfiniteImpl(12, true); - } - - private static void checkSerDeInfiniteImpl(final int k, final boolean hra) { - final ReqCompactor c1 = new ReqCompactor((byte)0, hra, k, null); - final FloatBuffer fbuf = c1.getBuffer(); - - fbuf.append(Float.POSITIVE_INFINITY); - fbuf.append(1); - fbuf.append(Float.NEGATIVE_INFINITY); - fbuf.append(-1); - - final byte[] c1ser = c1.toByteArray(); - final PositionalSegment posSeg = PositionalSegment.wrap(MemorySegment.ofArray(c1ser)); - final Compactor compactor = ReqSerDe.extractCompactor(posSeg, fbuf.isSorted(), hra); - assertEquals(compactor.minItem, Float.NEGATIVE_INFINITY); - assertEquals(compactor.maxItem, Float.POSITIVE_INFINITY); - } -} diff --git a/src/test/java/org/apache/datasketches/req/ReqDebugImplTest.java b/src/test/java/org/apache/datasketches/req/ReqDebugImplTest.java deleted file mode 100644 index da19aa9ea..000000000 --- a/src/test/java/org/apache/datasketches/req/ReqDebugImplTest.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import java.util.List; - -import org.apache.datasketches.req.ReqCompactor; -import org.apache.datasketches.req.ReqDebug; -import org.apache.datasketches.req.ReqSketch; - -/** - * The implementation of the ReqDebug interface. The current levels are - * implemented: - *
  • Level 0: The random generator in the compactor will be given a fixed - * seed which will make the sketch deterministic.
  • - *
  • Level 1: Print summaries, but not the data retained by the sketch. This is useful - * when the sketch is large.
  • - *
  • Level 2: Print summaries and all data retained by the sketch.
  • - *
- * - * @author Lee Rhodes - */ -public class ReqDebugImplTest implements ReqDebug { - private static final String LS = System.getProperty("line.separator"); - private static final String TAB = "\t"; - private ReqSketch sk; - final int debugLevel; - final String fmt; - - /** - * Constructor - * @param debugLevel sets the debug level of detail - * @param fmt string format to use when printing values - */ - public ReqDebugImplTest(final int debugLevel, final String fmt) { - this.debugLevel = debugLevel; - this.fmt = fmt; - } - - @Override - public void emitStart(final ReqSketch sk) { - if (debugLevel == 0) { return; } - this.sk = sk; //SpotBugs EI_EXPOSE_REP2 suppressed by FindBugsExcludeFilter - println("START"); - } - - @Override - public void emitStartCompress() { - if (debugLevel == 0) { return; } - final int retItems = sk.getNumRetained(); - final int maxNomSize = sk.getMaxNomSize(); - final long totalN = sk.getN(); - final StringBuilder sb = new StringBuilder(); - sb.append("COMPRESS: "); - sb.append("skRetItems: ").append(retItems).append(" >= "); - sb.append("MaxNomSize: ").append(maxNomSize); - sb.append(" N: ").append(totalN); - println(sb.toString()); - emitAllHorizList(); - } - - @Override - public void emitCompressDone() { - if (debugLevel == 0) { return; } - final int retItems = sk.getNumRetained(); - final int maxNomSize = sk.getMaxNomSize(); - emitAllHorizList(); - println("COMPRESS: DONE: SketchSize: " + retItems + TAB - + " MaxNomSize: " + maxNomSize + LS + LS); - } - - @Override - public void emitAllHorizList() { - if (debugLevel == 0) { return; } - final List compactors = sk.getCompactors(); - for (int h = 0; h < sk.getCompactors().size(); h++) { - final ReqCompactor c = compactors.get(h); - println(c.toListPrefix()); - if (debugLevel > 1) { - print(c.getBuffer().toHorizList(fmt, 20) + LS); - } else { - print(LS); - } - } - } - - @Override - public void emitMustAddCompactor() { - if (debugLevel == 0) { return; } - final int curLevels = sk.getNumLevels(); - final List compactors = sk.getCompactors(); - final ReqCompactor topC = compactors.get(curLevels - 1); - final int lgWt = topC.getLgWeight(); - final int retCompItems = topC.getBuffer().getCount(); - final int nomCap = topC.getNomCapacity(); - final StringBuilder sb = new StringBuilder(); - sb.append(" "); - sb.append("Must Add Compactor: len(c[").append(lgWt).append("]): "); - sb.append(retCompItems).append(" >= c[").append(lgWt).append("].nomCapacity(): ") - .append(nomCap); - println(sb.toString()); - } - - //compactor signals - - @Override - public void emitCompactingStart(final byte lgWeight) { - if (debugLevel == 0) { return; } - final List compactors = sk.getCompactors(); - final ReqCompactor comp = compactors.get(lgWeight); - final int nomCap = comp.getNomCapacity(); - final int secSize = comp.getSectionSize(); - final int numSec = comp.getNumSections(); - final long state = comp.getState(); - final int bufCap = comp.getBuffer().getCapacity(); - final StringBuilder sb = new StringBuilder(); - sb.append(LS + " "); - sb.append("COMPACTING[").append(lgWeight).append("] "); - sb.append("NomCapacity: ").append(nomCap); - sb.append(TAB + " SectionSize: ").append(secSize); - sb.append(TAB + " NumSections: ").append(numSec); - sb.append(TAB + " State(bin): ").append(Long.toBinaryString(state)); - sb.append(TAB + " BufCapacity: ").append(bufCap); - println(sb.toString()); - } - - @Override - public void emitNewCompactor(final byte lgWeight) { - if (debugLevel == 0) { return; } - final List compactors = sk.getCompactors(); - final ReqCompactor comp = compactors.get(lgWeight); - println(" New Compactor: lgWeight: " + comp.getLgWeight() - + TAB + "sectionSize: " + comp.getSectionSize() - + TAB + "numSections: " + comp.getNumSections()); - } - - @Override - public void emitAdjSecSizeNumSec(final byte lgWeight) { - if (debugLevel == 0) { return; } - final List compactors = sk.getCompactors(); - final ReqCompactor comp = compactors.get(lgWeight); - final int secSize = comp.getSectionSize(); - final int numSec = comp.getNumSections(); - final StringBuilder sb = new StringBuilder(); - sb.append(" "); - sb.append("Adjust: SectionSize: ").append(secSize); - sb.append(" NumSections: ").append(numSec); - println(sb.toString()); - } - - @Override - public void emitCompactionDetail(final int compactionStart, final int compactionEnd, - final int secsToCompact, final int promoteLen, final boolean coin) { - if (debugLevel == 0) { return; } - final StringBuilder sb = new StringBuilder(); - sb.append(" "); - sb.append("SecsToCompact: ").append(secsToCompact); - sb.append(TAB + " CompactStart: ").append(compactionStart); - sb.append(TAB + " CompactEnd: ").append(compactionEnd).append(LS); - final int delete = compactionEnd - compactionStart; - final String oddOrEven = coin ? "Odds" : "Evens"; - sb.append(" "); - sb.append("Promote: ").append(promoteLen); - sb.append(TAB + " Delete: ").append(delete); - sb.append(TAB + " Choose: ").append(oddOrEven); - println(sb.toString()); - } - - @Override - public void emitCompactionDone(final byte lgWeight) { - if (debugLevel == 0) { return; } - final List compactors = sk.getCompactors(); - final ReqCompactor comp = compactors.get(lgWeight); - final long state = comp.getState(); - println(" COMPACTING DONE: NumCompactions: " + state + LS); - } - - static final void printf(final String format, final Object ...args) { - System.out.printf(format, args); - } - - static final void print(final Object o) { System.out.print(o.toString()); } - - static final void println(final Object o) { System.out.println(o.toString()); } - -} diff --git a/src/test/java/org/apache/datasketches/req/ReqFloatBufferTest.java b/src/test/java/org/apache/datasketches/req/ReqFloatBufferTest.java deleted file mode 100644 index 7a7f77d05..000000000 --- a/src/test/java/org/apache/datasketches/req/ReqFloatBufferTest.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import static java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.req.FloatBuffer; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class ReqFloatBufferTest { - - @Test - public void checkTrimCount() { - checkTrimCountImpl(true); - checkTrimCountImpl(false); - } - - private static void checkTrimCountImpl(final boolean spaceAtBottom) { - final FloatBuffer buf = new FloatBuffer(16, 4, spaceAtBottom); - for (int i = 0; i < 8; i++) { buf.append(i+1); } - assertEquals(buf.getCount(), 8); - buf.trimCount(4); - assertEquals(buf.getCount(), 4); - } - - @Test - public void checkGetEvensOrOdds() { - checkGetEvensOrOddsImpl(false, false); - checkGetEvensOrOddsImpl(false, true); - checkGetEvensOrOddsImpl(true, false); - checkGetEvensOrOddsImpl(true, true); - } - - private static void checkGetEvensOrOddsImpl(final boolean odds, final boolean spaceAtBottom) { - final int cap = 16; - final FloatBuffer buf = new FloatBuffer(cap, 0, spaceAtBottom); - for (int i = 0; i < (cap/2); i++) { - buf.append(i); - } - final FloatBuffer out = buf.getEvensOrOdds(0, cap/2, odds); - //println("odds: " + odds + ", spaceAtBottom: " + spaceAtBottom); - for (int i = 0; i < out.getCount(); i++) { - final int v = (int)out.getItem(i); - if (odds) { assertTrue((v & 1) == 1); } - else { assertTrue((v & 1) == 0); } - //print(v + " "); - } - //println(""); - } - - @Test - public void checkAppendAndSpaceTop() { - checkAppendAndSpaceImpl(true); - checkAppendAndSpaceImpl(false); - } - - private static void checkAppendAndSpaceImpl(final boolean spaceAtBottom) { - final FloatBuffer buf = new FloatBuffer(2, 2, spaceAtBottom); - assertEquals(buf.getCount(), 0); - assertEquals(buf.getCapacity(), 2); - assertEquals(buf.getSpace(), 2); - buf.append(1); - assertEquals(buf.getCount(), 1); - assertEquals(buf.getCapacity(), 2); - assertEquals(buf.getSpace(), 1); - buf.append(2); - assertEquals(buf.getCount(), 2); - assertEquals(buf.getCapacity(), 2); - assertEquals(buf.getSpace(), 0); - buf.append(3); - assertEquals(buf.getCount(), 3); - assertEquals(buf.getCapacity(), 5); - assertEquals(buf.getSpace(), 2); - } - - @Test - public void checkEnsureCapacity() { - checkEnsureCapacityImpl(true); - checkEnsureCapacityImpl(false); - } - - private static void checkEnsureCapacityImpl(final boolean spaceAtBottom) { - final FloatBuffer buf = new FloatBuffer(4, 2, spaceAtBottom); - buf.append(2); - buf.append(1); - buf.append(3); - buf.ensureCapacity(8); - buf.sort(); - assertEquals(buf.getItem(0), 1.0f); - assertEquals(buf.getItem(1), 2.0f); - assertEquals(buf.getItem(2), 3.0f); - } - - @Test - public void checkCountLessThan() { - checkCountLessThanImpl(true); - checkCountLessThanImpl(false); - } - - private static void checkCountLessThanImpl(final boolean spaceAtBottom) { - final float[] sortedArr = {1,2,3,4,5,6,7}; - final FloatBuffer buf = FloatBuffer.wrap(sortedArr, true, spaceAtBottom); - final FloatBuffer buf2 = new FloatBuffer(7,0, spaceAtBottom); - buf2.mergeSortIn(buf); - assertEquals(buf2.getCountWithCriterion(4, EXCLUSIVE), 3); - buf2.mergeSortIn(buf); - assertEquals(buf2.getCountWithCriterion(4, EXCLUSIVE), 6); - assertEquals(buf2.getCount(), 14); - buf2.trimCount(12); - assertEquals(buf2.getCount(), 12); - } - - @Test - public void checkCountWcriteria() { - final int delta = 0; - final int cap = 16; - final boolean spaceAtBottom = true; - for (int len = 5; len < 10; len++) { - iterateValues(createSortedFloatBuffer(cap, delta, spaceAtBottom, len), len); - iterateValues(createSortedFloatBuffer(cap, delta, !spaceAtBottom, len), len); - } - } - - private static void iterateValues(final FloatBuffer buf, final int len) { - for (float v = 0.5f; v <= (len + 0.5f); v += 0.5f) { - checkCountWithCriteria(buf, v); - } - } - - //@Test - public void checkCount() { - final FloatBuffer buf = createSortedFloatBuffer(120, 0, true, 100); - println("LT: " + buf.getCountWithCriterion(100, EXCLUSIVE)); - println("LE: " + buf.getCountWithCriterion(100, INCLUSIVE)); - } - - private static void checkCountWithCriteria(final FloatBuffer buf, final float v) { - int count; - final int len = buf.getCount(); - final int iv = (int) v; - count = buf.getCountWithCriterion(v, EXCLUSIVE); - assertEquals(count, v > len ? len : v <= 1 ? 0 : iv == v? iv - 1 : iv); - count = buf.getCountWithCriterion(v, INCLUSIVE); - assertEquals(count, v >= len ? len : v < 1 ? 0 : iv); - } - - /** - * Creates a FloatBuffer with data - * @param cap size of the buffer - * @param delta incremental growth size - * @param sab space-at-bottom T/F - * @param len number of values to load, starting at 1.0f. - * @return FloatBuffer - */ - private static FloatBuffer createSortedFloatBuffer(final int cap, final int delta, - final boolean sab, final int len) { - final FloatBuffer buf = new FloatBuffer(cap, delta, sab); - for (int i = 0; i < len; i++) { buf.append(i + 1); } - return buf; - } - - @Test - public void checkMergeSortIn() { - checkMergeSortInImpl(true); - checkMergeSortInImpl(false); - } - - private static void checkMergeSortInImpl(final boolean spaceAtBottom) { - final float[] arr1 = {1,2,5,6}; //both must be sorted - final float[] arr2 = {3,4,7,8}; - final FloatBuffer buf1 = new FloatBuffer(12, 0, spaceAtBottom); - final FloatBuffer buf2 = new FloatBuffer(12, 0, spaceAtBottom); - for (int i = 0; i < arr1.length; i++) { buf1.append(arr1[i]); } - for (int i = 0; i < arr2.length; i++) { buf2.append(arr2[i]); } - - assertEquals(buf1.getSpace(), 8); - assertEquals(buf2.getSpace(), 8); - assertEquals(buf1.getCount(), 4); - assertEquals(buf2.getCount(), 4); - - buf1.sort(); - buf2.sort(); - buf1.mergeSortIn(buf2); - - assertEquals(buf1.getSpace(), 4); - final int len = buf1.getCount(); - assertEquals(len, 8); - - for (int i = 0; i < len; i++) { - final int item = (int)buf1.getItem(i); - assertEquals(item, i+1); - //print(item + " "); - } - //println(""); - } - - @Test - private static void checkMergeSortInNotSorted() { - final float[] arr1 = {6,5,2,1}; - final float[] arr2 = {8,7,4,3}; - final FloatBuffer buf1 = new FloatBuffer(4, 0, false); - final FloatBuffer buf2 = new FloatBuffer(4, 0, false); - for (int i = 0; i < 4; i++) { - buf1.append(arr1[i]); - buf2.append(arr2[i]); - } - try { buf1.mergeSortIn(buf2); fail(); } - catch (final SketchesArgumentException e) { } - } - - @Test - public void checkGetCountLtOrEqOddRange() { - final FloatBuffer buf = new FloatBuffer(8, 0, false); - assertTrue(buf.isEmpty()); - buf.append(3); buf.append(2); buf.append(1); - buf.trimCount(4); - assertEquals(buf.getCount(), 3); - final int cnt = buf.getCountWithCriterion(3.0f, INCLUSIVE); - assertEquals(cnt, 3); - assertEquals(buf.getItemFromIndex(2), 3.0f); - try { buf.getEvensOrOdds(0, 3, false); fail(); } catch (final SketchesArgumentException e) {} - } - - @Test - public void checkTrimCapacityToCount() { - final FloatBuffer buf = new FloatBuffer(100, 100, true); - for (int i = 0; i <= 100; i++) { buf.append(i); } - assertEquals(buf.getCapacity(), 201); - assertEquals(buf.getCount(), 101); - buf.trimCapacity(); - assertEquals(buf.getItemFromIndex(0), 100f); - assertEquals(buf.getCapacity(), 101); - assertEquals(buf.getCount(), 101); - } - - @Test - public void checkSerDe() { - checkSerDeImpl(true); - checkSerDeImpl(false); - } - - private static void checkSerDeImpl(final boolean hra) { - final FloatBuffer fbuf = new FloatBuffer(100, 100, hra); - for (int i = 0; i <= 100; i++) { fbuf.append(i); } - final int capacity = fbuf.getCapacity(); - final int count = fbuf.getCount(); - final int delta = fbuf.getDelta(); - final boolean sorted = fbuf.isSorted(); - final boolean sab = fbuf.isSpaceAtBottom(); - assertEquals(fbuf.getItemFromIndex(100), 100.0f); - assertEquals(fbuf.getItemFromIndex(hra ? 199 : 1), 1.0f); - assertEquals(fbuf.isSpaceAtBottom(), hra); - //uses the serialization method - final MemorySegment wseg = MemorySegment.ofArray(fbuf.floatsToBytes()); - final float[] farr2 = new float[101]; - MemorySegment.copy(wseg, JAVA_FLOAT_UNALIGNED, 0, farr2, 0, 101); - //uses the deserialization method - final FloatBuffer fbuf2 = FloatBuffer.reconstruct(farr2, count, capacity, delta, sorted, sab); - assertEquals(fbuf2.getCapacity(), capacity); - assertEquals(fbuf2.getCount(), count); - assertEquals(fbuf2.getDelta(), delta); - assertEquals(fbuf2.isSorted(), sorted); - assertEquals(fbuf2.getItemFromIndex(100), 100.0f); - assertEquals(fbuf2.getItemFromIndex(hra ? 199 : 1), 1.0f); - assertEquals(fbuf2.isSpaceAtBottom(), sab); - } - - static void print(final Object o) { System.out.print(o.toString()); } - - static void println(final Object o) { System.out.println(o.toString()); } -} diff --git a/src/test/java/org/apache/datasketches/req/ReqSketchBuilderTest.java b/src/test/java/org/apache/datasketches/req/ReqSketchBuilderTest.java deleted file mode 100644 index e21405f70..000000000 --- a/src/test/java/org/apache/datasketches/req/ReqSketchBuilderTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import org.apache.datasketches.req.ReqSketchBuilder; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class ReqSketchBuilderTest { - - @Test - public void checkBldr() { - final ReqSketchBuilder bldr = new ReqSketchBuilder(); - final ReqDebugImplTest rdi = new ReqDebugImplTest(2, "%4.0f"); - bldr.setK(50).setHighRankAccuracy(true).setReqDebug(rdi); - assertEquals(bldr.getK(), 50); - assertEquals(bldr.getHighRankAccuracy(), true); - assertTrue(bldr.getReqDebug() != null); - println(bldr.toString()); - bldr.setReqDebug(null); - println(bldr.toString()); - } - - /** - * @param o object to be printed - */ - static void println(final Object o) { - //System.out.println(o.toString()); - } -} diff --git a/src/test/java/org/apache/datasketches/req/ReqSketchCrossLanguageTest.java b/src/test/java/org/apache/datasketches/req/ReqSketchCrossLanguageTest.java deleted file mode 100644 index 8e38b9b16..000000000 --- a/src/test/java/org/apache/datasketches/req/ReqSketchCrossLanguageTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES; -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.getFileBytes; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator; -import org.testng.annotations.Test; - -/** - * Serialize binary sketches to be tested by C++ code. - * Test deserialization of binary sketches serialized by C++ code. - */ -public class ReqSketchCrossLanguageTest { - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTesting() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (final int n: nArr) { - final ReqSketch sk = ReqSketch.builder().build(); - for (int i = 1; i <= n; i++) { - sk.update(i); - } - putBytesToJavaPath("req_float_n" + n + "_java.sk", sk.toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateNegativeBinariesForCompatibilityTesting() throws IOException { - final int[] nArr = {1, 10}; - for (final int n: nArr) { - final ReqSketch sk = ReqSketch.builder().build(); - for (int i = 1; i <= n; i++) { - sk.update(-i); - } - putBytesToJavaPath("req_float_negative_n" + n + "_java.sk", sk.toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateMixedBinariesForCompatibilityTesting() throws IOException { - final int[] nArr = {1, 10}; - for (final int n: nArr) { - final ReqSketch sk = ReqSketch.builder().build(); - for (int i = -n; i <= n; i++) { - sk.update(i); - } - putBytesToJavaPath("req_float_mixed_n" + n + "_java.sk", sk.toByteArray()); - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCpp() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "req_float_n" + n + "_cpp.sk"); - final ReqSketch sk = ReqSketch.heapify(MemorySegment.ofArray(bytes)); - assertTrue(n == 0 ? sk.isEmpty() : !sk.isEmpty()); - assertTrue(n > 10 ? sk.isEstimationMode() : !sk.isEstimationMode()); - assertEquals(sk.getN(), n); - if (n > 0) { - assertEquals(sk.getMinItem(), 1); - assertEquals(sk.getMaxItem(), n); - final QuantilesFloatsSketchIterator it = sk.iterator(); - long weight = 0; - while(it.next()) { - assertTrue(it.getQuantile() >= sk.getMinItem()); - assertTrue(it.getQuantile() <= sk.getMaxItem()); - weight += it.getWeight(); - } - assertEquals(weight, n); - } - } - } -} diff --git a/src/test/java/org/apache/datasketches/req/ReqSketchOtherTest.java b/src/test/java/org/apache/datasketches/req/ReqSketchOtherTest.java deleted file mode 100644 index 4a54c7c69..000000000 --- a/src/test/java/org/apache/datasketches/req/ReqSketchOtherTest.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import static org.apache.datasketches.quantilescommon.InequalitySearch.GE; -import static org.apache.datasketches.quantilescommon.InequalitySearch.GT; -import static org.apache.datasketches.quantilescommon.InequalitySearch.LE; -import static org.apache.datasketches.quantilescommon.InequalitySearch.LT; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.FloatsSortedView; -import org.apache.datasketches.quantilescommon.InequalitySearch; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -@SuppressWarnings("unused") -public class ReqSketchOtherTest { - final ReqSketchTest reqSketchTest = new ReqSketchTest(); - static InequalitySearch critLT = LT; - static InequalitySearch critLE = LE; - static InequalitySearch critGT = GT; - static InequalitySearch critGE = GE; - - /** - * - */ - @Test - public void checkConstructors() { - final ReqSketch sk = ReqSketch.builder().build(); - assertEquals(sk.getK(), 12); - } - - @Test - public void checkCopyConstructors() { - final boolean ltEq = true; - final ReqSketch sk = reqSketchTest.loadSketch( 6, 1, 50, true, true, 0); - final long n = sk.getN(); - final float min = sk.getMinItem(); - final float max = sk.getMaxItem(); - final ReqSketch sk2 = new ReqSketch(sk); - assertEquals(sk2.getMinItem(), min); - assertEquals(sk2.getMaxItem(), max); - } - - @Test - public void checkNonFinitePMF_CDF() { - final ReqSketch sk = ReqSketch.builder().build(); - sk.update(1); - try { //splitpoint values must be finite - sk.getCDF(new float[] { Float.NaN }); - fail(); - } - catch (final SketchesArgumentException e) {} - } - - @Test - public void checkQuantilesExceedLimits() { - final boolean ltEq = true; - final ReqSketch sk = reqSketchTest.loadSketch( 6, 1, 200, true, true, 0); - try { sk.getQuantile(2.0f); fail(); } catch (final SketchesArgumentException e) {} - try { sk.getQuantile(-2.0f); fail(); } catch (final SketchesArgumentException e) {} - } - - @Test - public void checkEstimationMode() { - final boolean up = true; - final boolean hra = true; - final boolean ltEq = true; - final ReqSketch sk = reqSketchTest.loadSketch( 20, 1, 119, up, hra, 0); - assertEquals(sk.isEstimationMode(), false); - final double lb = sk.getRankLowerBound(1.0, 1); - final double ub = sk.getRankUpperBound(1.0, 1); - assertEquals(lb, 1.0); - assertEquals(ub, 1.0); - int maxNomSize = sk.getMaxNomSize(); - assertEquals(maxNomSize, 120); - sk.update(120); - assertEquals(sk.isEstimationMode(), true); - // lb = sk.getRankLowerBound(0, 1); - // ub = sk.getRankUpperBound(1.0, 1); - // assertEquals(lb, 0.0); - // assertEquals(ub, 2.0); - maxNomSize = sk.getMaxNomSize(); - assertEquals(maxNomSize, 240); - final float v = sk.getQuantile(1.0); - assertEquals(v, 120.0f); - final FloatsSortedView aux = sk.getSortedView(); - assertNotNull(aux); - assertTrue(BaseReqSketch.getRSE(sk.getK(), .5, false, 120) >= 0); - assertTrue(sk.getSerializedSizeBytes() > 0); - } - - @Test - public void checkNaNUpdate() { - final InequalitySearch criterion = LE; - final ReqSketch sk = ReqSketch.builder().build(); - sk.update(Float.NaN); - assertTrue(sk.isEmpty()); - } - - @Test - public void checkNonFiniteGetRank() { - final ReqSketch sk = ReqSketch.builder().build(); - sk.update(1); - try { sk.getRank(Float.POSITIVE_INFINITY); fail(); } catch (final AssertionError e) {} - } - - @Test - public void moreMergeTests() { - final ReqSketch sk1 = ReqSketch.builder().build(); - final ReqSketch sk2 = ReqSketch.builder().build(); - for (int i = 5; i < 10; i++) {sk1.update(i); } - sk1.merge(sk2); //does nothing - for (int i = 1; i <= 15; i++) {sk2.update(i); } - sk1.merge(sk2); - assertEquals(sk1.getN(), 20); - for (int i = 16; i <= 300; i++) { sk2.update(i); } - sk1.merge(sk2); - } - - @Test - public void simpleTest() { - ReqSketch sk; - final ReqSketchBuilder bldr = ReqSketch.builder(); - bldr.setK(50).setHighRankAccuracy(false); - bldr.setReqDebug(null); - sk = bldr.build(); - final float[] vArr = { 5, 5, 5, 6, 6, 6, 7, 8, 8, 8 }; - for (int i = 0; i < vArr.length; i++) { sk.update(vArr[i]); } - - final double[] rArrLT = {0.0, 0.0, 0.0, 0.3, 0.3, 0.3, 0.6, 0.7, 0.7, 0.7}; - for (int i = 0; i < vArr.length; i++) { - assertEquals(sk.getRank(vArr[i], EXCLUSIVE), rArrLT[i]); - //System.out.println("v:" + vArr[i] + " r:" + sk.getRank(vArr[i])); - } - - final double[] rArrLE = {0.3, 0.3, 0.3, 0.6, 0.6, 0.6, 0.7, 1.0, 1.0, 1.0}; - for (int i = 0; i < vArr.length; i++) { - assertEquals(sk.getRank(vArr[i], INCLUSIVE), rArrLE[i]); - //System.out.println("v:" + vArr[i] + " r:" + sk.getRank(vArr[i])); - } - } - - @Test - public void checkGetRankUBLB() { - checkGetRank(true, false); - checkGetRank(false, true); - } - - @Test - public void checkEmpty() { - final ReqSketchBuilder bldr = new ReqSketchBuilder(); - final ReqSketch sk = bldr.build(); - try { sk.getRank(1f); fail(); } catch (IllegalArgumentException e) {} - try { sk.getRanks(new float[] {1f}); fail(); } catch (IllegalArgumentException e) {} - try { sk.getQuantile(0.5); fail(); } catch (IllegalArgumentException e) {} - try { sk.getQuantiles(new double[] {0.5}); fail(); } catch (IllegalArgumentException e) {} - try { sk.getPMF(new float[] {1f}); fail(); } catch (IllegalArgumentException e) {} - try { sk.getCDF(new float[] {1f}); fail(); } catch (IllegalArgumentException e) {} - assertTrue(BaseReqSketch.getRSE(50, 0.5, true, 0) >= 0); - assertTrue(sk.getRankUpperBound(0.5, 1) > 0); - } - - private void checkGetRank(final boolean hra, final boolean ltEq) { - final int k = 12; - final boolean up = true; - final int min = 1; - final int max = 1000; - final int skDebug = 0; - final ReqSketch sk = reqSketchTest.loadSketch(k, min, max, up, hra, skDebug); - double rLB = sk.getRankLowerBound(0.5, 1); - assertTrue(rLB > 0); - if (hra) { rLB = sk.getRankLowerBound(995.0/1000, 1); } - else { rLB = sk.getRankLowerBound(5.0/1000, 1); } - assertTrue(rLB > 0); - double rUB = sk.getRankUpperBound(0.5, 1); - assertTrue(rUB > 0); - if (hra) { rUB = sk.getRankUpperBound(995.0/1000, 1); } - else { rUB = sk.getRankUpperBound(5.0/1000, 1); } - assertTrue(rUB > 0); - final double[] ranks = sk.getRanks(new float[] {5f, 100f}); - } - - private static void myAssertEquals(final double v1, final double v2) { - if (Double.isNaN(v1) && Double.isNaN(v2)) { assert true; } - else if (v1 == v2) { assert true; } - else { assert false; } - } - - private static void myAssertEquals(final float v1, final float v2) { - if (Float.isNaN(v1) && Float.isNaN(v2)) { assert true; } - else if (v1 == v2) { assert true; } - else { assert false; } - } - -} diff --git a/src/test/java/org/apache/datasketches/req/ReqSketchSortedViewTest.java b/src/test/java/org/apache/datasketches/req/ReqSketchSortedViewTest.java deleted file mode 100644 index dbd7d9ffe..000000000 --- a/src/test/java/org/apache/datasketches/req/ReqSketchSortedViewTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import org.apache.datasketches.quantilescommon.FloatsSortedView; -import org.apache.datasketches.quantilescommon.FloatsSortedViewIterator; -import org.apache.datasketches.req.ReqSketch; -import org.apache.datasketches.req.ReqSketchBuilder; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class ReqSketchSortedViewTest { - private final int k = 32; - private final boolean hra = false; - private final int numV = 3; - private final int dup = 2; - private final int n = numV * dup; - - @Test - public void twoValueSketch() { - ReqSketch sketch = ReqSketch.builder().build(); - sketch.update(1f); - sketch.update(2f); - FloatsSortedViewIterator itr = sketch.getSortedView().iterator(); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 1f); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 0); - assertEquals(itr.getNaturalRank(INCLUSIVE), 1); - assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0); - assertEquals(itr.getNormalizedRank(INCLUSIVE), 0.5); - - assertTrue(itr.next()); - - assertEquals(itr.getQuantile(), 2f); - assertEquals(itr.getWeight(), 1); - assertEquals(itr.getNaturalRank(EXCLUSIVE), 1); - assertEquals(itr.getNaturalRank(INCLUSIVE), 2); - assertEquals(itr.getNormalizedRank(EXCLUSIVE), 0.5); - assertEquals(itr.getNormalizedRank(INCLUSIVE), 1.0); - } - - //@Test //visual only - public void checkIterator() { - println(""); - println("CHECK ReqSketchSortedViewIterator"); - println(" k: " + k + ", hra: " + hra); - println(" numV: " + numV + ", dup: " + dup + ", Total n = " + n); - ReqSketch sketch = buildDataLoadSketch(); - checkIterator(sketch); - } - - private ReqSketch buildDataLoadSketch() { - float[] fArr = new float[n]; - int h = 0; - for (int i = 0; i < numV; i++) { - float flt = (i + 1) * 10; - for (int j = 1; j <= dup; j++) { fArr[h++] = flt; } - } - ReqSketchBuilder bldr = ReqSketch.builder(); - ReqSketch sketch = bldr.build(); - for (int i = 0; i < n; i++) { sketch.update(fArr[i]); } - return sketch; - } - - private static void checkIterator(final ReqSketch sketch) { - println("\nNot Deduped:"); - FloatsSortedView sv = sketch.getSortedView(); - FloatsSortedViewIterator itr = sv.iterator(); - printIterator(itr); - } - - private static void printIterator(final FloatsSortedViewIterator itr) { - println(""); - String[] header = {"Value", "Wt", "CumWtNotInc", "NormRankNotInc", "CumWtInc", "NormRankInc"}; - String hfmt = "%8s%6s%16s%16s%16s%16s\n"; - String fmt = "%8.1f%6d%16d%16.3f%16d%16.3f\n"; - printf(hfmt, (Object[]) header); - while (itr.next()) { - float v = itr.getQuantile(); - long wt = itr.getWeight(); - long cumWtNotInc = itr.getNaturalRank(EXCLUSIVE); - double nRankNotInc = itr.getNormalizedRank(EXCLUSIVE); - long cumWtInc = itr.getNaturalRank(INCLUSIVE); - double nRankInc = itr.getNormalizedRank(INCLUSIVE); - printf(fmt, v, wt, cumWtNotInc, nRankNotInc, cumWtInc, nRankInc); - } - } - - private final static boolean enablePrinting = false; - - /** - * @param format the format - * @param args the args - */ - private static final void printf(final String format, final Object ...args) { - if (enablePrinting) { System.out.printf(format, args); } - } - - /** - * @param o the Object to println - */ - private static final void println(final Object o) { - if (enablePrinting) { System.out.println(o.toString()); } - } - -} diff --git a/src/test/java/org/apache/datasketches/req/ReqSketchTest.java b/src/test/java/org/apache/datasketches/req/ReqSketchTest.java deleted file mode 100644 index 98cece3f9..000000000 --- a/src/test/java/org/apache/datasketches/req/ReqSketchTest.java +++ /dev/null @@ -1,393 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.req; - -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.EXCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantileSearchCriteria.INCLUSIVE; -import static org.apache.datasketches.quantilescommon.QuantilesUtil.evenlySpacedDoubles; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.quantilescommon.FloatsSketchSortedView; -import org.apache.datasketches.quantilescommon.FloatsSortedViewIterator; -import org.apache.datasketches.quantilescommon.QuantileSearchCriteria; -import org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator; -import org.apache.datasketches.quantilescommon.QuantilesUtil; -import org.apache.datasketches.req.ReqSketch; -import org.apache.datasketches.req.ReqSketchBuilder; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -@SuppressWarnings("unused") -public class ReqSketchTest { - private static final String LS = System.getProperty("line.separator"); - - //To control debug printing: - private final static int skDebug = 0; // sketch debug printing: 0 = none, 1 = summary, 2 = extensive detail - private final static int iDebug = 0; // debug printing for individual tests below, same scale as above - - @Test - public void bigTest() { //ALL IN EXACT MODE - // k, min, max, up, hra, crit, skDebug - bigTestImpl(20, 1, 100, true, true, INCLUSIVE, skDebug); - bigTestImpl(20, 1, 100, false, false, INCLUSIVE, skDebug); - bigTestImpl(20, 1, 100, false, true, EXCLUSIVE, skDebug); - bigTestImpl(20, 1, 100, true, false, INCLUSIVE, skDebug); - } - - public void bigTestImpl(final int k, final int min, final int max, final boolean up, final boolean hra, - final QuantileSearchCriteria crit, final int skDebug) { - if (iDebug > 0) { - println(LS + "*************************"); - println("k=" + k + " min=" + min + " max=" + max - + " up=" + up + " hra=" + hra + " criterion=" + crit + LS); - } - final ReqSketch sk = loadSketch(k, min, max, up, hra, skDebug); - checkToString(sk, iDebug); - checkSortedView(sk, iDebug); - checkGetRank(sk, min, max, iDebug); - checkGetRanks(sk, max, iDebug); - checkGetQuantiles(sk, iDebug); - checkGetCDF(sk, iDebug); - checkGetPMF(sk, iDebug); - checkIterator(sk, iDebug); - checkMerge(sk, iDebug); - printBoundary(skDebug); - sk.reset(); - } - - //Common loadSketch - public ReqSketch loadSketch(final int k, final int min, final int max, final boolean up, - final boolean hra, final int skDebug) { - final ReqSketchBuilder bldr = ReqSketch.builder(); - bldr.setReqDebug(new ReqDebugImplTest(skDebug, "%5.0f")); - bldr.setK(k); - bldr.setHighRankAccuracy(hra); - final ReqSketch sk = bldr.build(); - if (up) { - for (int i = min; i <= max; i++) { - sk.update(i); - } - } else { //down - for (int i = max + 1; i-- > min; ) { - sk.update(i); - } - } - return sk; - } - - private static void printBoundary(final int iDebug) { - if (iDebug > 0) { - println("==========================================================="); - } - } - - private static void checkToString(final ReqSketch sk, final int iDebug) { - final boolean summary = iDebug == 1; - final boolean allData = iDebug == 2; - final String brief = sk.toString(); - final String all = sk.viewCompactorDetail("%4.0f", true); - if (summary) { - println(brief); - println(sk.viewCompactorDetail("%4.0f", false)); - } - if (allData) { - println(brief); - println(all); - } - } - - private static void checkGetRank(final ReqSketch sk, final int min, final int max, final int iDebug) { - if (iDebug > 0) { println("GetRank Test: INCLUSIVE"); } - final float[] spArr = QuantilesUtil.evenlySpacedFloats(0, max, 11); - final double[] trueRanks = evenlySpacedDoubles(0, 1.0, 11); - final String dfmt = "%10.2f%10.6f" + LS; - final String sfmt = "%10s%10s" + LS; - if (iDebug > 0) { printf(sfmt, "Value", "Rank"); } - final float va = 0; - final double ranka = 0; - for (int i = 0; i < spArr.length; i++) { - final float v = spArr[i]; - final double trueRank = trueRanks[i]; - final double rank = sk.getRank(v); - if (iDebug > 0) { printf(dfmt, v, rank); } - assertEquals(rank, trueRank, .01); - - } - if (iDebug > 0) { println(""); } - } - - private static void checkGetRanks(final ReqSketch sk, final int max, final int iDebug) { - if (iDebug > 0) { println("GetRanks Test:"); } - final float[] sp = QuantilesUtil.evenlySpacedFloats(0, max, 11); - final String dfmt = "%10.2f%10.6f" + LS; - final String sfmt = "%10s%10s" + LS; - if (iDebug > 0) { printf(sfmt, "Value", "Rank"); } - final double[] nRanks = sk.getRanks(sp); - for (int i = 0; i < nRanks.length; i++) { - if (iDebug > 0) { printf(dfmt, sp[i], nRanks[i]); } - } - if (iDebug > 0) { println(""); } - } - - private static void checkSortedView(final ReqSketch sk, final int iDebug) { - final FloatsSketchSortedView sv = sk.getSortedView(); - final FloatsSortedViewIterator itr = sv.iterator(); - final int retainedCount = sk.getNumRetained(); - final long totalN = sk.getN(); - int count = 0; - long cumWt = 0; - while (itr.next()) { - cumWt = itr.getNaturalRank(INCLUSIVE); - count++; - } - assertEquals(cumWt, totalN); - assertEquals(count, retainedCount); - } - - private static void checkGetQuantiles(final ReqSketch sk, final int iDebug) { - if (iDebug > 0) { println("GetQuantiles() Test"); } - final double[] rArr = {0, .1F, .2F, .3F, .4F, .5F, .6F, .7F, .8F, .9F, 1.0F}; - final float[] qOut = sk.getQuantiles(rArr); - if (iDebug > 0) { - for (int i = 0; i < qOut.length; i++) { - final String r = String.format("%6.3f", rArr[i]); - println("nRank: " + r + ", q: " + qOut[i]); - } - } - if (iDebug > 0) { println(""); } - } - - private static void checkGetCDF(final ReqSketch sk, final int iDebug) { - if (iDebug > 0) { println("GetCDF() Test"); } - final float[] spArr = { 20, 40, 60, 80 }; - final double[] cdf = sk.getCDF(spArr); - if (iDebug > 0) { - for (int i = 0; i < cdf.length; i++) { - final float sp = i == spArr.length ? sk.getMaxItem() : spArr[i]; - println("SP: " +sp + ", Den: " + cdf[i]); - } - } - if (iDebug > 0) { println(""); } - } - - private static void checkGetPMF(final ReqSketch sk, final int iDebug) { - if (iDebug > 0) { println("GetPMF() Test"); } - final float[] spArr = { 20, 40, 60, 80 }; - final double[] pmf = sk.getPMF(spArr); - if (iDebug > 0) { - for (int i = 0; i < pmf.length; i++) { - final float sp = i == spArr.length ? sk.getMaxItem() : spArr[i]; - println("SP: " +sp + ", Mass: " + pmf[i]); - } - } - if (iDebug > 0) { println(""); } - } - - private static void checkIterator(final ReqSketch sk, final int iDebug) { - if (iDebug > 0) { println("Sketch iterator() Test"); } - final QuantilesFloatsSketchIterator itr = sk.iterator(); - while (itr.next()) { - final float v = itr.getQuantile(); - final long wt = itr.getWeight(); - if (iDebug > 0) { println(" v=" + v + " wt=" +wt); } - } - if (iDebug > 0) { println(""); } - } - - private static void checkMerge(final ReqSketch sk, final int iDebug) { - final boolean allData = iDebug > 1; - final boolean summary = iDebug > 0; - if (summary) { - println("Merge Test"); - println("Before Merge:"); - outputCompactorDetail(sk, "%5.0f", allData, "Host Sketch:"); - } - final ReqSketch sk2 = new ReqSketch(sk); //copy ctr - if (summary) { - outputCompactorDetail(sk2, "%5.0f", allData, "Incoming Sketch:"); - println("Merge Process:"); - } - sk.merge(sk2); - assertEquals(sk.getN(), 200); - } - - //specific tests - - @Test - public void merge() { - final ReqSketch s1 = ReqSketch.builder().setK(12).build(); - for (int i = 0; i < 40; i++) { - s1.update(i); - } - final ReqSketch s2 = ReqSketch.builder().setK(12).build(); - for (int i = 0; i < 40; i++) { - s2.update(i); - } - final ReqSketch s3 = ReqSketch.builder().setK(12).build(); - for (int i = 0; i < 40; i++) { - s3.update(i); - } - final ReqSketch s = ReqSketch.builder().setK(12).build(); - s.merge(s1); - s.merge(s2); - s.merge(s3); - } - - @Test - public void checkValidateSplits() { - final float[] arr = {1,2,3,4,5}; - ReqSketch.validateSplits(arr); - try { - final float[] arr1 = {1,2,4,3,5}; - ReqSketch.validateSplits(arr1); - fail(); - } - catch (final SketchesArgumentException e) { } - } - - @Test - public void checkSerDe() { - final int k = 12; - final int exact = (2 * 3 * k) - 1; - checkSerDeImpl(12, false, 0); - checkSerDeImpl(12, true, 0); - checkSerDeImpl(12, false, 4); - checkSerDeImpl(12, true, 4); - checkSerDeImpl(12, false, exact); - checkSerDeImpl(12, true, exact); - checkSerDeImpl(12, false, 2 * exact); //more than one compactor - checkSerDeImpl(12, true, 2 * exact); - } - - private static void checkSerDeImpl(final int k, final boolean hra, final int count) { - final ReqSketch sk1 = ReqSketch.builder().setK(k).setHighRankAccuracy(hra).build(); - for (int i = 1; i <= count; i++) { - sk1.update(i); - } - final byte[] sk1Arr = sk1.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(sk1Arr); - final ReqSketch sk2 = ReqSketch.heapify(seg); - assertEquals(sk2.getNumRetained(), sk1.getNumRetained()); - assertEquals(sk1.isEmpty(), sk2.isEmpty()); - if (sk2.isEmpty()) { - try { sk2.getMinItem(); fail(); } catch (final IllegalArgumentException e) {} - try { sk2.getMaxItem(); fail(); } catch (final IllegalArgumentException e) {} - } else { - assertEquals(sk2.getMinItem(), sk1.getMinItem()); - assertEquals(sk2.getMaxItem(), sk1.getMaxItem()); - } - assertEquals(sk2.getN(), sk1.getN()); - assertEquals(sk2.getHighRankAccuracyMode(),sk1.getHighRankAccuracyMode()); - assertEquals(sk2.getK(), sk1.getK()); - assertEquals(sk2.getMaxNomSize(), sk1.getMaxNomSize()); - assertEquals(sk2.getNumLevels(), sk1.getNumLevels()); - assertEquals(sk2.getSerializedSizeBytes(), sk1.getSerializedSizeBytes()); - } - - @Test - public void checkK() { - try { - final ReqSketch sk1 = ReqSketch.builder().setK(1).build(); - fail(); - } catch (final SketchesArgumentException e) {} - } - - @Test - public void tenValues() { - final ReqSketch sketch = ReqSketch.builder().build(); - for (int i = 1; i <= 10; i++) { sketch.update(i); } - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getN(), 10); - assertEquals(sketch.getNumRetained(), 10); - for (int i = 1; i <= 10; i++) { - assertEquals(sketch.getRank(i), (i) / 10.0); - assertEquals(sketch.getRank(i, EXCLUSIVE), (i - 1) / 10.0); - assertEquals(sketch.getRank(i, INCLUSIVE), (i) / 10.0); - } - // inclusive = false - assertEquals(sketch.getQuantile(0, EXCLUSIVE), 1); - assertEquals(sketch.getQuantile(0.1, EXCLUSIVE), 2); - assertEquals(sketch.getQuantile(0.2, EXCLUSIVE), 3); - assertEquals(sketch.getQuantile(0.3, EXCLUSIVE), 4); - assertEquals(sketch.getQuantile(0.4, EXCLUSIVE), 5); - assertEquals(sketch.getQuantile(0.5, EXCLUSIVE), 6); - assertEquals(sketch.getQuantile(0.6, EXCLUSIVE), 7); - assertEquals(sketch.getQuantile(0.7, EXCLUSIVE), 8); - assertEquals(sketch.getQuantile(0.8, EXCLUSIVE), 9); - assertEquals(sketch.getQuantile(0.9, EXCLUSIVE), 10); - assertEquals(sketch.getQuantile(1, EXCLUSIVE), 10.0); - // inclusive = true - assertEquals(sketch.getQuantile(0, INCLUSIVE), 1); - assertEquals(sketch.getQuantile(0.1, INCLUSIVE), 1); - assertEquals(sketch.getQuantile(0.2, INCLUSIVE), 2); - assertEquals(sketch.getQuantile(0.3, INCLUSIVE), 3); - assertEquals(sketch.getQuantile(0.4, INCLUSIVE), 4); - assertEquals(sketch.getQuantile(0.5, INCLUSIVE), 5); - assertEquals(sketch.getQuantile(0.6, INCLUSIVE), 6); - assertEquals(sketch.getQuantile(0.7, INCLUSIVE), 7); - assertEquals(sketch.getQuantile(0.8, INCLUSIVE), 8); - assertEquals(sketch.getQuantile(0.9, INCLUSIVE), 9); - assertEquals(sketch.getQuantile(1, INCLUSIVE), 10); - - // getQuantile() and getQuantiles() equivalence - { - // inclusive = false (default) - final float[] quantiles = - sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1}); - for (int i = 0; i <= 10; i++) { - assertEquals(sketch.getQuantile(i / 10.0), quantiles[i]); - } - } - { - // inclusive = true - final float[] quantiles = - sketch.getQuantiles(new double[] {0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1}, INCLUSIVE); - for (int i = 0; i <= 10; i++) { - assertEquals(sketch.getQuantile(i / 10.0, INCLUSIVE), quantiles[i]); - } - } - } - - private static void outputCompactorDetail(final ReqSketch sk, final String fmt, final boolean allData, - final String text) { - println(text); - println(sk.viewCompactorDetail(fmt, allData)); - } - - private static final void printf(final String format, final Object ...args) { - System.out.printf(format, args); - } - - private static final void print(final Object o) { - System.out.print(o.toString()); - } - - private static final void println(final Object o) { - System.out.println(o.toString()); - } - -} diff --git a/src/test/java/org/apache/datasketches/sampling/EbppsItemsSampleTest.java b/src/test/java/org/apache/datasketches/sampling/EbppsItemsSampleTest.java deleted file mode 100644 index cdcb022da..000000000 --- a/src/test/java/org/apache/datasketches/sampling/EbppsItemsSampleTest.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Random; - -import org.apache.datasketches.sampling.EbppsItemsSample; -import org.testng.annotations.Test; - -public class EbppsItemsSampleTest { - private static final double EPS = 1e-14; - - @Test - public void basicInitialization() { - EbppsItemsSample sample = new EbppsItemsSample<>(0); - assertEquals(sample.getC(), 0.0); - assertEquals(sample.getNumRetainedItems(), 0); - assertNull(sample.getSample()); - } - - @Test - public void initializeWithData() { - final double theta1 = 1.0; - EbppsItemsSample sample = new EbppsItemsSample<>(1); - sample.replaceContent(-1, theta1); - assertEquals(sample.getC(), theta1); - assertEquals(sample.getNumRetainedItems(), 1); - assertEquals(sample.getSample().size(), 1); - assertEquals(sample.getSample().get(0), -1); - assertFalse(sample.hasPartialItem()); - - final double theta2 = 1e-300; - sample.replaceContent(-2, theta2); - assertEquals(sample.getC(), theta2); - assertEquals(sample.getNumRetainedItems(), 1); - // next check assumes random number is > 1e-300 - assertNull(sample.getSample()); - assertTrue(sample.hasPartialItem()); - } - - @Test - public void downsampleToZeroOrOneItem() { - EbppsItemsSample sample = new EbppsItemsSample<>(1); - sample.replaceContent("a", 1.0); - - sample.downsample(2.0); // no-op - assertEquals(sample.getC(), 1.0); - assertEquals(sample.getNumRetainedItems(), 1); - assertEquals(sample.getSample().get(0), "a"); - assertFalse(sample.hasPartialItem()); - - // downsample and result in an empty sample - ArrayList items = new ArrayList<>(Arrays.asList("a", "b")); - sample = new EbppsItemsSample<>(items, null, 1.8); - sample.replaceRandom(new Random(85942)); - sample.downsample(0.5); - assertEquals(sample.getC(), 0.9); - assertEquals(sample.getNumRetainedItems(), 0); - assertNull(sample.getSample()); - assertFalse(sample.hasPartialItem()); - - // downsample and result in a sample with a partial item - // create a new ArrayList each time to be sure it's clean - items = new ArrayList<>(Arrays.asList("a", "b")); - sample = new EbppsItemsSample<>(items, null, 1.5); - sample.replaceRandom(new Random(15)); - sample.downsample(0.5); - assertEquals(sample.getC(), 0.75); - assertEquals(sample.getNumRetainedItems(), 1); - assertTrue(sample.hasPartialItem()); - for (String s : sample.getSample()) { - assertTrue("a".equals(s) || "b".equals(s)); - } - } - - @Test - public void downsampleMultipleItems() { - // downsample to an exact integer c (7.5 * 0.8 = 6.0) - ArrayList items = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e", "f", "g")); - String partial = "h"; - ArrayList referenceItems = new ArrayList<>(items); // copy of inputs - referenceItems.add("h"); // include the partial item - - EbppsItemsSample sample = new EbppsItemsSample<>(items, partial, 7.5); - sample.downsample(0.8); - assertEquals(sample.getC(), 6.0); - assertEquals(sample.getNumRetainedItems(), 6); - assertFalse(sample.hasPartialItem()); - for (String s : sample.getSample()) { - assertTrue(referenceItems.contains(s)); - } - - // downsample to c > 1 with partial item - items = new ArrayList<>(referenceItems); // includes previous optional - partial = "i"; - referenceItems.add("i"); - sample = new EbppsItemsSample<>(items, partial, 8.5); - sample.downsample(0.8); - assertEquals(sample.getC(), 6.8, EPS); - assertEquals(sample.getNumRetainedItems(), 7); - assertTrue(sample.hasPartialItem()); - for (String s : sample.getSample()) { - assertTrue(referenceItems.contains(s)); - } - } - - @Test - public void mergeUnitSamples() { - int k = 8; - EbppsItemsSample sample = new EbppsItemsSample<>(k); - EbppsItemsSample s = new EbppsItemsSample<>(1); - - for (int i = 1; i <= k; ++i) { - s.replaceContent(i, 1.0); - sample.merge(s); - assertEquals(sample.getC(), i); - assertEquals(sample.getNumRetainedItems(), i); - } - - sample.reset(); - assertEquals(sample.getC(), 0.0); - assertEquals(sample.getNumRetainedItems(), 0); - assertFalse(sample.hasPartialItem()); - } -} diff --git a/src/test/java/org/apache/datasketches/sampling/EbppsItemsSketchTest.java b/src/test/java/org/apache/datasketches/sampling/EbppsItemsSketchTest.java deleted file mode 100644 index 142cfe237..000000000 --- a/src/test/java/org/apache/datasketches/sampling/EbppsItemsSketchTest.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; -import java.util.ArrayList; - -import org.apache.datasketches.common.ArrayOfLongsSerDe; -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.sampling.EbppsItemsSketch; -import org.apache.datasketches.sampling.PreambleUtil; -import org.testng.annotations.Test; - -public class EbppsItemsSketchTest { - private static final double EPS = 1e-13; - - static EbppsItemsSketch createUnweightedSketch(final int k, final long n) { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(k); - for (long i = 0; i < n; ++i) { - sk.update((int) i); - } - return sk; - } - - static void checkIfEqual(final EbppsItemsSketch sk1, final EbppsItemsSketch sk2) { - assertEquals(sk1.getK(), sk2.getK()); - assertEquals(sk1.getN(), sk2.getN()); - assertEquals(sk1.getC(), sk2.getC()); - assertEquals(sk1.getCumulativeWeight(), sk2.getCumulativeWeight()); - - // results may validly differ in size based on presence of partial items - final ArrayList sample1 = sk1.getResult(); - final ArrayList sample2 = sk2.getResult(); - - if (sk1.getC() < 1.0) { - if ((sample1 != null) && (sample2 != null)) { - assertEquals(sample1.size(), sample2.size()); - assertEquals(sample1.get(0), sample2.get(0)); - } - // nothing to test if one is null and the other isn't - } else { - // sk1.getC() >= 1.0 and sk2.getC() >= 1.0 (they're equal per above) - // so the samples shouldn't be null - assertTrue((sample1 != null) && (sample2 != null)); - final int len = Math.min(sample1.size(), sample2.size()); - for (int i = 0; i < len; ++i) { - assertEquals(sample1.get(i), sample2.get(i)); - } - assertTrue(((len == Math.floor(sk1.getC())) || (len == Math.ceil(sk1.getC())))); - - // if c != floor(c) one sketch may not have reached the end, - // but that's not reliably testable from the external API - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkZeroK() { - new EbppsItemsSketch(0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkTooBigK() { - new EbppsItemsSketch(Integer.MAX_VALUE); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkNegativeWeight() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(1); - sk.update("a", -1.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInfiniteWeight() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(1); - sk.update("a", Double.POSITIVE_INFINITY); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkNaNWeight() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(1); - sk.update("a", Double.NaN); - } - - @Test - public void insertItems() { - int n = 0; - final int k = 5; - - // empty sketch - EbppsItemsSketch sk = createUnweightedSketch(k, n); - assertEquals(sk.getK(), k); - assertEquals(sk.getN(), 0); - assertEquals(sk.getC(), 0.0); - assertEquals(sk.getCumulativeWeight(), 0.0); - assertTrue(sk.isEmpty()); - - // exact mode - n = k; - sk = createUnweightedSketch(k, n); - assertFalse(sk.isEmpty()); - assertEquals(sk.getN(), n); - assertEquals(sk.getC(), k); - assertEquals(sk.getCumulativeWeight(), n); - assertEquals(sk.getResult().size(), sk.getK()); - for (final Integer val : sk.getResult()) { - assertTrue(val < n); - } - - // sampling mode with uniform eights - n = k * 10; - sk = createUnweightedSketch(k, n); - assertFalse(sk.isEmpty()); - assertEquals(sk.getN(), n); - assertEquals(sk.getCumulativeWeight(), n); - assertEquals(sk.getC(), k, EPS); - assertEquals(sk.getResult().size(), sk.getK()); - for (final Integer val : sk.getResult()) { - assertTrue(val < n); - } - - // add a very heavy item - sk.update(n, n); - assertTrue(sk.getC() < sk.getK()); - } - - @Test - public void mergeSmallIntoLarge() { - final int k = 100; - - final EbppsItemsSketch sk1 = createUnweightedSketch(k, k); - final EbppsItemsSketch sk2 = new EbppsItemsSketch<>(k / 2); - sk2.update(-1, k / 10.0); // one heavy item, but less than sk1 weight - - sk1.merge(sk2); - assertEquals(sk1.getK(), k / 2); - assertEquals(sk1.getN(), k + 1); - assertTrue(sk1.getC() < k); - assertEquals(sk1.getCumulativeWeight(), 1.1 * k, EPS); - } - - @Test - public void mergeLargeIntoSmall() { - final int k = 100; - - final EbppsItemsSketch sk1 = new EbppsItemsSketch<>(k / 2); - sk1.update(-1, k / 4.0); - sk1.update(-2, k / 8.0); - final EbppsItemsSketch sk2 = createUnweightedSketch(k, k); - assertEquals(sk2.getN(), k); - assertEquals(sk2.getC(), k, EPS); - - sk1.merge(sk2); - assertEquals(sk1.getK(), k / 2); - assertEquals(sk1.getN(), k + 2); - assertTrue(sk1.getC() < k); - // cumulative weight is now (1 + 0.25 + 0.125)k = 1.375k - assertEquals(sk1.getCumulativeWeight(), 1.375 * k, EPS); - } - - @Test - public void serializeDeserializeString() { - // since C <= k we don't have the usual sketch notion of exact vs estimation - // mode at any time. The only real serialization cases are empty and non-empty - // with and without a partial item - final int k = 10; - final EbppsItemsSketch sk = new EbppsItemsSketch<>(k); - - // empty - byte[] bytes = sk.toByteArray(new ArrayOfStringsSerDe()); - assertEquals(bytes.length, sk.getSerializedSizeBytes(new ArrayOfStringsSerDe())); - MemorySegment seg = MemorySegment.ofArray(bytes); - EbppsItemsSketch sk_heapify = EbppsItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - checkIfEqual(sk, sk_heapify); - - // add uniform items - for (int i = 0; i < k; ++i) { - sk.update(Integer.toString(i)); - } - - // non-empty, no partial item - bytes = sk.toByteArray(new ArrayOfStringsSerDe()); - assertEquals(bytes.length, sk.getSerializedSizeBytes(new ArrayOfStringsSerDe())); - seg = MemorySegment.ofArray(bytes); - sk_heapify = EbppsItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - checkIfEqual(sk, sk_heapify); - - // non-empty with partial item - sk.update(Integer.toString(2 * k), 2.5); - assertEquals(sk.getCumulativeWeight(), k + 2.5, EPS); - bytes = sk.toByteArray(new ArrayOfStringsSerDe()); - assertEquals(bytes.length, sk.getSerializedSizeBytes(new ArrayOfStringsSerDe())); - seg = MemorySegment.ofArray(bytes); - sk_heapify = EbppsItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - checkIfEqual(sk, sk_heapify); - - assertNotNull(sk.toString()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeZeroK() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(5); - final byte[] bytes = sk.toByteArray(new ArrayOfStringsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - PreambleUtil.insertK(seg, 0); - EbppsItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeTooLargeK() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(5); - final byte[] bytes = sk.toByteArray(new ArrayOfStringsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - PreambleUtil.insertK(seg, Integer.MAX_VALUE); - EbppsItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeBadSerVer() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(5); - final byte[] bytes = sk.toByteArray(new ArrayOfStringsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - PreambleUtil.insertSerVer(seg, -1); - EbppsItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeBadFamily() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(5); - final byte[] bytes = sk.toByteArray(new ArrayOfStringsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - PreambleUtil.insertFamilyID(seg, 0); - EbppsItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeNegativeN() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(5); - for (int i = 0; i < 10; ++i) { - sk.update(Integer.toString(i)); - } - final byte[] bytes = sk.toByteArray(new ArrayOfStringsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - PreambleUtil.insertN(seg, -1000); - EbppsItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeNaNCumulativeWeight() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(5); - for (int i = 0; i < 10; ++i) { - sk.update(Integer.toString(i)); - } - final byte[] bytes = sk.toByteArray(new ArrayOfStringsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - PreambleUtil.insertEbppsCumulativeWeight(seg, Double.NaN); - EbppsItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeInfiniteMaxWeight() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(5); - for (int i = 0; i < 10; ++i) { - sk.update(Integer.toString(i)); - } - final byte[] bytes = sk.toByteArray(new ArrayOfStringsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - PreambleUtil.insertEbppsMaxWeight(seg, Double.POSITIVE_INFINITY); - EbppsItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeNegativeRho() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(5); - for (int i = 0; i < 10; ++i) { - sk.update(Integer.toString(i)); - } - final byte[] bytes = sk.toByteArray(new ArrayOfStringsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - PreambleUtil.insertEbppsRho(seg, -0.1); - EbppsItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeNegativeC() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(5); - for (int i = 0; i < 10; ++i) { - sk.update(Integer.toString(i)); - } - final byte[] bytes = sk.toByteArray(new ArrayOfStringsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - seg.set(JAVA_DOUBLE_UNALIGNED, 40, -2.0); // from the defined spec - EbppsItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeTooShort() { - final EbppsItemsSketch sk = new EbppsItemsSketch<>(5); - for (long i = 0; i < 10; ++i) { - sk.update(i); - } - final byte[] bytes = sk.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - final MemorySegment shortSeg = seg.asSlice(0, seg.byteSize() - 1); - EbppsItemsSketch.heapify(shortSeg, new ArrayOfLongsSerDe()); - } -} diff --git a/src/test/java/org/apache/datasketches/sampling/ReservoirCrossLanguageTest.java b/src/test/java/org/apache/datasketches/sampling/ReservoirCrossLanguageTest.java deleted file mode 100644 index 564f3b53b..000000000 --- a/src/test/java/org/apache/datasketches/sampling/ReservoirCrossLanguageTest.java +++ /dev/null @@ -1,409 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; - -import java.io.IOException; -import java.util.ArrayList; - -import org.apache.datasketches.common.ArrayOfDoublesSerDe; -import org.apache.datasketches.common.ArrayOfLongsSerDe; -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.ResizeFactor; -import org.testng.annotations.Test; - -/** - * Serialize binary sketches to be tested by other language code. - * Test deserialization of binary sketches serialized by other language code. - */ -public class ReservoirCrossLanguageTest { - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirLongsSketchEmpty() throws IOException { - final int k = 128; - final ReservoirLongsSketch sk = ReservoirLongsSketch.newInstance(k); - - putBytesToJavaPath("reservoir_longs_empty_k" + k + "_java.sk", sk.toByteArray()); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirLongsSketchExact() throws IOException { - final int k = 128; - final int[] nArr = {1, 10, 32, 100, 128}; - - for (final int n : nArr) { - final ReservoirLongsSketch sk = ReservoirLongsSketch.newInstance(k); - for (int i = 0; i < n; i++) { - sk.update(i); - } - putBytesToJavaPath("reservoir_longs_exact_n" + n + "_k" + k + "_java.sk", sk.toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirLongsSketchSampling() throws IOException { - final int[] kArr = {32, 64, 128}; - final long n = 1000; - - for (final int k : kArr) { - final long[] predeterminedSamples = new long[k]; - for (int i = 0; i < k; i++) { - predeterminedSamples[i] = i * 2; - } - - final ReservoirLongsSketch sk = ReservoirLongsSketch.getInstance( - predeterminedSamples, - n, - ResizeFactor.X8, - k - ); - - putBytesToJavaPath("reservoir_longs_sampling_n" + n + "_k" + k + "_java.sk", sk.toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirLongsUnionEmpty() throws IOException { - int maxK = 128; - ReservoirLongsUnion union = ReservoirLongsUnion.newInstance(maxK); - - putBytesToJavaPath("reservoir_longs_union_empty_maxk" + maxK + "_java.sk", union.toByteArray()); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirLongsUnionExact() throws IOException { - int maxK = 128; - int[] nArr = {1, 10, 32, 100, 128}; - - for (int n : nArr) { - ReservoirLongsUnion union = ReservoirLongsUnion.newInstance(maxK); - for (int i = 0; i < n; i++) { - union.update(i); - } - putBytesToJavaPath("reservoir_longs_union_exact_n" + n + "_maxk" + maxK + "_java.sk", union.toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirLongsUnionSampling() throws IOException { - int[] maxKArr = {32, 64, 128}; - long n = 1000; - - for (int maxK : maxKArr) { - long[] predeterminedSamples = new long[maxK]; - for (int i = 0; i < maxK; i++) { - predeterminedSamples[i] = i * 2; - } - - ReservoirLongsSketch sk = ReservoirLongsSketch.getInstance( - predeterminedSamples, - n, - ResizeFactor.X8, - maxK - ); - - ReservoirLongsUnion union = ReservoirLongsUnion.newInstance(maxK); - union.update(sk); - - putBytesToJavaPath("reservoir_longs_union_sampling_n" + n + "_maxk" + maxK + "_java.sk", union.toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsSketchLongEmpty() throws IOException { - final int k = 128; - final ReservoirItemsSketch sk = ReservoirItemsSketch.newInstance(k); - - putBytesToJavaPath("reservoir_items_long_empty_k" + k + "_java.sk", sk.toByteArray(new ArrayOfLongsSerDe())); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsSketchLongExact() throws IOException { - final int k = 128; - final int[] nArr = {1, 10, 32, 100, 128}; - - for (final int n : nArr) { - final ReservoirItemsSketch sk = ReservoirItemsSketch.newInstance(k); - for (int i = 0; i < n; i++) { - sk.update((long) i); - } - putBytesToJavaPath("reservoir_items_long_exact_n" + n + "_k" + k + "_java.sk", sk.toByteArray(new ArrayOfLongsSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsSketchLongSampling() throws IOException { - final int[] kArr = {32, 64, 128}; - final long n = 1000; - - for (final int k : kArr) { - final java.util.ArrayList predeterminedSamples = new java.util.ArrayList<>(); - for (int i = 0; i < k; i++) { - predeterminedSamples.add((long) (i * 2)); - } - - final ReservoirItemsSketch sk = ReservoirItemsSketch.newInstance( - predeterminedSamples, - n, - ResizeFactor.X8, - k - ); - - putBytesToJavaPath("reservoir_items_long_sampling_n" + n + "_k" + k + "_java.sk", sk.toByteArray(new ArrayOfLongsSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsSketchDoubleEmpty() throws IOException { - final int k = 128; - final ReservoirItemsSketch sk = ReservoirItemsSketch.newInstance(k); - - putBytesToJavaPath("reservoir_items_double_empty_k" + k + "_java.sk", sk.toByteArray(new ArrayOfDoublesSerDe())); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsSketchDoubleExact() throws IOException { - final int k = 128; - final int[] nArr = {1, 10, 32, 100, 128}; - - for (final int n : nArr) { - final ReservoirItemsSketch sk = ReservoirItemsSketch.newInstance(k); - for (int i = 0; i < n; i++) { - sk.update((double) i); - } - putBytesToJavaPath("reservoir_items_double_exact_n" + n + "_k" + k + "_java.sk", sk.toByteArray(new ArrayOfDoublesSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsSketchDoubleSampling() throws IOException { - final int[] kArr = {32, 64, 128}; - final long n = 1000; - - for (final int k : kArr) { - final java.util.ArrayList predeterminedSamples = new java.util.ArrayList<>(); - for (int i = 0; i < k; i++) { - predeterminedSamples.add((double) (i * 2)); - } - - final ReservoirItemsSketch sk = ReservoirItemsSketch.newInstance( - predeterminedSamples, - n, - ResizeFactor.X8, - k - ); - - putBytesToJavaPath("reservoir_items_double_sampling_n" + n + "_k" + k + "_java.sk", sk.toByteArray(new ArrayOfDoublesSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsSketchStringEmpty() throws IOException { - final int k = 128; - final ReservoirItemsSketch sk = ReservoirItemsSketch.newInstance(k); - - putBytesToJavaPath("reservoir_items_string_empty_k" + k + "_java.sk", sk.toByteArray(new ArrayOfStringsSerDe())); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsSketchStringExact() throws IOException { - final int k = 128; - final int[] nArr = {1, 10, 32, 100, 128}; - - for (final int n : nArr) { - final ReservoirItemsSketch sk = ReservoirItemsSketch.newInstance(k); - for (int i = 0; i < n; i++) { - sk.update("item" + i); - } - putBytesToJavaPath("reservoir_items_string_exact_n" + n + "_k" + k + "_java.sk", sk.toByteArray(new ArrayOfStringsSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsSketchStringSampling() throws IOException { - final int[] kArr = {32, 64, 128}; - final long n = 1000; - - for (final int k : kArr) { - final java.util.ArrayList predeterminedSamples = new java.util.ArrayList<>(); - for (int i = 0; i < k; i++) { - predeterminedSamples.add("item" + (i * 2)); - } - - final ReservoirItemsSketch sk = ReservoirItemsSketch.newInstance( - predeterminedSamples, - n, - ResizeFactor.X8, - k - ); - - putBytesToJavaPath("reservoir_items_string_sampling_n" + n + "_k" + k + "_java.sk", sk.toByteArray(new ArrayOfStringsSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsUnionLongEmpty() throws IOException { - int maxK = 128; - ReservoirItemsUnion union = ReservoirItemsUnion.newInstance(maxK); - - putBytesToJavaPath("reservoir_items_union_long_empty_maxk" + maxK + "_java.sk", union.toByteArray(new ArrayOfLongsSerDe())); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsUnionLongExact() throws IOException { - int maxK = 128; - int[] nArr = {1, 10, 32, 100, 128}; - - for (int n : nArr) { - ReservoirItemsUnion union = ReservoirItemsUnion.newInstance(maxK); - for (int i = 0; i < n; i++) { - union.update((long) i); - } - putBytesToJavaPath("reservoir_items_union_long_exact_n" + n + "_maxk" + maxK + "_java.sk", - union.toByteArray(new ArrayOfLongsSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsUnionLongSampling() throws IOException { - int[] maxKArr = {32, 64, 128}; - long n = 1000; - - for (int maxK : maxKArr) { - ArrayList predeterminedSamples = new ArrayList<>(); - for (int i = 0; i < maxK; i++) { - predeterminedSamples.add((long) (i * 2)); - } - - ReservoirItemsSketch sk = ReservoirItemsSketch.newInstance( - predeterminedSamples, - n, - ResizeFactor.X8, - maxK - ); - - ReservoirItemsUnion union = ReservoirItemsUnion.newInstance(maxK); - union.update(sk); - - putBytesToJavaPath("reservoir_items_union_long_sampling_n" + n + "_maxk" + maxK + "_java.sk", - union.toByteArray(new ArrayOfLongsSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsUnionDoubleEmpty() throws IOException { - int maxK = 128; - ReservoirItemsUnion union = ReservoirItemsUnion.newInstance(maxK); - - putBytesToJavaPath("reservoir_items_union_double_empty_maxk" + maxK + "_java.sk", union.toByteArray(new ArrayOfDoublesSerDe())); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsUnionDoubleExact() throws IOException { - int maxK = 128; - int[] nArr = {1, 10, 32, 100, 128}; - - for (int n : nArr) { - ReservoirItemsUnion union = ReservoirItemsUnion.newInstance(maxK); - for (int i = 0; i < n; i++) { - union.update((double) i); - } - putBytesToJavaPath("reservoir_items_union_double_exact_n" + n + "_maxk" + maxK + "_java.sk", - union.toByteArray(new ArrayOfDoublesSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsUnionDoubleSampling() throws IOException { - int[] maxKArr = {32, 64, 128}; - long n = 1000; - - for (int maxK : maxKArr) { - ArrayList predeterminedSamples = new ArrayList<>(); - for (int i = 0; i < maxK; i++) { - predeterminedSamples.add((double) (i * 2)); - } - - ReservoirItemsSketch sk = ReservoirItemsSketch.newInstance( - predeterminedSamples, - n, - ResizeFactor.X8, - maxK - ); - - ReservoirItemsUnion union = ReservoirItemsUnion.newInstance(maxK); - union.update(sk); - - putBytesToJavaPath("reservoir_items_union_double_sampling_n" + n + "_maxk" + maxK + "_java.sk", - union.toByteArray(new ArrayOfDoublesSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsUnionStringEmpty() throws IOException { - int maxK = 128; - ReservoirItemsUnion union = ReservoirItemsUnion.newInstance(maxK); - - putBytesToJavaPath("reservoir_items_union_string_empty_maxk" + maxK + "_java.sk", union.toByteArray(new ArrayOfStringsSerDe())); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsUnionStringExact() throws IOException { - int maxK = 128; - int[] nArr = {1, 10, 32, 100, 128}; - - for (int n : nArr) { - ReservoirItemsUnion union = ReservoirItemsUnion.newInstance(maxK); - for (int i = 0; i < n; i++) { - union.update("item" + i); - } - putBytesToJavaPath("reservoir_items_union_string_exact_n" + n + "_maxk" + maxK + "_java.sk", - union.toByteArray(new ArrayOfStringsSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateReservoirItemsUnionStringSampling() throws IOException { - int[] maxKArr = {32, 64, 128}; - long n = 1000; - - for (int maxK : maxKArr) { - ArrayList predeterminedSamples = new ArrayList<>(); - for (int i = 0; i < maxK; i++) { - predeterminedSamples.add("item" + (i * 2)); - } - - ReservoirItemsSketch sk = ReservoirItemsSketch.newInstance( - predeterminedSamples, - n, - ResizeFactor.X8, - maxK - ); - - ReservoirItemsUnion union = ReservoirItemsUnion.newInstance(maxK); - union.update(sk); - - putBytesToJavaPath("reservoir_items_union_string_sampling_n" + n + "_maxk" + maxK + "_java.sk", - union.toByteArray(new ArrayOfStringsSerDe())); - } - } -} diff --git a/src/test/java/org/apache/datasketches/sampling/ReservoirItemsSketchTest.java b/src/test/java/org/apache/datasketches/sampling/ReservoirItemsSketchTest.java deleted file mode 100644 index 738b46bd0..000000000 --- a/src/test/java/org/apache/datasketches/sampling/ReservoirItemsSketchTest.java +++ /dev/null @@ -1,652 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.sampling.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SIZE_INT; -import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SIZE_SHORT; -import static org.apache.datasketches.sampling.PreambleUtil.SER_VER_BYTE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.math.BigDecimal; -import java.util.ArrayList; - -import org.apache.datasketches.common.ArrayOfLongsSerDe; -import org.apache.datasketches.common.ArrayOfNumbersSerDe; -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesException; -import org.apache.datasketches.common.SketchesStateException; -import org.testng.annotations.Test; - -public class ReservoirItemsSketchTest { - private static final double EPS = 1e-8; - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidK() { - ReservoirItemsSketch.newInstance(0); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadSerVer() { - final MemorySegment seg = getBasicSerializedLongsRIS(); - seg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 0); // corrupt the serialization version - - ReservoirItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadFamily() { - final MemorySegment seg = getBasicSerializedLongsRIS(); - seg.set(JAVA_BYTE, FAMILY_BYTE, (byte) Family.ALPHA.getID()); // corrupt the family ID - - try { - PreambleUtil.preambleToString(seg); - } catch (final SketchesArgumentException e) { - assertTrue(e.getMessage().startsWith("Inspecting preamble with Sampling family")); - } - - ReservoirItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadPreLongs() { - final MemorySegment seg = getBasicSerializedLongsRIS(); - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) 0); // corrupt the preLongs count - - ReservoirItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadMemorySegment() { - byte[] bytes = new byte[4]; - MemorySegment seg = MemorySegment.ofArray(bytes); - - try { - PreambleUtil.getAndCheckPreLongs(seg); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - bytes = new byte[8]; - bytes[0] = 2; // only 1 preLong worth of items in bytearray - seg = MemorySegment.ofArray(bytes); - PreambleUtil.getAndCheckPreLongs(seg); - } - - - @Test - public void checkEmptySketch() { - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(5); - assertTrue(ris.getSamples() == null); - - final byte[] sketchBytes = ris.toByteArray(new ArrayOfStringsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - - // only minPreLongs bytes and should deserialize to empty - assertEquals(sketchBytes.length, Family.RESERVOIR.getMinPreLongs() << 3); - final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - final ReservoirItemsSketch loadedRis = ReservoirItemsSketch.heapify(seg, serDe); - assertEquals(loadedRis.getNumSamples(), 0); - - println("Empty sketch:"); - println(" Preamble:"); - println(PreambleUtil.preambleToString(seg)); - println(" Sketch:"); - println(ris.toString()); - } - - @Test - public void checkUnderFullReservoir() { - final int k = 128; - final int n = 64; - - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k); - int expectedLength = 0; - - for (int i = 0; i < n; ++i) { - final String intStr = Integer.toString(i); - expectedLength += intStr.length() + Integer.BYTES; - ris.update(intStr); - } - assertEquals(ris.getNumSamples(), n); - - final String[] data = ris.getSamples(); - assertNotNull(data); - assertEquals(ris.getNumSamples(), ris.getN()); - assertEquals(data.length, n); - - // items in submit order until reservoir at capacity so check - for (int i = 0; i < n; ++i) { - assertEquals(data[i], Integer.toString(i)); - } - - // not using validateSerializeAndDeserialize() to check with a non-Long - final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - expectedLength += Family.RESERVOIR.getMaxPreLongs() << 3; - final byte[] sketchBytes = ris.toByteArray(serDe); - assertEquals(sketchBytes.length, expectedLength); - - // ensure reservoir rebuilds correctly - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - final ReservoirItemsSketch loadedRis = ReservoirItemsSketch.heapify(seg, serDe); - - validateReservoirEquality(ris, loadedRis); - - println("Under-full reservoir:"); - println(" Preamble:"); - println(PreambleUtil.preambleToString(seg)); - println(" Sketch:"); - println(ris.toString()); - } - - @Test - public void checkFullReservoir() { - final int k = 1000; - final int n = 2000; - - // specify smaller ResizeFactor to ensure multiple resizes - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k, ResizeFactor.X2); - - for (int i = 0; i < n; ++i) { - ris.update((long) i); - } - assertEquals(ris.getNumSamples(), ris.getK()); - - validateSerializeAndDeserialize(ris); - - println("Full reservoir:"); - println(" Preamble:"); - final byte[] byteArr = ris.toByteArray(new ArrayOfLongsSerDe()); - println(ReservoirItemsSketch.toString(byteArr)); - ReservoirItemsSketch.toString(MemorySegment.ofArray(byteArr)); - println(" Sketch:"); - println(ris.toString()); - } - - @Test - public void checkPolymorphicType() { - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(6); - - assertNull(ris.getSamples()); - assertNull(ris.getSamples(Number.class)); - - // using mixed types - ris.update(1); - ris.update(2L); - ris.update(3.0); - ris.update((short) (44023 & 0xFFFF)); - ris.update((byte) (68 & 0xFF)); - ris.update(4.0F); - - final Number[] data = ris.getSamples(Number.class); - assertNotNull(data); - assertEquals(data.length, 6); - - // copying samples without specifying Number.class should fail - try { - ris.getSamples(); - fail(); - } catch (final ArrayStoreException e) { - // expected - } - - // likewise for toByteArray() (which uses getDataSamples() internally for type handling) - final ArrayOfNumbersSerDe serDe = new ArrayOfNumbersSerDe(); - try { - ris.toByteArray(serDe); - fail(); - } catch (final ArrayStoreException e) { - // expected - } - - final byte[] sketchBytes = ris.toByteArray(serDe, Number.class); - assertEquals(sketchBytes.length, 49); - - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - final ReservoirItemsSketch loadedRis = ReservoirItemsSketch.heapify(seg, serDe); - - assertEquals(ris.getNumSamples(), loadedRis.getNumSamples()); - - final Number[] samples1 = ris.getSamples(Number.class); - final Number[] samples2 = loadedRis.getSamples(Number.class); - assertNotNull(samples1); - assertNotNull(samples2); - assertEquals(samples1.length, samples2.length); - - for (int i = 0; i < samples1.length; ++i) { - assertEquals(samples1[i], samples2[i]); - } - } - - @Test - public void checkArrayOfNumbersSerDeErrors() { - // Highly debatable whether this belongs here vs a stand-alone test class - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(6); - - assertNull(ris.getSamples()); - assertNull(ris.getSamples(Number.class)); - - // using mixed types, but BigDecimal not supported by serde class - ris.update(1); - ris.update(new BigDecimal(2)); - - // this should work since BigDecimal is an instance of Number - final Number[] data = ris.getSamples(Number.class); - assertNotNull(data); - assertEquals(data.length, 2); - - // toByteArray() should fail - final ArrayOfNumbersSerDe serDe = new ArrayOfNumbersSerDe(); - try { - ris.toByteArray(serDe, Number.class); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - // force entry to a supported type - data[1] = 3.0; - final byte[] bytes = serDe.serializeToByteArray(data); - - // change first element to indicate something unsupported - bytes[0] = 'q'; - try { - serDe.deserializeFromMemorySegment(MemorySegment.ofArray(bytes), 0, 2); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - } - - @Test - public void checkBadConstructorArgs() { - final ArrayList data = new ArrayList<>(128); - for (int i = 0; i < 128; ++i) { - data.add(Integer.toString(i)); - } - - final ResizeFactor rf = ResizeFactor.X8; - - // no items - try { - ReservoirItemsSketch.newInstance(null, 128, rf, 128); - fail(); - } catch (final SketchesException e) { - assertTrue(e.getMessage().contains("null reservoir")); - } - - // size too small - try { - ReservoirItemsSketch.newInstance(data, 128, rf, 1); - fail(); - } catch (final SketchesException e) { - assertTrue(e.getMessage().contains("size less than 2")); - } - - // configured reservoir size smaller than items length - try { - ReservoirItemsSketch.newInstance(data, 128, rf, 64); - fail(); - } catch (final SketchesException e) { - assertTrue(e.getMessage().contains("max size less than array length")); - } - - // too many items seen vs items length, full sketch - try { - ReservoirItemsSketch.newInstance(data, 512, rf, 256); - fail(); - } catch (final SketchesException e) { - assertTrue(e.getMessage().contains("too few samples")); - } - - // too many items seen vs items length, under-full sketch - try { - ReservoirItemsSketch.newInstance(data, 256, rf, 256); - fail(); - } catch (final SketchesException e) { - assertTrue(e.getMessage().contains("too few samples")); - } - } - - @Test - public void checkRawSamples() { - final int k = 32; - final long n = 12; - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k, ResizeFactor.X2); - - for (long i = 0; i < n; ++i) { - ris.update(i); - } - - Long[] samples = ris.getSamples(); - assertNotNull(samples); - assertEquals(samples.length, n); - - final ArrayList rawSamples = ris.getRawSamplesAsList(); - assertEquals(rawSamples.size(), n); - - // change a value and make sure getDataSamples() reflects that change - assertEquals((long) rawSamples.get(0), 0L); - rawSamples.set(0, -1L); - - samples = ris.getSamples(); - assertEquals((long) samples[0], -1L); - assertEquals(samples.length, n); - } - - - @Test - public void checkSketchCapacity() { - final ArrayList data = new ArrayList<>(64); - for (long i = 0; i < 64; ++i) { - data.add(i); - } - final long itemsSeen = (1L << 48) - 2; - - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(data, itemsSeen, - ResizeFactor.X8, 64); - - // this should work, the next should fail - ris.update(0L); - - try { - ris.update(0L); - fail(); - } catch (final SketchesStateException e) { - assertTrue(e.getMessage().contains("Sketch has exceeded capacity for total items seen")); - } - - ris.reset(); - assertEquals(ris.getN(), 0); - ris.update(1L); - assertEquals(ris.getN(), 1L); - } - - @Test - public void checkSampleWeight() { - final int k = 32; - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k); - - for (int i = 0; i < (k / 2); ++i) { - ris.update(i); - } - assertEquals(ris.getImplicitSampleWeight(), 1.0); // should be exact value here - - // will have 3k/2 total samples when done - for (int i = 0; i < k; ++i) { - ris.update(i); - } - assertTrue((ris.getImplicitSampleWeight() - 1.5) < EPS); - } - - @Test - public void checkVersionConversion() { - // version change from 1 to 2 only impact first preamble long, so empty sketch is sufficient - final int k = 32768; - final short encK = ReservoirSize.computeSize(k); - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k); - final byte[] sketchBytesOrig = ris.toByteArray(serDe); - - // get a new byte[], manually revert to v1, then reconstruct - final byte[] sketchBytes = ris.toByteArray(serDe); - final MemorySegment sketchSeg = MemorySegment.ofArray(sketchBytes); - - sketchSeg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 1); - sketchSeg.set(JAVA_INT_UNALIGNED, RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes - sketchSeg.set(JAVA_SHORT_UNALIGNED, RESERVOIR_SIZE_SHORT, encK); - println(PreambleUtil.preambleToString(sketchSeg)); - - final ReservoirItemsSketch rebuilt = ReservoirItemsSketch.heapify(sketchSeg, serDe); - final byte[] rebuiltBytes = rebuilt.toByteArray(serDe); - - assertEquals(sketchBytesOrig.length, rebuiltBytes.length); - for (int i = 0; i < sketchBytesOrig.length; ++i) { - assertEquals(sketchBytesOrig[i], rebuiltBytes[i]); - } - } - - @Test - public void checkSetAndGetValue() { - final int k = 20; - final short tgtIdx = 5; - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k); - - ris.update(null); - assertEquals(ris.getN(), 0); - - for (short i = 0; i < k; ++i) { - ris.update(i); - } - - assertEquals((short) ris.getValueAtPosition(tgtIdx), tgtIdx); - ris.insertValueAtPosition((short) -1, tgtIdx); - assertEquals((short) ris.getValueAtPosition(tgtIdx), (short) -1); - } - - @Test - public void checkBadSetAndGetValue() { - final int k = 20; - final int tgtIdx = 5; - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k); - - try { - ris.getValueAtPosition(0); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - for (int i = 0; i < k; ++i) { - ris.update(i); - } - assertEquals((int) ris.getValueAtPosition(tgtIdx), tgtIdx); - - try { - ris.insertValueAtPosition(-1, -1); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - try { - ris.insertValueAtPosition(-1, k + 1); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - try { - ris.getValueAtPosition(-1); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - try { - ris.getValueAtPosition(k + 1); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - } - - @Test - public void checkForceIncrement() { - final int k = 100; - final ReservoirItemsSketch rls = ReservoirItemsSketch.newInstance(k); - - for (long i = 0; i < (2 * k); ++i) { - rls.update(i); - } - - assertEquals(rls.getN(), 2 * k); - rls.forceIncrementItemsSeen(k); - assertEquals(rls.getN(), 3 * k); - - try { - rls.forceIncrementItemsSeen((1L << 48) - 2); - fail(); - } catch (final SketchesStateException e) { - // expected - } - } - - @Test - public void checkEstimateSubsetSum() { - final int k = 10; - - //trial loop for probabilistic testing - int passLB = 0; - int passUB = 0; - for (int t = 0; t < 3; t++) { - final ReservoirItemsSketch sketch = ReservoirItemsSketch.newInstance(k); - - // empty sketch -- all zeros - SampleSubsetSummary ss = sketch.estimateSubsetSum(item -> true); - assertEquals(ss.getEstimate(), 0.0); - assertEquals(ss.getTotalSketchWeight(), 0.0); - - // add items, keeping in exact mode - double itemCount = 0.0; - for (long i = 1; i <= (k - 1); ++i) { - sketch.update(i); - itemCount += 1.0; - } - - ss = sketch.estimateSubsetSum(item -> true); - assertEquals(ss.getEstimate(), itemCount); - assertEquals(ss.getLowerBound(), itemCount); - assertEquals(ss.getUpperBound(), itemCount); - assertEquals(ss.getTotalSketchWeight(), itemCount); - - // add a few more items, pushing to sampling mode - for (long i = k; i <= (k + 1); ++i) { - sketch.update(i); - itemCount += 1.0; - } - - // predicate always true so estimate == upper bound - ss = sketch.estimateSubsetSum(item -> true); - assertEquals(ss.getEstimate(), itemCount); - assertEquals(ss.getUpperBound(), itemCount); - assertTrue(ss.getLowerBound() < itemCount); - assertEquals(ss.getTotalSketchWeight(), itemCount); - - // predicate always false so estimate == lower bound == 0.0 - ss = sketch.estimateSubsetSum(item -> false); - assertEquals(ss.getEstimate(), 0.0); - assertEquals(ss.getLowerBound(), 0.0); - assertTrue(ss.getUpperBound() > 0.0); - assertEquals(ss.getTotalSketchWeight(), itemCount); - - // finally, a non-degenerate predicate - // insert negative items with identical weights, filter for negative weights only - for (long i = 1; i <= (k + 1); ++i) { - sketch.update(-i); - itemCount += 1.0; - } - - ss = sketch.estimateSubsetSum(item -> item < 0); - assertTrue(ss.getEstimate() >= ss.getLowerBound()); - assertTrue(ss.getEstimate() <= ss.getUpperBound()); - - // allow pretty generous bounds when testing - if(ss.getLowerBound() < (itemCount / 1.4)) { passLB++; } - if(ss.getUpperBound() > (itemCount / 2.6)) { passUB++; } - assertEquals(ss.getTotalSketchWeight(), itemCount); - } //End trial loop - assertTrue(passLB >= 2 && passUB >= 2); //2 out of 3 must pass for LB and UB - } - - private static MemorySegment getBasicSerializedLongsRIS() { - final int k = 10; - final int n = 20; - - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k); - assertEquals(ris.getNumSamples(), 0); - - for (int i = 0; i < n; ++i) { - ris.update((long) i); - } - assertEquals(ris.getNumSamples(), Math.min(n, k)); - assertEquals(ris.getN(), n); - assertEquals(ris.getK(), k); - - final byte[] sketchBytes = ris.toByteArray(new ArrayOfLongsSerDe()); - return MemorySegment.ofArray(sketchBytes); - } - - private static void validateSerializeAndDeserialize(final ReservoirItemsSketch ris) { - final byte[] sketchBytes = ris.toByteArray(new ArrayOfLongsSerDe()); - assertEquals(sketchBytes.length, - (Family.RESERVOIR.getMaxPreLongs() + ris.getNumSamples()) << 3); - - // ensure full reservoir rebuilds correctly - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - final ReservoirItemsSketch loadedRis = ReservoirItemsSketch.heapify(seg, serDe); - - validateReservoirEquality(ris, loadedRis); - } - - static void validateReservoirEquality(final ReservoirItemsSketch ris1, - final ReservoirItemsSketch ris2) { - assertEquals(ris1.getNumSamples(), ris2.getNumSamples()); - - if (ris1.getNumSamples() == 0) { return; } - - final Object[] samples1 = ris1.getSamples(); - final Object[] samples2 = ris2.getSamples(); - assertNotNull(samples1); - assertNotNull(samples2); - assertEquals(samples1.length, samples2.length); - - for (int i = 0; i < samples1.length; ++i) { - assertEquals(samples1[i], samples2[i]); - } - } - - /** - * Wrapper around System.out.println() allowing a simple way to disable logging in tests - * @param msg The message to print - */ - private static void println(final String msg) { - //System.out.println(msg); - } -} diff --git a/src/test/java/org/apache/datasketches/sampling/ReservoirItemsUnionTest.java b/src/test/java/org/apache/datasketches/sampling/ReservoirItemsUnionTest.java deleted file mode 100644 index b474901a9..000000000 --- a/src/test/java/org/apache/datasketches/sampling/ReservoirItemsUnionTest.java +++ /dev/null @@ -1,500 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.sampling.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SIZE_INT; -import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SIZE_SHORT; -import static org.apache.datasketches.sampling.PreambleUtil.SER_VER_BYTE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.ArrayList; - -import org.apache.datasketches.common.ArrayOfDoublesSerDe; -import org.apache.datasketches.common.ArrayOfLongsSerDe; -import org.apache.datasketches.common.ArrayOfNumbersSerDe; -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.sampling.PreambleUtil; -import org.apache.datasketches.sampling.ReservoirItemsSketch; -import org.apache.datasketches.sampling.ReservoirItemsUnion; -import org.apache.datasketches.sampling.ReservoirSize; -import org.testng.annotations.Test; - -// Tests mostly focus on Long since other types are already tested in ReservoirItemsSketchTest. -public class ReservoirItemsUnionTest { - @Test - public void checkEmptyUnion() { - final ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(1024); - final byte[] unionBytes = riu.toByteArray(new ArrayOfLongsSerDe()); - - // will intentionally break if changing empty union serialization - assertEquals(unionBytes.length, 8); - - println(riu.toString()); - } - - @Test - public void checkInstantiation() { - final int n = 100; - final int k = 25; - - // create empty unions - ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(k); - assertNull(riu.getResult()); - riu.update(5L); - assertNotNull(riu.getResult()); - - // pass in a sketch, as both an object and MemorySegment - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k); - for (long i = 0; i < n; ++i) { - ris.update(i); - } - - riu.reset(); - assertEquals(riu.getResult().getN(), 0); - riu.update(ris); - assertEquals(riu.getResult().getN(), ris.getN()); - - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - final byte[] sketchBytes = ris.toByteArray(serDe); // only the gadget is serialized - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - riu = ReservoirItemsUnion.newInstance(ris.getK()); - riu.update(seg, serDe); - assertNotNull(riu.getResult()); - - println(riu.toString()); - } - - /* - @Test - public void checkReadOnlyInstantiation() { - final int k = 100; - final ReservoirItemsUnion union = ReservoirItemsUnion.newInstance(k); - for (long i = 0; i < 2 * k; ++i) { - union.update(i); - } - - final byte[] unionBytes = union.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(unionBytes); - - final ReservoirItemsUnion riu; - riu = ReservoirItemsUnion.heapify(seg, new ArrayOfLongsSerDe()); - - assertNotNull(riu); - assertEquals(riu.getMaxK(), k); - ReservoirItemsSketchTest.validateReservoirEquality(riu.getResult(), union.getResult()); - } - */ - - @Test - public void checkNullUpdate() { - final ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(1024); - assertNull(riu.getResult()); - - // null sketch - final ReservoirItemsSketch nullSketch = null; - riu.update(nullSketch); - assertNull(riu.getResult()); - - // null MemorySegment - riu.update(null, new ArrayOfLongsSerDe()); - assertNull(riu.getResult()); - - // null item - riu.update((Long) null); - assertNull(riu.getResult()); - - // valid input - riu.update(5L); - assertNotNull(riu.getResult()); - } - - @Test - public void checkSerialization() { - final int n = 100; - final int k = 25; - - final ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(k); - for (long i = 0; i < n; ++i) { - riu.update(i); - } - - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - final byte[] unionBytes = riu.toByteArray(serDe); - final MemorySegment seg = MemorySegment.ofArray(unionBytes); - println(PreambleUtil.preambleToString(seg)); - - final ReservoirItemsUnion rebuiltUnion = ReservoirItemsUnion.heapify(seg, serDe); - assertEquals(riu.getMaxK(), rebuiltUnion.getMaxK()); - ReservoirItemsSketchTest.validateReservoirEquality(riu.getResult(), rebuiltUnion.getResult()); - } - - @Test - public void checkVersionConversionWithEmptyGadget() { - final int k = 32768; - final short encK = ReservoirSize.computeSize(k); - final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - - final ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(k); - final byte[] unionBytesOrig = riu.toByteArray(serDe); - - // get a new byte[], manually revert to v1, then reconstruct - final byte[] unionBytes = riu.toByteArray(serDe); - final MemorySegment unionSeg = MemorySegment.ofArray(unionBytes); - - unionSeg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 1); - unionSeg.set(JAVA_INT_UNALIGNED, RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes - unionSeg.set(JAVA_SHORT_UNALIGNED, RESERVOIR_SIZE_SHORT, encK); - println(PreambleUtil.preambleToString(unionSeg)); - - final ReservoirItemsUnion rebuilt = ReservoirItemsUnion.heapify(unionSeg, serDe); - final byte[] rebuiltBytes = rebuilt.toByteArray(serDe); - - assertEquals(unionBytesOrig.length, rebuiltBytes.length); - for (int i = 0; i < unionBytesOrig.length; ++i) { - assertEquals(unionBytesOrig[i], rebuiltBytes[i]); - } - } - - @Test - public void checkVersionConversionWithGadget() { - final long n = 32; - final int k = 256; - final short encK = ReservoirSize.computeSize(k); - final ArrayOfNumbersSerDe serDe = new ArrayOfNumbersSerDe(); - - final ReservoirItemsUnion rlu = ReservoirItemsUnion.newInstance(k); - for (long i = 0; i < n; ++i) { - rlu.update(i); - } - final byte[] unionBytesOrig = rlu.toByteArray(serDe); - - // get a new byte[], manually revert to v1, then reconstruct - final byte[] unionBytes = rlu.toByteArray(serDe); - final MemorySegment unionSeg = MemorySegment.ofArray(unionBytes); - - unionSeg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 1); - unionSeg.set(JAVA_INT_UNALIGNED, RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes - unionSeg.set(JAVA_SHORT_UNALIGNED, RESERVOIR_SIZE_SHORT, encK); - - // force gadget header to v1, too - final int offset = Family.RESERVOIR_UNION.getMaxPreLongs() << 3; - unionSeg.set(JAVA_BYTE, offset + SER_VER_BYTE, (byte) 1); - unionSeg.set(JAVA_INT_UNALIGNED, offset + RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes - unionSeg.set(JAVA_SHORT_UNALIGNED, offset + RESERVOIR_SIZE_SHORT, encK); - - final ReservoirItemsUnion rebuilt = ReservoirItemsUnion.heapify(unionSeg, serDe); - final byte[] rebuiltBytes = rebuilt.toByteArray(serDe); - - assertEquals(unionBytesOrig.length, rebuiltBytes.length); - for (int i = 0; i < unionBytesOrig.length; ++i) { - assertEquals(unionBytesOrig[i], rebuiltBytes[i]); - } - } - - //@SuppressWarnings("null") // this is the point of the test - @Test(expectedExceptions = NullPointerException.class) - public void checkNullMemorySegmentInstantiation() { - ReservoirItemsUnion.heapify(null, new ArrayOfStringsSerDe()); - } - - @Test - public void checkDownsampledUpdate() { - final int bigK = 1024; - final int smallK = 256; - final int n = 2048; - final ReservoirItemsSketch sketch1 = getBasicSketch(n, smallK); - final ReservoirItemsSketch sketch2 = getBasicSketch(2 * n, bigK); - - final ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(smallK); - assertEquals(riu.getMaxK(), smallK); - - riu.update(sketch1); - assertNotNull(riu.getResult()); - assertEquals(riu.getResult().getK(), smallK); - - riu.update(sketch2); - assertEquals(riu.getResult().getK(), smallK); - assertEquals(riu.getResult().getNumSamples(), smallK); - } - - @Test - public void checkUnionResetWithInitialSmallK() { - final int maxK = 25; - final int sketchK = 10; - final ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(maxK); - - ReservoirItemsSketch ris = getBasicSketch(2 * sketchK, sketchK); // in sampling mode - riu.update(ris); - assertEquals(riu.getMaxK(), maxK); - assertNotNull(riu.getResult()); - assertEquals(riu.getResult().getK(), sketchK); - - riu.reset(); - assertNotNull(riu.getResult()); - - // feed in sketch in sampling mode, with larger k than old gadget - ris = getBasicSketch(2 * maxK, maxK + 1); - riu.update(ris); - assertEquals(riu.getMaxK(), maxK); - assertNotNull(riu.getResult()); - assertEquals(riu.getResult().getK(), maxK); - } - - @Test - public void checkNewGadget() { - final int maxK = 1024; - final int bigK = 1536; - final int smallK = 128; - - // downsample input sketch, use as gadget (exact mode, but irrelevant here) - final ReservoirItemsSketch bigKSketch = getBasicSketch(maxK / 2, bigK); - final byte[] bigKBytes = bigKSketch.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment bigKSeg = MemorySegment.ofArray(bigKBytes); - - ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(maxK); - riu.update(bigKSeg, new ArrayOfLongsSerDe()); - assertNotNull(riu.getResult()); - assertEquals(riu.getResult().getK(), maxK); - assertEquals(riu.getResult().getN(), maxK / 2); - - // sketch k < maxK but in sampling mode - final ReservoirItemsSketch smallKSketch = getBasicSketch(maxK, smallK); - final byte[] smallKBytes = smallKSketch.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment smallKSeg = MemorySegment.ofArray(smallKBytes); - - riu = ReservoirItemsUnion.newInstance(maxK); - riu.update(smallKSeg, new ArrayOfLongsSerDe()); - assertNotNull(riu.getResult()); - assertTrue(riu.getResult().getK() < maxK); - assertEquals(riu.getResult().getK(), smallK); - assertEquals(riu.getResult().getN(), maxK); - - // sketch k < maxK and in exact mode - final ReservoirItemsSketch smallKExactSketch = getBasicSketch(smallK, smallK); - final byte[] smallKExactBytes = smallKExactSketch.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment smallKExactSeg = MemorySegment.ofArray(smallKExactBytes); - - riu = ReservoirItemsUnion.newInstance(maxK); - riu.update(smallKExactSeg, new ArrayOfLongsSerDe()); - assertNotNull(riu.getResult()); - assertEquals(riu.getResult().getK(), maxK); - assertEquals(riu.getResult().getN(), smallK); - } - - @Test - public void checkListInputUpdate() { - final int k = 32; - final int n = 64; - final ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(k); - - ArrayList data = new ArrayList<>(k); - for (int i = 0; i < k; ++i) { - data.add(i); - } - riu.update(n, k, data); - assertNotNull(riu.getResult()); - assertEquals(riu.getResult().getN(), n); - assertEquals(riu.getResult().getK(), k); // power of 2, so exact - - data = new ArrayList<>(2 * k); - for (int i = 0; i < (2 * k); ++i) { - data.add(i); - } - riu.update(10 * n, 2 * k, data); - assertEquals(riu.getResult().getN(), 11 * n); // total = n + 10n - assertEquals(riu.getResult().getK(), k); // should have downsampled the 2nd - } - - @Test - public void checkStandardMergeNoCopy() { - final int k = 1024; - final int n1 = 256; - final int n2 = 256; - final ReservoirItemsSketch sketch1 = getBasicSketch(n1, k); - final ReservoirItemsSketch sketch2 = getBasicSketch(n2, k); - - final ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(k); - riu.update(sketch1); - riu.update(sketch2); - - assertNotNull(riu.getResult()); - assertEquals(riu.getResult().getK(), k); - assertEquals(riu.getResult().getN(), n1 + n2); - assertEquals(riu.getResult().getNumSamples(), n1 + n2); - - // creating from MemorySegment should avoid a copy - final int n3 = 2048; - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - final ReservoirItemsSketch sketch3 = getBasicSketch(n3, k); - final byte[] sketch3Bytes = sketch3.toByteArray(serDe); - final MemorySegment seg = MemorySegment.ofArray(sketch3Bytes); - riu.update(seg, serDe); - - assertEquals(riu.getResult().getK(), k); - assertEquals(riu.getResult().getN(), n1 + n2 + n3); - assertEquals(riu.getResult().getNumSamples(), k); - } - - @Test - public void checkStandardMergeWithCopy() { - // this will check the other code route to a standard merge, - // but will copy sketch2 to be non-destructive. - final int k = 1024; - final int n1 = 768; - final int n2 = 2048; - final ReservoirItemsSketch sketch1 = getBasicSketch(n1, k); - final ReservoirItemsSketch sketch2 = getBasicSketch(n2, k); - - final ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(k); - riu.update(sketch1); - riu.update(sketch2); - riu.update(10L); - - assertNotNull(riu.getResult()); - assertEquals(riu.getResult().getK(), k); - assertEquals(riu.getResult().getN(), n1 + n2 + 1); - assertEquals(riu.getResult().getNumSamples(), k); - } - - @Test - public void checkWeightedMerge() { - final int k = 1024; - final int n1 = 16384; - final int n2 = 2048; - final ReservoirItemsSketch sketch1 = getBasicSketch(n1, k); - final ReservoirItemsSketch sketch2 = getBasicSketch(n2, k); - - ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(k); - riu.update(sketch1); - riu.update(sketch2); - - assertNotNull(riu.getResult()); - assertEquals(riu.getResult().getK(), k); - assertEquals(riu.getResult().getN(), n1 + n2); - assertEquals(riu.getResult().getNumSamples(), k); - - // now merge into the sketch for updating -- results should match - riu = ReservoirItemsUnion.newInstance(k); - riu.update(sketch2); - riu.update(sketch1); - - assertNotNull(riu.getResult()); - assertEquals(riu.getResult().getK(), k); - assertEquals(riu.getResult().getN(), n1 + n2); - assertEquals(riu.getResult().getNumSamples(), k); - } - - @Test - public void checkPolymorphicType() { - final int k = 4; - - final ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(k); - riu.update(2.2); - riu.update(6L); - - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k); - ris.update(1); - ris.update(3.7f); - - riu.update(ris); - - final ArrayOfNumbersSerDe serDe = new ArrayOfNumbersSerDe(); - final byte[] sketchBytes = riu.toByteArray(serDe, Number.class); - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - - final ReservoirItemsUnion rebuiltRiu = ReservoirItemsUnion.heapify(seg, serDe); - - // validateReservoirEquality can't handle abstract base class - assertNotNull(riu.getResult()); - assertNotNull(rebuiltRiu.getResult()); - assertEquals(riu.getResult().getNumSamples(), rebuiltRiu.getResult().getNumSamples()); - - final Number[] samples1 = riu.getResult().getSamples(Number.class); - final Number[] samples2 = rebuiltRiu.getResult().getSamples(Number.class); - assertNotNull(samples1); - assertNotNull(samples2); - assertEquals(samples1.length, samples2.length); - - for (int i = 0; i < samples1.length; ++i) { - assertEquals(samples1[i], samples2[i]); - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadPreLongs() { - final ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(1024); - final MemorySegment seg = MemorySegment.ofArray(riu.toByteArray(new ArrayOfNumbersSerDe())); - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) 0); // corrupt the preLongs count - - ReservoirItemsUnion.heapify(seg, new ArrayOfNumbersSerDe()); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadSerVer() { - final ReservoirItemsUnion riu = ReservoirItemsUnion.newInstance(1024); - final MemorySegment seg = MemorySegment.ofArray(riu.toByteArray(new ArrayOfStringsSerDe())); - seg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 0); // corrupt the serialization version - - ReservoirItemsUnion.heapify(seg, new ArrayOfStringsSerDe()); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadFamily() { - final ReservoirItemsUnion rlu = ReservoirItemsUnion.newInstance(1024); - final MemorySegment seg = MemorySegment.ofArray(rlu.toByteArray(new ArrayOfDoublesSerDe())); - seg.set(JAVA_BYTE, FAMILY_BYTE, (byte) 0); // corrupt the family ID - - ReservoirItemsUnion.heapify(seg, new ArrayOfDoublesSerDe()); - fail(); - } - - private static ReservoirItemsSketch getBasicSketch(final int n, final int k) { - final ReservoirItemsSketch rls = ReservoirItemsSketch.newInstance(k); - - for (long i = 0; i < n; ++i) { - rls.update(i); - } - - return rls; - } - - /** - * Wrapper around System.out.println() allowing a simple way to disable logging in tests - * - * @param msg The message to print - */ - private static void println(final String msg) { - //System.out.println(msg); - } -} diff --git a/src/test/java/org/apache/datasketches/sampling/ReservoirLongsSketchTest.java b/src/test/java/org/apache/datasketches/sampling/ReservoirLongsSketchTest.java deleted file mode 100644 index 80c10e91c..000000000 --- a/src/test/java/org/apache/datasketches/sampling/ReservoirLongsSketchTest.java +++ /dev/null @@ -1,527 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.sampling.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SIZE_INT; -import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SIZE_SHORT; -import static org.apache.datasketches.sampling.PreambleUtil.SER_VER_BYTE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.sampling.ReservoirLongsSketch; -import org.apache.datasketches.sampling.ReservoirSize; -import org.apache.datasketches.sampling.SampleSubsetSummary; -import org.testng.annotations.Test; - -public class ReservoirLongsSketchTest { - private static final double EPS = 1e-8; - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidK() { - ReservoirLongsSketch.newInstance(0); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadPreLongs() { - final MemorySegment seg = getBasicSerializedRLS(); - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) 0); // corrupt the preLongs count - - ReservoirLongsSketch.heapify(seg); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadSerVer() { - final MemorySegment seg = getBasicSerializedRLS(); - seg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 0); // corrupt the serialization version - - ReservoirLongsSketch.heapify(seg); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadFamily() { - final MemorySegment seg = getBasicSerializedRLS(); - seg.set(JAVA_BYTE, FAMILY_BYTE, (byte) 0); // corrupt the family ID - - ReservoirLongsSketch.heapify(seg); - fail(); - } - - @Test - public void checkEmptySketch() { - final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(5); - assertTrue(rls.getSamples() == null); - - final byte[] sketchBytes = rls.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - - // only minPreLongs bytes and should deserialize to empty - assertEquals(sketchBytes.length, Family.RESERVOIR.getMinPreLongs() << 3); - final ReservoirLongsSketch loadedRls = ReservoirLongsSketch.heapify(seg); - assertEquals(loadedRls.getNumSamples(), 0); - - println("Empty sketch:"); - println(rls.toString()); - ReservoirLongsSketch.toString(sketchBytes); - ReservoirLongsSketch.toString(seg); - } - - @Test - public void checkUnderFullReservoir() { - final int k = 128; - final int n = 64; - - final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k); - - for (int i = 0; i < n; ++i) { - rls.update(i); - } - assertEquals(rls.getNumSamples(), n); - - final long[] data = rls.getSamples(); - assertEquals(rls.getNumSamples(), rls.getN()); - assertNotNull(data); - assertEquals(data.length, n); - - // items in submit order until reservoir at capacity so check - for (int i = 0; i < n; ++i) { - assertEquals(data[i], i); - } - - validateSerializeAndDeserialize(rls); - } - - @Test - public void checkFullReservoir() { - final int k = 1000; - final int n = 2000; - - // specify smaller ResizeFactor to ensure multiple resizes - final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k, ResizeFactor.X2); - - for (int i = 0; i < n; ++i) { - rls.update(i); - } - assertEquals(rls.getNumSamples(), rls.getK()); - - validateSerializeAndDeserialize(rls); - - println("Full reservoir:"); - println(rls.toString()); - } - - @Test - public void checkDownsampledCopy() { - final int k = 256; - final int tgtK = 64; - - final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k); - - // check status at 3 points: - // 1. n < encTgtK - // 2. encTgtK < n < k - // 3. n > k - - int i; - for (i = 0; i < (tgtK - 1); ++i) { - rls.update(i); - } - - ReservoirLongsSketch dsCopy = rls.downsampledCopy(tgtK); - assertEquals(dsCopy.getK(), tgtK); - - // should be identical other than value of k, which isn't checked here - validateReservoirEquality(rls, dsCopy); - - // check condition 2 next - for (; i < (k - 1); ++i) { - rls.update(i); - } - assertEquals(rls.getN(), k - 1); - - dsCopy = rls.downsampledCopy(tgtK); - assertEquals(dsCopy.getN(), rls.getN()); - assertEquals(dsCopy.getNumSamples(), tgtK); - - // and now condition 3 - for (; i < (2 * k); ++i) { - rls.update(i); - } - assertEquals(rls.getN(), 2 * k); - - dsCopy = rls.downsampledCopy(tgtK); - assertEquals(dsCopy.getN(), rls.getN()); - assertEquals(dsCopy.getNumSamples(), tgtK); - } - - @Test - public void checkBadConstructorArgs() { - final long[] data = new long[128]; - for (int i = 0; i < 128; ++i) { - data[i] = i; - } - - final ResizeFactor rf = ResizeFactor.X8; - - // no items - try { - ReservoirLongsSketch.getInstance(null, 128, rf, 128); - fail(); - } catch (final SketchesException e) { - assertTrue(e.getMessage().contains("null reservoir")); - } - - // size too small - try { - ReservoirLongsSketch.getInstance(data, 128, rf, 1); - fail(); - } catch (final SketchesException e) { - assertTrue(e.getMessage().contains("size less than 2")); - } - - // configured reservoir size smaller than items length - try { - ReservoirLongsSketch.getInstance(data, 128, rf, 64); - fail(); - } catch (final SketchesException e) { - assertTrue(e.getMessage().contains("max size less than array length")); - } - - // too many items seen vs items length, full sketch - try { - ReservoirLongsSketch.getInstance(data, 512, rf, 256); - fail(); - } catch (final SketchesException e) { - assertTrue(e.getMessage().contains("too few samples")); - } - - // too many items seen vs items length, under-full sketch - try { - ReservoirLongsSketch.getInstance(data, 256, rf, 256); - fail(); - } catch (final SketchesException e) { - assertTrue(e.getMessage().contains("too few samples")); - } - } - - @Test - public void checkSketchCapacity() { - final long[] data = new long[64]; - final long itemsSeen = (1L << 48) - 2; - - final ReservoirLongsSketch rls = ReservoirLongsSketch.getInstance(data, itemsSeen, - ResizeFactor.X8, data.length); - - // this should work, the next should fail - rls.update(0); - - try { - rls.update(0); - fail(); - } catch (final SketchesStateException e) { - assertTrue(e.getMessage().contains("Sketch has exceeded capacity for total items seen")); - } - - rls.reset(); - assertEquals(rls.getN(), 0); - rls.update(1L); - assertEquals(rls.getN(), 1L); - } - - @Test - public void checkSampleWeight() { - final int k = 32; - final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k); - - for (int i = 0; i < (k / 2); ++i) { - rls.update(i); - } - assertEquals(rls.getImplicitSampleWeight(), 1.0); // should be exact value here - - // will have 3k/2 total samples when done - for (int i = 0; i < k; ++i) { - rls.update(i); - } - assertTrue(Math.abs(rls.getImplicitSampleWeight() - 1.5) < EPS); - } - - @Test - public void checkVersionConversion() { - // version change from 1 to 2 only impact first preamble long, so empty sketch is sufficient - final int k = 32768; - final short encK = ReservoirSize.computeSize(k); - - final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k); - final byte[] sketchBytesOrig = rls.toByteArray(); - - // get a new byte[], manually revert to v1, then reconstruct - final byte[] sketchBytes = rls.toByteArray(); - final MemorySegment sketchSeg = MemorySegment.ofArray(sketchBytes); - - sketchSeg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 1); - sketchSeg.set(JAVA_INT_UNALIGNED, RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes - sketchSeg.set(JAVA_SHORT_UNALIGNED, RESERVOIR_SIZE_SHORT, encK); - - final ReservoirLongsSketch rebuilt = ReservoirLongsSketch.heapify(sketchSeg); - final byte[] rebuiltBytes = rebuilt.toByteArray(); - - assertEquals(sketchBytesOrig.length, rebuiltBytes.length); - for (int i = 0; i < sketchBytesOrig.length; ++i) { - assertEquals(sketchBytesOrig[i], rebuiltBytes[i]); - } - } - - @Test - public void checkSetAndGetValue() { - final int k = 20; - final int tgtIdx = 5; - final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k); - for (int i = 0; i < k; ++i) { - rls.update(i); - } - - assertEquals(rls.getValueAtPosition(tgtIdx), tgtIdx); - rls.insertValueAtPosition(-1, tgtIdx); - assertEquals(rls.getValueAtPosition(tgtIdx), -1); - } - - @Test - public void checkBadSetAndGetValue() { - final int k = 20; - final int tgtIdx = 5; - final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k); - - try { - rls.getValueAtPosition(0); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - for (int i = 0; i < k; ++i) { - rls.update(i); - } - assertEquals(rls.getValueAtPosition(tgtIdx), tgtIdx); - - try { - rls.insertValueAtPosition(-1, -1); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - try { - rls.insertValueAtPosition(-1, k + 1); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - try { - rls.getValueAtPosition(-1); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - try { - rls.getValueAtPosition(k + 1); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - } - - @Test - public void checkForceIncrement() { - final int k = 100; - final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k); - - for (int i = 0; i < (2 * k); ++i) { - rls.update(i); - } - - assertEquals(rls.getN(), 2 * k); - rls.forceIncrementItemsSeen(k); - assertEquals(rls.getN(), 3 * k); - - try { - rls.forceIncrementItemsSeen((1L << 48) - 1); - fail(); - } catch (final SketchesStateException e) { - // expected - } - } - - @Test - public void cluster_checkEstimateSubsetSum() { - final int cluster = 3; - int failCount = 0; - for (int i = 0; i < cluster; i++) { - try { - checkEstimateSubsetSum(); //Test to run cluster on - //System.out.println("Fail Count: " + failCount); //useful for debugging thresholds - break; - } catch (final AssertionError ae) { - if (++failCount >= cluster) { - final StringWriter sw = new StringWriter(); - ae.printStackTrace(new PrintWriter(sw)); - final String str = sw.toString(); - fail("Failed a cluster of " + cluster + "\n" + str); - } - } - } - } - - public void checkEstimateSubsetSum() { - final int k = 10; - final ReservoirLongsSketch sketch = ReservoirLongsSketch.newInstance(k); - - // empty sketch -- all zeros - SampleSubsetSummary ss = sketch.estimateSubsetSum(item -> true); - assertEquals(ss.getEstimate(), 0.0); - assertEquals(ss.getTotalSketchWeight(), 0.0); - - // add items, keeping in exact mode - double itemCount = 0.0; - for (long i = 1; i <= (k - 1); ++i) { - sketch.update(i); - itemCount += 1.0; - } - - ss = sketch.estimateSubsetSum(item -> true); - assertEquals(ss.getEstimate(), itemCount); - assertEquals(ss.getLowerBound(), itemCount); - assertEquals(ss.getUpperBound(), itemCount); - assertEquals(ss.getTotalSketchWeight(), itemCount); - - // add a few more items, pushing to sampling mode - for (long i = k; i <= (k + 1); ++i) { - sketch.update(i); - itemCount += 1.0; - } - - // predicate always true so estimate == upper bound - ss = sketch.estimateSubsetSum(item -> true); - assertEquals(ss.getEstimate(), itemCount); - assertEquals(ss.getUpperBound(), itemCount); - assertTrue(ss.getLowerBound() < itemCount); - assertEquals(ss.getTotalSketchWeight(), itemCount); - - // predicate always false so estimate == lower bound == 0.0 - ss = sketch.estimateSubsetSum(item -> false); - assertEquals(ss.getEstimate(), 0.0); - assertEquals(ss.getLowerBound(), 0.0); - assertTrue(ss.getUpperBound() > 0.0); - assertEquals(ss.getTotalSketchWeight(), itemCount); - - // finally, a non-degenerate predicate - // insert negative items with identical weights, filter for negative weights only - for (long i = 1; i <= (k + 1); ++i) { - sketch.update(-i); - itemCount += 1.0; - } - - ss = sketch.estimateSubsetSum(item -> item < 0); - assertTrue(ss.getEstimate() >= ss.getLowerBound()); - assertTrue(ss.getEstimate() <= ss.getUpperBound()); - - // allow pretty generous bounds when testing - assertTrue(ss.getLowerBound() < (itemCount / 1.4)); - assertTrue(ss.getUpperBound() > (itemCount / 2.6)); - assertEquals(ss.getTotalSketchWeight(), itemCount); - } - - private static MemorySegment getBasicSerializedRLS() { - final int k = 10; - final int n = 20; - - final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k); - assertEquals(rls.getNumSamples(), 0); - - for (int i = 0; i < n; ++i) { - rls.update(i); - } - assertEquals(rls.getNumSamples(), Math.min(n, k)); - assertEquals(rls.getN(), n); - assertEquals(rls.getK(), k); - - final byte[] sketchBytes = rls.toByteArray(); - return MemorySegment.ofArray(sketchBytes); - } - - private static void validateSerializeAndDeserialize(final ReservoirLongsSketch rls) { - final byte[] sketchBytes = rls.toByteArray(); - assertEquals(sketchBytes.length, - (Family.RESERVOIR.getMaxPreLongs() + rls.getNumSamples()) << 3); - - // ensure full reservoir rebuilds correctly - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - final ReservoirLongsSketch loadedRls = ReservoirLongsSketch.heapify(seg); - - validateReservoirEquality(rls, loadedRls); - } - - static void validateReservoirEquality(final ReservoirLongsSketch rls1, - final ReservoirLongsSketch rls2) { - assertEquals(rls1.getNumSamples(), rls2.getNumSamples()); - - if (rls1.getNumSamples() == 0) { - return; - } - - final long[] samples1 = rls1.getSamples(); - final long[] samples2 = rls2.getSamples(); - assertNotNull(samples1); - assertNotNull(samples2); - assertEquals(samples1.length, samples2.length); - - for (int i = 0; i < samples1.length; ++i) { - assertEquals(samples1[i], samples2[i]); - } - } - - /** - * Wrapper around System.out.println() allowing a simple way to disable logging in tests - * - * @param msg The message to print - */ - private static void println(final String msg) { - //System.out.println(msg); - } -} diff --git a/src/test/java/org/apache/datasketches/sampling/ReservoirLongsUnionTest.java b/src/test/java/org/apache/datasketches/sampling/ReservoirLongsUnionTest.java deleted file mode 100644 index 5d3ace740..000000000 --- a/src/test/java/org/apache/datasketches/sampling/ReservoirLongsUnionTest.java +++ /dev/null @@ -1,430 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED; -import static org.apache.datasketches.sampling.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SIZE_INT; -import static org.apache.datasketches.sampling.PreambleUtil.RESERVOIR_SIZE_SHORT; -import static org.apache.datasketches.sampling.PreambleUtil.SER_VER_BYTE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.sampling.PreambleUtil; -import org.apache.datasketches.sampling.ReservoirLongsSketch; -import org.apache.datasketches.sampling.ReservoirLongsUnion; -import org.apache.datasketches.sampling.ReservoirSize; -import org.testng.annotations.Test; - -public class ReservoirLongsUnionTest { - @Test - public void checkEmptyUnion() { - final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(1024); - final byte[] unionBytes = rlu.toByteArray(); - - // will intentionally break if changing empty union serialization - assertEquals(unionBytes.length, 8); - - println(rlu.toString()); - } - - @Test - public void checkInstantiation() { - final int n = 100; - final int k = 25; - - // create empty unions - ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k); - assertNull(rlu.getResult()); - rlu.update(5); - assertNotNull(rlu.getResult()); - - // pass in a sketch, as both an object and MemorySegment - final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k); - for (int i = 0; i < n; ++i) { - rls.update(i); - } - - rlu.reset(); - assertEquals(rlu.getResult().getN(), 0); - rlu.update(rls); - assertEquals(rlu.getResult().getN(), rls.getN()); - - final byte[] sketchBytes = rls.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - rlu = ReservoirLongsUnion.newInstance(rls.getK()); - rlu.update(seg); - assertNotNull(rlu.getResult()); - - println(rlu.toString()); - } - - /* - @Test - public void checkReadOnlyInstantiation() { - final int k = 100; - final ReservoirLongsUnion union = ReservoirLongsUnion.newInstance(k); - for (long i = 0; i < 2 * k; ++i) { - union.update(i); - } - - final byte[] unionBytes = union.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(unionBytes); - - final ReservoirLongsUnion rlu; - rlu = ReservoirLongsUnion.heapify(seg); - - assertNotNull(rlu); - assertEquals(rlu.getMaxK(), k); - ReservoirLongsSketchTest.validateReservoirEquality(rlu.getResult(), union.getResult()); - } - */ - - @Test - public void checkNullUpdate() { - final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(1024); - assertNull(rlu.getResult()); - - // null sketch - rlu.update((ReservoirLongsSketch) null); - assertNull(rlu.getResult()); - - // null MemorySegment - rlu.update((MemorySegment) null); - assertNull(rlu.getResult()); - - // valid input - rlu.update(5L); - assertNotNull(rlu.getResult()); - } - - @Test - public void checkSerialization() { - final int n = 100; - final int k = 25; - - final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k); - for (int i = 0; i < n; ++i) { - rlu.update(i); - } - - final byte[] unionBytes = rlu.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(unionBytes); - - final ReservoirLongsUnion rebuiltUnion = ReservoirLongsUnion.heapify(seg); - validateUnionEquality(rlu, rebuiltUnion); - } - - @Test - public void checkVersionConversionWithEmptyGadget() { - final int k = 32768; - final short encK = ReservoirSize.computeSize(k); - - final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k); - final byte[] unionBytesOrig = rlu.toByteArray(); - - // get a new byte[], manually revert to v1, then reconstruct - final byte[] unionBytes = rlu.toByteArray(); - final MemorySegment unionSeg = MemorySegment.ofArray(unionBytes); - - unionSeg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 1); - unionSeg.set(JAVA_INT_UNALIGNED, RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes - unionSeg.set(JAVA_SHORT_UNALIGNED, RESERVOIR_SIZE_SHORT, encK); - println(PreambleUtil.preambleToString(unionSeg)); - - final ReservoirLongsUnion rebuilt = ReservoirLongsUnion.heapify(unionSeg); - final byte[] rebuiltBytes = rebuilt.toByteArray(); - - assertEquals(unionBytesOrig.length, rebuiltBytes.length); - for (int i = 0; i < unionBytesOrig.length; ++i) { - assertEquals(unionBytesOrig[i], rebuiltBytes[i]); - } - } - - @Test - public void checkVersionConversionWithGadget() { - final long n = 32; - final int k = 256; - final short encK = ReservoirSize.computeSize(k); - - final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k); - for (long i = 0; i < n; ++i) { - rlu.update(i); - } - final byte[] unionBytesOrig = rlu.toByteArray(); - - // get a new byte[], manually revert to v1, then reconstruct - final byte[] unionBytes = rlu.toByteArray(); - final MemorySegment unionSeg = MemorySegment.ofArray(unionBytes); - - unionSeg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 1); - unionSeg.set(JAVA_INT_UNALIGNED, RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes - unionSeg.set(JAVA_SHORT_UNALIGNED, RESERVOIR_SIZE_SHORT, encK); - - // force gadget header to v1, too - final int offset = Family.RESERVOIR_UNION.getMaxPreLongs() << 3; - unionSeg.set(JAVA_BYTE, offset + SER_VER_BYTE, (byte) 1); - unionSeg.set(JAVA_INT_UNALIGNED, offset + RESERVOIR_SIZE_INT, 0); // zero out all 4 bytes - unionSeg.set(JAVA_SHORT_UNALIGNED, offset + RESERVOIR_SIZE_SHORT, encK); - - final ReservoirLongsUnion rebuilt = ReservoirLongsUnion.heapify(unionSeg); - final byte[] rebuiltBytes = rebuilt.toByteArray(); - - assertEquals(unionBytesOrig.length, rebuiltBytes.length); - for (int i = 0; i < unionBytesOrig.length; ++i) { - assertEquals(unionBytesOrig[i], rebuiltBytes[i]); - } - } - - //@SuppressWarnings("null") // this is the point of the test - @Test(expectedExceptions = java.lang.NullPointerException.class) - public void checkNullMemorySegmentInstantiation() { - ReservoirLongsUnion.heapify(null); - } - - @Test - public void checkDownsampledUpdate() { - final int bigK = 1024; - final int bigN = 131072; - final int smallK = 256; - final int smallN = 2048; - final ReservoirLongsSketch sketch1 = getBasicSketch(smallN, smallK); - final ReservoirLongsSketch sketch2 = getBasicSketch(bigN, bigK); - - final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(smallK); - assertEquals(rlu.getMaxK(), smallK); - - rlu.update(sketch1); - assertNotNull(rlu.getResult()); - assertEquals(rlu.getResult().getK(), smallK); - - rlu.update(sketch2); - assertEquals(rlu.getResult().getK(), smallK); - assertEquals(rlu.getResult().getNumSamples(), smallK); - } - - @Test - public void checkUnionResetWithInitialSmallK() { - final int maxK = 25; - final int sketchK = 10; - final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(maxK); - - ReservoirLongsSketch rls = getBasicSketch(2 * sketchK, sketchK); // in sampling mode - rlu.update(rls); - assertEquals(rlu.getMaxK(), maxK); - assertNotNull(rlu.getResult()); - assertEquals(rlu.getResult().getK(), sketchK); - - rlu.reset(); - assertNotNull(rlu.getResult()); - - // feed in sketch in sampling mode, with larger k than old gadget - rls = getBasicSketch(2 * maxK, maxK + 1); - rlu.update(rls); - assertEquals(rlu.getMaxK(), maxK); - assertNotNull(rlu.getResult()); - assertEquals(rlu.getResult().getK(), maxK); - } - - @Test - public void checkNewGadget() { - final int maxK = 1024; - final int bigK = 1536; - final int smallK = 128; - - // downsample input sketch, use as gadget (exact mode, but irrelevant here) - final ReservoirLongsSketch bigKSketch = getBasicSketch(maxK / 2, bigK); - final byte[] bigKBytes = bigKSketch.toByteArray(); - final MemorySegment bigKSeg = MemorySegment.ofArray(bigKBytes); - - ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(maxK); - rlu.update(bigKSeg); - assertNotNull(rlu.getResult()); - assertEquals(rlu.getResult().getK(), maxK); - assertEquals(rlu.getResult().getN(), maxK / 2); - - // sketch k < maxK but in sampling mode - final ReservoirLongsSketch smallKSketch = getBasicSketch(maxK, smallK); - final byte[] smallKBytes = smallKSketch.toByteArray(); - final MemorySegment smallKSeg = MemorySegment.ofArray(smallKBytes); - - rlu = ReservoirLongsUnion.newInstance(maxK); - rlu.update(smallKSeg); - assertNotNull(rlu.getResult()); - assertTrue(rlu.getResult().getK() < maxK); - assertEquals(rlu.getResult().getK(), smallK); - assertEquals(rlu.getResult().getN(), maxK); - - // sketch k < maxK and in exact mode - final ReservoirLongsSketch smallKExactSketch = getBasicSketch(smallK, smallK); - final byte[] smallKExactBytes = smallKExactSketch.toByteArray(); - final MemorySegment smallKExactSeg = MemorySegment.ofArray(smallKExactBytes); - - rlu = ReservoirLongsUnion.newInstance(maxK); - rlu.update(smallKExactSeg); - assertNotNull(rlu.getResult()); - assertEquals(rlu.getResult().getK(), maxK); - assertEquals(rlu.getResult().getN(), smallK); - } - - @Test - public void checkStandardMergeNoCopy() { - final int k = 1024; - final int n1 = 256; - final int n2 = 256; - final ReservoirLongsSketch sketch1 = getBasicSketch(n1, k); - final ReservoirLongsSketch sketch2 = getBasicSketch(n2, k); - - final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k); - rlu.update(sketch1); - rlu.update(sketch2); - - assertNotNull(rlu.getResult()); - assertEquals(rlu.getResult().getK(), k); - assertEquals(rlu.getResult().getN(), n1 + n2); - assertEquals(rlu.getResult().getNumSamples(), n1 + n2); - - // creating from MemorySegment should avoid a copy - final int n3 = 2048; - final ReservoirLongsSketch sketch3 = getBasicSketch(n3, k); - final byte[] sketch3Bytes = sketch3.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(sketch3Bytes); - rlu.update(seg); - - assertEquals(rlu.getResult().getK(), k); - assertEquals(rlu.getResult().getN(), n1 + n2 + n3); - assertEquals(rlu.getResult().getNumSamples(), k); - } - - @Test - public void checkStandardMergeWithCopy() { - // this will check the other code route to a standard merge, - // but will copy sketch2 to be non-destructive. - final int k = 1024; - final int n1 = 768; - final int n2 = 2048; - final ReservoirLongsSketch sketch1 = getBasicSketch(n1, k); - final ReservoirLongsSketch sketch2 = getBasicSketch(n2, k); - - final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k); - rlu.update(sketch1); - rlu.update(sketch2); - rlu.update(10); - - assertNotNull(rlu.getResult()); - assertEquals(rlu.getResult().getK(), k); - assertEquals(rlu.getResult().getN(), n1 + n2 + 1); - assertEquals(rlu.getResult().getNumSamples(), k); - } - - @Test - public void checkWeightedMerge() { - final int k = 1024; - final int n1 = 16384; - final int n2 = 2048; - final ReservoirLongsSketch sketch1 = getBasicSketch(n1, k); - final ReservoirLongsSketch sketch2 = getBasicSketch(n2, k); - - ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(k); - rlu.update(sketch1); - rlu.update(sketch2); - - assertNotNull(rlu.getResult()); - assertEquals(rlu.getResult().getK(), k); - assertEquals(rlu.getResult().getN(), n1 + n2); - assertEquals(rlu.getResult().getNumSamples(), k); - - // now merge into the sketch for updating -- results should match - rlu = ReservoirLongsUnion.newInstance(k); - rlu.update(sketch2); - rlu.update(sketch1); - - assertNotNull(rlu.getResult()); - assertEquals(rlu.getResult().getK(), k); - assertEquals(rlu.getResult().getN(), n1 + n2); - assertEquals(rlu.getResult().getNumSamples(), k); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadPreLongs() { - final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(1024); - final MemorySegment seg = MemorySegment.ofArray(rlu.toByteArray()); - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) 0); // corrupt the preLongs count - - ReservoirLongsUnion.heapify(seg); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadSerVer() { - final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(1024); - final MemorySegment seg = MemorySegment.ofArray(rlu.toByteArray()); - seg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 0); // corrupt the serialization version - - ReservoirLongsUnion.heapify(seg); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadFamily() { - final ReservoirLongsUnion rlu = ReservoirLongsUnion.newInstance(1024); - final MemorySegment seg = MemorySegment.ofArray(rlu.toByteArray()); - seg.set(JAVA_BYTE, FAMILY_BYTE, (byte) 0); // corrupt the family ID - - ReservoirLongsUnion.heapify(seg); - fail(); - } - - private static void validateUnionEquality(final ReservoirLongsUnion rlu1, - final ReservoirLongsUnion rlu2) { - assertEquals(rlu1.getMaxK(), rlu2.getMaxK()); - - ReservoirLongsSketchTest.validateReservoirEquality(rlu1.getResult(), rlu2.getResult()); - } - - private static ReservoirLongsSketch getBasicSketch(final int n, final int k) { - final ReservoirLongsSketch rls = ReservoirLongsSketch.newInstance(k); - - for (int i = 0; i < n; ++i) { - rls.update(i); - } - - return rls; - } - - /** - * Wrapper around System.out.println() allowing a simple way to disable logging in tests - * - * @param msg The message to print - */ - private static void println(final String msg) { - //System.out.println(msg); - } -} diff --git a/src/test/java/org/apache/datasketches/sampling/ReservoirSizeTest.java b/src/test/java/org/apache/datasketches/sampling/ReservoirSizeTest.java deleted file mode 100644 index db7648721..000000000 --- a/src/test/java/org/apache/datasketches/sampling/ReservoirSizeTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.sampling.ReservoirSize; -import org.apache.datasketches.sampling.SamplingUtil; -import org.testng.annotations.Test; - -public class ReservoirSizeTest { - - @Test - public void checkComputeSize() { - short enc; - enc = ReservoirSize.computeSize(1); - assertEquals(enc, (short) 0x0000); - - enc = ReservoirSize.computeSize(128); - assertEquals(enc, (short) 0x3800); - - enc = ReservoirSize.computeSize(200); - assertEquals(enc, (short) 0x3C80); - - enc = ReservoirSize.computeSize(4097); - assertEquals(enc, (short) 0x6001); - - // NOTE: 0x61C4 is exact but Java seems to have numerical precision issues - enc = ReservoirSize.computeSize(5000); - assertEquals(enc, (short) 0x61C5); - - enc = ReservoirSize.computeSize(25000); - assertEquals(enc, (short) 0x7436); - - // Encoding cannot represent 32767 with an exponent of 14, so need to go to the next power of 2 - enc = ReservoirSize.computeSize(32767); - assertEquals(enc, (short) 0x7800); - - enc = ReservoirSize.computeSize(95342); - assertEquals(enc, (short) 0x83A4); - - try { - ReservoirSize.computeSize(-1); - fail(); - } catch (final SketchesArgumentException e) { - assertTrue(e.getMessage().startsWith("Can only encode strictly positive sketch sizes less than")); - } - } - - @Test - public void checkDecodeValue() { - int dec; - - dec = ReservoirSize.decodeValue((short) 0x0000); - assertEquals(dec, 1); - - dec = ReservoirSize.decodeValue((short) 0x3800); - assertEquals(dec, 128); - - dec = ReservoirSize.decodeValue((short) 0x3C80); - assertEquals(dec, 200); - - dec = ReservoirSize.decodeValue((short) 0x6001); - assertEquals(dec, 4098); - - dec = ReservoirSize.decodeValue((short) 0x61C4); - assertEquals(dec, 5000); - - dec = ReservoirSize.decodeValue((short) 0x7435); - assertEquals(dec, 25000); - - dec = ReservoirSize.decodeValue((short) 0x83A4); - assertEquals(dec, 95360); - - try { - ReservoirSize.decodeValue((short) -1); - fail(); - } catch (final SketchesArgumentException e) { - assertTrue(e.getMessage().startsWith("Maximum valid encoded value is ")); - } - } - - @Test - public void checkRelativeError() { - // Generate some random values and ensure the relative error of the decoded result is - // within epsilon (eps) of the target. - // This condition should always hold regardless of the random seed used. - final double eps = 1.0 / ReservoirSize.BINS_PER_OCTAVE; - final int maxValue = 2146959359; // based on MAX_ABS_VALUE - final int numIters = 100; - - for (int i = 0; i < numIters; ++i) { - final int input = SamplingUtil.rand().nextInt(maxValue) + 1; - final int result = ReservoirSize.decodeValue(ReservoirSize.computeSize(input)); - - // result must be no smaller than input - assertTrue(result >= input, "encoded/decoded result < input: " + result + " vs " - + input + " (iter " + i + ")"); - - // cap on max error - final double relativeError = ((double) result - input) / input; - assertTrue(relativeError <= eps, "Error exceeds tolerance. Expected relative error <= " - + eps + "; " + "found " + relativeError); - } - } -} diff --git a/src/test/java/org/apache/datasketches/sampling/VarOptCrossLanguageTest.java b/src/test/java/org/apache/datasketches/sampling/VarOptCrossLanguageTest.java deleted file mode 100644 index c8db54da8..000000000 --- a/src/test/java/org/apache/datasketches/sampling/VarOptCrossLanguageTest.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES; -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.getFileBytes; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ArrayOfDoublesSerDe; -import org.apache.datasketches.common.ArrayOfLongsSerDe; -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.testng.annotations.Test; - -/** - * Serialize binary sketches to be tested by C++ code. - * Test deserialization of binary sketches serialized by C++ code. - */ -public class VarOptCrossLanguageTest { - static final double EPS = 1e-13; - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateSketchesLong() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (final int n: nArr) { - final VarOptItemsSketch sk = VarOptItemsSketch.newInstance(32); - for (int i = 1; i <= n; i++) { - sk.update(Long.valueOf(i), 1.0); - } - putBytesToJavaPath("varopt_sketch_long_n" + n + "_java.sk", sk.toByteArray(new ArrayOfLongsSerDe())); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateSketchStringExact() throws IOException { - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstance(1024); - for (int i = 1; i <= 200; ++i) { - sketch.update(Integer.toString(i), 1000.0 / i); - } - putBytesToJavaPath("varopt_sketch_string_exact_java.sk", sketch.toByteArray(new ArrayOfStringsSerDe())); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateSketchLongSampling() throws IOException { - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstance(1024); - for (long i = 0; i < 2000; ++i) { - sketch.update(i, 1.0); - } - // negative heavy items to allow a simple predicate to filter - sketch.update(-1L, 100000.0); - sketch.update(-2L, 110000.0); - sketch.update(-3L, 120000.0); - putBytesToJavaPath("varopt_sketch_long_sampling_java.sk", sketch.toByteArray(new ArrayOfLongsSerDe())); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateUnionDoubleSampling() throws IOException { - final int kSmall = 16; - final int n1 = 32; - final int n2 = 64; - final int kMax = 128; - - // small k sketch, but sampling - VarOptItemsSketch sketch = VarOptItemsSketch.newInstance(kSmall); - for (int i = 0; i < n1; ++i) { - sketch.update(1.0 * i, 1.0); - } - sketch.update(-1.0, n1 * n1); // negative heavy item to allow a simple predicate to filter - - - final VarOptItemsUnion union = VarOptItemsUnion.newInstance(kMax); - union.update(sketch); - - // another one, but different n to get a different per-item weight - sketch = VarOptItemsSketch.newInstance(kSmall); - for (int i = 0; i < n2; ++i) { - sketch.update(1.0 * i, 1.0); - } - union.update(sketch); - putBytesToJavaPath("varopt_union_double_sampling_java.sk", union.toByteArray(new ArrayOfDoublesSerDe())); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppSketchLongs() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "varopt_sketch_long_n" + n + "_cpp.sk"); - final VarOptItemsSketch sk = VarOptItemsSketch.heapify(MemorySegment.ofArray(bytes), new ArrayOfLongsSerDe()); - assertEquals(sk.getK(), 32); - assertEquals(sk.getN(), n); - assertEquals(sk.getNumSamples(), n > 10 ? 32 : n); - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppSketchStringsExact() throws IOException { - final byte[] bytes = getFileBytes(cppPath, "varopt_sketch_string_exact_cpp.sk"); - final VarOptItemsSketch sk = VarOptItemsSketch.heapify(MemorySegment.ofArray(bytes), new ArrayOfStringsSerDe()); - assertEquals(sk.getK(), 1024); - assertEquals(sk.getN(), 200); - assertEquals(sk.getNumSamples(), 200); - final SampleSubsetSummary ss = sk.estimateSubsetSum(item -> true); - double weight = 0; - for (int i = 1; i <= 200; ++i) { - weight += 1000.0 / i; - } - assertEquals(ss.getTotalSketchWeight(), weight, EPS); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppSketchLongsSampling() throws IOException { - final byte[] bytes = getFileBytes(cppPath, "varopt_sketch_long_sampling_cpp.sk"); - final VarOptItemsSketch sk = VarOptItemsSketch.heapify(MemorySegment.ofArray(bytes), new ArrayOfLongsSerDe()); - assertEquals(sk.getK(), 1024); - assertEquals(sk.getN(), 2003); - assertEquals(sk.getNumSamples(), 1024); - SampleSubsetSummary ss = sk.estimateSubsetSum(item -> true); - assertEquals(ss.getTotalSketchWeight(), 332000.0, EPS); - - ss = sk.estimateSubsetSum(item -> item < 0); - assertEquals(ss.getEstimate(), 330000.0); // heavy item, weight is exact - - ss = sk.estimateSubsetSum(item -> item >= 0); - assertEquals(ss.getEstimate(), 2000.0, EPS); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppUnionDoubleSampling() throws IOException { - final byte[] bytes = getFileBytes(cppPath, "varopt_union_double_sampling_cpp.sk"); - final VarOptItemsUnion u = VarOptItemsUnion.heapify(MemorySegment.ofArray(bytes), new ArrayOfDoublesSerDe()); - - // must reduce k in the process - final VarOptItemsSketch sk = u.getResult(); - assertTrue(sk.getK() < 128); - assertEquals(sk.getN(), 97); - - // light items, ignoring the heavy one - final SampleSubsetSummary ss = sk.estimateSubsetSum(item -> item >= 0); - assertEquals(ss.getEstimate(), 96.0, EPS); - assertEquals(ss.getTotalSketchWeight(), 96.0 + 1024.0, EPS); - } - -} diff --git a/src/test/java/org/apache/datasketches/sampling/VarOptItemsSamplesTest.java b/src/test/java/org/apache/datasketches/sampling/VarOptItemsSamplesTest.java deleted file mode 100644 index fcdd71ce8..000000000 --- a/src/test/java/org/apache/datasketches/sampling/VarOptItemsSamplesTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import org.apache.datasketches.sampling.VarOptItemsSamples; -import org.apache.datasketches.sampling.VarOptItemsSketch; -import org.testng.annotations.Test; - -/** - * @author Jon Malkin - */ -public class VarOptItemsSamplesTest { - @Test - public void compareIteratorToArrays() { - final int k = 64; - final int n = 1024; - final VarOptItemsSketch sketch = VarOptItemsSketchTest.getUnweightedLongsVIS(k, n); - // and a few heavy items - sketch.update(n * 10L, n * 10.0); - sketch.update(n * 11L, n * 11.0); - sketch.update(n * 12L, n * 12.0); - - final VarOptItemsSamples samples = sketch.getSketchSamples(); - final Long[] items = samples.items(); - final double[] weights = samples.weights(); - int i = 0; - for (VarOptItemsSamples.WeightedSample ws : samples) { - assertEquals(ws.getWeight(), weights[i]); - assertEquals(ws.getItem(), items[i]); - ++i; - } - } - - @Test(expectedExceptions = ConcurrentModificationException.class) - public void checkConcurrentModification() { - final int k = 128; - final VarOptItemsSketch sketch = VarOptItemsSketchTest.getUnweightedLongsVIS(k, k); - - final VarOptItemsSamples samples = sketch.getSketchSamples(); - - for (VarOptItemsSamples.WeightedSample ws : samples) { - if (ws.getItem() > (k / 2)) { // guaranteed to exist somewhere in the sketch - sketch.update(-1L, 1.0); - } - } - fail(); - } - - @Test(expectedExceptions = ConcurrentModificationException.class) - public void checkWeightCorrectingConcurrentModification() { - final int k = 128; - // sketch needs to be in sampling mode - final VarOptItemsSketch sketch = VarOptItemsSketchTest.getUnweightedLongsVIS(k, 2 * k); - - final Iterator.WeightedSample> iter; - iter = sketch.getSketchSamples().getWeightCorrRIter(); - - int i = 0; - while (iter.hasNext()) { - iter.next(); - if (++i > (k / 2)) { - sketch.update(-1L, 1.0); - } - } - fail(); - } - - @Test(expectedExceptions = NoSuchElementException.class) - public void checkReadingPastEndOfIterator() { - final int k = 128; - final VarOptItemsSketch sketch = VarOptItemsSketchTest.getUnweightedLongsVIS(k, k); - - final Iterator.WeightedSample> iter; - iter = sketch.getSketchSamples().iterator(); - - while (iter.hasNext()) { - iter.next(); - } - iter.next(); // no more elements - fail(); - } - - @Test(expectedExceptions = NoSuchElementException.class) - public void checkWeightCorrectionReadingPastEndOfIterator() { - final int k = 128; - final VarOptItemsSketch sketch = VarOptItemsSketchTest.getUnweightedLongsVIS(k, k); - - final Iterator.WeightedSample> iter; - iter = sketch.getSketchSamples().getWeightCorrRIter(); - - while (iter.hasNext()) { - iter.next(); - } - iter.next(); // no more elements - fail(); - } - - @Test - public void checkPolymorphicBaseClass() { - // use setClass() - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstance(12); - sketch.update(1, 0.5); - sketch.update(2L, 1.7); - sketch.update(3.0f, 2.0); - sketch.update(4.0, 3.1); - - try { - final VarOptItemsSamples samples = sketch.getSketchSamples(); - // will try to create array based on type of first item in the array and fail - samples.items(); - fail(); - } catch (final ArrayStoreException e) { - // expected - } - - final VarOptItemsSamples samples = sketch.getSketchSamples(); - samples.setClass(Number.class); - assertEquals(samples.items(0), 1); - assertEquals(samples.items(1), 2L); - assertEquals(samples.items(2), 3.0f); - assertEquals(samples.items(3), 4.0); - } - - @Test - public void checkEmptySketch() { - // verify what happens when n_ == 0 - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstance(32); - assertEquals(sketch.getNumSamples(), 0); - - final VarOptItemsSamples samples = sketch.getSketchSamples(); - assertEquals(samples.getNumSamples(), 0); - assertNull(samples.items()); - assertNull(samples.items(0)); - assertNull(samples.weights()); - assertTrue(Double.isNaN(samples.weights(0))); - } - - @Test - public void checkUnderFullSketchIterator() { - // needed to fully cover iterator's next() and hasNext() conditions - final int k = 128; - final VarOptItemsSketch sketch = VarOptItemsSketchTest.getUnweightedLongsVIS(k, k / 2); - - final VarOptItemsSamples samples = sketch.getSketchSamples(); - - for (VarOptItemsSamples.WeightedSample ws : samples) { - assertTrue((ws.getItem() >= 0) && (ws.getItem() < (k / 2))); - } - } -} diff --git a/src/test/java/org/apache/datasketches/sampling/VarOptItemsSketchTest.java b/src/test/java/org/apache/datasketches/sampling/VarOptItemsSketchTest.java deleted file mode 100644 index 4a9fa3a63..000000000 --- a/src/test/java/org/apache/datasketches/sampling/VarOptItemsSketchTest.java +++ /dev/null @@ -1,694 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED; -import static org.apache.datasketches.sampling.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.SER_VER_BYTE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ArrayOfLongsSerDe; -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.sampling.PreambleUtil; -import org.apache.datasketches.sampling.SampleSubsetSummary; -import org.apache.datasketches.sampling.SamplingUtil; -import org.apache.datasketches.sampling.VarOptItemsSamples; -import org.apache.datasketches.sampling.VarOptItemsSketch; -import org.testng.annotations.Test; - -public class VarOptItemsSketchTest { - static final double EPS = 1e-10; - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidK() { - VarOptItemsSketch.newInstance(0); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadSerVer() { - final VarOptItemsSketch sketch = getUnweightedLongsVIS(16, 16); - final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - - seg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 0); // corrupt the serialization version - - VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadFamily() { - final VarOptItemsSketch sketch = getUnweightedLongsVIS(32, 16); - final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - - seg.set(JAVA_BYTE, FAMILY_BYTE, (byte) 0); // corrupt the family ID - - VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } - - @Test - public void checkBadPreLongs() { - final VarOptItemsSketch sketch = getUnweightedLongsVIS(32, 33); - final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - - // corrupt the preLongs count to 0 - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) (Family.VAROPT.getMinPreLongs() - 1)); - try { - VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) 2); // corrupt the preLongs count to 2 - try { - VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - // corrupt the preLongs count to be too large - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) (Family.VAROPT.getMaxPreLongs() + 1)); - try { - VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadMemorySegment() { - byte[] bytes = new byte[4]; - MemorySegment seg = MemorySegment.ofArray(bytes); - - try { - PreambleUtil.getAndCheckPreLongs(seg); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - bytes = new byte[8]; - bytes[0] = 2; // only 1 preLong worth of items in bytearray - seg = MemorySegment.ofArray(bytes); - PreambleUtil.getAndCheckPreLongs(seg); - } - - @Test - public void checkMalformedPreamble() { - final int k = 50; - final VarOptItemsSketch sketch = getUnweightedLongsVIS(k, k); - - final byte[] sketchBytes = sketch.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment srcSeg = MemorySegment.ofArray(sketchBytes); - - // we'll use the same initial sketch a few times, so grab a copy of it - final byte[] copyBytes = new byte[sketchBytes.length]; - final MemorySegment seg = MemorySegment.ofArray(copyBytes); - - // copy the bytes - MemorySegment.copy(srcSeg, 0, seg, 0, sketchBytes.length); - assertEquals(PreambleUtil.extractPreLongs(seg), PreambleUtil.VO_PRELONGS_WARMUP); - - // no items in R but max preLongs - try { - PreambleUtil.insertPreLongs(seg, Family.VAROPT.getMaxPreLongs()); - VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } catch (final SketchesArgumentException e) { - assertTrue(e.getMessage().startsWith("Possible Corruption: " - + Family.VAROPT.getMaxPreLongs() + " preLongs but")); - } - - // refresh the copy - MemorySegment.copy(srcSeg, 0, seg, 0, sketchBytes.length); - assertEquals(PreambleUtil.extractPreLongs(seg), PreambleUtil.VO_PRELONGS_WARMUP); - - // negative H region count - try { - PreambleUtil.insertHRegionItemCount(seg, -1); - VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } catch (final SketchesArgumentException e) { - assertTrue(e.getMessage().equals("Possible Corruption: H region count cannot be negative: -1")); - } - - // refresh the copy - MemorySegment.copy(srcSeg, 0, seg, 0, sketchBytes.length); - assertEquals(PreambleUtil.extractHRegionItemCount(seg), k); - - // negative R region count - try { - PreambleUtil.insertRRegionItemCount(seg, -128); - VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } catch (final SketchesArgumentException e) { - assertTrue(e.getMessage().equals("Possible Corruption: R region count cannot be negative: -128")); - } - - // refresh the copy - MemorySegment.copy(srcSeg, 0, seg, 0, sketchBytes.length); - assertEquals(PreambleUtil.extractRRegionItemCount(seg), 0); - - // invalid k < 1 - try { - PreambleUtil.insertK(seg, 0); - VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } catch (final SketchesArgumentException e) { - assertTrue(e.getMessage().equals("Possible Corruption: k must be at least 1: 0")); - } - - // refresh the copy - MemorySegment.copy(srcSeg, 0, seg, 0, sketchBytes.length); - assertEquals(PreambleUtil.extractK(seg), k); - - // invalid n < 0 - try { - PreambleUtil.insertN(seg, -1024); - VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } catch (final SketchesArgumentException e) { - assertTrue(e.getMessage().equals("Possible Corruption: n cannot be negative: -1024")); - } - } - - @Test - public void checkEmptySketch() { - final VarOptItemsSketch vis = VarOptItemsSketch.newInstance(5); - assertEquals(vis.getN(), 0); - assertEquals(vis.getNumSamples(), 0); - assertNull(vis.getSamplesAsArrays()); - assertNull(vis.getSamplesAsArrays(Long.class)); - - final byte[] sketchBytes = vis.toByteArray(new ArrayOfStringsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - - // only minPreLongs bytes and should deserialize to empty - assertEquals(sketchBytes.length, Family.VAROPT.getMinPreLongs() << 3); - final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - final VarOptItemsSketch loadedVis = VarOptItemsSketch.heapify(seg, serDe); - assertEquals(loadedVis.getNumSamples(), 0); - - println("Empty sketch:"); - println(" Preamble:"); - VarOptItemsSketch.toString(sketchBytes); - println(VarOptItemsSketch.toString(seg)); - println(" Sketch:"); - println(vis.toString()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkNonEmptyDegenerateSketch() { - // make an empty serialized sketch, then copy the items into a - // PreambleUtil.VO_WARMUP_PRELONGS-sized byte array - // so there'll be no items, then clear the empty flag so it will try to load - // the rest. - final VarOptItemsSketch vis = VarOptItemsSketch.newInstance(12, ResizeFactor.X2); - final byte[] sketchBytes = vis.toByteArray(new ArrayOfStringsSerDe()); - final byte[] dstByteArr = new byte[PreambleUtil.VO_PRELONGS_WARMUP << 3]; - final MemorySegment seg = MemorySegment.ofArray(dstByteArr); - MemorySegment.copy(sketchBytes, 0, seg, JAVA_BYTE, 0, sketchBytes.length); - - // ensure non-empty but with H and R region sizes set to 0 - PreambleUtil.insertFlags(seg, 0); // set not-empty - PreambleUtil.insertHRegionItemCount(seg, 0); - PreambleUtil.insertRRegionItemCount(seg, 0); - - VarOptItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInvalidWeight() { - final VarOptItemsSketch vis = VarOptItemsSketch.newInstance(5); - try { - vis.update(null, 1.0); // should work fine - } catch (final SketchesArgumentException e) { - fail(); - } - - vis.update("invalidWeight", -1.0); // should fail - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkNaNWeight() { - final VarOptItemsSketch vis = VarOptItemsSketch.newInstance(5); - vis.update("invalidWeight", Double.NaN); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInfiniteWeight() { - final VarOptItemsSketch vis = VarOptItemsSketch.newInstance(5); - vis.update("invalidWeight", Double.POSITIVE_INFINITY); - } - - @Test - public void checkCorruptSerializedWeight() { - final VarOptItemsSketch vis = VarOptItemsSketch.newInstance(24); - for (int i = 1; i < 10; ++i) { - vis.update(Integer.toString(i), i); - } - - final byte[] sketchBytes = vis.toByteArray(new ArrayOfStringsSerDe(), String.class); - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - - // weights will be stored in the first double after the preamble - final int numPreLongs = PreambleUtil.extractPreLongs(seg); - final int weightOffset = numPreLongs << 3; - seg.set(JAVA_DOUBLE_UNALIGNED, weightOffset, -1.25); // inject a negative weight - - try { - VarOptItemsSketch.heapify(seg, new ArrayOfStringsSerDe()); - fail(); - } catch (final SketchesArgumentException e) { - assertTrue(e.getMessage().equals("Possible Corruption: Non-positive weight in " - + "heapify(): -1.25")); - } - } - - @Test - public void checkCorruptSerializedRWeightNaN() { - final int k = 32; - final VarOptItemsSketch sketch = getUnweightedLongsVIS(k, k + 1); - final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - assertEquals(PreambleUtil.extractPreLongs(seg), Family.VAROPT.getMaxPreLongs()); - - PreambleUtil.insertTotalRWeight(seg, Double.NaN); - - try { - VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } catch (final SketchesArgumentException e) { - assertTrue(e.getMessage().contains("invalid R region weight")); - } - } - - @Test - public void checkCorruptSerializedRWeightZero() { - final int k = 32; - final VarOptItemsSketch sketch = getUnweightedLongsVIS(k, k + 1); - final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - assertEquals(PreambleUtil.extractPreLongs(seg), Family.VAROPT.getMaxPreLongs()); - - PreambleUtil.insertTotalRWeight(seg, 0.0); - - try { - VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } catch (final SketchesArgumentException e) { - assertTrue(e.getMessage().contains("invalid R region weight")); - } - } - - @Test - public void checkCumulativeWeight() { - final int k = 256; - final int n = 10 * k; - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstance(k); - - double inputSum = 0.0; - for (long i = 0; i < n; ++i) { - // generate weights above and below 1.0 using w ~ exp(5*N(0,1)) which covers about - // 10 orders of magnitude - final double w = Math.exp(5 * SamplingUtil.rand().nextGaussian()); - inputSum += w; - sketch.update(i, w); - } - - final VarOptItemsSamples samples = sketch.getSketchSamples(); - double outputSum = 0; - for (final VarOptItemsSamples.WeightedSample ws : samples) { - outputSum += ws.getWeight(); - } - - final double wtRatio = outputSum / inputSum; - assertTrue(Math.abs(wtRatio - 1.0) < EPS); - } - - @Test - public void checkUnderFullSketchSerialization() { - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstance(2048); - for (long i = 0; i < 10; ++i) { - sketch.update(i, 1.0); - } - assertEquals(sketch.getNumSamples(), 10); - - final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - - // ensure correct number of preLongs - assertEquals(PreambleUtil.extractPreLongs(seg), PreambleUtil.VO_PRELONGS_WARMUP); - - final VarOptItemsSketch rebuilt - = VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - checkIfEqual(rebuilt, sketch); - } - - @Test - public void checkEndOfWarmupSketchSerialization() { - final int k = 2048; - final VarOptItemsSketch sketch = getUnweightedLongsVIS(k, k); - - final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - - // ensure still only 2 preLongs - assertEquals(PreambleUtil.extractPreLongs(seg), PreambleUtil.VO_PRELONGS_WARMUP); - - final VarOptItemsSketch rebuilt - = VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - checkIfEqual(rebuilt, sketch); - } - - @Test - public void checkFullSketchSerialization() { - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstance(32); - for (long i = 0; i < 32; ++i) { - sketch.update(i, 1.0); - } - sketch.update(100L, 100.0); - sketch.update(101L, 101.0); - assertEquals(sketch.getNumSamples(), 32); - - // first 2 entries should be heavy and in heap order (smallest at root) - final VarOptItemsSamples samples = sketch.getSketchSamples(); - final Long[] data = samples.items(); - final double[] weights = samples.weights(); - assertEquals(weights[0], 100.0); - assertEquals(weights[1], 101.0); - assertEquals((long) data[0], 100L); - assertEquals((long) data[1], 101L); - - final byte[] bytes = sketch.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - - // ensure 3 preLongs - assertEquals(PreambleUtil.extractPreLongs(seg), Family.VAROPT.getMaxPreLongs()); - - final VarOptItemsSketch rebuilt - = VarOptItemsSketch.heapify(seg, new ArrayOfLongsSerDe()); - checkIfEqual(rebuilt, sketch); - } - - @Test - public void checkPseudoLightUpdate() { - final int k = 1024; - final VarOptItemsSketch sketch = getUnweightedLongsVIS(k, k + 1); - sketch.update(0L, 1.0); // k+2-nd update - - // checking weights(0), assuming all k items are unweighted (and consequently in R) - // Expected: (k + 2) / |R| = (k+2) / k - final VarOptItemsSamples samples = sketch.getSketchSamples(); - final double wtDiff = samples.weights(0) - ((1.0 * (k + 2)) / k); - assertTrue(Math.abs(wtDiff) < EPS); - } - - @Test - public void checkPseudoHeavyUpdates() { - final int k = 1024; - final double wtScale = 10.0 * k; - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstance(k); - for (long i = 0; i <= k; ++i) { - sketch.update(i, 1.0); - } - - // Next k-1 updates should be updatePseudoHeavyGeneral() - // Last one should call updatePseudoHeavyREq1(), since we'll have added k-1 heavy - // items, leaving only 1 item left in R - for (long i = 1; i <= k; ++i) { - sketch.update(-i, k + (i * wtScale)); - } - - final VarOptItemsSamples samples = sketch.getSketchSamples(); - final double[] weights = samples.weights(); - - // Don't know which R item is left, but should be only one at the end of the array - // Expected: k+1 + (min "heavy" item) / |R| = ((k+1) + (k+wtScale)) / 1 = wtScale + 2k + 1 - double wtDiff = weights[k - 1] - (1.0 * (wtScale + (2 * k) + 1)); - assertTrue(Math.abs(wtDiff) < EPS); - - // Expected: 2nd lightest "heavy" item: k + 2*wtScale - wtDiff = weights[0] - (1.0 * (k + (2 * wtScale))); - assertTrue(Math.abs(wtDiff) < EPS); - } - - @Test(expectedExceptions = SketchesStateException.class) - public void checkDecreaseKWithUnderfullSketch() { - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstanceAsGadget(5); - assertEquals(sketch.getK(), 5); - - // shrink empty sketch - sketch.decreaseKBy1(); - assertEquals(sketch.getK(), 4); - - // insert 3 values - sketch.update(1, 1.0); - sketch.update(2, 2.0); - sketch.update(3, 3.0); - - // shrink to k=3, should do nothing - assertEquals(sketch.getTotalWtR(), 0.0); - sketch.decreaseKBy1(); - assertEquals(sketch.getTotalWtR(), 0.0); - - // one more time, to k=2, which exist warmup phase - sketch.decreaseKBy1(); - assertEquals(sketch.getHRegionCount(), 1); - assertEquals(sketch.getRRegionCount(), 1); - assertEquals(sketch.getTotalWtR(), 3.0); - - // decrease twice more to trigger an exception - sketch.decreaseKBy1(); - sketch.decreaseKBy1(); - } - - @Test - public void checkDecreaseKWithFullSketch() { - final int[] itemList = {10, 1, 9, 2, 8, 3, 7, 4, 6, 5}; - - final int startK = 7; - final int tgtK = 5; - - // Create sketch with k = startK and another with k = tgtK. We'll then decrease k until - // they're equal and ensure the results "match" - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstanceAsGadget(startK); - final VarOptItemsSketch tgtSketch = VarOptItemsSketch.newInstanceAsGadget(tgtK); - - double totalWeight = 0.0; - for (final int val : itemList) { - sketch.update(val, val); - tgtSketch.update(val, val); - totalWeight += val; - } - - // larger sketch has heavy items, smaller does not - assertEquals(sketch.getHRegionCount(), 4); - assertEquals(sketch.getRRegionCount(), 3); - assertEquals(tgtSketch.getHRegionCount(), 0); - assertEquals(tgtSketch.getRRegionCount(), 5); - - while (sketch.getK() > tgtK) { - sketch.decreaseKBy1(); - } - - assertEquals(sketch.getK(), tgtSketch.getK()); - assertEquals(sketch.getHRegionCount(), 0); - assertTrue(Math.abs(sketch.getTau() - tgtSketch.getTau()) < EPS); - - // decrease again from reservoir-only mode - sketch.decreaseKBy1(); - - assertEquals(sketch.getK(), tgtK - 1); - assertEquals(sketch.getK(), sketch.getRRegionCount()); - assertEquals(sketch.getTotalWtR(), totalWeight); - } - - @Test - public void checkReset() { - final int k = 25; - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstanceAsGadget(k); - sketch.update("a", 1.0); - sketch.update("b", 2.0); - sketch.update("c", 3.0); - sketch.update("d", 4.0); - - assertEquals(sketch.getN(), 4); - assertEquals(sketch.getHRegionCount(), 4); - assertEquals(sketch.getRRegionCount(), 0); - assertEquals(sketch.getMark(0), false); - - sketch.reset(); - assertEquals(sketch.getN(), 0); - assertEquals(sketch.getHRegionCount(), 0); - assertEquals(sketch.getRRegionCount(), 0); - try { - sketch.getMark(0); - fail(); - } catch (final IndexOutOfBoundsException e) { - // expected - } - - // strip marks and try again - sketch.stripMarks(); - for (int i = 0; i < (2 * k); ++i) { - sketch.update("a", 100.0 + i); - } - assertEquals(sketch.getN(), 2 * k); - assertEquals(sketch.getHRegionCount(), 0); - assertEquals(sketch.getRRegionCount(), k); - sketch.reset(); - assertEquals(sketch.getN(), 0); - assertEquals(sketch.getHRegionCount(), 0); - assertEquals(sketch.getRRegionCount(), 0); - } - - @Test - public void checkEstimateSubsetSum() { - final int k = 10; - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstance(k); - - // empty sketch -- all zeros - SampleSubsetSummary ss = sketch.estimateSubsetSum(item -> true); - assertEquals(ss.getEstimate(), 0.0); - assertEquals(ss.getTotalSketchWeight(), 0.0); - - // add items, keeping in exact mode - double totalWeight = 0.0; - for (long i = 1; i <= (k - 1); ++i) { - sketch.update(i, 1.0 * i); - totalWeight += 1.0 * i; - } - - ss = sketch.estimateSubsetSum(item -> true); - assertEquals(ss.getEstimate(), totalWeight); - assertEquals(ss.getLowerBound(), totalWeight); - assertEquals(ss.getUpperBound(), totalWeight); - assertEquals(ss.getTotalSketchWeight(), totalWeight); - - // add a few more items, pushing to sampling mode - for (long i = k; i <= (k + 1); ++i) { - sketch.update(i, 1.0 * i); - totalWeight += 1.0 * i; - } - - // predicate always true so estimate == upper bound - ss = sketch.estimateSubsetSum(item -> true); - assertEquals(ss.getEstimate(), totalWeight); - assertEquals(ss.getUpperBound(), totalWeight); - assertTrue(ss.getLowerBound() < totalWeight); - assertEquals(ss.getTotalSketchWeight(), totalWeight); - - // predicate always false so estimate == lower bound == 0.0 - ss = sketch.estimateSubsetSum(item -> false); - assertEquals(ss.getEstimate(), 0.0); - assertEquals(ss.getLowerBound(), 0.0); - assertTrue(ss.getUpperBound() > 0.0); - assertEquals(ss.getTotalSketchWeight(), totalWeight); - - // finally, a non-degenerate predicate - // insert negative items with identical weights, filter for negative weights only - for (long i = 1; i <= (k + 1); ++i) { - sketch.update(-i, 1.0 * i); - totalWeight += 1.0 * i; - } - - ss = sketch.estimateSubsetSum(item -> item < 0); - assertTrue(ss.getEstimate() >= ss.getLowerBound()); - assertTrue(ss.getEstimate() <= ss.getUpperBound()); - - // allow pretty generous bounds when testing - assertTrue(ss.getLowerBound() < (totalWeight / 1.4)); - assertTrue(ss.getUpperBound() > (totalWeight / 2.6)); - assertEquals(ss.getTotalSketchWeight(), totalWeight); - - // for good measure, test a different type - final VarOptItemsSketch boolSketch = VarOptItemsSketch.newInstance(k); - totalWeight = 0.0; - for (int i = 1; i <= (k - 1); ++i) { - boolSketch.update((i % 2) == 0, 1.0 * i); - totalWeight += i; - } - - ss = boolSketch.estimateSubsetSum(item -> !item); - assertTrue(ss.getEstimate() == ss.getLowerBound()); - assertTrue(ss.getEstimate() == ss.getUpperBound()); - assertTrue(ss.getEstimate() < totalWeight); // exact mode, so know it must be strictly less - } - - - /* Returns a sketch of size k that has been presented with n items. Use n = k+1 to obtain a - sketch that has just reached the sampling phase, so that the next update() is handled by - one of the non-warmup routes. - */ - static VarOptItemsSketch getUnweightedLongsVIS(final int k, final int n) { - final VarOptItemsSketch sketch = VarOptItemsSketch.newInstance(k); - for (long i = 0; i < n; ++i) { - sketch.update(i, 1.0); - } - - return sketch; - } - - private static void checkIfEqual(final VarOptItemsSketch s1, - final VarOptItemsSketch s2) { - assertEquals(s1.getK(), s2.getK(), "Sketches have different values of k"); - assertEquals(s1.getNumSamples(), s2.getNumSamples(), "Sketches have different sample counts"); - - final int len = s1.getNumSamples(); - final VarOptItemsSamples r1 = s1.getSketchSamples(); - final VarOptItemsSamples r2 = s2.getSketchSamples(); - - // next 2 lines also trigger copying results - assertEquals(len, r1.getNumSamples()); - assertEquals(r1.getNumSamples(), r2.getNumSamples()); - - for (int i = 0; i < len; ++i) { - assertEquals(r1.items(i), r2.items(i), "Data values differ at sample " + i); - assertEquals(r1.weights(i), r2.weights(i), "Weights differ at sample " + i); - } - } - - /** - * Wrapper around System.out.println() allowing a simple way to disable logging in tests - * @param msg The message to print - */ - private static void println(final String msg) { - //System.out.println(msg); - } -} diff --git a/src/test/java/org/apache/datasketches/sampling/VarOptItemsUnionTest.java b/src/test/java/org/apache/datasketches/sampling/VarOptItemsUnionTest.java deleted file mode 100644 index 03a0c866b..000000000 --- a/src/test/java/org/apache/datasketches/sampling/VarOptItemsUnionTest.java +++ /dev/null @@ -1,457 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.sampling; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.sampling.PreambleUtil.SER_VER_BYTE; -import static org.apache.datasketches.sampling.VarOptItemsSketchTest.EPS; -import static org.apache.datasketches.sampling.VarOptItemsSketchTest.getUnweightedLongsVIS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ArrayOfLongsSerDe; -import org.apache.datasketches.common.ArrayOfStringsSerDe; -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.sampling.ReservoirItemsSketch; -import org.apache.datasketches.sampling.VarOptItemsSamples; -import org.apache.datasketches.sampling.VarOptItemsSketch; -import org.apache.datasketches.sampling.VarOptItemsUnion; -import org.testng.annotations.Test; - -/** - * @author Jon Malkin - */ -public class VarOptItemsUnionTest { - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadSerVer() { - final int k = 25; - final int n = 30; - final VarOptItemsUnion union = VarOptItemsUnion.newInstance(k); - union.update(getUnweightedLongsVIS(k, n)); - final byte[] bytes = union.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - - seg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 0); // corrupt the serialization version - - VarOptItemsUnion.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadPreLongs() { - final int k = 25; - final int n = 30; - final VarOptItemsUnion union = VarOptItemsUnion.newInstance(k); - union.update(getUnweightedLongsVIS(k, n)); - final byte[] bytes = union.toByteArray(new ArrayOfLongsSerDe()); - final MemorySegment seg = MemorySegment.ofArray(bytes); - - // corrupt the preLongs count to 0 - seg.set(JAVA_BYTE, PREAMBLE_LONGS_BYTE, (byte) (Family.VAROPT.getMinPreLongs() - 1)); - VarOptItemsUnion.heapify(seg, new ArrayOfLongsSerDe()); - fail(); - } - - @Test - public void unionEmptySketch() { - final int k = 2048; - final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - - // we'll union from MemorySegment for good measure - final byte[] sketchBytes = VarOptItemsSketch.newInstance(k).toByteArray(serDe); - final MemorySegment seg = MemorySegment.ofArray(sketchBytes); - - final VarOptItemsUnion union = VarOptItemsUnion.newInstance(k); - union.update(seg, serDe); - - final VarOptItemsSketch result = union.getResult(); - assertEquals(result.getN(), 0); - assertEquals(result.getHRegionCount(), 0); - assertEquals(result.getRRegionCount(), 0); - assertTrue(Double.isNaN(result.getTau())); - } - - @Test - public void unionTwoExactSketches() { - final int n = 4; // 2n < k - final int k = 10; - final VarOptItemsSketch sk1 = VarOptItemsSketch.newInstance(k); - final VarOptItemsSketch sk2 = VarOptItemsSketch.newInstance(k); - - for (int i = 1; i <= n; ++i) { - sk1.update(i, i); - sk2.update(-i, i); - } - - final VarOptItemsUnion union = VarOptItemsUnion.newInstance(k); - union.update(sk1); - union.update(sk2); - - final VarOptItemsSketch result = union.getResult(); - assertEquals(result.getN(), 2 * n); - assertEquals(result.getHRegionCount(), 2 * n); - assertEquals(result.getRRegionCount(), 0); - } - - @Test - public void unionHeavySamplingSketch() { - final int n1 = 20; - final int k1 = 10; - final int n2 = 6; - final int k2 = 5; - final VarOptItemsSketch sk1 = VarOptItemsSketch.newInstance(k1); - final VarOptItemsSketch sk2 = VarOptItemsSketch.newInstance(k2); - - for (int i = 1; i <= n1; ++i) { - sk1.update(i, i); - } - - for (int i = 1; i < n2; ++i) { // we'll add a very heavy one later - sk2.update(-i, i + 1000.0); - } - sk2.update(-n2, 1000000.0); - - final VarOptItemsUnion union = VarOptItemsUnion.newInstance(k1); - union.update(sk1); - union.update(sk2); - - VarOptItemsSketch result = union.getResult(); - assertEquals(result.getN(), n1 + n2); - assertEquals(result.getK(), k2); // heavy enough it'll pull back to k2 - assertEquals(result.getHRegionCount(), 1); - assertEquals(result.getRRegionCount(), k2 - 1); - - union.reset(); - assertEquals(union.getOuterTau(), 0.0); - result = union.getResult(); - assertEquals(result.getK(), k1); - assertEquals(result.getN(), 0); - } - - @Test - public void unionIdenticalSamplingSketches() { - final int k = 20; - final int n = 50; - VarOptItemsSketch sketch = getUnweightedLongsVIS(k, n); - - final VarOptItemsUnion union = VarOptItemsUnion.newInstance(k); - union.update(sketch); - union.update(sketch); - - VarOptItemsSketch result = union.getResult(); - double expectedWeight = 2.0 * n; // unweighted, aka uniform weight of 1.0 - assertEquals(result.getN(), 2 * n); - assertEquals(result.getTotalWtR(), expectedWeight); - - // add another sketch, such that sketchTau < outerTau - sketch = getUnweightedLongsVIS(k, k + 1); // tau = (k + 1) / k - union.update(sketch); - result = union.getResult(); - expectedWeight = (2.0 * n) + k + 1; - assertEquals(result.getN(), (2 * n) + k + 1); - assertEquals(result.getTotalWtR(), expectedWeight, EPS); - - union.reset(); - assertEquals(union.getOuterTau(), 0.0); - result = union.getResult(); - assertEquals(result.getK(), k); - assertEquals(result.getN(), 0); - } - - @Test - public void unionSmallSamplingSketch() { - final int kSmall = 16; - final int n1 = 32; - final int n2 = 64; - final int kMax = 128; - - // small k sketch, but sampling - VarOptItemsSketch sketch = getUnweightedLongsVIS(kSmall, n1); - sketch.update(-1L, n1 ^ 2); // add a heavy item - - final VarOptItemsUnion union = VarOptItemsUnion.newInstance(kMax); - union.update(sketch); - - // another one, but different n to get a different per-item weight - sketch = getUnweightedLongsVIS(kSmall, n2); - union.update(sketch); - - // should trigger migrateMarkedItemsByDecreasingK() - final VarOptItemsSketch result = union.getResult(); - assertEquals(result.getN(), n1 + n2 + 1); - assertEquals(result.getTotalWtR(), 96.0, EPS); // n1+n2 light items, ignore the heavy one - } - - @Test - public void unionExactReservoirSketch() { - // build a varopt union which contains both heavy and light items, then copy it and - // compare unioning: - // 1. A varopt sketch of items with weight 1.0 - // 2. A reservoir sample made of the same input items as above - // and we should find that the resulting unions are equivalent. - - final int k = 20; - final long n = 2 * k; - - final VarOptItemsSketch baseVis = VarOptItemsSketch.newInstance(k); - for (long i = 1; i <= n; ++i) { - baseVis.update(-i, i); - } - baseVis.update(-n - 1L, n * n); - baseVis.update(-n - 2L, n * n); - baseVis.update(-n - 3L, n * n); - - final VarOptItemsUnion union1 = VarOptItemsUnion.newInstance(k); - union1.update(baseVis); - - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - final MemorySegment unionImg = MemorySegment.ofArray(union1.toByteArray(serDe)); - final VarOptItemsUnion union2 = VarOptItemsUnion.heapify(unionImg, serDe); - - compareUnionsExact(union1, union2); // sanity check - - final VarOptItemsSketch vis = VarOptItemsSketch.newInstance(k); - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k); - - union2.update((ReservoirItemsSketch) null); - union2.update(ris); // empty - - compareUnionsExact(union1, union2); // union2 should be unchanged - - for (long i = 1; i < (k - 1); ++i) { - ris.update(i); - vis.update(i, 1.0); - } - - union1.update(vis); - union2.update(ris); - - compareUnionsEquivalent(union1, union2); - } - - @Test - public void unionSamplingReservoirSketch() { - // Like unionExactReservoirSketch, but merge in reservoir first, with reservoir in sampling mode - final int k = 20; - final long n = k * k; - - final VarOptItemsUnion union1 = VarOptItemsUnion.newInstance(k); - final VarOptItemsUnion union2 = VarOptItemsUnion.newInstance(k); - - compareUnionsExact(union1, union2); // sanity check - - final VarOptItemsSketch vis = VarOptItemsSketch.newInstance(k); - final ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k); - - for (long i = 1; i < n; ++i) { - ris.update(i); - vis.update(i, 1.0); - } - - union1.update(vis); - union2.update(ris); - compareUnionsEquivalent(union1, union2); - - // repeat to trigger equal tau scenario - union1.update(vis); - union2.update(ris); - compareUnionsEquivalent(union1, union2); - - // create and add a sketch with some heavy items - final VarOptItemsSketch newVis = VarOptItemsSketch.newInstance(k); - for (long i = 1; i <= n; ++i) { - newVis.update(-i, i); - } - newVis.update(-n - 1L, n * n); - newVis.update(-n - 2L, n * n); - newVis.update(-n - 3L, n * n); - - union1.update(newVis); - union2.update(newVis); - compareUnionsEquivalent(union1, union2); - } - - @Test - public void unionReservoirVariousTauValues() { - final int k = 20; - final long n = 2 * k; - - final VarOptItemsSketch baseVis = VarOptItemsSketch.newInstance(k); - for (long i = 1; i <= n; ++i) { - baseVis.update(-i, 1.0); - } - - final VarOptItemsUnion union1 = VarOptItemsUnion.newInstance(k); - union1.update(baseVis); - - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - final MemorySegment unionImg = MemorySegment.ofArray(union1.toByteArray(serDe)); - final VarOptItemsUnion union2 = VarOptItemsUnion.heapify(unionImg, serDe); - - compareUnionsExact(union1, union2); // sanity check - - // reservoir tau will be greater than gadget's tau - VarOptItemsSketch vis = VarOptItemsSketch.newInstance(k); - ReservoirItemsSketch ris = ReservoirItemsSketch.newInstance(k); - for (long i = 1; i < (2 * n); ++i) { - ris.update(i); - vis.update(i, 1.0); - } - - union1.update(vis); - union2.update(ris); - compareUnionsEquivalent(union1, union2); - - // reservoir tau will be smaller than gadget's tau - vis = VarOptItemsSketch.newInstance(k); - ris = ReservoirItemsSketch.newInstance(k); - for (long i = 1; i <= (k + 1); ++i) { - ris.update(i); - vis.update(i, 1.0); - } - - union1.update(vis); - union2.update(ris); - compareUnionsEquivalent(union1, union2); - } - - @Test - public void serializeEmptyUnion() { - final int k = 100; - final VarOptItemsUnion union = VarOptItemsUnion.newInstance(k); - // null inputs to update() should leave the union empty - union.update((VarOptItemsSketch) null); - union.update(null, new ArrayOfStringsSerDe()); - - final ArrayOfStringsSerDe serDe = new ArrayOfStringsSerDe(); - final byte[] bytes = union.toByteArray(serDe); - assertEquals(bytes.length, 8); - - final MemorySegment seg = MemorySegment.ofArray(bytes); - final VarOptItemsUnion rebuilt = VarOptItemsUnion.heapify(seg, serDe); - - final VarOptItemsSketch sketch = rebuilt.getResult(); - assertEquals(sketch.getN(), 0); - - assertEquals(rebuilt.toString(), union.toString()); - } - - @Test - public void serializeExactUnion() { - final int n1 = 32; - final int n2 = 64; - final int k = 128; - final VarOptItemsSketch sketch1 = getUnweightedLongsVIS(k, n1); - final VarOptItemsSketch sketch2 = getUnweightedLongsVIS(k, n2); - - final VarOptItemsUnion union = VarOptItemsUnion.newInstance(k); - union.update(sketch1); - union.update(sketch2); - - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - final byte[] unionBytes = union.toByteArray(serDe); - final MemorySegment seg = MemorySegment.ofArray(unionBytes); - - final VarOptItemsUnion rebuilt = VarOptItemsUnion.heapify(seg, serDe); - compareUnionsExact(rebuilt, union); - - assertEquals(rebuilt.toString(), union.toString()); - } - - @Test - public void serializeSamplingUnion() { - final int n = 256; - final int k = 128; - final VarOptItemsSketch sketch = getUnweightedLongsVIS(k, n); - sketch.update(n + 1L, 1000.0); - sketch.update(n + 2L, 1001.0); - sketch.update(n + 3L, 1002.0); - sketch.update(n + 4L, 1003.0); - sketch.update(n + 5L, 1004.0); - sketch.update(n + 6L, 1005.0); - sketch.update(n + 7L, 1006.0); - sketch.update(n + 8L, 1007.0); - - final VarOptItemsUnion union = VarOptItemsUnion.newInstance(k); - union.update(sketch); - - final ArrayOfLongsSerDe serDe = new ArrayOfLongsSerDe(); - final byte[] unionBytes = union.toByteArray(serDe); - final MemorySegment seg = MemorySegment.ofArray(unionBytes); - - final VarOptItemsUnion rebuilt = VarOptItemsUnion.heapify(seg, serDe); - compareUnionsExact(rebuilt, union); - - assertEquals(rebuilt.toString(), union.toString()); - } - - private static void compareUnionsExact(final VarOptItemsUnion u1, - final VarOptItemsUnion u2) { - assertEquals(u1.getOuterTau(), u2.getOuterTau()); - - final VarOptItemsSketch sketch1 = u1.getResult(); - final VarOptItemsSketch sketch2 = u2.getResult(); - assertEquals(sketch1.getN(), sketch2.getN()); - assertEquals(sketch1.getHRegionCount(), sketch2.getHRegionCount()); - assertEquals(sketch1.getRRegionCount(), sketch2.getRRegionCount()); - - final VarOptItemsSamples s1 = sketch1.getSketchSamples(); - final VarOptItemsSamples s2 = sketch2.getSketchSamples(); - - assertEquals(s1.getNumSamples(), s2.getNumSamples()); - assertEquals(s1.weights(), s2.weights()); - assertEquals(s1.items(), s2.items()); - } - - private static void compareUnionsEquivalent(final VarOptItemsUnion u1, - final VarOptItemsUnion u2) { - assertEquals(u1.getOuterTau(), u2.getOuterTau()); - - final VarOptItemsSketch sketch1 = u1.getResult(); - final VarOptItemsSketch sketch2 = u2.getResult(); - assertEquals(sketch1.getN(), sketch2.getN()); - assertEquals(sketch1.getHRegionCount(), sketch2.getHRegionCount()); - assertEquals(sketch1.getRRegionCount(), sketch2.getRRegionCount()); - - final VarOptItemsSamples s1 = sketch1.getSketchSamples(); - final VarOptItemsSamples s2 = sketch2.getSketchSamples(); - - assertEquals(s1.getNumSamples(), s2.getNumSamples()); - assertEquals(s1.weights(), s2.weights()); - // only compare exact items; others can differ as long as weights match - for (int i = 0; i < sketch1.getHRegionCount(); ++i) { - assertEquals(s1.items(i), s2.items(i)); - } - } - - /** - * Wrapper around System.out.println() allowing a simple way to disable logging in tests - * @param msg The message to print - */ - @SuppressWarnings("unused") - private static void println(final String msg) { - //System.out.println(msg); - } -} diff --git a/src/test/java/org/apache/datasketches/tdigest/SortTest.java b/src/test/java/org/apache/datasketches/tdigest/SortTest.java deleted file mode 100644 index 775b70547..000000000 --- a/src/test/java/org/apache/datasketches/tdigest/SortTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tdigest; - -import static org.testng.Assert.assertEquals; - -import org.apache.datasketches.common.Shuffle; -import org.testng.annotations.Test; - -public class SortTest { - - @Test - public void smallWithRepetition() { - final double[] keys = {3, 1, 4, 2, 1}; - final long[] values = {4, 1, 5, 3, 2}; - Sort.stableSort(keys, values, keys.length); - assertEquals(keys[0], 1); - assertEquals(keys[1], 1); - assertEquals(keys[2], 2); - assertEquals(keys[3], 3); - assertEquals(keys[4], 4); - assertEquals(values[0], 1); - assertEquals(values[1], 2); - assertEquals(values[2], 3); - assertEquals(values[3], 4); - assertEquals(values[4], 5); - } - - @Test - public void large() { - final int n = 1000; - final double[] keys = new double[n]; - final long[] values = new long[n]; - for (int i = 0; i < n; i++) { - values[i] = i; - } - Shuffle.shuffle(values); - for (int i = 0; i < n; i++) { - keys[i] = values[i]; - } - Sort.stableSort(keys, values, n); - for (int i = 0; i < n; i++) { - assertEquals(keys[i], i); - assertEquals(values[i], i); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/tdigest/TDigestCrossLanguageTest.java b/src/test/java/org/apache/datasketches/tdigest/TDigestCrossLanguageTest.java deleted file mode 100644 index 99d88b429..000000000 --- a/src/test/java/org/apache/datasketches/tdigest/TDigestCrossLanguageTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tdigest; - -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES; -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.getFileBytes; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -public class TDigestCrossLanguageTest { - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppDouble() throws IOException { - final boolean[] with_buffer = {false, true}; - for (final boolean buffered : with_buffer) { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (final int n : nArr) { - final byte[] bytes; - if (buffered) { - bytes = getFileBytes(cppPath, "tdigest_double_buf_n" + n + "_cpp.sk"); - } else { - bytes = getFileBytes(cppPath, "tdigest_double_n" + n + "_cpp.sk"); - } - final TDigestDouble td = TDigestDouble.heapify(MemorySegment.ofArray(bytes)); - assertTrue(n == 0 ? td.isEmpty() : !td.isEmpty()); - assertEquals(td.getTotalWeight(), n); - if (n > 0) { - assertEquals(td.getMinValue(), 1); - assertEquals(td.getMaxValue(), n); - assertEquals(td.getRank(0), 0); - assertEquals(td.getRank(n + 1), 1); - if (n == 1) { - assertEquals(td.getRank(n), 0.5); - } else { - assertEquals(td.getRank(n / 2), 0.5, 0.05); - } - } - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppFloat() throws IOException { - final boolean[] with_buffer = {false, true}; - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (final boolean buffered : with_buffer) { - for (final int n : nArr) { - final byte[] bytes; - if (buffered) { - bytes = getFileBytes(cppPath, "tdigest_float_buf_n" + n + "_cpp.sk"); - } else { - bytes = getFileBytes(cppPath, "tdigest_float_n" + n + "_cpp.sk"); - } - final TDigestDouble td = TDigestDouble.heapify(MemorySegment.ofArray(bytes), true); - assertTrue(n == 0 ? td.isEmpty() : !td.isEmpty()); - assertEquals(td.getTotalWeight(), n); - if (n > 0) { - assertEquals(td.getMinValue(), 1); - assertEquals(td.getMaxValue(), n); - assertEquals(td.getRank(0), 0); - assertEquals(td.getRank(n + 1), 1); - if (n == 1) { - assertEquals(td.getRank(n), 0.5); - } else { - assertEquals(td.getRank(n / 2), 0.5, 0.05); - } - } - } - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateForCppDouble() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (final int n : nArr) { - final TDigestDouble td = new TDigestDouble((short) 100); - for (int i = 1; i <= n; i++) { - td.update(i); - } - putBytesToJavaPath("tdigest_double_n" + n + "_java.sk", td.toByteArray()); - } - } - -} diff --git a/src/test/java/org/apache/datasketches/tdigest/TDigestDoubleTest.java b/src/test/java/org/apache/datasketches/tdigest/TDigestDoubleTest.java deleted file mode 100644 index c940648be..000000000 --- a/src/test/java/org/apache/datasketches/tdigest/TDigestDoubleTest.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tdigest; - -import static org.apache.datasketches.common.TestUtil.resPath; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.TestUtil; -import org.testng.annotations.Test; - -public class TDigestDoubleTest { - - @Test - public void empty() { - final TDigestDouble td = new TDigestDouble((short) 100); - assertTrue(td.isEmpty()); - assertEquals(td.getK(), 100); - assertEquals(td.getTotalWeight(), 0); - assertThrows(SketchesStateException.class, () -> td.getMinValue()); - assertThrows(SketchesStateException.class, () -> td.getMaxValue()); - assertThrows(SketchesStateException.class, () -> td.getRank(0)); - assertThrows(SketchesStateException.class, () -> td.getQuantile(0.5)); - assertThrows(SketchesStateException.class, () -> td.getPMF(new double[]{0})); - assertThrows(SketchesStateException.class, () -> td.getCDF(new double[]{0})); - } - - @Test - public void oneValue() { - final TDigestDouble td = new TDigestDouble(); - td.update(1); - assertFalse(td.isEmpty()); - assertEquals(td.getK(), 200); - assertEquals(td.getTotalWeight(), 1); - assertEquals(td.getMinValue(), 1); - assertEquals(td.getMaxValue(), 1); - assertEquals(td.getRank(0.99), 0); - assertEquals(td.getRank(1), 0.5); - assertEquals(td.getRank(1.01), 1); - assertEquals(td.getQuantile(0), 1); - assertEquals(td.getQuantile(0.5), 1); - assertEquals(td.getQuantile(1), 1); - } - - @Test - public void manyValues() { - final TDigestDouble td = new TDigestDouble(); - final int n = 10000; - for (int i = 0; i < n; i++) { - td.update(i); - } - assertFalse(td.isEmpty()); - assertEquals(td.getTotalWeight(), n); - assertEquals(td.getMinValue(), 0); - assertEquals(td.getMaxValue(), n - 1); - assertEquals(td.getRank(0), 0, 0.0001); - assertEquals(td.getRank(n / 4), 0.25, 0.0001); - assertEquals(td.getRank(n / 2), 0.5, 0.0001); - assertEquals(td.getRank((n * 3) / 4), 0.75, 0.0001); - assertEquals(td.getRank(n), 1); - assertEquals(td.getQuantile(0), 0); - assertEquals(td.getQuantile(0.5), n / 2, (n / 2) * 0.03); - assertEquals(td.getQuantile(0.9), n * 0.9, n * 0.9 * 0.01); - assertEquals(td.getQuantile(0.95), n * 0.95, n * 0.95 * 0.01); - assertEquals(td.getQuantile(1), n - 1); - final double[] pmf = td.getPMF(new double[] {n / 2}); - assertEquals(pmf.length, 2); - assertEquals(pmf[0], 0.5, 0.0001); - assertEquals(pmf[1], 0.5, 0.0001); - final double[] cdf = td.getCDF(new double[] {n / 2}); - assertEquals(cdf.length, 2); - assertEquals(cdf[0], 0.5, 0.0001); - assertEquals(cdf[1], 1.0); - } - - @Test - public void mergeSmall() { - final TDigestDouble td1 = new TDigestDouble(); - td1.update(1); - td1.update(2); - final TDigestDouble td2 = new TDigestDouble(); - td2.update(2); - td2.update(3); - td1.merge(td2); - assertEquals(td1.getTotalWeight(), 4); - assertEquals(td1.getMinValue(), 1); - assertEquals(td1.getMaxValue(), 3); - } - - @Test - public void mergeLarge() { - final int n = 10000; - final TDigestDouble td1 = new TDigestDouble(); - final TDigestDouble td2 = new TDigestDouble(); - for (int i = 0; i < (n / 2); i++) { - td1.update(i); - td2.update((n / 2) + i); - } - td1.merge(td2); - assertEquals(td1.getTotalWeight(), n); - assertEquals(td1.getMinValue(), 0); - assertEquals(td1.getMaxValue(), n - 1); - } - - @Test - public void serializeDeserializeEmpty() { - final TDigestDouble td1 = new TDigestDouble(); - final byte[] bytes = td1.toByteArray(); - final TDigestDouble td2 = TDigestDouble.heapify(MemorySegment.ofArray(bytes)); - assertEquals(td2.getK(), td1.getK()); - assertEquals(td2.getTotalWeight(), td1.getTotalWeight()); - assertEquals(td2.isEmpty(), td1.isEmpty()); - } - - @Test - public void serializeDeserializeNonEmpty() { - final TDigestDouble td1 = new TDigestDouble(); - for (int i = 0; i < 10000; i++) { - td1.update(i); - } - final byte[] bytes = td1.toByteArray(); - final TDigestDouble td2 = TDigestDouble.heapify(MemorySegment.ofArray(bytes)); - assertEquals(td2.getK(), td1.getK()); - assertEquals(td2.getTotalWeight(), td1.getTotalWeight()); - assertEquals(td2.isEmpty(), td1.isEmpty()); - assertEquals(td2.getMinValue(), td1.getMinValue()); - assertEquals(td2.getMaxValue(), td1.getMaxValue()); - assertEquals(td2.getRank(5000), td1.getRank(5000)); - assertEquals(td2.getQuantile(0.5), td1.getQuantile(0.5)); - } - - @Test - public void deserializeFromReferenceImplementationDouble() { - final byte[] bytes = TestUtil.getFileBytes(resPath, "tdigest_ref_k100_n10000_double.sk"); - final TDigestDouble td = TDigestDouble.heapify(MemorySegment.ofArray(bytes)); - final int n = 10000; - assertEquals(td.getK(), 100); - assertEquals(td.getTotalWeight(), n); - assertEquals(td.getMinValue(), 0); - assertEquals(td.getMaxValue(), n - 1); - assertEquals(td.getRank(0), 0, 0.0001); - assertEquals(td.getRank(n / 4), 0.25, 0.0001); - assertEquals(td.getRank(n / 2), 0.5, 0.0001); - assertEquals(td.getRank((n * 3) / 4), 0.75, 0.0001); - assertEquals(td.getRank(n), 1); - } - - @Test - public void deserializeFromReferenceImplementationFloat() { - final byte[] bytes = TestUtil.getFileBytes(resPath, "tdigest_ref_k100_n10000_float.sk"); - final TDigestDouble td = TDigestDouble.heapify(MemorySegment.ofArray(bytes)); - final int n = 10000; - assertEquals(td.getK(), 100); - assertEquals(td.getTotalWeight(), n); - assertEquals(td.getMinValue(), 0); - assertEquals(td.getMaxValue(), n - 1); - assertEquals(td.getRank(0), 0, 0.0001); - assertEquals(td.getRank(n / 4), 0.25, 0.0001); - assertEquals(td.getRank(n / 2), 0.5, 0.0001); - assertEquals(td.getRank((n * 3) / 4), 0.75, 0.0001); - assertEquals(td.getRank(n), 1); - } -} diff --git a/src/test/java/org/apache/datasketches/theta/AnotBimplTest.java b/src/test/java/org/apache/datasketches/theta/AnotBimplTest.java deleted file mode 100644 index 414308280..000000000 --- a/src/test/java/org/apache/datasketches/theta/AnotBimplTest.java +++ /dev/null @@ -1,333 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class AnotBimplTest { - - @Test - public void checkExactAnotB_AvalidNoOverlap() { - final int k = 512; - - final UpdatableThetaSketch usk1 = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - final UpdatableThetaSketch usk2 = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - - for (int i=0; i>> 3; - bitOffset = (bitOffset + bits) & 7; - } - - long[] output = new long[8]; - bitOffset = 0; - bufOffset = 0; - for (int i = 0; i < 8; ++i) { - BitPacking.unpackBits(output, i, bits, bytes, bufOffset, bitOffset); - bufOffset += (bitOffset + bits) >>> 3; - bitOffset = (bitOffset + bits) & 7; - } - - for (int i = 0; i < 8; ++i) { - assertEquals(output[i], input[i]); - } - } - } - } - - @Test - public void packUnpackBlocks() { - long value = 0xaa55aa55aa55aa55L; // arbitrary starting value - for (int n = 0; n < 10000; n++) { - for (int bits = 1; bits <= 63; bits++) { - if (enablePrinting) { System.out.println("bits " + bits); } - final long mask = (1L << bits) - 1; - long[] input = new long[8]; - for (int i = 0; i < 8; ++i) { - input[i] = value & mask; - value += Util.INVERSE_GOLDEN_U64; - } - - byte[] bytes = new byte[8 * Long.BYTES]; - BitPacking.packBitsBlock8(input, 0, bytes, 0, bits); - if (enablePrinting) { hexDump(bytes); } - - long[] output = new long[8]; - BitPacking.unpackBitsBlock8(output, 0, bytes, 0, bits); - - for (int i = 0; i < 8; ++i) { - if (enablePrinting) { System.out.println("checking value " + i); } - assertEquals(output[i], input[i]); - } - } - } - } - - @Test - public void packBitsUnpackBlocks() { - long value = 0; // arbitrary starting value - for (int n = 0; n < 10000; n++) { - for (int bits = 1; bits <= 63; bits++) { - final long mask = (1 << bits) - 1; - long[] input = new long[8]; - for (int i = 0; i < 8; ++i) { - input[i] = value & mask; - value += Util.INVERSE_GOLDEN_U64; - } - - byte[] bytes = new byte[8 * Long.BYTES]; - int bitOffset = 0; - int bufOffset = 0; - for (int i = 0; i < 8; ++i) { - BitPacking.packBits(input[i], bits, bytes, bufOffset, bitOffset); - bufOffset += (bitOffset + bits) >>> 3; - bitOffset = (bitOffset + bits) & 7; - } - - long[] output = new long[8]; - BitPacking.unpackBitsBlock8(output, 0, bytes, 0, bits); - - for (int i = 0; i < 8; ++i) { - assertEquals(output[i], input[i]); - } - } - } - } - - @Test - public void packBlocksUnpackBits() { - long value = 123L; // arbitrary starting value - for (int n = 0; n < 10000; n++) { - for (int bits = 1; bits <= 63; bits++) { - final long mask = (1 << bits) - 1; - long[] input = new long[8]; - for (int i = 0; i < 8; ++i) { - input[i] = value & mask; - value += Util.INVERSE_GOLDEN_U64; - } - - byte[] bytes = new byte[8 * Long.BYTES]; - BitPacking.packBitsBlock8(input, 0, bytes, 0, bits); - - long[] output = new long[8]; - int bitOffset = 0; - int bufOffset = 0; - for (int i = 0; i < 8; ++i) { - BitPacking.unpackBits(output, i, bits, bytes, bufOffset, bitOffset); - bufOffset += (bitOffset + bits) >>> 3; - bitOffset = (bitOffset + bits) & 7; - } - - for (int i = 0; i < 8; ++i) { - assertEquals(output[i], input[i]); - } - } - } - } - - void hexDump(byte[] bytes) { - for (int i = 0; i < bytes.length; i++) { - System.out.print(String.format("%02x ", bytes[i])); - } - System.out.println(); - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/CompactSketchTest.java b/src/test/java/org/apache/datasketches/theta/CompactSketchTest.java deleted file mode 100644 index 23a3d5e0d..000000000 --- a/src/test/java/org/apache/datasketches/theta/CompactSketchTest.java +++ /dev/null @@ -1,692 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class CompactSketchTest { - - @Test - public void checkHeapifyWrap() { - final int k = 4096; - final boolean ordered = true; - checkHeapifyWrap(k, 0, ordered); - checkHeapifyWrap(k, 1, ordered); - checkHeapifyWrap(k, 1, !ordered); - checkHeapifyWrap(k, k, ordered); //exact - checkHeapifyWrap(k, k, !ordered); //exact - checkHeapifyWrap(k, 4 * k, ordered); //estimating - checkHeapifyWrap(k, 4 * k, !ordered); //estimating - } - - //test combinations of compact ordered/not ordered and heap/direct - public void checkHeapifyWrap(final int k, final int u, final boolean ordered) { - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - - for (int i=0; i k); - - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - - for (int i=0; i k); - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - - assertEquals(local.getClass().getSimpleName(), "ConcurrentHeapThetaBuffer"); - assertFalse(local.isOffHeap()); - assertTrue(local.hasMemorySegment()); - - for (int i=0; i k); - } - - @Test - public void checkErrorBounds() { - final int lgK = 9; - final int k = 1 << lgK; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - - //Exact mode - for (int i = 0; i < k; i++ ) { local.update(i); } - waitForBgPropagationToComplete(shared); - - double est = local.getEstimate(); - double lb = local.getLowerBound(2); - double ub = local.getUpperBound(2); - assertEquals(est, ub, 0.0); - assertEquals(est, lb, 0.0); - - //Est mode - final int u = 100*k; - for (int i = k; i < u; i++ ) { - local.update(i); - local.update(i); //test duplicate rejection - } - waitForBgPropagationToComplete(shared); - est = local.getEstimate(); - lb = local.getLowerBound(2); - ub = local.getUpperBound(2); - assertTrue(est <= ub); - assertTrue(est >= lb); - } - - - @Test - public void checkUpperAndLowerBounds() { - final int lgK = 9; - final int k = 1 << lgK; - final int u = 2*k; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - - for (int i = 0; i < u; i++ ) { local.update(i); } - waitForBgPropagationToComplete(shared); - - final double est = local.getEstimate(); - final double ub = local.getUpperBound(1); - final double lb = local.getLowerBound(1); - assertTrue(ub > est); - assertTrue(lb < est); - } - - @Test - public void checkRebuild() { - final int lgK = 9; - final int k = 1 << lgK; - final int u = 4*k; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - - assertTrue(local.isEmpty()); - - for (int i = 0; i< u; i++) { local.update(i); } - waitForBgPropagationToComplete(shared); - - assertFalse(local.isEmpty()); - assertTrue(local.getEstimate() > 0.0); - assertTrue(shared.getRetainedEntries(false) >= k); - - shared.rebuild(); - assertEquals(shared.getRetainedEntries(false), k); - assertEquals(shared.getRetainedEntries(true), k); - local.rebuild(); - assertEquals(shared.getRetainedEntries(false), k); - assertEquals(shared.getRetainedEntries(true), k); - } - - @Test - public void checkResetAndStartingSubMultiple() { - final int lgK = 9; - final int k = 1 << lgK; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - - assertTrue(local.isEmpty()); - - final int u = 4*k; - for (int i = 0; i< u; i++) { local.update(i); } - waitForBgPropagationToComplete(shared); - - assertFalse(local.isEmpty()); - assertTrue(shared.getRetainedEntries(false) >= k); - assertTrue(local.getThetaLong() < Long.MAX_VALUE); - - shared.reset(); - local.reset(); - assertTrue(local.isEmpty()); - assertEquals(shared.getRetainedEntries(false), 0); - assertEquals(local.getEstimate(), 0.0, 0.0); - assertEquals(local.getThetaLong(), Long.MAX_VALUE); - } - - @Test - public void checkExactModeMemorySegmentArr() { - final int lgK = 12; - final int k = 1 << lgK; - final int u = k; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - assertTrue(local.isEmpty()); - - for (int i = 0; i< u; i++) { local.update(i); } - waitForBgPropagationToComplete(shared); - - assertEquals(local.getEstimate(), u, 0.0); - assertEquals(shared.getRetainedEntries(false), u); - } - - @Test - public void checkEstModeMemorySegmentArr() { - final int lgK = 12; - final int k = 1 << lgK; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - assertTrue(local.isEmpty()); - - final int u = 3*k; - for (int i = 0; i< u; i++) { local.update(i); } - waitForBgPropagationToComplete(shared); - - final double est = local.getEstimate(); - assertTrue(est < u * 1.05 && est > u * 0.95); - assertTrue(shared.getRetainedEntries(false) >= k); - } - - @Test - public void checkEstModeNativeMemorySegment() { - final int lgK = 12; - final int k = 1 << lgK; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - assertTrue(local.isEmpty()); - - final int u = 3*k; - for (int i = 0; i< u; i++) { local.update(i); } - waitForBgPropagationToComplete(shared); - final double est = local.getEstimate(); - assertTrue(est < u * 1.05 && est > u * 0.95); - assertTrue(shared.getRetainedEntries(false) >= k); - } - - @Test - public void checkConstructReconstructFromMemorySegment() { - final int lgK = 12; - final int k = 1 << lgK; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - - assertTrue(local.isEmpty()); - final int u = 3*k; - - for (int i = 0; i< u; i++) { local.update(i); } //force estimation - waitForBgPropagationToComplete(shared); - - final double est1 = local.getEstimate(); - final int count1 = shared.getRetainedEntries(false); - assertTrue(est1 < u * 1.05 && est1 > u * 0.95); - assertTrue(count1 >= k); - - byte[] serArr; - double est2; - - serArr = shared.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(serArr); - final UpdatableThetaSketch recoveredShared = UpdatableThetaSketch.wrap(seg); - - //reconstruct to Native/Direct - final int bytes = ThetaSketch.getMaxUpdateSketchBytes(k); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - shared = sl.bldr.buildSharedFromSketch(recoveredShared, wseg); - final UpdatableThetaSketch local2 = sl.bldr.buildLocal(shared); - est2 = local2.getEstimate(); - - assertEquals(est2, est1, 0.0); - } - - @Test - public void checkNullMemorySegment() { - final UpdatableThetaSketchBuilder bldr = new UpdatableThetaSketchBuilder(); - final UpdatableThetaSketch sk = bldr.build(); - for (int i = 0; i < 1000; i++) { sk.update(i); } - final UpdatableThetaSketch shared = bldr.buildSharedFromSketch(sk, null); - assertEquals(shared.getRetainedEntries(true), 1000); - assertFalse(shared.hasMemorySegment()); - } - - //checks Alex's bug where lgArrLongs > lgNomLongs +1. - @Test - public void checkResizeInBigSeg() { - final int lgK = 14; - final int u = 1 << 20; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, SEED, useSeg, true, 8); //seg is 8X larger than needed - final UpdatableThetaSketch local = sl.local; - - for (int i = 0; i < u; i++) { local.update(i); } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkConstructorKtooSmall() { - final int lgK = 3; - final boolean useSeg = true; - new SharedLocal(lgK, lgK, useSeg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkConstructorSegTooSmall() { - final int lgK = 4; - final int k = 1 << lgK; - final MemorySegment wseg = MemorySegment.ofArray(new byte[k/2]); - final UpdatableThetaSketchBuilder bldr = new UpdatableThetaSketchBuilder(); - bldr.setLogNominalEntries(lgK); - bldr.buildShared(wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyIllegalFamilyID_heapify() { - final int lgK = 9; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - sl.wseg.set(JAVA_BYTE, FAMILY_BYTE, (byte) 0); //corrupt the Family ID byte - //try to heapify the corrupted seg - ThetaSketch.heapify(sl.wseg); //catch in ThetaSketch.constructHeapSketch - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadLgNomLongs() { - final int lgK = 4; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - sl.wseg.set(JAVA_BYTE, LG_NOM_LONGS_BYTE, (byte) 3); //Corrupt LgNomLongs byte - DirectQuickSelectSketch.writableWrap(sl.wseg, null, Util.DEFAULT_UPDATE_SEED); - } - - @Test - public void checkBackgroundPropagation() { - final int lgK = 4; - final int k = 1 << lgK; - final int u = 10*k; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - assertTrue(local.isEmpty()); - final ConcurrentHeapThetaBuffer sk1 = (ConcurrentHeapThetaBuffer)local; //for internal checks - - int i = 0; - for (; i< k; i++) { - local.update(i); - } - waitForBgPropagationToComplete(shared); - assertFalse(local.isEmpty()); - assertTrue(local.getEstimate() > 0.0); - final long theta1 = ((ConcurrentSharedThetaSketch)shared).getVolatileTheta(); - - for (; i< u; i++) { - local.update(i); - } - waitForBgPropagationToComplete(shared); - - final long theta2 = ((ConcurrentSharedThetaSketch)shared).getVolatileTheta(); - final int entries = shared.getRetainedEntries(false); - assertTrue(entries > k || theta2 < theta1, - "entries="+entries+" k="+k+" theta1="+theta1+" theta2="+theta2); - - shared.rebuild(); - assertEquals(shared.getRetainedEntries(false), k); - assertEquals(shared.getRetainedEntries(true), k); - sk1.rebuild(); - assertEquals(shared.getRetainedEntries(false), k); - assertEquals(shared.getRetainedEntries(true), k); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadSerVer() { - final int lgK = 9; - final int k = 1 << lgK; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - assertTrue(local.isEmpty()); - - for (int i = 0; i< k; i++) { local.update(i); } - waitForBgPropagationToComplete(shared); - - assertFalse(local.isEmpty()); - assertEquals(local.getEstimate(), k, 0.0); - assertEquals(shared.getRetainedEntries(false), k); - - sl.wseg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 0); //corrupt the SerVer byte - ThetaSketch.wrap(sl.wseg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkWrapIllegalFamilyID_wrap() { - final int lgK = 9; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - - sl.wseg.set(JAVA_BYTE, FAMILY_BYTE, (byte) 0); //corrupt the FamilyID byte - //try to wrap the corrupted seg - ThetaSketch.wrap(sl.wseg); //catch in ThetaSketch.constructDirectSketch - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkWrapIllegalFamilyID_direct() { - final int lgK = 9; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - - sl.wseg.set(JAVA_BYTE, FAMILY_BYTE, (byte) 0); //corrupt the FamilyID byte - //try to wrap the corrupted seg - DirectQuickSelectSketch.writableWrap(sl.wseg, null, Util.DEFAULT_UPDATE_SEED); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifySeedConflict() { - final int lgK = 9; - final long seed1 = 1021; - final long seed2 = Util.DEFAULT_UPDATE_SEED; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, seed1, useSeg, true, 1); - final UpdatableThetaSketch shared = sl.shared; - - final MemorySegment srcSeg = MemorySegment.ofArray(shared.toByteArray()).asReadOnly(); - ThetaSketch.heapify(srcSeg, seed2); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkCorruptLgNomLongs() { - final int lgK = 4; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - - sl.wseg.set(JAVA_BYTE, LG_NOM_LONGS_BYTE, (byte)2); //corrupt - ThetaSketch.heapify(sl.wseg, Util.DEFAULT_UPDATE_SEED); - } - - @Test(expectedExceptions = UnsupportedOperationException.class) - public void checkIllegalHashUpdate() { - final int lgK = 4; - final boolean useSeg = true; - final SharedLocal sl = new SharedLocal(lgK, lgK, useSeg); - final UpdatableThetaSketch shared = sl.shared; - shared.hashUpdate(1); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - - private static void checkMemorySegmentDirectProxyMethods(final ThetaSketch local, final ThetaSketch shared) { - assertEquals( - local.hasMemorySegment(), - shared.hasMemorySegment()); - assertEquals(local.isOffHeap(), shared.isOffHeap()); - } - - //Does not check hasMemorySegment(), isOffHeap() - private static void checkOtherProxyMethods(final ThetaSketch local, final ThetaSketch shared) { - assertEquals(local.getCompactBytes(), shared.getCompactBytes()); - assertEquals(local.getCurrentBytes(), shared.getCurrentBytes()); - assertEquals(local.getEstimate(), shared.getEstimate()); - assertEquals(local.getLowerBound(2), shared.getLowerBound(2)); - assertEquals(local.getUpperBound(2), shared.getUpperBound(2)); - assertEquals(local.isEmpty(), shared.isEmpty()); - assertEquals(local.isEstimationMode(), shared.isEstimationMode()); - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/ConcurrentHeapQuickSelectSketchTest.java b/src/test/java/org/apache/datasketches/theta/ConcurrentHeapQuickSelectSketchTest.java deleted file mode 100644 index 0e3f4241a..000000000 --- a/src/test/java/org/apache/datasketches/theta/ConcurrentHeapQuickSelectSketchTest.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.LG_NOM_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.testng.annotations.Test; - -/** - * @author eshcar - */ -public class ConcurrentHeapQuickSelectSketchTest { - - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadSerVer() { - final int lgK = 9; - final int k = 1 << lgK; - final int u = k; - final SharedLocal sl = new SharedLocal(lgK); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - - assertTrue(local.isEmpty()); - - for (int i = 0; i< u; i++) { - local.update(i); - } - waitForBgPropagationToComplete(shared); - - assertFalse(local.isEmpty()); - assertEquals(local.getEstimate(), u, 0.0); - assertEquals(shared.getRetainedEntries(false), u); - - final byte[] serArr = shared.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(serArr); - final ThetaSketch sk = ThetaSketch.heapify(seg, sl.seed); - assertTrue(sk instanceof HeapQuickSelectSketch); //Intentional promotion to Parent - - seg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 0); //corrupt the SerVer byte - ThetaSketch.heapify(seg, sl.seed); - } - - @Test - public void checkPropagationNotOrdered() { - final int lgK = 8; - final int k = 1 << lgK; - final int u = 200*k; - final SharedLocal sl = new SharedLocal(lgK, 4, false, false); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - assertEquals((sl.bldr.getConCurLgNominalEntries()), 4); - assertTrue(local.isEmpty()); - - for (int i = 0; i < u; i++) { - local.update(i); - } - waitForBgPropagationToComplete(shared); - - assertFalse(local.isEmpty()); - assertTrue(shared.getRetainedEntries(true) <= u); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkIllegalSketchID_UpdateSketch() { - final int lgK = 9; - final int k = 1 << lgK; - final int u = k; - final SharedLocal sl = new SharedLocal(lgK); - - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - assertTrue(local.isEmpty()); - assertTrue(shared instanceof ConcurrentHeapQuickSelectSketch); - for (int i = 0; i< u; i++) { - local.update(i); - } - assertTrue(shared.compact().isCompact()); - - assertFalse(local.isEmpty()); - assertEquals(local.getEstimate(), u, 0.0); - assertEquals(shared.getRetainedEntries(false), u); - final byte[] byteArray = shared.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArray); - seg.set(JAVA_BYTE, FAMILY_BYTE, (byte) 0); //corrupt the FamilyID byte - - //try to heapify the corrupted seg - ThetaSketch.heapify(seg, sl.seed); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifySeedConflict() { - final int lgK = 9; - final long seed = 1021; - final long seed2 = Util.DEFAULT_UPDATE_SEED; - final SharedLocal sl = new SharedLocal(lgK, lgK, seed); - final byte[] byteArray = sl.shared.toByteArray(); - final MemorySegment srcSeg = MemorySegment.ofArray(byteArray); - ThetaSketch.heapify(srcSeg, seed2); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyCorruptLgNomLongs() { - final int lgK = 4; - final SharedLocal sl = new SharedLocal(lgK); - final byte[] serArr = sl.shared.toByteArray(); - final MemorySegment srcSeg = MemorySegment.ofArray(serArr); - srcSeg.set(JAVA_BYTE, LG_NOM_LONGS_BYTE, (byte)2); //corrupt - ThetaSketch.heapify(srcSeg, Util.DEFAULT_UPDATE_SEED); - } - - @Test(expectedExceptions = UnsupportedOperationException.class) - public void checkIllegalHashUpdate() { - final int lgK = 4; - final SharedLocal sl = new SharedLocal(lgK); - sl.shared.hashUpdate(1); - } - - @Test - public void checkHeapifyByteArrayExact() { - final int lgK = 9; - final int k = 1 << lgK; - final int u = k; - final SharedLocal sl = new SharedLocal(lgK); - UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - - for (int i=0; i k); - // it could be exactly k, but in this case must be greater - } - - @Test - public void checkErrorBounds() { - final int lgK = 9; - final int k = 1 << lgK; - final SharedLocal sl = new SharedLocal(lgK); - final UpdatableThetaSketch local = sl.local; - final UpdatableThetaSketch shared = sl.shared; - - //Exact mode - //int limit = (int)ConcurrentSharedThetaSketch.computeExactLimit(lim, 0); //? ask Eshcar - for (int i = 0; i < k; i++ ) { - local.update(i); - } - - double est = local.getEstimate(); - double lb = local.getLowerBound(2); - double ub = local.getUpperBound(2); - assertEquals(est, ub, 0.0); - assertEquals(est, lb, 0.0); - - //Est mode - final int u = 2 * k; - for (int i = k; i < u; i++ ) { - local.update(i); - local.update(i); //test duplicate rejection - } - waitForBgPropagationToComplete(shared); - est = local.getEstimate(); - lb = local.getLowerBound(2); - ub = local.getUpperBound(2); - assertTrue(est <= ub); - assertTrue(est >= lb); - } - - @Test - public void checkRebuild() { - final int lgK = 4; - final int k = 1 << lgK; - final SharedLocal sl = new SharedLocal(lgK); - //must build shared first - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - - assertTrue(local.isEmpty()); - final int t = ((ConcurrentHeapThetaBuffer)local).getHashTableThreshold(); - - for (int i = 0; i< t; i++) { - local.update(i); - } - waitForBgPropagationToComplete(shared); - - assertFalse(local.isEmpty()); - assertTrue(local.getEstimate() > 0.0); - assertTrue(shared.getRetainedEntries(false) > k); - - shared.rebuild(); - assertEquals(shared.getRetainedEntries(false), k); - assertEquals(shared.getRetainedEntries(true), k); - shared.rebuild(); - assertEquals(shared.getRetainedEntries(false), k); - assertEquals(shared.getRetainedEntries(true), k); - } - - @Test - public void checkBuilder() { - final int lgK = 4; - final SharedLocal sl = new SharedLocal(lgK); - assertEquals(sl.bldr.getConCurLgNominalEntries(), lgK); - assertEquals(sl.bldr.getLgNominalEntries(), lgK); - println(sl.bldr.toString()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBuilderSmallNominal() { - final int lgK = 2; //too small - new SharedLocal(lgK); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkNegativeHashes() { - final int lgK = 9; - final SharedLocal sl = new SharedLocal(lgK); - final UpdatableThetaSketch local = sl.local; - local.hashUpdate(-1L); - } - - @Test - public void checkResetAndStartingSubMultiple() { - final int lgK = 9; - final int k = 1 << lgK; - final SharedLocal sl = new SharedLocal(lgK); - final UpdatableThetaSketch shared = sl.shared; - final UpdatableThetaSketch local = sl.local; - - assertTrue(local.isEmpty()); - final int u = 3*k; - - for (int i = 0; i< u; i++) { local.update(i); } - waitForBgPropagationToComplete(shared); - - assertFalse(local.isEmpty()); - assertTrue(shared.getRetainedEntries(false) >= k); - assertTrue(local.getThetaLong() < Long.MAX_VALUE); - - shared.reset(); - local.reset(); - assertTrue(local.isEmpty()); - assertEquals(shared.getRetainedEntries(false), 0); - assertEquals(local.getEstimate(), 0.0, 0.0); - assertEquals(local.getThetaLong(), Long.MAX_VALUE); - } - - @Test - public void checkDQStoCompactEmptyForms() { - final int lgK = 9; - final SharedLocal sl = new SharedLocal(lgK); - final UpdatableThetaSketch local = sl.local; - final UpdatableThetaSketch shared = sl.shared; - - //empty - local.toString(false, true, 0, false); //exercise toString - assertTrue(local instanceof ConcurrentHeapThetaBuffer); - final double localEst = local.getEstimate(); - final double localLB = local.getLowerBound(2); - final double uskUB = local.getUpperBound(2); - assertFalse(local.isEstimationMode()); - - final int bytes = local.getCompactBytes(); - assertEquals(bytes, 8); - final byte[] segArr2 = new byte[bytes]; - final MemorySegment seg2 = MemorySegment.ofArray(segArr2); - - final CompactThetaSketch csk2 = shared.compact(false, seg2); - assertEquals(csk2.getEstimate(), localEst); - assertEquals(csk2.getLowerBound(2), localLB); - assertEquals(csk2.getUpperBound(2), uskUB); - assertTrue(csk2.isEmpty()); - assertFalse(csk2.isEstimationMode()); - assertTrue(csk2.isOrdered()); - - final CompactThetaSketch csk3 = shared.compact(true, seg2); - csk3.toString(false, true, 0, false); - csk3.toString(); - assertEquals(csk3.getEstimate(), localEst); - assertEquals(csk3.getLowerBound(2), localLB); - assertEquals(csk3.getUpperBound(2), uskUB); - assertTrue(csk3.isEmpty()); - assertFalse(csk3.isEstimationMode()); - assertTrue(csk2.isOrdered()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkMinReqBytes() { - final int lgK = 4; - final int k = 1 << lgK; - final SharedLocal sl = new SharedLocal(lgK); - for (int i = 0; i < (4 * k); i++) { sl.local.update(i); } - waitForBgPropagationToComplete(sl.shared); - final byte[] byteArray = sl.shared.toByteArray(); - final byte[] badBytes = Arrays.copyOfRange(byteArray, 0, 24); //corrupt no. bytes - final MemorySegment seg = MemorySegment.ofArray(badBytes).asReadOnly(); - ThetaSketch.heapify(seg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkThetaAndLgArrLongs() { - final int lgK = 4; - final int k = 1 << lgK; - final SharedLocal sl = new SharedLocal(lgK); - for (int i = 0; i < k; i++) { sl.local.update(i); } - waitForBgPropagationToComplete(sl.shared); - final byte[] badArray = sl.shared.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(badArray); - PreambleUtil.insertLgArrLongs(seg, 4); //corrupt - PreambleUtil.insertThetaLong(seg, Long.MAX_VALUE / 2); //corrupt - ThetaSketch.heapify(seg); - } - - @Test - public void checkFamily() { - final SharedLocal sl = new SharedLocal(); - final UpdatableThetaSketch local = sl.local; - assertEquals(local.getFamily(), Family.QUICKSELECT); - } - - @Test - public void checkBackgroundPropagation() { - final int lgK = 4; - final int k = 1 << lgK; - final int u = 5*k; - final SharedLocal sl = new SharedLocal(lgK); - assertTrue(sl.local.isEmpty()); - - int i = 0; - for (; i < k; i++) { sl.local.update(i); } //exact - waitForBgPropagationToComplete(sl.shared); - - assertFalse(sl.local.isEmpty()); - assertTrue(sl.local.getEstimate() > 0.0); - final long theta1 = sl.sharedIf.getVolatileTheta(); - - for (; i < u; i++) { sl.local.update(i); } //continue, make it estimating - waitForBgPropagationToComplete(sl.shared); - - final long theta2 = sl.sharedIf.getVolatileTheta(); - final int entries = sl.shared.getRetainedEntries(false); - assertTrue((entries > k) || (theta2 < theta1), - "entries= " + entries + " k= " + k + " theta1= " + theta1 + " theta2= " + theta2); - - sl.shared.rebuild(); - assertEquals(sl.shared.getRetainedEntries(false), k); - assertEquals(sl.shared.getRetainedEntries(true), k); - sl.local.rebuild(); - assertEquals(sl.shared.getRetainedEntries(false), k); - assertEquals(sl.shared.getRetainedEntries(true), k); - } - - @Test - public void checkBuilderExceptions() { - final UpdatableThetaSketchBuilder bldr = new UpdatableThetaSketchBuilder(); - try { - bldr.setNominalEntries(8); - fail(); - } catch (final SketchesArgumentException e) { } - try { - bldr.setConCurNominalEntries(8); - fail(); - } catch (final SketchesArgumentException e) { } - try { - bldr.setConCurLogNominalEntries(3); - fail(); - } catch (final SketchesArgumentException e) { } - bldr.setNumPoolThreads(4); - assertEquals(bldr.getNumPoolThreads(), 4); - bldr.setMaxConcurrencyError(0.04); - assertEquals(bldr.getMaxConcurrencyError(), 0.04); - bldr.setMaxNumLocalThreads(4); - assertEquals(bldr.getMaxNumLocalThreads(), 4); - } - - @Test(expectedExceptions = UnsupportedOperationException.class) - public void checkToByteArray() { - final SharedLocal sl = new SharedLocal(); - sl.local.toByteArray(); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - - static class SharedLocal { - static final long DefaultSeed = Util.DEFAULT_UPDATE_SEED; - final UpdatableThetaSketch shared; - final ConcurrentSharedThetaSketch sharedIf; - final UpdatableThetaSketch local; - final int sharedLgK; - final int localLgK; - final long seed; - final MemorySegment wseg; - final UpdatableThetaSketchBuilder bldr = new UpdatableThetaSketchBuilder(); - - SharedLocal() { - this(9, 9, DefaultSeed, false, true, 1); - } - - SharedLocal(final int lgK) { - this(lgK, lgK, DefaultSeed, false, true, 1); - } - - SharedLocal(final int sharedLgK, final int localLgK) { - this(sharedLgK, localLgK, DefaultSeed, false, true, 1); - } - - SharedLocal(final int sharedLgK, final int localLgK, final long seed) { - this(sharedLgK, localLgK, seed, false, true, 1); - } - - SharedLocal(final int sharedLgK, final int localLgK, final boolean useSeg) { - this(sharedLgK, localLgK, DefaultSeed, useSeg, true, 1); - } - - SharedLocal(final int sharedLgK, final int localLgK, final boolean useSeg, final boolean ordered) { - this(sharedLgK, localLgK, DefaultSeed, useSeg, ordered, 1); - } - - SharedLocal(final int sharedLgK, final int localLgK, final long seed, final boolean useSeg, final boolean ordered, final int segMult) { - this.sharedLgK = sharedLgK; - this.localLgK = localLgK; - this.seed = seed; - if (useSeg) { - final int bytes = (((4 << sharedLgK) * segMult) + (Family.QUICKSELECT.getMaxPreLongs())) << 3; - wseg = MemorySegment.ofArray(new byte[bytes]); - } else { - wseg = null; - } - bldr.setLogNominalEntries(sharedLgK); - bldr.setConCurLogNominalEntries(localLgK); - bldr.setPropagateOrderedCompact(ordered); - bldr.setSeed(this.seed); - shared = bldr.buildShared(wseg); - local = bldr.buildLocal(shared); - sharedIf = (ConcurrentSharedThetaSketch) shared; - } - } - - static void waitForBgPropagationToComplete(final UpdatableThetaSketch shared) { - try { - Thread.sleep(10); - } catch (final InterruptedException e) { - e.printStackTrace(); - } - final ConcurrentSharedThetaSketch csts = (ConcurrentSharedThetaSketch)shared; - csts.awaitBgPropagationTermination(); - ConcurrentPropagationService.resetExecutorService(Thread.currentThread().getId()); - csts.initBgPropagationService(); - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/CornerCaseThetaSetOperationsTest.java b/src/test/java/org/apache/datasketches/theta/CornerCaseThetaSetOperationsTest.java deleted file mode 100644 index 29fba0ec9..000000000 --- a/src/test/java/org/apache/datasketches/theta/CornerCaseThetaSetOperationsTest.java +++ /dev/null @@ -1,518 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import org.testng.annotations.Test; -//import static org.apache.datasketches.Util.DEFAULT_UPDATE_SEED; -//import static org.apache.datasketches.hash.MurmurHash3.hash; - -public class CornerCaseThetaSetOperationsTest { - - /* Hash Values - * 9223372036854775807 Theta = 1.0 - * - * 6730918654704304314 hash(3L)[0] >>> 1 GT_MIDP - * 4611686018427387904 Theta for p = 0.5f = MIDP - * - * 1206007004353599230 hash(6L)[0] >>> 1 GT_LOWP_V - * 922337217429372928 Theta for p = 0.1f = LOWP - * 593872385995628096 hash(4L)[0] >>> 1 LT_LOWP_V - */ - - private static final long GT_MIDP_V = 3L; - private static final float MIDP = 0.5f; - - private static final long GT_LOWP_V = 6L; - private static final float LOWP = 0.1f; - private static final long LT_LOWP_V = 4L; - - private static final double LOWP_THETA = LOWP; - - private enum SkType { - EMPTY, // { 1.0, 0, T} Bin: 101 Oct: 05 - EXACT, // { 1.0, >0, F} Bin: 110 Oct: 06, specify only value - ESTIMATION, // {<1.0, >0, F} Bin: 010 Oct: 02, specify only value - DEGENERATE // {<1.0, 0, F} Bin: 000 Oct: 0, specify p, value - } - - //================================= - - @Test - public void emptyEmpty() { - UpdatableThetaSketch thetaA = getSketch(SkType.EMPTY, 0, 0); - UpdatableThetaSketch thetaB = getSketch(SkType.EMPTY, 0, 0); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = 1.0; - final int expectedUnionCount = 0; - final boolean expectedUnionEmpty = true; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void emptyExact() { - UpdatableThetaSketch thetaA = getSketch(SkType.EMPTY, 0, 0); - UpdatableThetaSketch thetaB = getSketch(SkType.EXACT, 0, GT_MIDP_V); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = 1.0; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void emptyDegenerate() { - UpdatableThetaSketch thetaA = getSketch(SkType.EMPTY, 0, 0); - UpdatableThetaSketch thetaB = getSketch(SkType.DEGENERATE, LOWP, GT_LOWP_V); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = LOWP; - final int expectedUnionCount = 0; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void emptyEstimation() { - UpdatableThetaSketch thetaA = getSketch(SkType.EMPTY, 0, 0); - UpdatableThetaSketch thetaB = getSketch(SkType.ESTIMATION, LOWP, LT_LOWP_V); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = LOWP; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - //================================= - - @Test - public void exactEmpty() { - UpdatableThetaSketch thetaA = getSketch(SkType.EXACT, 0, GT_MIDP_V); - UpdatableThetaSketch thetaB = getSketch(SkType.EMPTY, 0, 0); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 1; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = 1.0; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void exactExact() { - UpdatableThetaSketch thetaA = getSketch(SkType.EXACT, 0, GT_MIDP_V); - UpdatableThetaSketch thetaB = getSketch(SkType.EXACT, 0, GT_MIDP_V); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 1; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = 1.0; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void exactDegenerate() { - UpdatableThetaSketch thetaA = getSketch(SkType.EXACT, 0, LT_LOWP_V); - UpdatableThetaSketch thetaB = getSketch(SkType.DEGENERATE, LOWP, GT_LOWP_V); //entries = 0 - final double expectedIntersectTheta = LOWP_THETA; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_THETA; - final int expectedAnotbCount = 1; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void exactEstimation() { - UpdatableThetaSketch thetaA = getSketch(SkType.EXACT, 0, LT_LOWP_V); - UpdatableThetaSketch thetaB = getSketch(SkType.ESTIMATION, LOWP, LT_LOWP_V); - final double expectedIntersectTheta = LOWP_THETA; - final int expectedIntersectCount = 1; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_THETA; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - //================================= - - @Test - public void estimationEmpty() { - UpdatableThetaSketch thetaA = getSketch(SkType.ESTIMATION, LOWP, LT_LOWP_V); - UpdatableThetaSketch thetaB = getSketch(SkType.EMPTY, 0, 0); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = LOWP_THETA; - final int expectedAnotbCount = 1; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void estimationExact() { - UpdatableThetaSketch thetaA = getSketch(SkType.ESTIMATION, LOWP, LT_LOWP_V); - UpdatableThetaSketch thetaB = getSketch(SkType.EXACT, 0, LT_LOWP_V); - final double expectedIntersectTheta = LOWP_THETA; - final int expectedIntersectCount = 1; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_THETA; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void estimationDegenerate() { - UpdatableThetaSketch thetaA = getSketch(SkType.ESTIMATION, MIDP, LT_LOWP_V); - UpdatableThetaSketch thetaB = getSketch(SkType.DEGENERATE, LOWP, GT_LOWP_V); - final double expectedIntersectTheta = LOWP_THETA; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_THETA; - final int expectedAnotbCount = 1; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void estimationEstimation() { - UpdatableThetaSketch thetaA = getSketch(SkType.ESTIMATION, MIDP, LT_LOWP_V); - UpdatableThetaSketch thetaB = getSketch(SkType.ESTIMATION, LOWP, LT_LOWP_V); - final double expectedIntersectTheta = LOWP_THETA; - final int expectedIntersectCount = 1; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_THETA; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - //================================= - - @Test - public void degenerateEmpty() { - UpdatableThetaSketch thetaA = getSketch(SkType.DEGENERATE, LOWP, GT_LOWP_V); //entries = 0 - UpdatableThetaSketch thetaB = getSketch(SkType.EMPTY, 0, 0); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = LOWP_THETA; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP; - final int expectedUnionCount = 0; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void degenerateExact() { - UpdatableThetaSketch thetaA = getSketch(SkType.DEGENERATE, LOWP, GT_LOWP_V); //entries = 0 - UpdatableThetaSketch thetaB = getSketch(SkType.EXACT, 0, LT_LOWP_V); - final double expectedIntersectTheta = LOWP_THETA; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_THETA; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void degenerateDegenerate() { - UpdatableThetaSketch thetaA = getSketch(SkType.DEGENERATE, MIDP, GT_MIDP_V); //entries = 0 - UpdatableThetaSketch thetaB = getSketch(SkType.DEGENERATE, LOWP, GT_LOWP_V); - final double expectedIntersectTheta = LOWP_THETA; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_THETA; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP; - final int expectedUnionCount = 0; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void degenerateEstimation() { - UpdatableThetaSketch thetaA = getSketch(SkType.DEGENERATE, MIDP, GT_MIDP_V); //entries = 0 - UpdatableThetaSketch thetaB = getSketch(SkType.ESTIMATION, LOWP, LT_LOWP_V); - final double expectedIntersectTheta = LOWP_THETA; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_THETA; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - //================================= - //================================= - - private static void checks( - UpdatableThetaSketch thetaA, - UpdatableThetaSketch thetaB, - double expectedIntersectTheta, - int expectedIntersectCount, - boolean expectedIntersectEmpty, - double expectedAnotbTheta, - int expectedAnotbCount, - boolean expectedAnotbEmpty, - double expectedUnionTheta, - int expectedUnionCount, - boolean expectedUnionEmpty) { - CompactThetaSketch csk; - ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(); - ThetaAnotB anotb = ThetaSetOperation.builder().buildANotB(); - ThetaUnion union = new ThetaSetOperationBuilder().buildUnion(); - - //ThetaIntersection Stateless Theta, Theta Updatable - csk = inter.intersect(thetaA, thetaB); - checkResult("ThetaIntersect Stateless Theta, Theta", csk, expectedIntersectTheta, expectedIntersectCount, - expectedIntersectEmpty); - //ThetaIntersection Stateless Theta, Theta Compact - csk = inter.intersect(thetaA.compact(), thetaB.compact()); - checkResult("ThetaIntersect Stateless Theta, Theta", csk, expectedIntersectTheta, expectedIntersectCount, - expectedIntersectEmpty); - - //ThetaAnotB Stateless Theta, Theta Updatable - csk = anotb.aNotB(thetaA, thetaB); - checkResult("ThetaAnotB Stateless Theta, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - //ThetaAnotB Stateless Theta, Theta Compact - csk = anotb.aNotB(thetaA.compact(), thetaB.compact()); - checkResult("ThetaAnotB Stateless Theta, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - - //ThetaAnotB Stateful Theta, Theta Updatable - anotb.setA(thetaA); - anotb.notB(thetaB); - csk = anotb.getResult(true); - checkResult("ThetaAnotB Stateful Theta, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - //ThetaAnotB Stateful Theta, Theta Compact - anotb.setA(thetaA.compact()); - anotb.notB(thetaB.compact()); - csk = anotb.getResult(true); - checkResult("ThetaAnotB Stateful Theta, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - - //ThetaUnion Stateful Theta, Theta Updatable - union.union(thetaA); - union.union(thetaB); - csk = union.getResult(); - union.reset(); - checkResult("ThetaUnion Stateless Theta, Theta", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - //ThetaUnion Stateful Theta, Theta Compact - union.union(thetaA.compact()); - union.union(thetaB.compact()); - csk = union.getResult(); - union.reset(); - checkResult("ThetaUnion Stateless Theta, Theta", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - - } - - private static void checkResult( - String comment, - CompactThetaSketch csk, - double expectedTheta, - int expectedEntries, - boolean expectedEmpty) { - double actualTheta = csk.getTheta(); - int actualEntries = csk.getRetainedEntries(); - boolean actualEmpty = csk.isEmpty(); - - boolean thetaOk = actualTheta == expectedTheta; - boolean entriesOk = actualEntries == expectedEntries; - boolean emptyOk = actualEmpty == expectedEmpty; - if (!thetaOk || !entriesOk || !emptyOk) { - StringBuilder sb = new StringBuilder(); - sb.append(comment + ": "); - if (!thetaOk) { sb.append("Theta: expected " + expectedTheta + ", got " + actualTheta + "; "); } - if (!entriesOk) { sb.append("Entries: expected " + expectedEntries + ", got " + actualEntries + "; "); } - if (!emptyOk) { sb.append("Empty: expected " + expectedEmpty + ", got " + actualEmpty + "."); } - throw new IllegalArgumentException(sb.toString()); - } - } - - private static UpdatableThetaSketch getSketch(SkType skType, float p, long value) { - UpdatableThetaSketchBuilder bldr = UpdatableThetaSketch.builder(); - bldr.setLogNominalEntries(4); - UpdatableThetaSketch sk; - switch(skType) { - case EMPTY: { // { 1.0, 0, T} p and value are not used - sk = bldr.build(); - break; - } - case EXACT: { // { 1.0, >0, F} p is not used - sk = bldr.build(); - sk.update(value); - break; - } - case ESTIMATION: { // {<1.0, >0, F} - bldr.setP(p); - sk = bldr.build(); - sk.update(value); - break; - } - case DEGENERATE: { // {<1.0, 0, F} - bldr.setP(p); - sk = bldr.build(); - sk.update(value); - break; - } - - default: { return null; } // should not happen - } - return sk; - } - -// private static void println(Object o) { -// System.out.println(o.toString()); -// } -// -// @Test -// public void printHash() { -// long seed = DEFAULT_UPDATE_SEED; -// long v = 6; -// long hash = (hash(v, seed)[0]) >>> 1; -// println(v + ", " + hash); -// } -// -// @Test -// public void printPAsLong() { -// float p = 0.5f; -// println("p = " + p + ", " + (long)(Long.MAX_VALUE * p)); -// } - -} diff --git a/src/test/java/org/apache/datasketches/theta/DirectIntersectionTest.java b/src/test/java/org/apache/datasketches/theta/DirectIntersectionTest.java deleted file mode 100644 index 34403c1d8..000000000 --- a/src/test/java/org/apache/datasketches/theta/DirectIntersectionTest.java +++ /dev/null @@ -1,766 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; -import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE; -import static org.apache.datasketches.theta.ThetaSetOperation.CONST_PREAMBLE_LONGS; -import static org.apache.datasketches.theta.ThetaSetOperation.getMaxIntersectionBytes; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesReadOnlyException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.common.Util; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class DirectIntersectionTest { - private static final int PREBYTES = CONST_PREAMBLE_LONGS << 3; //24 - - @Test - public void checkExactIntersectionNoOverlap() { - final int lgK = 9; - final int k = 1< k); - println("Est: "+est); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkOverflow() { - final int lgK = 9; //512 - final int k = 1< k); - println("Est: "+est); - - final byte[] byteArray = inter.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArray); - final ThetaIntersection inter2 = (ThetaIntersection) ThetaSetOperation.heapify(seg); - comp2 = inter2.getResult(false, null); - est2 = comp2.getEstimate(); - println("Est2: "+est2); - } - - /** - * This proves that the hash of 7 is < 0.5. This fact will be used in other tests involving P. - */ - @Test - public void checkPreject() { - final UpdatableThetaSketch sk = UpdatableThetaSketch.builder().setP((float) .5).build(); - sk.update(7); - assertEquals(sk.getRetainedEntries(), 0); - } - - @Test - public void checkWrapVirginEmpty() { - final int lgK = 5; - final int k = 1 << lgK; - ThetaIntersection inter1, inter2; - UpdatableThetaSketch sk1; - - final int segBytes = getMaxIntersectionBytes(k); - MemorySegment iSeg = MemorySegment.ofArray(new byte[segBytes]); - - inter1 = ThetaSetOperation.builder().buildIntersection(iSeg); //virgin off-heap - inter2 = ThetaIntersection.wrap(iSeg); //virgin off-heap, identical to inter1 - //both in virgin state, empty = false - //note: both inter1 and inter2 are tied to the same MemorySegment, - // so an intersect to one also affects the other. Don't do what I do! - assertFalse(inter1.hasResult()); - assertFalse(inter2.hasResult()); - - //This constructs a sketch with 0 entries and theta < 1.0 - sk1 = UpdatableThetaSketch.builder().setP((float) .5).setNominalEntries(k).build(); - sk1.update(7); //will be rejected by P, see proof above. - - //A virgin intersection (empty = false) intersected with a not-empty zero cache sketch - //remains empty = false! - inter1.intersect(sk1); - assertFalse(inter1.isEmpty()); - assertTrue(inter1.hasResult()); - //note that inter2 is not independent - assertFalse(inter2.isEmpty()); - assertTrue(inter2.hasResult()); - - //test the path via toByteArray, now in a different state - iSeg = MemorySegment.ofArray(inter1.toByteArray()); - inter2 = ThetaIntersection.wrap(iSeg); - assertTrue(inter2.hasResult()); //still true - - //test the compaction path - final CompactThetaSketch comp = inter2.getResult(true, null); - assertEquals(comp.getRetainedEntries(false), 0); - assertFalse(comp.isEmpty()); - } - - @Test - public void checkWrapNullEmpty2() { - final int lgK = 5; - final int k = 1< k); - println("Est: "+est); - - final byte[] segArr3 = inter2.toByteArray(); - final MemorySegment srcSeg2 = MemorySegment.ofArray(segArr3); - inter3 = ThetaIntersection.wrap(srcSeg2); - resultComp2 = inter3.getResult(false, null); - est2 = resultComp2.getEstimate(); - println("Est2: "+est2); - - inter.reset(); - inter2.reset(); - inter3.reset(); - } - - @Test - public void checkDefaultMinSize() { - final int k = 32; - final MemorySegment seg = MemorySegment.ofArray(new byte[k*8 + PREBYTES]); - ThetaIntersectionImpl.initNewDirectInstance(Util.DEFAULT_UPDATE_SEED, seg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkExceptionMinSize() { - final int k = 16; - final MemorySegment seg = MemorySegment.ofArray(new byte[k*8 + PREBYTES]); - ThetaIntersectionImpl.initNewDirectInstance(Util.DEFAULT_UPDATE_SEED, seg); - } - - @Test - public void checkGetResult() { - final int k = 1024; - final UpdatableThetaSketch sk = UpdatableThetaSketch.builder().build(); - - final int segBytes = getMaxIntersectionBytes(k); - final byte[] segArr = new byte[segBytes]; - final MemorySegment iSeg = MemorySegment.ofArray(segArr); - - final ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(iSeg); - inter.intersect(sk); - final CompactThetaSketch csk = inter.getResult(); - assertEquals(csk.getCompactBytes(), 8); - } - - @Test - public void checkFamily() { - //cheap trick - final int k = 16; - final MemorySegment seg = MemorySegment.ofArray(new byte[k*16 + PREBYTES]); - final ThetaIntersectionImpl impl = ThetaIntersectionImpl.initNewDirectInstance(Util.DEFAULT_UPDATE_SEED, seg); - assertEquals(impl.getFamily(), Family.INTERSECTION); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkExceptions1() { - final int k = 16; - final MemorySegment seg = MemorySegment.ofArray(new byte[k*16 + PREBYTES]); - ThetaIntersectionImpl.initNewDirectInstance(Util.DEFAULT_UPDATE_SEED, seg); - //corrupt SerVer - seg.set(JAVA_BYTE, PreambleUtil.SER_VER_BYTE, (byte) 2); - ThetaIntersectionImpl.wrapInstance(seg, Util.DEFAULT_UPDATE_SEED, false); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkExceptions2() { - final int k = 16; - final MemorySegment seg = MemorySegment.ofArray(new byte[k*16 + PREBYTES]); - ThetaIntersectionImpl.initNewDirectInstance(Util.DEFAULT_UPDATE_SEED, seg); - //seg now has non-empty intersection - //corrupt empty and CurCount - Util.setBits(seg, PreambleUtil.FLAGS_BYTE, (byte) PreambleUtil.EMPTY_FLAG_MASK); - seg.set(JAVA_INT_UNALIGNED, PreambleUtil.RETAINED_ENTRIES_INT, 2); - ThetaIntersectionImpl.wrapInstance(seg, Util.DEFAULT_UPDATE_SEED, false); - } - - //Check Alex's bug intersecting 2 direct full sketches with only overlap of 2 - // - @Test - public void checkOverlappedDirect() { - final int k = 1 << 4; - final int segBytes = 2*k*16 +PREBYTES; //plenty of room - final UpdatableThetaSketch sk1 = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - final UpdatableThetaSketch sk2 = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - for (int i=0; i k); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Test - public void checkSamplingMode() { - final int k = 4096; - final float p = (float)0.5; - - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = makeNativeMemorySegment(k, arena); - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setP(p).setNominalEntries(k).build(wseg); - final DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks - - for (int i = 0; i < k; i++ ) { usk.update(i); } - - final double p2 = sk1.getP(); - final double theta = sk1.getTheta(); - assertTrue(theta <= p2); - - final double est = usk.getEstimate(); - assertEquals(k, est, k *.05); - final double ub = usk.getUpperBound(1); - assertTrue(ub > est); - final double lb = usk.getLowerBound(1); - assertTrue(lb < est); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Test - public void checkErrorBounds() { - final int k = 512; - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = makeNativeMemorySegment(k, arena); - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setNominalEntries(k).build(wseg); - - //Exact mode - for (int i = 0; i < k; i++ ) { usk.update(i); } - - double est = usk.getEstimate(); - double lb = usk.getLowerBound(2); - double ub = usk.getUpperBound(2); - assertEquals(est, ub, 0.0); - assertEquals(est, lb, 0.0); - - //Est mode - final int u = 100*k; - for (int i = k; i < u; i++ ) { - usk.update(i); - usk.update(i); //test duplicate rejection - } - est = usk.getEstimate(); - lb = usk.getLowerBound(2); - ub = usk.getUpperBound(2); - assertTrue(est <= ub); - assertTrue(est >= lb); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - //Empty Tests - @Test - public void checkEmptyAndP() { - //virgin, p = 1.0 - final int k = 1024; - float p = (float)1.0; - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = makeNativeMemorySegment(k, arena); - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setP(p).setNominalEntries(k).build(wseg); - DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks - - assertTrue(usk.isEmpty()); - usk.update(1); - assertEquals(sk1.getRetainedEntries(true), 1); - assertFalse(usk.isEmpty()); - - //virgin, p = .001 - p = (float)0.001; - final byte[] segArr2 = new byte[(int) wseg.byteSize()]; - final MemorySegment seg2 = MemorySegment.ofArray(segArr2); - final UpdatableThetaSketch usk2 = UpdatableThetaSketch.builder().setP(p).setNominalEntries(k).build(seg2); - sk1 = (DirectQuickSelectSketch)usk2; - - assertTrue(usk2.isEmpty()); - usk2.update(1); //will be rejected - assertEquals(sk1.getRetainedEntries(true), 0); - assertFalse(usk2.isEmpty()); - final double est = usk2.getEstimate(); - //println("Est: "+est); - assertEquals(est, 0.0, 0.0); //because curCount = 0 - final double ub = usk2.getUpperBound(2); //huge because theta is tiny! - //println("UB: "+ub); - assertTrue(ub > 0.0); - final double lb = usk2.getLowerBound(2); - assertTrue(lb <= est); - //println("LB: "+lb); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Test - public void checkUpperAndLowerBounds() { - final int k = 512; - final int u = 2*k; - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = makeNativeMemorySegment(k, arena); - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setNominalEntries(k).build(wseg); - - for (int i = 0; i < u; i++ ) { usk.update(i); } - - final double est = usk.getEstimate(); - final double ub = usk.getUpperBound(1); - final double lb = usk.getLowerBound(1); - assertTrue(ub > est); - assertTrue(lb < est); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Test - public void checkRebuild() { - final int k = 512; - final int u = 4*k; - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = makeNativeMemorySegment(k, arena); - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setNominalEntries(k).build(wseg); - final DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks - - assertTrue(usk.isEmpty()); - - for (int i = 0; i< u; i++) { usk.update(i); } - - assertFalse(usk.isEmpty()); - assertTrue(usk.getEstimate() > 0.0); - assertTrue(sk1.getRetainedEntries(false) > k); - - sk1.rebuild(); - assertEquals(sk1.getRetainedEntries(false), k); - assertEquals(sk1.getRetainedEntries(true), k); - sk1.rebuild(); - assertEquals(sk1.getRetainedEntries(false), k); - assertEquals(sk1.getRetainedEntries(true), k); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Test - public void checkResetAndStartingSubMultiple() { - final int k = 512; - final int u = 4*k; - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = makeNativeMemorySegment(k, arena); - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setNominalEntries(k).build(wseg); - final DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks - - assertTrue(usk.isEmpty()); - - for (int i = 0; i< u; i++) { usk.update(i); } - - assertFalse(usk.isEmpty()); - assertTrue(sk1.getRetainedEntries(false) > k); - assertTrue(sk1.getThetaLong() < Long.MAX_VALUE); - - sk1.reset(); - assertTrue(usk.isEmpty()); - assertEquals(sk1.getRetainedEntries(false), 0); - assertEquals(usk.getEstimate(), 0.0, 0.0); - assertEquals(sk1.getThetaLong(), Long.MAX_VALUE); - - assertNotNull(sk1.getMemorySegment()); - assertFalse(sk1.isOrdered()); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Test - public void checkExactModeMemorySegmentArr() { - final int k = 4096; - final int u = 4096; - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = makeNativeMemorySegment(k, arena); - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setNominalEntries(k).build(wseg); - final DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks - assertTrue(usk.isEmpty()); - - for (int i = 0; i< u; i++) { usk.update(i); } - - assertEquals(usk.getEstimate(), u, 0.0); - assertEquals(sk1.getRetainedEntries(false), u); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Test - public void checkEstModeMemorySegmentArr() { - final int k = 4096; - final int u = 2*k; - - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = makeNativeMemorySegment(k, arena); - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setNominalEntries(k).build(wseg); - final DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks - assertTrue(usk.isEmpty()); - - for (int i = 0; i< u; i++) { usk.update(i); } - - assertEquals(usk.getEstimate(), u, u*.05); - assertTrue(sk1.getRetainedEntries(false) > k); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Test - public void checkEstModeNativeMemorySegment() { - final int k = 4096; - final int u = 2*k; - final int segCapacity = (k << 4) + (Family.QUICKSELECT.getMinPreLongs() << 3); - - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = makeNativeMemorySegment(segCapacity, arena); - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setNominalEntries(k).build(wseg); - final DirectQuickSelectSketch sk1 = (DirectQuickSelectSketch)usk; //for internal checks - assertTrue(usk.isEmpty()); - - for (int i = 0; i< u; i++) { usk.update(i); } - final double est = usk.getEstimate(); - println(""+est); - assertEquals(usk.getEstimate(), u, u*.05); - assertTrue(sk1.getRetainedEntries(false) > k); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Test - public void checkConstructReconstructFromMemorySegment() { - final int k = 4096; - final int u = 2*k; - try (Arena arena = Arena.ofConfined()) { - final MemorySegment wseg = makeNativeMemorySegment(k, arena); - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setNominalEntries(k).build(wseg); - assertTrue(usk.isEmpty()); - - for (int i = 0; i< u; i++) { usk.update(i); } //force estimation - - final double est1 = usk.getEstimate(); - final int count1 = usk.getRetainedEntries(false); - assertEquals(est1, u, u*.05); - assertTrue(count1 >= k); - - byte[] serArr; - double est2; - int count2; - - serArr = usk.toByteArray(); - - final MemorySegment seg2 = MemorySegment.ofArray(serArr); - - //reconstruct to Native/Direct - final UpdatableThetaSketch usk2 = UpdatableThetaSketch.wrap(seg2); - - est2 = usk2.getEstimate(); - count2 = usk2.getRetainedEntries(false); - - assertEquals(count2, count1); - assertEquals(est2, est1, 0.0); - } catch (final Exception e) { - throw new RuntimeException(e); - } - } - - @Test(expectedExceptions = SketchesReadOnlyException.class) - public void updateAfterReadOnlyWrap() { - final UpdatableThetaSketch usk1 = UpdatableThetaSketch.builder().build(); - final UpdatableThetaSketch usk2 = (UpdatableThetaSketch) ThetaSketch.wrap(MemorySegment.ofArray(usk1.toByteArray())); - usk2.update(0); - } - - public void updateAfterWritableWrap() { - final UpdatableThetaSketch usk1 = UpdatableThetaSketch.builder().build(); - final UpdatableThetaSketch usk2 = UpdatableThetaSketch.wrap(MemorySegment.ofArray(usk1.toByteArray())); - usk2.update(0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkNegativeHashes() { - final int k = 512; - final UpdatableThetaSketch qs = UpdatableThetaSketch.builder().setFamily(QUICKSELECT).setNominalEntries(k).build(); - qs.hashUpdate(-1L); - } - - @Test - public void checkConstructorSrcSegCorruptions() { - final int k = 1024; //lgNomLongs = 10 - final int u = k; //exact mode, lgArrLongs = 11 - - final int bytes = ThetaSketch.getMaxUpdateSketchBytes(k); - final byte[] arr1 = new byte[bytes]; - final MemorySegment seg1 = MemorySegment.ofArray(arr1); - final ResizeFactor rf = ResizeFactor.X1; //0 - final UpdatableThetaSketch usk1 = UpdatableThetaSketch.builder().setNominalEntries(k).setResizeFactor(rf).build(seg1); - for (int i=0; i>> 1); //corrupt theta and - seg1.set(JAVA_BYTE, LG_ARR_LONGS_BYTE, (byte) 10); //corrupt lgArrLongs - try { - usk2 = DirectQuickSelectSketch.writableWrap(seg1, null, Util.DEFAULT_UPDATE_SEED); - fail("Expected SketchesArgumentException"); - } catch (final SketchesArgumentException e) { - //pass - } - seg1.set(JAVA_LONG_UNALIGNED, THETA_LONG, Long.MAX_VALUE); //fix theta and - seg1.set(JAVA_BYTE, LG_ARR_LONGS_BYTE, (byte) 11); //fix lgArrLongs - final byte badFlags = (byte) (COMPACT_FLAG_MASK | READ_ONLY_FLAG_MASK | ORDERED_FLAG_MASK); - seg1.set(JAVA_BYTE, FLAGS_BYTE, badFlags); - try { - usk2 = DirectQuickSelectSketch.writableWrap(seg1, null, Util.DEFAULT_UPDATE_SEED); - fail("Expected SketchesArgumentException"); - } catch (final SketchesArgumentException e) { - //pass - } - - final byte[] arr2 = Arrays.copyOfRange(arr1, 0, bytes-1); //corrupt length - final MemorySegment seg2 = MemorySegment.ofArray(arr2); - try { - usk2 = DirectQuickSelectSketch.writableWrap(seg2, null, Util.DEFAULT_UPDATE_SEED); - fail("Expected SketchesArgumentException"); - } catch (final SketchesArgumentException e) { - //pass - } - } - - @Test - public void checkCorruptRFWithInsufficientArray() { - final int k = 1024; //lgNomLongs = 10 - - final int bytes = ThetaSketch.getMaxUpdateSketchBytes(k); - final byte[] arr = new byte[bytes]; - final MemorySegment seg = MemorySegment.ofArray(arr); - final ResizeFactor rf = ResizeFactor.X8; // 3 - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setNominalEntries(k).setResizeFactor(rf).build(seg); - usk.update(0); - - insertLgResizeFactor(seg, 0); // corrupt RF: X1 - final UpdatableThetaSketch dqss = DirectQuickSelectSketch.writableWrap(seg, null, Util.DEFAULT_UPDATE_SEED); - assertEquals(dqss.getResizeFactor(), ResizeFactor.X2); // force-promote to X2 - } - - @Test - public void checkFamilyAndRF() { - final int k = 16; - final MemorySegment seg = MemorySegment.ofArray(new byte[k*16 + 24]); - final UpdatableThetaSketch sketch = UpdatableThetaSketch.builder().setNominalEntries(k).build(seg); - assertEquals(sketch.getFamily(), Family.QUICKSELECT); - assertEquals(sketch.getResizeFactor(), ResizeFactor.X8); - } - - //checks Alex's bug where lgArrLongs > lgNomLongs +1. - @Test - public void checkResizeInBigSeg() { - final int k = 1 << 14; - final int u = 1 << 20; - final MemorySegment seg = MemorySegment.ofArray(new byte[8*k*16 +24]); - final UpdatableThetaSketch sketch = UpdatableThetaSketch.builder().setNominalEntries(k).build(seg); - for (int i=0; i 98663.0); - assertTrue(est < 101530.0); - } - - @Test - public void checkForDruidBug2() { //update union with just sketch segment reference - final int k = 16384; - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - for (int i = 0; i < 100000; i++) { - usk.update(Integer.toString(i)); - } - usk.rebuild(); //optional but created the symptom - final MemorySegment segIn = MemorySegment.ofArray(new byte[usk.getCompactBytes()]); - usk.compact(true, segIn); //side effect of loading the segIn - - //create empty target union in off-heap segment - final MemorySegment seg = MemorySegment.ofArray(new byte[getMaxUnionBytes(k)]); - final ThetaUnion union1 = ThetaSetOperation.builder().setNominalEntries(k).buildUnion(seg); - - union1.union(segIn); - - final CompactThetaSketch csk = union1.getResult(); - - assertTrue(csk.getTheta() < 0.2); - assertEquals(csk.getRetainedEntries(true), 16384); - final double est = csk.getEstimate(); - assertTrue(est > 98663.0); - assertTrue(est < 101530.0); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //Disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/EmptyTest.java b/src/test/java/org/apache/datasketches/theta/EmptyTest.java deleted file mode 100644 index fec264b26..000000000 --- a/src/test/java/org/apache/datasketches/theta/EmptyTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -/** - * Empty essentially means that the sketch has never seen data. - * - * @author Lee Rhodes - */ -public class EmptyTest { - - @Test - public void checkEmpty() { - final UpdatableThetaSketch sk1 = UpdatableThetaSketch.builder().build(); - final UpdatableThetaSketch sk2 = UpdatableThetaSketch.builder().build(); - final ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(); - - final int u = 100; - for (int i = 0; i < u; i++) { //disjoint - sk1.update(i); - sk2.update(i + u); - } - inter.intersect(sk1); - inter.intersect(sk2); - - final CompactThetaSketch csk = inter.getResult(); - //The intersection of two disjoint, exact-mode sketches is empty, T == 1.0. - println(csk.toString()); - assertTrue(csk.isEmpty()); - - final ThetaAnotB aNotB = ThetaSetOperation.builder().buildANotB(); - final CompactThetaSketch csk2 = aNotB.aNotB(csk, sk1); - //The ThetaAnotB of an empty, T == 1.0 sketch with another exact-mode sketch is empty, T == 1.0 - assertTrue(csk2.isEmpty()); - } - - @Test - public void checkNotEmpty() { - final UpdatableThetaSketch sk1 = UpdatableThetaSketch.builder().build(); - final UpdatableThetaSketch sk2 = UpdatableThetaSketch.builder().build(); - final ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(); - - final int u = 10000; //estimating - for (int i = 0; i < u; i++) { //disjoint - sk1.update(i); - sk2.update(i + u); - } - inter.intersect(sk1); - inter.intersect(sk2); - - final CompactThetaSketch csk = inter.getResult(); - println(csk.toString()); - //The intersection of two disjoint, est-mode sketches is not-empty, T < 1.0. - assertFalse(csk.isEmpty()); - - ThetaAnotB aNotB = ThetaSetOperation.builder().buildANotB(); - final CompactThetaSketch csk2 = aNotB.aNotB(csk, sk1); //empty, T < 1.0; with est-mode sketch - println(csk2.toString()); - //The ThetaAnotB of an empty, T < 1.0 sketch with another exact-mode sketch is not-empty. - assertFalse(csk2.isEmpty()); - - final UpdatableThetaSketch sk3 = UpdatableThetaSketch.builder().build(); - aNotB = ThetaSetOperation.builder().buildANotB(); - final CompactThetaSketch csk3 = aNotB.aNotB(sk3, sk1); //empty, T == 1.0; with est-mode sketch - println(csk3.toString()); - //the ThetaAnotB of an empty, T == 1.0 sketch with another est-mode sketch is empty, T < 1.0 - assertTrue(csk3.isEmpty()); - } - - @Test - public void checkPsampling() { - final UpdatableThetaSketch sk1 = UpdatableThetaSketch.builder().setP(.5F).build(); - assertTrue(sk1.isEmpty()); - //An empty P-sampling sketch where T < 1.0 and has never seen data is also empty - // and will have a full preamble of 24 bytes. But when compacted, theta returns to 1.0, so - // it will be stored as only 8 bytes. - assertEquals(sk1.compact().toByteArray().length, 8); - } - - @Test - public void checkEmptyToCompact() { - final UpdatableThetaSketch sk1 = UpdatableThetaSketch.builder().build(); - final CompactThetaSketch csk = sk1.compact(); - assertTrue(csk instanceof EmptyCompactSketch); - final CompactThetaSketch csk2 = csk.compact(); - assertTrue(csk2 instanceof EmptyCompactSketch); - final CompactThetaSketch csk3 = csk.compact(true, MemorySegment.ofArray(new byte[8])); - assertTrue(csk3 instanceof DirectCompactSketch); - assertEquals(csk2.getCurrentPreambleLongs(), 1); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/ExamplesTest.java b/src/test/java/org/apache/datasketches/theta/ExamplesTest.java deleted file mode 100644 index f621e8448..000000000 --- a/src/test/java/org/apache/datasketches/theta/ExamplesTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class ExamplesTest { - - @Test - public void simpleCountingSketch() { - final int k = 4096; - final int u = 1000000; - - final UpdatableThetaSketch sketch = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - for (int i = 0; i < u; i++) { - sketch.update(i); - } - - println(sketch.toString()); - } - /* -### HeapQuickSelectSketch SUMMARY: - Nominal Entries (k) : 4096 - Estimate : 1002714.745231455 - Upper Bound, 95% conf : 1027777.3354974985 - Lower Bound, 95% conf : 978261.4472857157 - p : 1.0 - Theta (double) : 0.00654223948655085 - Theta (long) : 60341508738660257 - Theta (long, hex : 00d66048519437a1 - EstMode? : true - Empty? : false - Resize Factor : 8 - Array Size Entries : 8192 - Retained Entries : 6560 - Update Seed : 9001 - Seed Hash : ffff93cc -### END SKETCH SUMMARY - */ - - @Test - public void theta2dot0Examples() { - //Load source sketches - final UpdatableThetaSketchBuilder bldr = UpdatableThetaSketch.builder(); - final UpdatableThetaSketch skA = bldr.build(); - final UpdatableThetaSketch skB = bldr.build(); - for (int i = 1; i <= 1000; i++) { - skA.update(i); - skB.update(i + 250); - } - - //ThetaUnion Stateless: - ThetaUnion union = ThetaSetOperation.builder().buildUnion(); - CompactThetaSketch csk = union.union(skA, skB); - assert csk.getEstimate() == 1250; - - //ThetaUnion Stateful: - union = ThetaSetOperation.builder().buildUnion(); - union.union(skA); //first call - union.union(skB); //2nd through nth calls - //... - csk = union.getResult(); - assert csk.getEstimate() == 1250; - - //ThetaIntersection Stateless: - ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(); - csk = inter.intersect(skA, skB); - assert csk.getEstimate() == 750; - - //ThetaIntersection Stateful: - inter = ThetaSetOperation.builder().buildIntersection(); - inter.intersect(skA); //first call - inter.intersect(skB); //2nd through nth calls - //... - csk = inter.getResult(); - assert csk.getEstimate() == 750; - - //ThetaAnotB Stateless: - ThetaAnotB diff = ThetaSetOperation.builder().buildANotB(); - csk = diff.aNotB(skA, skB); - assert csk.getEstimate() == 250; - - //ThetaAnotB Stateful: - diff = ThetaSetOperation.builder().buildANotB(); - diff.setA(skA); //first call - diff.notB(skB); //2nd through nth calls - //... - csk = diff.getResult(true); - assert csk.getEstimate() == 250; - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //enable/disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/HeapAlphaSketchTest.java b/src/test/java/org/apache/datasketches/theta/HeapAlphaSketchTest.java deleted file mode 100644 index 08a833b2d..000000000 --- a/src/test/java/org/apache/datasketches/theta/HeapAlphaSketchTest.java +++ /dev/null @@ -1,697 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.common.Family.ALPHA; -import static org.apache.datasketches.common.ResizeFactor.X1; -import static org.apache.datasketches.common.ResizeFactor.X2; -import static org.apache.datasketches.common.ResizeFactor.X8; -import static org.apache.datasketches.common.Util.clear; -import static org.apache.datasketches.theta.PreambleUtil.FAMILY_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.FLAGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.LG_NOM_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.PREAMBLE_LONGS_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE; -import static org.apache.datasketches.theta.PreambleUtil.THETA_LONG; -import static org.apache.datasketches.theta.PreambleUtil.insertLgResizeFactor; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.ThetaUtil; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class HeapAlphaSketchTest { - private Family fam_ = ALPHA; - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadSerVer() { - int k = 512; - int u = k; - long seed = Util.DEFAULT_UPDATE_SEED; - UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setSeed(seed) - .setNominalEntries(k).build(); - HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks - - assertTrue(usk.isEmpty()); - - for (int i = 0; i< u; i++) { - sk1.update(i); - } - - assertFalse(usk.isEmpty()); - assertEquals(usk.getEstimate(), u, 0.0); - assertEquals(sk1.getRetainedEntries(false), u); - - byte[] byteArray = usk.toByteArray(); - MemorySegment seg = MemorySegment.ofArray(byteArray); - seg.set(JAVA_BYTE, SER_VER_BYTE, (byte) 0); //corrupt the SerVer byte - - ThetaSketch.heapify(seg, seed); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkConstructorKtooSmall() { - int k = 256; - UpdatableThetaSketch.builder().setFamily(fam_).setNominalEntries(k).build(); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkAlphaIncompatibleWithSeg() { - MemorySegment seg = MemorySegment.ofArray(new byte[(512*16)+24]); - UpdatableThetaSketch.builder().setFamily(Family.ALPHA).setNominalEntries(512).build(seg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkIllegalSketchID_UpdateSketch() { - int k = 512; - int u = k; - long seed = Util.DEFAULT_UPDATE_SEED; - UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setSeed(seed) - .setNominalEntries(k).build(); - HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks - assertTrue(usk.isEmpty()); - - for (int i = 0; i< u; i++) { - usk.update(i); - } - - assertFalse(usk.isEmpty()); - assertEquals(usk.getEstimate(), u, 0.0); - assertEquals(sk1.getRetainedEntries(false), u); - byte[] byteArray = usk.toByteArray(); - MemorySegment seg = MemorySegment.ofArray(byteArray); - seg.set(JAVA_BYTE, FAMILY_BYTE, (byte) 0); //corrupt the FamilyID byte - - //try to heapify the corrupted seg - ThetaSketch.heapify(seg, seed); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifySeedConflict() { - int k = 512; - long seed1 = 1021; - long seed2 = Util.DEFAULT_UPDATE_SEED; - UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setSeed(seed1) - .setNominalEntries(k).build(); - byte[] byteArray = usk.toByteArray(); - MemorySegment srcSeg = MemorySegment.ofArray(byteArray).asReadOnly(); - ThetaSketch.heapify(srcSeg, seed2); - } - - @Test - public void checkHeapifyByteArrayExact() { - int k = 512; - int u = k; - long seed = Util.DEFAULT_UPDATE_SEED; - UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setSeed(seed) - .setNominalEntries(k).build(); - - for (int i=0; i k); - } - - @Test - public void checkSamplingMode() { - int k = 4096; - int u = k; - float p = (float)0.5; - - UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setP(p) - .setNominalEntries(k).build(); - HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks - - for (int i = 0; i < u; i++ ) { - usk.update(i); - } - - double p2 = sk1.getP(); - double theta = sk1.getTheta(); - assertTrue(theta <= p2); - - double est = usk.getEstimate(); - double kdbl = k; - assertEquals(kdbl, est, kdbl*.05); - double ub = usk.getUpperBound(1); - assertTrue(ub > est); - double lb = usk.getLowerBound(1); - assertTrue(lb < est); - } - - @Test - public void checkErrorBounds() { - int k = 512; - - UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setResizeFactor(X1) - .setNominalEntries(k).build(); - - //Exact mode - for (int i = 0; i < k; i++ ) { - usk.update(i); - } - - double est = usk.getEstimate(); - double lb = usk.getLowerBound(2); - double ub = usk.getUpperBound(2); - assertEquals(est, ub, 0.0); - assertEquals(est, lb, 0.0); - - //Est mode - int u = 10*k; - for (int i = k; i < u; i++ ) { - usk.update(i); - usk.update(i); //test duplicate rejection - } - est = usk.getEstimate(); - lb = usk.getLowerBound(2); - ub = usk.getUpperBound(2); - assertTrue(est <= ub); - assertTrue(est >= lb); - } - - //Empty Tests - @Test - public void checkEmptyAndP() { - //virgin, p = 1.0 - int k = 1024; - - UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setNominalEntries(k).build(); - HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks - - assertTrue(usk.isEmpty()); - usk.update(1); - assertEquals(sk1.getRetainedEntries(true), 1); - assertFalse(usk.isEmpty()); - - //virgin, p = .001 - UpdatableThetaSketch usk2 = UpdatableThetaSketch.builder().setFamily(fam_).setP((float)0.001) - .setNominalEntries(k).build(); - sk1 = (HeapAlphaSketch)usk2; - assertTrue(usk2.isEmpty()); - usk2.update(1); //will be rejected - assertEquals(sk1.getRetainedEntries(true), 0); - assertFalse(usk2.isEmpty()); - double est = usk2.getEstimate(); - //println("Est: "+est); - assertEquals(est, 0.0, 0.0); //because curCount = 0 - double ub = usk2.getUpperBound(2); //huge because theta is tiny! - //println("UB: "+ub); - assertTrue(ub > 0.0); - double lb = usk2.getLowerBound(2); - assertTrue(lb <= est); - //println("LB: "+lb); - } - - @Test - public void checkUpperAndLowerBounds() { - int k = 512; - int u = 2*k; - - UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setResizeFactor(X2) - .setNominalEntries(k).build(); - - for (int i = 0; i < u; i++ ) { - usk.update(i); - } - - double est = usk.getEstimate(); - double ub = usk.getUpperBound(1); - double lb = usk.getLowerBound(1); - assertTrue(ub > est); - assertTrue(lb < est); - } - - @Test - public void checkRebuild() { - int k = 512; - int u = 4*k; - - UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setNominalEntries(k).build(); - HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks - - assertTrue(usk.isEmpty()); - - for (int i = 0; i< u; i++) { - usk.update(i); - } - - assertFalse(usk.isEmpty()); - assertTrue(usk.getEstimate() > 0.0); - assertNotEquals(sk1.getRetainedEntries(false), sk1.getRetainedEntries(true)); - - sk1.rebuild(); - assertEquals(sk1.getRetainedEntries(false), sk1.getRetainedEntries(true)); - sk1.rebuild(); - assertEquals(sk1.getRetainedEntries(false), sk1.getRetainedEntries(true)); - } - - @Test - public void checkResetAndStartingSubMultiple() { - int k = 1024; - int u = 4*k; - - UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setResizeFactor(X8) - .setNominalEntries(k).build(); - HeapAlphaSketch sk1 = (HeapAlphaSketch)usk; //for internal checks - - assertTrue(usk.isEmpty()); - - for (int i=0; i k); - println("Est: "+est); - } - - @Test - public void checkHeapifyAndWrap() { - final int lgK = 9; - final int k = 1< k); // in general it might be exactly k, but in this case must be greater - } - - @Test - public void checkSamplingMode() { - final int k = 4096; - final int u = k; - final float p = (float)0.5; - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setP(p).setNominalEntries(k).build(); - final HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks - - for (int i = 0; i < u; i++ ) { - usk.update(i); - } - - final double p2 = sk1.getP(); - final double theta = sk1.getTheta(); - assertTrue(theta <= p2); - - final double est = usk.getEstimate(); - final double kdbl = k; - assertEquals(kdbl, est, kdbl*.05); - final double ub = usk.getUpperBound(1); - assertTrue(ub > est); - final double lb = usk.getLowerBound(1); - assertTrue(lb < est); - } - - @Test - public void checkErrorBounds() { - final int k = 512; - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setResizeFactor(X1).setNominalEntries(k).build(); - - //Exact mode - for (int i = 0; i < k; i++ ) { - usk.update(i); - } - - double est = usk.getEstimate(); - double lb = usk.getLowerBound(2); - double ub = usk.getUpperBound(2); - assertEquals(est, ub, 0.0); - assertEquals(est, lb, 0.0); - - //Est mode - final int u = 10*k; - for (int i = k; i < u; i++ ) { - usk.update(i); - usk.update(i); //test duplicate rejection - } - est = usk.getEstimate(); - lb = usk.getLowerBound(2); - ub = usk.getUpperBound(2); - assertTrue(est <= ub); - assertTrue(est >= lb); - } - - //Empty Tests - @Test - public void checkEmptyAndP() { - //virgin, p = 1.0 - final int k = 1024; - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setNominalEntries(k).build(); - HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks - - assertTrue(usk.isEmpty()); - usk.update(1); - assertEquals(sk1.getRetainedEntries(true), 1); - assertFalse(usk.isEmpty()); - - //virgin, p = .001 - final UpdatableThetaSketch usk2 = UpdatableThetaSketch.builder().setFamily(fam_).setP((float)0.001).setNominalEntries(k).build(); - sk1 = (HeapQuickSelectSketch)usk2; - assertTrue(usk2.isEmpty()); - usk2.update(1); //will be rejected - assertEquals(sk1.getRetainedEntries(true), 0); - assertFalse(usk2.isEmpty()); - final double est = usk2.getEstimate(); - //println("Est: "+est); - assertEquals(est, 0.0, 0.0); //because curCount = 0 - final double ub = usk2.getUpperBound(2); //huge because theta is tiny! - //println("UB: "+ub); - assertTrue(ub > 0.0); - final double lb = usk2.getLowerBound(2); - assertTrue(lb <= est); - //println("LB: "+lb); - } - - @Test - public void checkUpperAndLowerBounds() { - final int k = 512; - final int u = 2*k; - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setResizeFactor(X2).setNominalEntries(k).build(); - - for (int i = 0; i < u; i++ ) { - usk.update(i); - } - - final double est = usk.getEstimate(); - final double ub = usk.getUpperBound(1); - final double lb = usk.getLowerBound(1); - assertTrue(ub > est); - assertTrue(lb < est); - } - - @Test - public void checkRebuild() { - final int k = 16; - final int u = 4*k; - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setNominalEntries(k).build(); - final HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks - - assertTrue(usk.isEmpty()); - - for (int i = 0; i< u; i++) { - usk.update(i); - } - - assertFalse(usk.isEmpty()); - assertTrue(usk.getEstimate() > 0.0); - assertTrue(sk1.getRetainedEntries(false) > k); - - sk1.rebuild(); - assertEquals(sk1.getRetainedEntries(false), k); - assertEquals(sk1.getRetainedEntries(true), k); - sk1.rebuild(); - assertEquals(sk1.getRetainedEntries(false), k); - assertEquals(sk1.getRetainedEntries(true), k); - } - - @Test - public void checkResetAndStartingSubMultiple() { - final int k = 1024; - final int u = 4*k; - - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setFamily(fam_).setResizeFactor(X8).setNominalEntries(k).build(); - HeapQuickSelectSketch sk1 = (HeapQuickSelectSketch)usk; //for internal checks - - assertTrue(usk.isEmpty()); - - for (int i=0; i threshold; - println("null \t null:\t" + state + "\t" + jaccardString(jResults)); - assertFalse(state); - - state = exactlyEqual(null, null); - assertFalse(state); - - UpdatableThetaSketch measured = UpdatableThetaSketch.builder().setNominalEntries(minK).build(); - UpdatableThetaSketch expected = UpdatableThetaSketch.builder().setNominalEntries(minK).build(); - - //check both empty - jResults = jaccard(measured, expected); - state = jResults[1] > threshold; - println("empty\tempty:\t" + state + "\t" + jaccardString(jResults)); - assertTrue(state); - - state = exactlyEqual(measured, expected); - assertTrue(state); - - state = exactlyEqual(measured, measured); - assertTrue(state); - - //adjust one - expected.update(1); - jResults = jaccard(measured, expected); - state = jResults[1] > threshold; - println("empty\t 1:\t" + state + "\t" + jaccardString(jResults)); - assertFalse(state); - - state = exactlyEqual(measured, expected); - assertFalse(state); - - println(""); - } - - @Test - public void checkExactMode() { - int k = 1 << 12; - int u = k; - double threshold = 0.9999; - println("Exact Mode, minK: " + k + "\t Th: " + threshold); - - UpdatableThetaSketch measured = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - UpdatableThetaSketch expected = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - - for (int i = 0; i < (u-1); i++) { //one short - measured.update(i); - expected.update(i); - } - - double[] jResults = jaccard(measured, expected); - boolean state = jResults[1] > threshold; - println(state + "\t" + jaccardString(jResults)); - assertTrue(state); - - state = exactlyEqual(measured, expected); - assertTrue(state); - - measured.update(u-1); //now exactly k entries - expected.update(u); //now exactly k entries but differs by one - jResults = jaccard(measured, expected); - state = jResults[1] > threshold; - println(state + "\t" + jaccardString(jResults)); - assertFalse(state); - - state = exactlyEqual(measured, expected); - assertFalse(state); - - println(""); - } - - @Test - public void checkEstMode() { - int k = 1 << 12; - int u = 1 << 20; - double threshold = 0.9999; - println("Estimation Mode, minK: " + k + "\t Th: " + threshold); - - UpdatableThetaSketch measured = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - UpdatableThetaSketch expected = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - - for (int i = 0; i < u; i++) { - measured.update(i); - expected.update(i); - } - - double[] jResults = jaccard(measured, expected); - boolean state = jResults[1] > threshold; - println(state + "\t" + jaccardString(jResults)); - assertTrue(state); - - state = exactlyEqual(measured, expected); - assertTrue(state); - - for (int i = u; i < (u + 50); i++) { //empirically determined - measured.update(i); - } - - jResults = jaccard(measured, expected); - state = jResults[1] >= threshold; - println(state + "\t" + jaccardString(jResults)); - assertFalse(state); - - state = exactlyEqual(measured, expected); - assertFalse(state); - - println(""); - } - - /** - * Enable printing on this test and you will see that the distribution is pretty tight, - * about +/- 0.7%, which is pretty good since the accuracy of the underlying sketch is about - * +/- 1.56%. - */ - @Test - public void checkSimilarity() { - int minK = 1 << 12; - int u1 = 1 << 20; - int u2 = (int) (u1 * 0.95); - double threshold = 0.943; - println("Estimation Mode, minK: " + minK + "\t Th: " + threshold); - - UpdatableThetaSketch expected = UpdatableThetaSketch.builder().setNominalEntries(minK).build(); - UpdatableThetaSketch measured = UpdatableThetaSketch.builder().setNominalEntries(minK).build(); - - for (int i = 0; i < u1; i++) { - expected.update(i); - } - - for (int i = 0; i < u2; i++) { - measured.update(i); - } - - double[] jResults = JaccardSimilarity.jaccard(measured, expected); - boolean state = JaccardSimilarity.similarityTest(measured, expected, threshold); - println(state + "\t" + jaccardString(jResults)); - assertTrue(state); - //check identity case - state = JaccardSimilarity.similarityTest(measured, measured, threshold); - assertTrue(state); - } - - /** - * Enable printing on this test and you will see that the distribution is much looser, - * about +/- 14%. This is due to the fact that intersections loose accuracy as the ratio of - * intersection to the union becomes a small number. - */ - @Test - public void checkDissimilarity() { - int minK = 1 << 12; - int u1 = 1 << 20; - int u2 = (int) (u1 * 0.05); - double threshold = 0.061; - println("Estimation Mode, minK: " + minK + "\t Th: " + threshold); - - UpdatableThetaSketch expected = UpdatableThetaSketch.builder().setNominalEntries(minK).build(); - UpdatableThetaSketch measured = UpdatableThetaSketch.builder().setNominalEntries(minK).build(); - - for (int i = 0; i < u1; i++) { - expected.update(i); - } - - for (int i = 0; i < u2; i++) { - measured.update(i); - } - - double[] jResults = JaccardSimilarity.jaccard(measured, expected); - boolean state = JaccardSimilarity.dissimilarityTest(measured, expected, threshold); - println(state + "\t" + jaccardString(jResults)); - assertTrue(state); - } - - private static String jaccardString(double[] jResults) { - double lb = jResults[0]; - double est = jResults[1]; - double ub = jResults[2]; - return lb + "\t" + est + "\t" + ub + "\t" + ((lb/est) - 1.0) + "\t" + ((ub/est) - 1.0); - } - - @Test - public void checkMinK() { - UpdatableThetaSketch skA = UpdatableThetaSketch.builder().build(); //4096 - UpdatableThetaSketch skB = UpdatableThetaSketch.builder().build(); //4096 - skA.update(1); - skB.update(1); - double[] result = JaccardSimilarity.jaccard(skA, skB); - println(result[0] + ", " + result[1] + ", " + result[2]); - for (int i = 1; i < 4096; i++) { - skA.update(i); - skB.update(i); - } - result = JaccardSimilarity.jaccard(skA, skB); - println(result[0] + ", " + result[1] + ", " + result[2]); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/PairwiseSetOperationsTest.java b/src/test/java/org/apache/datasketches/theta/PairwiseSetOperationsTest.java deleted file mode 100644 index 06733d3fb..000000000 --- a/src/test/java/org/apache/datasketches/theta/PairwiseSetOperationsTest.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.annotations.Test; - -public class PairwiseSetOperationsTest { - - // ThetaIntersection - - @Test - public void checkIntersectionNoOverlap() { - int lgK = 9; - int k = 1< k); - println(quick1.toString()); - println(PreambleUtil.preambleToString(seg)); - - final MemorySegment uSeg = MemorySegment.ofArray(new byte[getMaxUnionBytes(k)]); - final ThetaUnion union = ThetaSetOperation.builder().setNominalEntries(k).buildUnion(uSeg); - union.union(quick1); - println(PreambleUtil.preambleToString(uSeg)); - } - - @Test - public void checkToStringWithPrelongsOf2() { - final int k = 16; - final int u = k; - final UpdatableThetaSketch quick1 = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - for (int i = 0; i< u; i++) { - quick1.update(i); - } - final byte[] bytes = quick1.compact().toByteArray(); - println(ThetaSketch.toString(bytes)); - } - - @Test - public void checkPreambleToStringExceptions() { - byte[] byteArr = new byte[7]; - try { //check preLongs < 8 fails - ThetaSketch.toString(byteArr); - fail("Did not throw SketchesArgumentException."); - } catch (final SketchesArgumentException e) { - //expected - } - byteArr = new byte[8]; - byteArr[0] = (byte) 2; //needs min capacity of 16 - try { //check preLongs == 2 fails - ThetaSketch.toString(MemorySegment.ofArray(byteArr).asReadOnly()); - fail("Did not throw SketchesArgumentException."); - } catch (final SketchesArgumentException e) { - //expected - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadSeedHashFromSeed() { - //In the first 64K values 50541 produces a seedHash of 0, - Util.computeSeedHash(50541); - } - - @Test - public void checkPreLongs() { - final UpdatableThetaSketch sketch = UpdatableThetaSketch.builder().setNominalEntries(16).build(); - CompactThetaSketch comp = sketch.compact(false, null); - byte[] byteArr = comp.toByteArray(); - println(ThetaSketch.toString(byteArr)); //PreLongs = 1 - - sketch.update(1); - comp = sketch.compact(false, null); - byteArr = comp.toByteArray(); - println(ThetaSketch.toString(byteArr)); //PreLongs = 2 - - for (int i=2; i<=32; i++) { - sketch.update(i); - } - comp = sketch.compact(false, null); - byteArr = comp.toByteArray(); - println(ThetaSketch.toString(MemorySegment.ofArray(byteArr).asReadOnly())); //PreLongs = 3 - } - - @Test - public void checkInsertsAndExtracts() { - final byte[] arr = new byte[32]; - final MemorySegment wseg = MemorySegment.ofArray(arr); - - int v = 0; - insertPreLongs(wseg, ++v); - assertEquals(extractPreLongs(wseg), v); - insertPreLongs(wseg, 0); - - insertLgResizeFactor(wseg, 3); //limited to 2 bits - assertEquals(extractLgResizeFactor(wseg), 3); - insertLgResizeFactor(wseg, 0); - - insertSerVer(wseg, ++v); - assertEquals(extractSerVer(wseg), v); - insertSerVer(wseg, 0); - - insertFamilyID(wseg, ++v); - assertEquals(extractFamilyID(wseg), v); - insertFamilyID(wseg, 0); - - insertLgNomLongs(wseg, ++v); - assertEquals(extractLgNomLongs(wseg), v); - insertLgNomLongs(wseg, 0); - - insertLgArrLongs(wseg, ++v); - assertEquals(extractLgArrLongs(wseg), v); - insertLgArrLongs(wseg, 0); - - insertFlags(wseg, 3); - assertEquals(extractFlags(wseg), 3); - insertFlags(wseg, 0); - - insertSeedHash(wseg, ++v); - assertEquals(extractSeedHash(wseg), v); - insertSeedHash(wseg, 0); - - insertCurCount(wseg, ++v); - assertEquals(extractCurCount(wseg), v); - insertCurCount(wseg, 0); - - insertP(wseg, (float) 1.0); - assertEquals(extractP(wseg), (float) 1.0); - insertP(wseg, (float) 0.0); - - insertThetaLong(wseg, ++v); - assertEquals(extractThetaLong(wseg), v); - insertThetaLong(wseg, 0L); - - insertUnionThetaLong(wseg, ++v); - assertEquals(extractUnionThetaLong(wseg), v); - insertUnionThetaLong(wseg, 0L); - - setEmpty(wseg); - assertTrue(isEmptyFlag(wseg)); - - clearEmpty(wseg); - assertFalse(isEmptyFlag(wseg)); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/ReadOnlyMemorySegmentTest.java b/src/test/java/org/apache/datasketches/theta/ReadOnlyMemorySegmentTest.java deleted file mode 100644 index 396d0f0cf..000000000 --- a/src/test/java/org/apache/datasketches/theta/ReadOnlyMemorySegmentTest.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import org.apache.datasketches.common.SketchesReadOnlyException; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class ReadOnlyMemorySegmentTest { - - @Test - public void wrapAndTryUpdatingUpdateSketch() { - final UpdatableThetaSketch updateSketch = UpdatableThetaSketch.builder().build(); - updateSketch.update(1); - final MemorySegment seg = MemorySegment.ofBuffer( - ByteBuffer.wrap(updateSketch.toByteArray()).asReadOnlyBuffer().order(ByteOrder.nativeOrder())); - final UpdatableThetaSketch sketch = (UpdatableThetaSketch) ThetaSketch.wrap(seg); - assertEquals(sketch.getEstimate(), 1.0); - assertTrue(seg.isReadOnly()); - - boolean thrown = false; - try { - sketch.update(2); - } catch (final SketchesReadOnlyException e) { - thrown = true; - } - Assert.assertTrue(thrown); - } - - @Test - public void wrapCompactUnorderedSketch() { - final UpdatableThetaSketch updateSketch = UpdatableThetaSketch.builder().build(); - updateSketch.update(1); - final MemorySegment seg = MemorySegment.ofBuffer( - ByteBuffer.wrap(updateSketch.compact(false, null).toByteArray()).asReadOnlyBuffer().order(ByteOrder.nativeOrder())); - final ThetaSketch sketch = ThetaSketch.wrap(seg); - assertEquals(sketch.getEstimate(), 1.0); - assertTrue(seg.isReadOnly()); - } - - @Test - public void wrapCompactOrderedSketch() { - final UpdatableThetaSketch updateSketch = UpdatableThetaSketch.builder().build(); - updateSketch.update(1); - final MemorySegment seg = MemorySegment.ofBuffer(ByteBuffer.wrap(updateSketch.compact().toByteArray()) - .asReadOnlyBuffer().order(ByteOrder.nativeOrder())); - final ThetaSketch sketch = ThetaSketch.wrap(seg); - assertEquals(sketch.getEstimate(), 1.0); - assertTrue(seg.isReadOnly()); - } - - @Test - public void heapifyUpdateSketch() { - final UpdatableThetaSketch us1 = UpdatableThetaSketch.builder().build(); - us1.update(1); - final MemorySegment seg = MemorySegment.ofBuffer( - ByteBuffer.wrap(us1.toByteArray()).asReadOnlyBuffer().order(ByteOrder.nativeOrder())); - // downcasting is not recommended, for testing only - final UpdatableThetaSketch us2 = (UpdatableThetaSketch) ThetaSketch.heapify(seg); - us2.update(2); - assertEquals(us2.getEstimate(), 2.0); - assertTrue(seg.isReadOnly()); - } - - @Test - public void heapifyCompactUnorderedSketch() { - final UpdatableThetaSketch updateSketch = UpdatableThetaSketch.builder().build(); - updateSketch.update(1); - final MemorySegment seg = MemorySegment.ofBuffer( - ByteBuffer.wrap(updateSketch.compact(false, null).toByteArray()).asReadOnlyBuffer().order(ByteOrder.nativeOrder())); - final ThetaSketch sketch = ThetaSketch.heapify(seg); - assertEquals(sketch.getEstimate(), 1.0); - assertTrue(seg.isReadOnly()); - } - - @Test - public void heapifyCompactOrderedSketch() { - final UpdatableThetaSketch updateSketch = UpdatableThetaSketch.builder().build(); - updateSketch.update(1); - final MemorySegment seg = MemorySegment.ofBuffer( - ByteBuffer.wrap(updateSketch.compact().toByteArray()).asReadOnlyBuffer().order(ByteOrder.nativeOrder())); - final ThetaSketch sketch = ThetaSketch.heapify(seg); - assertEquals(sketch.getEstimate(), 1.0); - assertTrue(seg.isReadOnly()); - } - - @Test - public void heapifyUnion() { - final ThetaUnion u1 = ThetaSetOperation.builder().buildUnion(); - u1.update(1); - final MemorySegment seg = MemorySegment.ofBuffer( - ByteBuffer.wrap(u1.toByteArray()).asReadOnlyBuffer().order(ByteOrder.nativeOrder())); - final ThetaUnion u2 = (ThetaUnion) ThetaSetOperation.heapify(seg); - u2.update(2); - Assert.assertEquals(u2.getResult().getEstimate(), 2.0); - assertTrue(seg.isReadOnly()); - } - - @Test - public void wrapAndTryUpdatingUnion() { - final ThetaUnion u1 = ThetaSetOperation.builder().buildUnion(); - u1.update(1); - final MemorySegment seg = MemorySegment.ofBuffer( - ByteBuffer.wrap(u1.toByteArray()).asReadOnlyBuffer().order(ByteOrder.nativeOrder())); - - final ThetaUnion u2 = (ThetaUnion) ThetaSetOperation.wrap(seg); - final ThetaUnion u3 = ThetaUnion.wrap(seg); - Assert.assertEquals(u2.getResult().getEstimate(), 1.0); - Assert.assertEquals(u3.getResult().getEstimate(), 1.0); - assertTrue(seg.isReadOnly()); - - try { - u2.update(2); - fail(); - } catch (final SketchesReadOnlyException e) { - //expected - } - - try { - u3.update(2); - fail(); - } catch (final SketchesReadOnlyException e) { - //expected - } - } - - @Test - public void heapifyIntersection() { - final UpdatableThetaSketch us1 = UpdatableThetaSketch.builder().build(); - us1.update(1); - us1.update(2); - final UpdatableThetaSketch us2 = UpdatableThetaSketch.builder().build(); - us2.update(2); - us2.update(3); - - final ThetaIntersection i1 = ThetaSetOperation.builder().buildIntersection(); - i1.intersect(us1); - i1.intersect(us2); - final MemorySegment seg = MemorySegment.ofBuffer( - ByteBuffer.wrap(i1.toByteArray()).asReadOnlyBuffer().order(ByteOrder.nativeOrder())); - final ThetaIntersection i2 = (ThetaIntersection) ThetaSetOperation.heapify(seg); - i2.intersect(us1); - Assert.assertEquals(i2.getResult().getEstimate(), 1.0); - assertTrue(seg.isReadOnly()); - } - - @Test - public void wrapIntersection() { - final UpdatableThetaSketch us1 = UpdatableThetaSketch.builder().build(); - us1.update(1); - us1.update(2); - final UpdatableThetaSketch us2 = UpdatableThetaSketch.builder().build(); - us2.update(2); - us2.update(3); - - final ThetaIntersection i1 = ThetaSetOperation.builder().buildIntersection(); - i1.intersect(us1); - i1.intersect(us2); - final MemorySegment seg = MemorySegment.ofBuffer( - ByteBuffer.wrap(i1.toByteArray()).asReadOnlyBuffer().order(ByteOrder.nativeOrder())); - final ThetaIntersection i2 = (ThetaIntersection) ThetaSetOperation.wrap(seg); - Assert.assertEquals(i2.getResult().getEstimate(), 1.0); - - boolean thrown = false; - try { - i2.intersect(us1); - } catch (final SketchesReadOnlyException e) { - thrown = true; - } - Assert.assertTrue(thrown); - assertTrue(seg.isReadOnly()); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/SetOperationTest.java b/src/test/java/org/apache/datasketches/theta/SetOperationTest.java deleted file mode 100644 index 45481b49f..000000000 --- a/src/test/java/org/apache/datasketches/theta/SetOperationTest.java +++ /dev/null @@ -1,438 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.apache.datasketches.common.ResizeFactor.X4; -import static org.apache.datasketches.theta.ThetaSketch.getMaxUpdateSketchBytes; -import static org.apache.datasketches.thetacommon.HashOperations.minLgHashTableSize; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.ThetaUtil; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class SetOperationTest { - - @Test - public void checkBuilder() { - final int k = 2048; - final long seed = 1021; - - final UpdatableThetaSketch usk1 = UpdatableThetaSketch.builder().setSeed(seed).setNominalEntries(k).build(); - final UpdatableThetaSketch usk2 = UpdatableThetaSketch.builder().setSeed(seed).setNominalEntries(k).build(); - - for (int i=0; i Next, we recover the ThetaUnion SetOp and the 3 sketches and the space for the result. Then - * recompute the union using a ThetaUnion of the same size as the input sketches, where the end result - * will be an estimate. - */ - @Test - public void checkDirectUnionExample() { - //The first task is to compute how much off-heap space we need and set the heap large enough. - //For the first trial, we will set the ThetaUnion large enough for an exact result for THIS example. - final int sketchNomEntries = 1 << 14; //16K - int unionNomEntries = 1 << 15; //32K - final int[] heapLayout = getHeapLayout(sketchNomEntries, unionNomEntries); - - //This BB belongs to you and you always retain a link to it until you are completely - // done and then let java garbage collect it. - //I use a heap backing array, because for this example it is easier to peak into it and - // see what is going on. - final byte[] backingArr = new byte[heapLayout[5]]; - final ByteBuffer heapBuf = ByteBuffer.wrap(backingArr).order(ByteOrder.nativeOrder()); - - // Attaches a MemorySegment object to the underlying heap space of heapBuf. - // heapSeg will have a Read/Write view of the complete backing segment of heapBuf (direct or not). - // Any R/W action from heapSeg will be visible via heapBuf and visa versa. - // - // However, if you had created this WM object off-heap - // you would have the responsibility to close it when you are done. - // But, since it was allocated via BB, it closes it for you. - final MemorySegment heapSeg = MemorySegment.ofBuffer(heapBuf); - - double result = directUnionTrial1(heapSeg, heapLayout, sketchNomEntries, unionNomEntries); - println("1st est: "+result); - final int expected = sketchNomEntries*2; - assertEquals(result, expected, 0.0); //est must be exact. - - //For trial 2, we will use the same union space but use only part of it. - unionNomEntries = 1 << 14; //16K - result = directUnionTrial2(heapSeg, heapLayout, sketchNomEntries, unionNomEntries); - - //intentionally loose bounds - assertEquals(result, expected, expected*0.05); - println("2nd est: "+result); - println("Error %: "+(result/expected -1.0)*100); - } - - @Test - public void setOpsExample() { - println("Set Operations Example:"); - final int k = 4096; - final UpdatableThetaSketch skA = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - final UpdatableThetaSketch skB = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - final UpdatableThetaSketch skC = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - - for (int i=1; i<=10; i++) { skA.update(i); } - for (int i=1; i<=20; i++) { skB.update(i); } - for (int i=6; i<=15; i++) { skC.update(i); } //overlapping set - - final ThetaUnion union = ThetaSetOperation.builder().setNominalEntries(k).buildUnion(); - union.union(skA); - union.union(skB); - // ... continue to iterate on the input sketches to union - - final CompactThetaSketch unionSk = union.getResult(); //the result union sketch - println("A U B : "+unionSk.getEstimate()); //the estimate of the union - - //ThetaIntersection is similar - - final ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(); - inter.intersect(unionSk); - inter.intersect(skC); - // ... continue to iterate on the input sketches to intersect - - final CompactThetaSketch interSk = inter.getResult(); //the result intersection sketch - println("(A U B) ^ C: "+interSk.getEstimate()); //the estimate of the intersection - - //The ThetaAnotB operation is a little different as it is stateless: - - final ThetaAnotB aNotB = ThetaSetOperation.builder().buildANotB(); - final CompactThetaSketch not = aNotB.aNotB(skA, skC); - - println("A \\ C : "+not.getEstimate()); //the estimate of the ThetaAnotB operation - } - - @Test - public void checkIsSameResource() { - final int k = 16; - final MemorySegment wseg = MemorySegment.ofArray(new byte[k*16 + 32]);//288 - final MemorySegment emptySeg = MemorySegment.ofArray(new byte[8]); - final ThetaUnion union = ThetaSetOperation.builder().setNominalEntries(k).buildUnion(wseg); - assertTrue(union.isSameResource(wseg)); - assertFalse(union.isSameResource(emptySeg)); - - final ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(wseg); - assertTrue(inter.isSameResource(wseg)); - assertFalse(inter.isSameResource(emptySeg)); - - final ThetaAnotB aNotB = ThetaSetOperation.builder().buildANotB(); - - assertFalse(aNotB.isSameResource(emptySeg)); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - - /** - * Compute offsets for MyHeap for ThetaUnion, sketch1, sketch2, sketch3, resultSketch, total layout. - * @param sketchNomEntries the configured nominal entries of the sketch - * @param unionNomEntries configured nominal entries of the union - * @return array of offsets for ThetaUnion, sketch1, sketch2, sketch3, resultSketch, total layout - */ - private static int[] getHeapLayout(final int sketchNomEntries, final int unionNomEntries) { - final int[] heapLayout = new int[6]; - final int unionBytes = ThetaSetOperation.getMaxUnionBytes(unionNomEntries); - final int sketchBytes = getMaxUpdateSketchBytes(sketchNomEntries); - final int resultBytes = ThetaSketch.getMaxCompactSketchBytes(unionNomEntries); - heapLayout[0] = 0; //offset for ThetaUnion - heapLayout[1] = unionBytes; //offset for sketch1 - heapLayout[2] = unionBytes + sketchBytes; //offset for sketch2 - heapLayout[3] = unionBytes + 2*sketchBytes; //offset for sketch3 - heapLayout[4] = unionBytes + 3*sketchBytes; //offset for result - heapLayout[5] = unionBytes + 3*sketchBytes + resultBytes; //total - return heapLayout; - } - - private static double directUnionTrial1( - final MemorySegment heapSeg, final int[] heapLayout, final int sketchNomEntries, final int unionNomEntries) { - - final int offset = heapLayout[0]; - final int bytes = heapLayout[1] - offset; - final MemorySegment unionSeg = heapSeg.asSlice(offset, bytes); - - ThetaUnion union = ThetaSetOperation.builder().setNominalEntries(unionNomEntries).buildUnion(unionSeg); - - final MemorySegment sketch1seg = heapSeg.asSlice(heapLayout[1], heapLayout[2]-heapLayout[1]); - final MemorySegment sketch2seg = heapSeg.asSlice(heapLayout[2], heapLayout[3]-heapLayout[2]); - final MemorySegment sketch3seg = heapSeg.asSlice(heapLayout[3], heapLayout[4]-heapLayout[3]); - final MemorySegment resultSeg = heapSeg.asSlice(heapLayout[4], heapLayout[5]-heapLayout[4]); - - //Initialize the 3 sketches - final UpdatableThetaSketch sk1 = UpdatableThetaSketch.builder().setNominalEntries(sketchNomEntries).build(sketch1seg); - final UpdatableThetaSketch sk2 = UpdatableThetaSketch.builder().setNominalEntries(sketchNomEntries).build(sketch2seg); - final UpdatableThetaSketch sk3 = UpdatableThetaSketch.builder().setNominalEntries(sketchNomEntries).build(sketch3seg); - - //This little trial has sk1 and sk2 distinct and sk2 overlap both. - //Build the sketches. - for (int i=0; i< sketchNomEntries; i++) { - sk1.update(i); - sk2.update(i + sketchNomEntries/2); - sk3.update(i + sketchNomEntries); - } - - //confirm that each of these 3 sketches is exact. - assertEquals(sk1.getEstimate(), sketchNomEntries, 0.0); - assertEquals(sk2.getEstimate(), sketchNomEntries, 0.0); - assertEquals(sk3.getEstimate(), sketchNomEntries, 0.0); - - //Let's union the first 2 sketches - union.union(sk1); - union.union(sk2); - - //Let's recover the union and the 3rd sketch - union = ThetaUnion.wrap(unionSeg); - union.union(ThetaSketch.wrap(sketch3seg)); - - final ThetaSketch resSk = union.getResult(true, resultSeg); - final double est = resSk.getEstimate(); - - return est; - } - - private static double directUnionTrial2( - final MemorySegment heapSeg, final int[] heapLayout, final int sketchNomEntries, final int unionNomEntries) { - - final MemorySegment unionSeg = heapSeg.asSlice(heapLayout[0], heapLayout[1]-heapLayout[0]); - final MemorySegment sketch1seg = heapSeg.asSlice(heapLayout[1], heapLayout[2]-heapLayout[1]); - final MemorySegment sketch2seg = heapSeg.asSlice(heapLayout[2], heapLayout[3]-heapLayout[2]); - final MemorySegment sketch3seg = heapSeg.asSlice(heapLayout[3], heapLayout[4]-heapLayout[3]); - final MemorySegment resultSeg = heapSeg.asSlice(heapLayout[4], heapLayout[5]-heapLayout[4]); - - //Recover the 3 sketches - final UpdatableThetaSketch sk1 = (UpdatableThetaSketch) ThetaSketch.wrap(sketch1seg); - final UpdatableThetaSketch sk2 = (UpdatableThetaSketch) ThetaSketch.wrap(sketch2seg); - final UpdatableThetaSketch sk3 = (UpdatableThetaSketch) ThetaSketch.wrap(sketch3seg); - - //confirm that each of these 3 sketches is exact. - assertEquals(sk1.getEstimate(), sketchNomEntries, 0.0); - assertEquals(sk2.getEstimate(), sketchNomEntries, 0.0); - assertEquals(sk3.getEstimate(), sketchNomEntries, 0.0); - - //Create a new union in the same space with a smaller size. - Util.clear(unionSeg); - final ThetaUnion union = ThetaSetOperation.builder().setNominalEntries(unionNomEntries).buildUnion(unionSeg); - union.union(sk1); - union.union(sk2); - union.union(sk3); - - final ThetaSketch resSk = union.getResult(true, resultSeg); - final double est = resSk.getEstimate(); - - return est; - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/SetOpsCornerCasesTest.java b/src/test/java/org/apache/datasketches/theta/SetOpsCornerCasesTest.java deleted file mode 100644 index 06bbd4dd7..000000000 --- a/src/test/java/org/apache/datasketches/theta/SetOpsCornerCasesTest.java +++ /dev/null @@ -1,500 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.apache.datasketches.theta.SetOpsCornerCasesTest.State.EMPTY; -import static org.apache.datasketches.theta.SetOpsCornerCasesTest.State.EST_HEAP; -import static org.apache.datasketches.theta.SetOpsCornerCasesTest.State.EST_SEGMENT_UNORDERED; -import static org.apache.datasketches.theta.SetOpsCornerCasesTest.State.EXACT; -import static org.apache.datasketches.theta.SetOpsCornerCasesTest.State.NULL; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; - -import java.lang.foreign.MemorySegment; -import java.util.Random; - -import org.testng.Assert; -import org.testng.annotations.Test; - -public class SetOpsCornerCasesTest { - - /*******************************************/ - Random rand = new Random(9001); //deterministic - - @Test - public void checkSetOpsRandom() { - int hiA = 0, loB = 0, hiB = 0; - for (int i = 0; i < 1000; i++) { - hiA = rand.nextInt(128); //skA fed values between 0 and 127 - loB = rand.nextInt(64); - hiB = loB + rand.nextInt(64); //skB fed up to 63 values starting at loB - compareSetOpsRandom(64, 0, hiA, loB, hiB); - } - } - - private static void compareSetOpsRandom(final int k, final int loA, final int hiA, final int loB, final int hiB) { - final UpdatableThetaSketch tskA = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - final UpdatableThetaSketch tskB = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - - for (int i = loA; i < hiA; i++) { tskA.update(i); } - for (int i = loB; i < hiB; i++) { tskB.update(i); } - - final CompactThetaSketch rcskStdU = doStdUnion(tskA, tskB, k, null); - final CompactThetaSketch rcskPwU = doPwUnion(tskA, tskB, k); - checkCornerCase(rcskPwU, rcskStdU); - - final CompactThetaSketch rcskStdPairU = doStdPairUnion(tskA, tskB, k, null); - checkCornerCase(rcskStdPairU, rcskStdU); - - final CompactThetaSketch rcskStdI = doStdIntersection(tskA, tskB, null); - final CompactThetaSketch rcskPwI = doPwIntersection(tskA, tskB); - checkCornerCase(rcskPwI, rcskStdI); - - final CompactThetaSketch rcskStdPairI = doStdPairIntersection(tskA, tskB, null); - checkCornerCase(rcskStdPairI, rcskStdI); - - final CompactThetaSketch rcskStdAnotB = doStdAnotB(tskA, tskB, null); - final CompactThetaSketch rcskPwAnotB = doPwAnotB(tskA, tskB); - checkCornerCase(rcskPwAnotB, rcskStdAnotB); - - final CompactThetaSketch rcskStdStatefulAnotB = doStdStatefulAnotB(tskA, tskB, null); - checkCornerCase(rcskStdStatefulAnotB, rcskStdAnotB); - } - - /*******************************************/ - - @Test - //Check all corner cases against standard ThetaUnion, ThetaIntersection, and ThetaAnotB. - //The unordered case is not tested - public void compareCornerCases() { - final int k = 64; - for (final State stateA : State.values()) { - for (final State stateB : State.values()) { - if ((stateA == EST_SEGMENT_UNORDERED) || (stateB == EST_SEGMENT_UNORDERED) || (stateA == NULL) || (stateB == NULL)) { continue; } - cornerCaseChecks(stateA, stateB, k); - cornerCaseChecksMemorySegment(stateA, stateB, k); - } - } - } - -// @Test -// public void checkExactNullSpecificCase() { -// cornerCaseChecksMemorySegment(State.EXACT, State.NULL, 64); -// } - - private static void cornerCaseChecksMemorySegment(final State stateA, final State stateB, final int k) { - println("StateA: " + stateA + ", StateB: " + stateB); - final CompactThetaSketch tcskA = generate(stateA, k); - final CompactThetaSketch tcskB = generate(stateB, k); - - MemorySegment wseg = MemorySegment.ofArray(new byte[ThetaSetOperation.getMaxUnionBytes(k)]); - - CompactThetaSketch rcskStdU = doStdUnion(tcskA, tcskB, k, null); - final CompactThetaSketch rcskPwU = doPwUnion(tcskA, tcskB, k); - checkCornerCase(rcskPwU, rcskStdU); //heap, heap - - rcskStdU = doStdUnion(tcskA, tcskB, k, wseg); - final CompactThetaSketch rcskStdPairU = doStdPairUnion(tcskA, tcskB, k, wseg); - checkCornerCase(rcskStdPairU, rcskStdU); //direct, direct - - wseg = MemorySegment.ofArray(new byte[ThetaSetOperation.getMaxIntersectionBytes(k)]); - - CompactThetaSketch rcskStdI = doStdIntersection(tcskA, tcskB, null); - final CompactThetaSketch rcskPwI = doPwIntersection(tcskA, tcskB); - checkCornerCase(rcskPwI, rcskStdI); //empty, empty - - rcskStdI = doStdIntersection(tcskA, tcskB, wseg); - final CompactThetaSketch rcskStdPairI = doStdPairIntersection(tcskA, tcskB, wseg); - checkCornerCase(rcskStdPairI, rcskStdI); //empty, empty //direct, direct??? - - wseg = MemorySegment.ofArray(new byte[ThetaSetOperation.getMaxAnotBResultBytes(k)]); - - CompactThetaSketch rcskStdAnotB = doStdAnotB(tcskA, tcskB, null); - final CompactThetaSketch rcskPwAnotB = doPwAnotB(tcskA, tcskB); - checkCornerCase(rcskPwAnotB, rcskStdAnotB); //heap, heap - - rcskStdAnotB = doStdAnotB(tcskA, tcskB, wseg); - final CompactThetaSketch rcskStdStatefulAnotB = doStdStatefulAnotB(tcskA, tcskB, wseg); - checkCornerCase(rcskStdStatefulAnotB, rcskStdAnotB); //direct, heap - } - - private static void cornerCaseChecks(final State stateA, final State stateB, final int k) { - println("StateA: " + stateA + ", StateB: " + stateB); - final CompactThetaSketch tcskA = generate(stateA, k); - final CompactThetaSketch tcskB = generate(stateB, k); - - final CompactThetaSketch rcskStdU = doStdUnion(tcskA, tcskB, k, null); - final CompactThetaSketch rcskPwU = doPwUnion(tcskA, tcskB, k); - checkCornerCase(rcskPwU, rcskStdU); - - final CompactThetaSketch rcskStdPairU = doStdPairUnion(tcskA, tcskB, k, null); - checkCornerCase(rcskStdPairU, rcskStdU); - - final CompactThetaSketch rcskStdI = doStdIntersection(tcskA, tcskB, null); - final CompactThetaSketch rcskPwI = doPwIntersection(tcskA, tcskB); - checkCornerCase(rcskPwI, rcskStdI); - - final CompactThetaSketch rcskStdPairI = doStdPairIntersection(tcskA, tcskB, null); - checkCornerCase(rcskStdPairI, rcskStdI); - - final CompactThetaSketch rcskStdAnotB = doStdAnotB(tcskA, tcskB, null); - final CompactThetaSketch rcskPwAnotB = doPwAnotB(tcskA, tcskB); - checkCornerCase(rcskPwAnotB, rcskStdAnotB); - - final CompactThetaSketch rcskStdStatefulAnotB = doStdStatefulAnotB(tcskA, tcskB, null); - checkCornerCase(rcskStdStatefulAnotB, rcskStdAnotB); - } - - private static CompactThetaSketch doStdUnion(final ThetaSketch tskA, final ThetaSketch tskB, final int k, final MemorySegment wseg) { - final ThetaUnion union = ThetaSetOperation.builder().setNominalEntries(k).buildUnion(); - union.union(tskA); - union.union(tskB); - return union.getResult(true, wseg); - } - - private static CompactThetaSketch doStdPairUnion(final ThetaSketch tskA, final ThetaSketch tskB, final int k, final MemorySegment wseg) { - final ThetaUnion union = ThetaSetOperation.builder().setNominalEntries(k).buildUnion(); - return union.union(tskA, tskB, true, wseg); - } - - private static CompactThetaSketch doStdIntersection(final ThetaSketch tskA, final ThetaSketch tskB, final MemorySegment wseg) { - final ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(); - inter.intersect(tskA); - inter.intersect(tskB); - return inter.getResult(true, wseg); - } - - private static CompactThetaSketch doStdPairIntersection(final ThetaSketch tskA, final ThetaSketch tskB, final MemorySegment wseg) { - final ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(); - return inter.intersect(tskA, tskB, true, wseg); - } - - private static CompactThetaSketch doStdAnotB(final ThetaSketch tskA, final ThetaSketch tskB, final MemorySegment wseg) { - final ThetaAnotB anotb = ThetaSetOperation.builder().buildANotB(); - return anotb.aNotB(tskA, tskB, true, wseg); - } - - private static CompactThetaSketch doStdStatefulAnotB(final ThetaSketch tskA, final ThetaSketch tskB, final MemorySegment wseg) { - final ThetaAnotB anotb = ThetaSetOperation.builder().buildANotB(); - anotb.setA(tskA); - anotb.notB(tskB); - anotb.getResult(false); - return anotb.getResult(true, wseg, true); - } - - private static CompactThetaSketch doPwUnion(final ThetaSketch tskA, final ThetaSketch tskB, final int k) { - CompactThetaSketch tcskA, tcskB; - if (tskA == null) { tcskA = null; } - else { tcskA = (tskA instanceof CompactThetaSketch) ? (CompactThetaSketch) tskA : tskA.compact(); } - if (tskB == null) { tcskB = null; } - else { tcskB = (tskB instanceof CompactThetaSketch) ? (CompactThetaSketch) tskB : tskB.compact(); } - final ThetaUnion union = ThetaSetOperation.builder().setNominalEntries(k).buildUnion(); - return union.union(tcskA, tcskB); - } - - private static CompactThetaSketch doPwIntersection(final ThetaSketch tskA, final ThetaSketch tskB) { - final ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(); - return inter.intersect(tskA, tskB); - } - - private static CompactThetaSketch doPwAnotB(final ThetaSketch tskA, final ThetaSketch tskB) { - final ThetaAnotB aNotB = ThetaSetOperation.builder().buildANotB(); - return aNotB.aNotB(tskA, tskB); - } - - - private static void checkCornerCase(final ThetaSketch rskA, final ThetaSketch rskB) { - final double estA = rskA.getEstimate(); - final double estB = rskB.getEstimate(); - final boolean emptyA = rskA.isEmpty(); - final boolean emptyB = rskB.isEmpty(); - final long thetaLongA = rskA.getThetaLong(); - final long thetaLongB = rskB.getThetaLong(); - final int countA = rskA.getRetainedEntries(true); - final int countB = rskB.getRetainedEntries(true); - Assert.assertEquals(estB, estA, 0.0); - Assert.assertEquals(emptyB, emptyA); - Assert.assertEquals(thetaLongB, thetaLongA); - Assert.assertEquals(countB, countA); - Assert.assertEquals(rskA.getClass().getSimpleName(), rskB.getClass().getSimpleName()); - } - - /*******************************************/ - - @Test - public void checkUnionNotOrdered() { - final int k = 64; - final CompactThetaSketch skNull = generate(NULL, k); - final CompactThetaSketch skEmpty = generate(EMPTY, k); - final CompactThetaSketch skHeap = generate(EST_HEAP, k); - final CompactThetaSketch skHeapUO = generate(EST_SEGMENT_UNORDERED, k); - final ThetaUnion union = ThetaSetOperation.builder().setNominalEntries(k).buildUnion(); - union.union(skNull, skHeapUO); - union.union(skEmpty, skHeapUO); - union.union(skHeapUO, skNull); - union.union(skHeapUO, skEmpty); - union.union(skHeapUO, skHeap); - union.union(skHeap, skHeapUO); - } - - @Test - public void checkSeedHash() { - final int k = 64; - final UpdatableThetaSketch tmp1 = UpdatableThetaSketch.builder().setNominalEntries(k).setSeed(123).build(); - tmp1.update(1); - tmp1.update(3); - final CompactThetaSketch skSmallSeed2A = tmp1.compact(true, null); - - final UpdatableThetaSketch tmp2 = UpdatableThetaSketch.builder().setNominalEntries(k).setSeed(123).build(); - tmp2.update(1); - tmp2.update(2); - final CompactThetaSketch skSmallSeed2B = tmp2.compact(true, null); - - final CompactThetaSketch skExact = generate(EXACT, k); - final CompactThetaSketch skHeap = generate(EST_HEAP, 2 * k); - - final ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(); - final ThetaAnotB aNotB = ThetaSetOperation.builder().buildANotB(); - final ThetaUnion union = ThetaSetOperation.builder().setNominalEntries(k).buildUnion(); - - //Intersect - try { - inter.intersect(skExact, skSmallSeed2A); - Assert.fail(); - } catch (final Exception e) { } //pass - try { - inter.intersect(skExact, skSmallSeed2B); - Assert.fail(); - } catch (final Exception e) { } //pass - try { - inter.intersect(skSmallSeed2B, skExact); - Assert.fail(); - } catch (final Exception e) { } //pass - try { - inter.intersect(skHeap, skSmallSeed2B); - Assert.fail(); - } catch (final Exception e) { } //pass - //A NOT B - try { - aNotB.aNotB(skExact, skSmallSeed2A); - Assert.fail(); - } catch (final Exception e) { } //pass - try { - aNotB.aNotB(skExact, skSmallSeed2B); - Assert.fail(); - } catch (final Exception e) { } //pass - try { - aNotB.aNotB(skSmallSeed2B, skExact); - Assert.fail(); - } catch (final Exception e) { } //pass - try { - aNotB.aNotB(skHeap, skSmallSeed2B); - Assert.fail(); - } catch (final Exception e) { } //pass - //ThetaUnion - try { - union.union(skExact, skSmallSeed2A); - Assert.fail(); - } catch (final Exception e) { } //pass - try { - union.union(skExact, skSmallSeed2B); - Assert.fail(); - } catch (final Exception e) { } //pass - try { - union.union(skSmallSeed2B, skExact); - Assert.fail(); - } catch (final Exception e) { } //pass - try { - union.union(skHeap, skSmallSeed2B); - Assert.fail(); - } catch (final Exception e) { } //pass - } - - @Test - public void checkPwUnionReduceToK() { - final int k = 16; - final CompactThetaSketch skNull = generate(NULL, k); - final CompactThetaSketch skEmpty = generate(EMPTY, k); - final CompactThetaSketch skHeap1 = generate(EST_HEAP, k); - final CompactThetaSketch skHeap2 = generate(EST_HEAP, k); - final ThetaUnion union = ThetaSetOperation.builder().setNominalEntries(k).buildUnion(); - CompactThetaSketch csk; - csk = union.union(skNull, skHeap1); - Assert.assertEquals(csk.getRetainedEntries(true), k); - csk = union.union(skEmpty, skHeap1); - Assert.assertEquals(csk.getRetainedEntries(true), k); - csk = union.union(skHeap1, skNull); - Assert.assertEquals(csk.getRetainedEntries(true), k); - csk = union.union(skHeap1, skEmpty); - Assert.assertEquals(csk.getRetainedEntries(true), k); - csk = union.union(skHeap1, skHeap2); - Assert.assertEquals(csk.getRetainedEntries(true), k); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - - @Test - public void checkGenerator() { - final int k = 16; - CompactThetaSketch csk; - - csk = generate(State.NULL, 0); - assertNull(csk); - - csk = generate(State.EMPTY, k); - assertEquals(csk.isEmpty(), true); - assertEquals(csk.isEstimationMode(), false); - assertEquals(csk.getRetainedEntries(true), 0); - assertEquals(csk.getThetaLong(), Long.MAX_VALUE); - assertEquals(csk.isOffHeap(), false); - assertEquals(csk.hasMemorySegment(), false); - assertEquals(csk.isOrdered(), true); - - csk = generate(State.SINGLE, k); - assertEquals(csk.isEmpty(), false); - assertEquals(csk.isEstimationMode(), false); - assertEquals(csk.getRetainedEntries(true), 1); - assertEquals(csk.getThetaLong(), Long.MAX_VALUE); - assertEquals(csk.isOffHeap(), false); - assertEquals(csk.hasMemorySegment(), false); - assertEquals(csk.isOrdered(), true); - - csk = generate(State.EXACT, k); - assertEquals(csk.isEmpty(), false); - assertEquals(csk.isEstimationMode(), false); - assertEquals(csk.getRetainedEntries(true), k); - assertEquals(csk.getThetaLong(), Long.MAX_VALUE); - assertEquals(csk.isOffHeap(), false); - assertEquals(csk.hasMemorySegment(), false); - assertEquals(csk.isOrdered(), true); - - csk = generate(State.EST_HEAP, k); - assertEquals(csk.isEmpty(), false); - assertEquals(csk.isEstimationMode(), true); - assertEquals(csk.getRetainedEntries(true) > k, true); - assertEquals(csk.getThetaLong() < Long.MAX_VALUE, true); - assertEquals(csk.isOffHeap(), false); - assertEquals(csk.hasMemorySegment(), false); - assertEquals(csk.isOrdered(), true); - - csk = generate(State.THLT1_CNT0_FALSE, k); - assertEquals(csk.isEmpty(), false); - assertEquals(csk.isEstimationMode(), true); - assertEquals(csk.getRetainedEntries(true), 0); - assertEquals(csk.getThetaLong() < Long.MAX_VALUE, true); - assertEquals(csk.isOffHeap(), false); - assertEquals(csk.hasMemorySegment(), false); - assertEquals(csk.isOrdered(), true); - - csk = generate(State.THEQ1_CNT0_TRUE, k); - assertEquals(csk.isEmpty(), true); - assertEquals(csk.isEstimationMode(), false); - assertEquals(csk.getRetainedEntries(true), 0); - assertEquals(csk.getThetaLong() < Long.MAX_VALUE, false); - assertEquals(csk.isOffHeap(), false); - assertEquals(csk.hasMemorySegment(), false); - assertEquals(csk.isOrdered(), true); - - csk = generate(State.EST_SEGMENT_UNORDERED, k); - assertEquals(csk.isEmpty(), false); - assertEquals(csk.isEstimationMode(), true); - assertEquals(csk.getRetainedEntries(true) > k, true); - assertEquals(csk.getThetaLong() < Long.MAX_VALUE, true); - assertEquals(csk.isOffHeap(), false); - assertEquals(csk.hasMemorySegment(), true); - assertEquals(csk.isOrdered(), false); - } - - enum State {NULL, EMPTY, SINGLE, EXACT, EST_HEAP, THLT1_CNT0_FALSE, THEQ1_CNT0_TRUE, EST_SEGMENT_UNORDERED} - - private static CompactThetaSketch generate(final State state, final int k) { - UpdatableThetaSketch sk = null; - CompactThetaSketch csk = null; - - switch(state) { - case NULL : { - //already null - break; - } - case EMPTY : { //results in EmptyCompactSketch - csk = UpdatableThetaSketch.builder().setNominalEntries(k).build().compact(true, null); - break; - } - case SINGLE : { //results in SingleItemSketches most of the time - sk = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - sk.update(1); - csk = sk.compact(true, null); - break; - } - case EXACT : { - sk = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - for (int i = 0; i < k; i++) { - sk.update(i); - } - csk = sk.compact(true, null); - break; - } - case EST_HEAP : { - sk = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - for (int i = 0; i < (4 * k); i++) { - sk.update(i); - } - csk = sk.compact(true, null); - break; - } - case THLT1_CNT0_FALSE : { - sk = UpdatableThetaSketch.builder().setP((float)0.5).setNominalEntries(k).build(); - sk.update(7); //above theta - assert(sk.getRetainedEntries(true) == 0); - csk = sk.compact(true, null); //compact as {Th < 1.0, 0, F} - break; - } - case THEQ1_CNT0_TRUE : { - sk = UpdatableThetaSketch.builder().setP((float)0.5).setNominalEntries(k).build(); - assert(sk.getRetainedEntries(true) == 0); - csk = sk.compact(true, null); //compact as {Th < 1.0, 0, T} - break; - } - case EST_SEGMENT_UNORDERED : { - sk = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - for (int i = 0; i < (4 * k); i++) { - sk.update(i); - } - final int bytes = ThetaSketch.getMaxCompactSketchBytes(sk.getRetainedEntries(true)); - final byte[] byteArr = new byte[bytes]; - final MemorySegment wseg = MemorySegment.ofArray(byteArr); - csk = sk.compact(false, wseg); - break; - } - } - return csk; - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/SingleItemSketchTest.java b/src/test/java/org/apache/datasketches/theta/SingleItemSketchTest.java deleted file mode 100644 index 09a536274..000000000 --- a/src/test/java/org/apache/datasketches/theta/SingleItemSketchTest.java +++ /dev/null @@ -1,378 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED; -import static org.apache.datasketches.hash.MurmurHash3.hash; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class SingleItemSketchTest { - final static short DEFAULT_SEED_HASH = (short) (Util.computeSeedHash(Util.DEFAULT_UPDATE_SEED) & 0XFFFFL); - - @Test - public void check1() { - final ThetaUnion union = ThetaSetOperation.builder().buildUnion(); - union.union(SingleItemSketch.create(1)); - union.union(SingleItemSketch.create(1.0)); - union.union(SingleItemSketch.create(0.0)); - union.union(SingleItemSketch.create("1")); - union.union(SingleItemSketch.create(new byte[] {1,2,3,4})); - union.union(SingleItemSketch.create(new char[] {'a'})); - union.union(SingleItemSketch.create(new int[] {2})); - union.union(SingleItemSketch.create(new long[] {3})); - - union.union(SingleItemSketch.create(-0.0)); //duplicate - - final double est = union.getResult().getEstimate(); - println(""+est); - assertEquals(est, 8.0, 0.0); - - assertNull(SingleItemSketch.create("")); - final String str = null; - assertNull(SingleItemSketch.create(str));//returns null - - assertNull(SingleItemSketch.create(new byte[0]));//returns null - final byte[] byteArr = null; - assertNull(SingleItemSketch.create(byteArr));//returns null - - assertNull(SingleItemSketch.create(new char[0]));//returns null - final char[] charArr = null; - assertNull(SingleItemSketch.create(charArr));//returns null - - assertNull(SingleItemSketch.create(new int[0]));//returns null - final int[] intArr = null; - assertNull(SingleItemSketch.create(intArr));//returns null - - assertNull(SingleItemSketch.create(new long[0]));//returns null - final long[] longArr = null; - assertNull(SingleItemSketch.create(longArr));//returns null - } - - @Test - public void check2() { - final long seed = Util.DEFAULT_UPDATE_SEED; - final ThetaUnion union = ThetaSetOperation.builder().buildUnion(); - union.union(SingleItemSketch.create(1, seed)); - union.union(SingleItemSketch.create(1.0, seed)); - union.union(SingleItemSketch.create(0.0, seed)); - union.union(SingleItemSketch.create("1", seed)); - union.union(SingleItemSketch.create(new byte[] {1,2,3,4}, seed)); - union.union(SingleItemSketch.create(new char[] {'a'}, seed)); - union.union(SingleItemSketch.create(new int[] {2}, seed)); - union.union(SingleItemSketch.create(new long[] {3}, seed)); - - union.union(SingleItemSketch.create(-0.0, seed)); //duplicate - - final double est = union.getResult().getEstimate(); - println(""+est); - assertEquals(est, 8.0, 0.0); - - assertNull(SingleItemSketch.create("", seed)); - final String str = null; - assertNull(SingleItemSketch.create(str, seed));//returns null - - assertNull(SingleItemSketch.create(new byte[0], seed));//returns null - final byte[] byteArr = null; - assertNull(SingleItemSketch.create(byteArr, seed));//returns null - - assertNull(SingleItemSketch.create(new char[0], seed));//returns null - final char[] charArr = null; - assertNull(SingleItemSketch.create(charArr, seed));//returns null - - assertNull(SingleItemSketch.create(new int[0], seed));//returns null - final int[] intArr = null; - assertNull(SingleItemSketch.create(intArr, seed));//returns null - - assertNull(SingleItemSketch.create(new long[0], seed));//returns null - final long[] longArr = null; - assertNull(SingleItemSketch.create(longArr, seed));//returns null - } - - @Test - public void checkSketchInterface() { - final SingleItemSketch sis = SingleItemSketch.create(1); - assertEquals(sis.getCompactBytes(), 16); - assertEquals(sis.getEstimate(), 1.0); - assertEquals(sis.getLowerBound(1), 1.0); - assertEquals(sis.getRetainedEntries(true), 1); - assertEquals(sis.getUpperBound(1), 1.0); - assertFalse(sis.isOffHeap()); - assertFalse(sis.hasMemorySegment()); - assertFalse(sis.isEmpty()); - assertTrue(sis.isOrdered()); - } - - @Test - public void checkLessThanThetaLong() { - for (int i = 0; i < 10; i++) { - final long[] data = { i }; - final long h = hash(data, Util.DEFAULT_UPDATE_SEED)[0] >>> 1; - final SingleItemSketch sis = SingleItemSketch.create(i); - final long halfMax = Long.MAX_VALUE >> 1; - final int count = sis.getCountLessThanThetaLong(halfMax); - assertEquals(count, (h < halfMax) ? 1 : 0); - } - } - - @Test - public void checkSerDe() { - final SingleItemSketch sis = SingleItemSketch.create(1); - final byte[] byteArr = sis.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArr); - final short defaultSeedHash = Util.computeSeedHash(Util.DEFAULT_UPDATE_SEED); - final SingleItemSketch sis2 = SingleItemSketch.heapify(seg, defaultSeedHash); - assertEquals(sis2.getEstimate(), 1.0); - - final SingleItemSketch sis3 = SingleItemSketch.heapify(seg , defaultSeedHash); - assertEquals(sis3.getEstimate(), 1.0); - - final ThetaUnion union = ThetaSetOperation.builder().buildUnion(); - union.union(sis); - union.union(sis2); - union.union(sis3); - final CompactThetaSketch csk = union.getResult(); - assertTrue(csk instanceof SingleItemSketch); - assertEquals(union.getResult().getEstimate(), 1.0); - } - - @Test - public void checkRestricted() { - final SingleItemSketch sis = SingleItemSketch.create(1); - assertNull(sis.getMemorySegment()); - assertEquals(sis.getCompactPreambleLongs(), 1); - } - - @Test - public void unionWrapped() { - final ThetaSketch sketch = SingleItemSketch.create(1); - final ThetaUnion union = ThetaSetOperation.builder().buildUnion(); - final MemorySegment seg = MemorySegment.ofArray(sketch.toByteArray()); - union.union(seg ); - assertEquals(union.getResult().getEstimate(), 1, 0); - } - - @Test - public void buildAndCompact() { - UpdatableThetaSketch sk1; - CompactThetaSketch csk; - int bytes; - //On-heap - sk1 = UpdatableThetaSketch.builder().setNominalEntries(32).build(); - sk1.update(1); - csk = sk1.compact(true, null); - assertTrue(csk instanceof SingleItemSketch); - csk = sk1.compact(false, null); - assertTrue(csk instanceof SingleItemSketch); - - //Off-heap - bytes = ThetaSketch.getMaxUpdateSketchBytes(32); - MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - sk1= UpdatableThetaSketch.builder().setNominalEntries(32).build(wseg ); - sk1.update(1); - csk = sk1.compact(true, null); - assertTrue(csk instanceof SingleItemSketch); - csk = sk1.compact(false, null); - assertTrue(csk instanceof SingleItemSketch); - - bytes = ThetaSketch.getMaxCompactSketchBytes(1); - wseg = MemorySegment.ofArray(new byte[bytes]); - csk = sk1.compact(true, wseg ); - assertTrue(csk.isOrdered()); - csk = sk1.compact(false, wseg ); - assertTrue(csk.isOrdered()); - } - - @Test - public void intersection() { - UpdatableThetaSketch sk1, sk2; - CompactThetaSketch csk; - int bytes; - //ThetaIntersection on-heap - sk1 = UpdatableThetaSketch.builder().setNominalEntries(32).build(); - sk2 = UpdatableThetaSketch.builder().setNominalEntries(32).build(); - sk1.update(1); - sk1.update(2); - sk2.update(1); - ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(); - inter.intersect(sk1); - inter.intersect(sk2); - csk = inter.getResult(true, null); - assertTrue(csk instanceof SingleItemSketch); - - //ThetaIntersection off-heap - bytes = ThetaSetOperation.getMaxIntersectionBytes(32); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - inter = ThetaSetOperation.builder().buildIntersection(wseg ); - inter.intersect(sk1); - inter.intersect(sk2); - csk = inter.getResult(true, null); - assertTrue(csk instanceof SingleItemSketch); - csk = inter.getResult(false, null); - assertTrue(csk instanceof SingleItemSketch); - } - - @Test - public void union() { - UpdatableThetaSketch sk1, sk2; - CompactThetaSketch csk; - int bytes; - //ThetaUnion on-heap - sk1 = UpdatableThetaSketch.builder().setNominalEntries(32).build(); - sk2 = UpdatableThetaSketch.builder().setNominalEntries(32).build(); - sk1.update(1); - sk2.update(1); - ThetaUnion union = ThetaSetOperation.builder().buildUnion(); - union.union(sk1); - union.union(sk2); - csk = union.getResult(true, null); - assertTrue(csk instanceof SingleItemSketch); - - //ThetaUnion off-heap - bytes = ThetaSetOperation.getMaxUnionBytes(32); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - union = ThetaSetOperation.builder().buildUnion(wseg ); - union.union(sk1); - union.union(sk2); - csk = union.getResult(true, null); - assertTrue(csk instanceof SingleItemSketch); - csk = union.getResult(false, null); - assertTrue(csk instanceof SingleItemSketch); - } - - @Test - public void aNotB() { - UpdatableThetaSketch sk1, sk2; - CompactThetaSketch csk; - //ThetaAnotB on-heap - sk1 = UpdatableThetaSketch.builder().setNominalEntries(32).build(); - sk2 = UpdatableThetaSketch.builder().setNominalEntries(32).build(); - sk1.update(1); - sk2.update(2); - final ThetaAnotB aNotB = ThetaSetOperation.builder().buildANotB(); - aNotB.setA(sk1); - aNotB.notB(sk2); - csk = aNotB.getResult(true, null, true); - assertTrue(csk instanceof SingleItemSketch); - //not ThetaAnotB off-heap form - } - - @Test - public void checkHeapifyInstance() { - final UpdatableThetaSketch sk1 = new UpdatableThetaSketchBuilder().build(); - sk1.update(1); - final UpdatableThetaSketch sk2 = new UpdatableThetaSketchBuilder().build(); - sk2.update(1); - final ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection(); - inter.intersect(sk1); - inter.intersect(sk2); - final MemorySegment wseg = MemorySegment.ofArray(new byte[16]); - final CompactThetaSketch csk = inter.getResult(false, wseg ); - assertTrue(csk.isOrdered()); - final ThetaSketch csk2 = ThetaSketch.heapify(wseg ); - assertTrue(csk2 instanceof SingleItemSketch); - println(csk2.toString(true, true, 1, true)); - } - - @Test - public void checkSingleItemBadFlags() { - final short defaultSeedHash = Util.computeSeedHash(Util.DEFAULT_UPDATE_SEED); - final UpdatableThetaSketch sk1 = new UpdatableThetaSketchBuilder().build(); - sk1.update(1); - final MemorySegment wseg = MemorySegment.ofArray(new byte[16]); - sk1.compact(true, wseg ); - wseg .set(JAVA_BYTE, 5, (byte) 0); //corrupt flags to zero - try { - SingleItemSketch.heapify(wseg , defaultSeedHash); //fails due to corrupted flags bytes - fail(); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkDirectUnionSingleItem2() { - ThetaSketch sk = ThetaSketch.wrap(siSkWoutSiFlag24Bytes()); - assertEquals(sk.getEstimate(), 1.0, 0.0); - //println(sk.toString()); - sk = ThetaSketch.wrap(siSkWithSiFlag24Bytes()); - assertEquals(sk.getEstimate(), 1.0, 0.0); - //println(sk.toString()); - } - - @Test - public void checkSingleItemCompact() { - final UpdatableThetaSketch sk1 = new UpdatableThetaSketchBuilder().build(); - sk1.update(1); - final CompactThetaSketch csk = sk1.compact(); - assertTrue(csk instanceof SingleItemSketch); - final CompactThetaSketch csk2 = csk.compact(); - assertEquals(csk, csk2); - final CompactThetaSketch csk3 = csk.compact(true, MemorySegment.ofArray(new byte[16])); - assertTrue(csk3 instanceof DirectCompactSketch); - assertEquals(csk2.getCurrentPreambleLongs(), 1); - assertEquals(csk3.getCurrentPreambleLongs(), 1); - } - - - static final long SiSkPre0WithSiFlag = 0x93cc3a0000030301L; - static final long SiSkPre0WoutSiFlag = 0x93cc1a0000030301L; - static final long Hash = 0x05a186bdcb7df915L; - - static MemorySegment siSkWithSiFlag24Bytes() { - final int cap = 24; //8 extra bytes - final MemorySegment wseg = MemorySegment.ofArray(new byte[cap]); - wseg .set(JAVA_LONG_UNALIGNED, 0, SiSkPre0WithSiFlag); - wseg .set(JAVA_LONG_UNALIGNED, 8, Hash); - return wseg ; - } - - static MemorySegment siSkWoutSiFlag24Bytes() { - final int cap = 24; //8 extra bytes - final MemorySegment wseg = MemorySegment.ofArray(new byte[cap]); - wseg .set(JAVA_LONG_UNALIGNED, 0, SiSkPre0WoutSiFlag); - wseg .set(JAVA_LONG_UNALIGNED, 8, Hash); - return wseg; - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/SketchMiscTest.java b/src/test/java/org/apache/datasketches/theta/SketchMiscTest.java deleted file mode 100644 index cc896e344..000000000 --- a/src/test/java/org/apache/datasketches/theta/SketchMiscTest.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.testng.Assert.assertEquals; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.thetacommon.ThetaUtil; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class SketchMiscTest { - - private static MemorySegment getCompactSketchMemorySegment(final int k, final int from, final int to) { - final UpdatableThetaSketch sk1 = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - for (int i=from; i 1) { assertEquals(maxCompBytes, 24 + (i * 8)); } //assumes maybe estimation mode - } - } - - @Test - public void checkBuilder() { - final int k = 2048; - final int lgK = Integer.numberOfTrailingZeros(k); - final long seed = 1021; - final float p = (float)0.5; - final ResizeFactor rf = X4; - final Family fam = Family.ALPHA; - - UpdatableThetaSketch sk1 = UpdatableThetaSketch.builder().setSeed(seed) - .setP(p).setResizeFactor(rf).setFamily(fam).setNominalEntries(k).build(); - String nameS1 = sk1.getClass().getSimpleName(); - assertEquals(nameS1, "HeapAlphaSketch"); - assertEquals(sk1.getLgNomLongs(), lgK); - assertEquals(sk1.getSeed(), seed); - assertEquals(sk1.getP(), p); - - //check reset of defaults - - sk1 = UpdatableThetaSketch.builder().build(); - nameS1 = sk1.getClass().getSimpleName(); - assertEquals(nameS1, "HeapQuickSelectSketch"); - assertEquals(sk1.getLgNomLongs(), Integer.numberOfTrailingZeros(ThetaUtil.DEFAULT_NOMINAL_ENTRIES)); - assertEquals(sk1.getSeed(), Util.DEFAULT_UPDATE_SEED); - assertEquals(sk1.getP(), (float)1.0); - assertEquals(sk1.getResizeFactor(), ResizeFactor.X8); - } - - @Test - public void checkBuilderNonPowerOf2() { - final int k = 1000; - final UpdatableThetaSketch sk = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - assertEquals(sk.getLgNomLongs(), 10); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBuilderIllegalP() { - final float p = (float)1.5; - UpdatableThetaSketch.builder().setP(p).build(); - } - - @Test - public void checkBuilderResizeFactor() { - ResizeFactor rf; - rf = X1; - assertEquals(rf.getValue(), 1); - assertEquals(rf.lg(), 0); - assertEquals(ResizeFactor.getRF(0), X1); - rf = X2; - assertEquals(rf.getValue(), 2); - assertEquals(rf.lg(), 1); - assertEquals(ResizeFactor.getRF(1), X2); - rf = X4; - assertEquals(rf.getValue(), 4); - assertEquals(rf.lg(), 2); - assertEquals(ResizeFactor.getRF(2), X4); - rf = X8; - assertEquals(rf.getValue(), 8); - assertEquals(rf.lg(), 3); - assertEquals(ResizeFactor.getRF(3), X8); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkWrapBadFamily() { - final UpdatableThetaSketch sketch = UpdatableThetaSketch.builder().setFamily(Family.ALPHA).setNominalEntries(1024).build(); - final byte[] byteArr = sketch.toByteArray(); - final MemorySegment srcSeg = MemorySegment.ofArray(byteArr); - ThetaSketch.wrap(srcSeg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadFamily() { - UpdatableThetaSketch.builder().setFamily(Family.INTERSECTION).setNominalEntries(1024).build(); - } - - @SuppressWarnings("static-access") - @Test - public void checkSerVer() { - final UpdatableThetaSketch sketch = UpdatableThetaSketch.builder().setNominalEntries(1024).build(); - final byte[] sketchArray = sketch.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(sketchArray); - int serVer = ThetaSketch.getSerializationVersion(seg); - assertEquals(serVer, 3); - final MemorySegment wseg = MemorySegment.ofArray(sketchArray); - final UpdatableThetaSketch sk2 = UpdatableThetaSketch.wrap(wseg); - serVer = sk2.getSerializationVersion(wseg); - assertEquals(serVer, 3); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyAlphaCompactExcep() { - final int k = 512; - final ThetaSketch sketch1 = UpdatableThetaSketch.builder().setFamily(ALPHA).setNominalEntries(k).build(); - final byte[] byteArray = sketch1.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArray); - //corrupt: - Util.setBits(seg, FLAGS_BYTE, (byte) COMPACT_FLAG_MASK); - ThetaSketch.heapify(seg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyQSCompactExcep() { - final int k = 512; - final ThetaSketch sketch1 = UpdatableThetaSketch.builder().setFamily(QUICKSELECT).setNominalEntries(k).build(); - final byte[] byteArray = sketch1.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArray); - //corrupt: - Util.setBits(seg, FLAGS_BYTE, (byte) COMPACT_FLAG_MASK); - ThetaSketch.heapify(seg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyNotCompactExcep() { - final int k = 512; - final UpdatableThetaSketch sketch1 = UpdatableThetaSketch.builder().setFamily(QUICKSELECT).setNominalEntries(k).build(); - final int bytes = ThetaSketch.getMaxCompactSketchBytes(0); - final byte[] byteArray = new byte[bytes]; - final MemorySegment seg = MemorySegment.ofArray(byteArray); - sketch1.compact(false, seg); - //corrupt: - Util.clearBits(seg, FLAGS_BYTE, (byte) COMPACT_FLAG_MASK); - ThetaSketch.heapify(seg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHeapifyFamilyExcep() { - final int k = 512; - final ThetaUnion union = ThetaSetOperation.builder().setNominalEntries(k).buildUnion(); - final byte[] byteArray = union.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArray); - //Improper use - ThetaSketch.heapify(seg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkWrapAlphaCompactExcep() { - final int k = 512; - final ThetaSketch sketch1 = UpdatableThetaSketch.builder().setFamily(ALPHA).setNominalEntries(k).build(); - final byte[] byteArray = sketch1.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArray); - //corrupt: - Util.setBits(seg, FLAGS_BYTE, (byte) COMPACT_FLAG_MASK); - ThetaSketch.wrap(seg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkWrapQSCompactExcep() { - final int k = 512; - final ThetaSketch sketch1 = UpdatableThetaSketch.builder().setFamily(QUICKSELECT).setNominalEntries(k).build(); - final byte[] byteArray = sketch1.toByteArray(); - final MemorySegment seg = MemorySegment.ofArray(byteArray); - //corrupt: - Util.setBits(seg, FLAGS_BYTE, (byte) COMPACT_FLAG_MASK); - ThetaSketch.wrap(seg); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkWrapNotCompactExcep() { - final int k = 512; - final UpdatableThetaSketch sketch1 = UpdatableThetaSketch.builder().setFamily(QUICKSELECT).setNominalEntries(k).build(); - final int bytes = ThetaSketch.getMaxCompactSketchBytes(0); - final byte[] byteArray = new byte[bytes]; - final MemorySegment seg = MemorySegment.ofArray(byteArray); - sketch1.compact(false, seg); - //corrupt: - Util.clearBits(seg, FLAGS_BYTE, (byte) COMPACT_FLAG_MASK); - ThetaSketch.wrap(seg); - } - - @Test - public void checkValidSketchID() { - assertFalse(ThetaSketch.isValidSketchID(0)); - assertTrue(ThetaSketch.isValidSketchID(ALPHA.getID())); - assertTrue(ThetaSketch.isValidSketchID(QUICKSELECT.getID())); - assertTrue(ThetaSketch.isValidSketchID(COMPACT.getID())); - } - - @Test - public void checkIsSameResource() { - final int k = 16; - final MemorySegment seg = MemorySegment.ofArray(new byte[(k*16) + 24]); //280 - final MemorySegment cseg = MemorySegment.ofArray(new byte[32]); - final UpdatableThetaSketch sketch = UpdatableThetaSketch.builder().setNominalEntries(k).build(seg); - sketch.update(1); - sketch.update(2); - assertTrue(sketch.isSameResource(seg)); - final DirectCompactSketch dcos = (DirectCompactSketch) sketch.compact(true, cseg); - assertTrue(MemorySegmentStatus.isSameResource(dcos.getMemorySegment(), cseg)); - assertTrue(dcos.isOrdered()); - //never create 2 sketches with the same MemorySegment, so don't do as I do :) - final DirectCompactSketch dcs = (DirectCompactSketch) sketch.compact(false, cseg); - assertTrue(MemorySegmentStatus.isSameResource(dcs.getMemorySegment(), cseg)); - assertFalse(dcs.isOrdered()); - } - - @Test - public void checkCountLessThanTheta() { - final int k = 512; - final UpdatableThetaSketch sketch1 = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - for (int i = 0; i < (2*k); i++) { sketch1.update(i); } - - final double theta = sketch1.rebuild().getTheta(); - final long thetaLong = (long) (LONG_MAX_VALUE_AS_DOUBLE * theta); - final int count = sketch1.getCountLessThanThetaLong(thetaLong); - assertEquals(count, k); - } - - private static MemorySegment createCompactSketchMemorySegment(final int k, final int u) { - final UpdatableThetaSketch usk = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - for (int i = 0; i < u; i++) { usk.update(i); } - final int bytes = ThetaSketch.getMaxCompactSketchBytes(usk.getRetainedEntries(true)); - final MemorySegment wseg = MemorySegment.ofArray(new byte[bytes]); - usk.compact(true, wseg); - return wseg; - } - - @Test - public void checkCompactFlagsOnWrap() { - final MemorySegment wseg = createCompactSketchMemorySegment(16, 32); - ThetaSketch sk = ThetaSketch.wrap(wseg); - assertTrue(sk instanceof CompactThetaSketch); - final int flags = PreambleUtil.extractFlags(wseg); - - final int flagsNoCompact = flags & ~COMPACT_FLAG_MASK; - PreambleUtil.insertFlags(wseg, flagsNoCompact); - try { - sk = ThetaSketch.wrap(wseg); - fail(); - } catch (final SketchesArgumentException e) { } - - final int flagsNoReadOnly = flags & ~READ_ONLY_FLAG_MASK; - PreambleUtil.insertFlags(wseg, flagsNoReadOnly); - try { - sk = ThetaSketch.wrap(wseg); - fail(); - } catch (final SketchesArgumentException e) { } - PreambleUtil.insertFlags(wseg, flags); //repair to original - PreambleUtil.insertSerVer(wseg, 5); - try { - sk = ThetaSketch.wrap(wseg); - fail(); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void checkCompactSizeAndFlagsOnHeapify() { - MemorySegment wseg = createCompactSketchMemorySegment(16, 32); - ThetaSketch sk = ThetaSketch.heapify(wseg); - assertTrue(sk instanceof CompactThetaSketch); - final int flags = PreambleUtil.extractFlags(wseg); - - final int flagsNoCompact = flags & ~READ_ONLY_FLAG_MASK; - PreambleUtil.insertFlags(wseg, flagsNoCompact); - try { - sk = ThetaSketch.heapify(wseg); - fail(); - } catch (final SketchesArgumentException e) { } - - wseg = MemorySegment.ofArray(new byte[7]); - PreambleUtil.insertSerVer(wseg, 3); - //PreambleUtil.insertFamilyID(wseg, 3); - try { - sk = ThetaSketch.heapify(wseg); - fail(); - } catch (final SketchesArgumentException e) { } - } - - @Test - public void check2Methods() { - final int k = 16; - final ThetaSketch sk = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - final int bytes1 = sk.getCompactBytes(); - final int bytes2 = sk.getCurrentBytes(); - assertEquals(bytes1, 8); - assertEquals(bytes2, 280); //32*8 + 24 - final int retEnt = sk.getRetainedEntries(); - assertEquals(retEnt, 0); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/ThetaSketchCrossLanguageTest.java b/src/test/java/org/apache/datasketches/theta/ThetaSketchCrossLanguageTest.java deleted file mode 100644 index c9cf0361b..000000000 --- a/src/test/java/org/apache/datasketches/theta/ThetaSketchCrossLanguageTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES; -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.getFileBytes; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -/** - * Serialize binary sketches to be tested by C++ code. - * Test deserialization of binary sketches serialized by C++ code. - */ -public class ThetaSketchCrossLanguageTest { - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTesting() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (final int n: nArr) { - final UpdatableThetaSketch sk = UpdatableThetaSketch.builder().build(); - for (int i = 0; i < n; i++) { - sk.update(i); - } - putBytesToJavaPath("theta_n" + n + "_java.sk", sk.compact().toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingCompressed() throws IOException { - final int[] nArr = {10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (final int n: nArr) { - final UpdatableThetaSketch sk = UpdatableThetaSketch.builder().build(); - for (int i = 0; i < n; i++) { - sk.update(i); - } - putBytesToJavaPath("theta_compressed_n" + n + "_java.sk", sk.compact().toByteArrayCompressed()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingNonEmptyNoEntries() throws IOException { - final UpdatableThetaSketch sk = UpdatableThetaSketch.builder().setP(0.01f).build(); - sk.update(1); - assertFalse(sk.isEmpty()); - assertEquals(sk.getRetainedEntries(), 0); - putBytesToJavaPath("theta_non_empty_no_entries_java.sk", sk.compact().toByteArray()); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppSegment() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "theta_n" + n + "_cpp.sk"); - final CompactThetaSketch sketch = CompactThetaSketch.wrap(MemorySegment.ofArray(bytes)); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertEquals(sketch.getEstimate(), n, n * 0.03); - assertTrue(sketch.isOrdered()); - final HashIterator it = sketch.iterator(); - long previous = 0; - while (it.next()) { - assertTrue(it.get() < sketch.getThetaLong()); - assertTrue(it.get() > previous); - previous = it.get(); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppBytes() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "theta_n" + n + "_cpp.sk"); - final CompactThetaSketch sketch = CompactThetaSketch.wrap(bytes); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertEquals(sketch.getEstimate(), n, n * 0.03); - assertTrue(sketch.isOrdered()); - final HashIterator it = sketch.iterator(); - long previous = 0; - while (it.next()) { - assertTrue(it.get() < sketch.getThetaLong()); - assertTrue(it.get() > previous); - previous = it.get(); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppCompressedSegment() throws IOException { - final int[] nArr = {10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "theta_compressed_n" + n + "_cpp.sk"); - final CompactThetaSketch sketch = CompactThetaSketch.wrap(MemorySegment.ofArray(bytes)); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertEquals(sketch.getEstimate(), n, n * 0.03); - assertTrue(sketch.isOrdered()); - final HashIterator it = sketch.iterator(); - long previous = 0; - while (it.next()) { - assertTrue(it.get() < sketch.getThetaLong()); - assertTrue(it.get() > previous); - previous = it.get(); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppCompressedBytes() throws IOException { - final int[] nArr = {10, 100, 1000, 10000, 100000, 1000000}; - for (final int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "theta_compressed_n" + n + "_cpp.sk"); - final CompactThetaSketch sketch = CompactThetaSketch.wrap(bytes); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertEquals(sketch.getEstimate(), n, n * 0.03); - assertTrue(sketch.isOrdered()); - final HashIterator it = sketch.iterator(); - long previous = 0; - while (it.next()) { - assertTrue(it.get() < sketch.getThetaLong()); - assertTrue(it.get() > previous); - previous = it.get(); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppNonEmptyNoEntriesSegment() throws IOException { - final byte[] bytes = getFileBytes(cppPath, "theta_non_empty_no_entries_cpp.sk"); - final CompactThetaSketch sketch = CompactThetaSketch.wrap(MemorySegment.ofArray(bytes)); - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getRetainedEntries(), 0); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppNonEmptyNoEntriesBytes() throws IOException { - final byte[] bytes = getFileBytes(cppPath, "theta_non_empty_no_entries_cpp.sk"); - final CompactThetaSketch sketch = CompactThetaSketch.wrap(bytes); - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getRetainedEntries(), 0); - } - -} diff --git a/src/test/java/org/apache/datasketches/theta/UnionImplTest.java b/src/test/java/org/apache/datasketches/theta/UnionImplTest.java deleted file mode 100644 index 9187f6e4d..000000000 --- a/src/test/java/org/apache/datasketches/theta/UnionImplTest.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.theta; - -import static java.lang.foreign.ValueLayout.JAVA_BYTE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.Arena; -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.MemorySegmentStatus; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.testng.annotations.Test; - -public class UnionImplTest { - - @Test - public void checkGetCurrentAndMaxBytes() { - final int lgK = 10; - final ThetaUnion union = ThetaSetOperation.builder().setLogNominalEntries(lgK).buildUnion(); - assertEquals(union.getCurrentBytes(), 288); - assertEquals(union.getMaxUnionBytes(), 16416); - } - - @Test - public void checkUpdateWithSketch() { - final int k = 16; - final MemorySegment seg = MemorySegment.ofArray(new byte[(k*8) + 24]); - final MemorySegment seg2 = MemorySegment.ofArray(new byte[(k*8) + 24]); - final UpdatableThetaSketch sketch = UpdatableThetaSketch.builder().setNominalEntries(k).build(); - for (int i=0; i 0 && (lgT - lgA) % lgR != 0; - final boolean rf0 = lgR == 0 && lgA != lgT; - assertTrue(lgRbad == rf0 || lgRbad == rf123); - } - } - } - } - - @Test - public void checkCompactOpsMemorySegmentToCompact() { - MemorySegment skwseg, cskwseg1, cskwseg2, cskwseg3; - CompactThetaSketch csk1, csk2, csk3; - final int lgK = 6; - final UpdatableThetaSketch sk = UpdatableThetaSketch.builder().setLogNominalEntries(lgK).build(); - final int n = 1 << (lgK + 1); - for (int i = 2; i < n; i++) { sk.update(i); } - final int cbytes = sk.getCompactBytes(); - final byte[] byteArr = sk.toByteArray(); - skwseg = MemorySegment.ofArray(byteArr); //updatable seg - cskwseg1 = MemorySegment.ofArray(new byte[cbytes]); //empty - cskwseg2 = MemorySegment.ofArray(new byte[cbytes]); //empty - cskwseg3 = MemorySegment.ofArray(new byte[cbytes]); //empty - csk1 = sk.compact(true, cskwseg1); //cskwseg1 has compact sk image, csk1 is the sketch - csk2 = CompactOperations.segmentToCompact(skwseg, true, cskwseg2); //cskwseg2 has compact skwseg image - csk3 = CompactOperations.segmentToCompact(cskwseg1, true, cskwseg3); - assertTrue(equalContents(cskwseg1,cskwseg2)); - assertTrue(equalContents(cskwseg1, cskwseg3)); - assertTrue(csk1.hasMemorySegment()); - assertTrue(csk2.hasMemorySegment()); - assertTrue(csk3.hasMemorySegment()); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/thetacommon/BinomialBoundsNTest.java b/src/test/java/org/apache/datasketches/thetacommon/BinomialBoundsNTest.java deleted file mode 100644 index 8fa709074..000000000 --- a/src/test/java/org/apache/datasketches/thetacommon/BinomialBoundsNTest.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -import static org.apache.datasketches.thetacommon.BinomialBoundsN.checkArgs; -import static org.apache.datasketches.thetacommon.BinomialBoundsN.getLowerBound; -import static org.apache.datasketches.thetacommon.BinomialBoundsN.getUpperBound; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; -import static org.testng.Assert.assertThrows; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.thetacommon.BinomialBoundsN; -import org.testng.annotations.Test; - -/** - * @author Kevin Lang - */ -public class BinomialBoundsNTest { - - public static double[] runTestAux(final long max_numSamplesI, final int ci, final double min_p) { - long numSamplesI = 0; - double p, lb, ub; - double sum1 = 0.0; - double sum2 = 0.0; - double sum3 = 0.0; - double sum4 = 0.0; - long count = 0; - - while (numSamplesI <= max_numSamplesI) { /* was <= */ - p = 1.0; - - while (p >= min_p) { - lb = BinomialBoundsN.getLowerBound(numSamplesI, p, ci, false); - ub = BinomialBoundsN.getUpperBound(numSamplesI, p, ci, false); - - // if (numSamplesI == 300 && p > 0.365 && p < 0.367) { ub += 0.01; } // artificial discrepancy - - // the logarithm helps discrepancies to not be swamped out of the total - sum1 += Math.log(lb + 1.0); - sum2 += Math.log(ub + 1.0); - count += 2; - - if (p < 1.0) { - lb = BinomialBoundsN.getLowerBound(numSamplesI, 1.0 - p, ci, false); - ub = BinomialBoundsN.getUpperBound(numSamplesI, 1.0 - p, ci, false); - sum3 += Math.log(lb + 1.0); - sum4 += Math.log(ub + 1.0); - count += 2; - } - - p *= 0.99; - } - numSamplesI = Math.max(numSamplesI + 1, (1001 * numSamplesI) / 1000); - } - - println(String.format("{%.15e, %.15e, %.15e, %.15e, %d}", sum1, sum2, sum3, sum4, count)); - final double[] arrOut = {sum1, sum2, sum3, sum4, count}; - return arrOut; - } - - private static final double TOL = 1E-15; - - @Test - public static void checkBounds() { - int i = 0; - for (int ci = 1; ci <= 3; ci++, i++) { - final double[] arr = runTestAux(20, ci, 1e-3); - for (int j = 0; j < 5; j++) { - assertTrue(((arr[j] / std[i][j]) - 1.0) < TOL); - } - } - for (int ci = 1; ci <= 3; ci++, i++) { - final double[] arr = runTestAux(200, ci, 1e-5); - for (int j = 0; j < 5; j++) { - assertTrue(((arr[j] / std[i][j]) - 1.0) < TOL); - } - } - //comment last one out for a shorter test - // for (int ci = 1; ci <= 3; ci++, i++) { - // final double[] arr = runTestAux(2000, ci, 1e-7); - // for (int j = 0; j < 5; j++) { - // assertTrue(((arr[j] / std[i][j]) - 1.0) < TOL); - // } - //} - } - - // With all 3 enabled the test should produce in groups of 3 */ - private static final double[][] std = { - {7.083330682531043e+04, 8.530373642825481e+04, 3.273647725073409e+04, 3.734024243699785e+04, 57750}, - {6.539415269641498e+04, 8.945522372568645e+04, 3.222302546497840e+04, 3.904738469737429e+04, 57750}, - {6.006043493107306e+04, 9.318105731423477e+04, 3.186269956585285e+04, 4.096466221922520e+04, 57750}, - - {2.275584770163813e+06, 2.347586549014998e+06, 1.020399409477305e+06, 1.036729927598294e+06, 920982}, - {2.243569126699713e+06, 2.374663344107342e+06, 1.017017233582122e+06, 1.042597845553438e+06, 920982}, - {2.210056231903739e+06, 2.400441267999687e+06, 1.014081235946986e+06, 1.049480769755676e+06, 920982}, - - {4.688240115809608e+07, 4.718067204619278e+07, 2.148362024482338e+07, 2.153118905212302e+07, 12834414}, - {4.674205938540214e+07, 4.731333757486791e+07, 2.146902141966406e+07, 2.154916650733873e+07, 12834414}, - {4.659896614422579e+07, 4.744404182094614e+07, 2.145525391547799e+07, 2.156815612325058e+07, 12834414} - }; - - @Test - public static void checkCheckArgs() { - assertThrows(SketchesArgumentException.class, - () -> checkArgs(-1L, 1.0, 1)); - assertThrows(SketchesArgumentException.class, - () -> checkArgs(10L, 0.0, 1)); - assertThrows(SketchesArgumentException.class, - () -> checkArgs(10L, 1.01, 1)); - checkArgs(10L, 1.0, 3); - assertThrows(SketchesArgumentException.class, - () -> checkArgs(10L, 1.0, 0)); - assertThrows(SketchesArgumentException.class, - () -> checkArgs(10L, 1.0, 4)); - } - - @Test - public static void checkComputeApproxBino_LB_UB() { - final long n = 100; - final double theta = (2.0 - 1e-5) / 2.0; - double result = getLowerBound(n, theta, 1, false); - assertEquals(result, n, 0.0); - result = getUpperBound(n, theta, 1, false); - assertEquals(result, n + 1, 0.0); - result = getLowerBound(n, theta, 1, true); - assertEquals(result, 0.0, 0.0); - result = getUpperBound(n, theta, 1, true); - assertEquals(result, 0.0, 0.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public static void checkThetaLimits1() { - BinomialBoundsN.getUpperBound(100, 1.1, 1, false); - } - - @Test - public static void boundsExample() { - println("BinomialBoundsN Example:"); - final int k = 500; - final double theta = 0.001; - final int stdDev = 2; - final double ub = BinomialBoundsN.getUpperBound(k, theta, stdDev, false); - final double est = k / theta; - final double lb = BinomialBoundsN.getLowerBound(k, theta, stdDev, false); - println("K=" + k + ", Theta=" + theta + ", SD=" + stdDev); - println("UB: " + ub); - println("Est: " + est); - println("LB: " + lb); - println(""); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInThetaSketchedSetsTest.java b/src/test/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInThetaSketchedSetsTest.java deleted file mode 100644 index 0ed9dcb14..000000000 --- a/src/test/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInThetaSketchedSetsTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.theta.CompactThetaSketch; -import org.apache.datasketches.theta.ThetaIntersection; -import org.apache.datasketches.theta.ThetaSetOperation; -import org.apache.datasketches.theta.UpdatableThetaSketch; -import org.testng.annotations.Test; - -public class BoundsOnRatiosInThetaSketchedSetsTest { - - @Test - public void checkNormalReturns() { - final UpdatableThetaSketch skA = UpdatableThetaSketch.builder().build(); //4K - final UpdatableThetaSketch skC = UpdatableThetaSketch.builder().build(); - final int uA = 10000; - final int uC = 100000; - for (int i = 0; i < uA; i++) { skA.update(i); } - for (int i = 0; i < uC; i++) { skC.update(i + (uA / 2)); } - final ThetaIntersection inter = ThetaSetOperation.builder().buildIntersection();//SetOperation.builder().buildIntersection(); - inter.intersect(skA); - inter.intersect(skC); - final CompactThetaSketch skB = inter.getResult(); - - double est = BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(skA, skB); - double lb = BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(skA, skB); - double ub = BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(skA, skB); - assertTrue(ub > est); - assertTrue(est > lb); - assertEquals(est, 0.5, .03); - println("ub : " + ub); - println("est: " + est); - println("lb : " + lb); - skA.reset(); //skA is now empty - est = BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(skA, skB); - lb = BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(skA, skB); - ub = BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(skA, skB); - println("ub : " + ub); - println("est: " + est); - println("lb : " + lb); - skC.reset(); //Now both are empty - est = BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(skA, skC); - lb = BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(skA, skC); - ub = BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(skA, skC); - println("ub : " + ub); - println("est: " + est); - println("lb : " + lb); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkAbnormalReturns() { - final UpdatableThetaSketch skA = UpdatableThetaSketch.builder().build(); // 4K - final UpdatableThetaSketch skC = UpdatableThetaSketch.builder().build(); - final int uA = 100000; - final int uC = 10000; - for (int i = 0; i < uA; i++) { skA.update(i); } - for (int i = 0; i < uC; i++) { skC.update(i + (uA / 2)); } - BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(skA, skC); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInTupleSketchedSetsTest.java b/src/test/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInTupleSketchedSetsTest.java deleted file mode 100644 index 96452c012..000000000 --- a/src/test/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInTupleSketchedSetsTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.theta.UpdatableThetaSketch; -import org.apache.datasketches.theta.UpdatableThetaSketchBuilder; -import org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets; -import org.apache.datasketches.tuple.TupleIntersection; -import org.apache.datasketches.tuple.TupleSketch; -import org.apache.datasketches.tuple.UpdatableTupleSketch; -import org.apache.datasketches.tuple.UpdatableTupleSketchBuilder; -import org.apache.datasketches.tuple.adouble.DoubleSummary; -import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; -import org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations; -import org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -/** - * @author Lee Rhodes - * @author David Cromberge - */ -public class BoundsOnRatiosInTupleSketchedSetsTest { - - private final DoubleSummary.Mode umode = DoubleSummary.Mode.Sum; - private final DoubleSummarySetOperations dsso = new DoubleSummarySetOperations(); - private final DoubleSummaryFactory factory = new DoubleSummaryFactory(umode); - private final UpdatableThetaSketchBuilder thetaBldr = UpdatableThetaSketch.builder(); - private final UpdatableTupleSketchBuilder tupleBldr = new UpdatableTupleSketchBuilder<>(factory); - private final Double constSummary = 1.0; - - @Test - public void checkNormalReturns1() { // tuple, tuple - final UpdatableTupleSketch skA = tupleBldr.build(); //4K - final UpdatableTupleSketch skC = tupleBldr.build(); - final int uA = 10000; - final int uC = 100000; - for (int i = 0; i < uA; i++) { skA.update(i, constSummary); } - for (int i = 0; i < uC; i++) { skC.update(i + (uA / 2), constSummary); } - final TupleIntersection inter = new TupleIntersection<>(dsso); - inter.intersect(skA); - inter.intersect(skC); - final TupleSketch skB = inter.getResult(); - - double est = BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skB); - double lb = BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA(skA, skB); - double ub = BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA(skA, skB); - assertTrue(ub > est); - assertTrue(est > lb); - assertEquals(est, 0.5, .03); - println("ub : " + ub); - println("est: " + est); - println("lb : " + lb); - skA.reset(); //skA is now empty - est = BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skB); - lb = BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA(skA, skB); - ub = BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA(skA, skB); - println("ub : " + ub); - println("est: " + est); - println("lb : " + lb); - skC.reset(); //Now both are empty - est = BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skC); - lb = BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA(skA, skC); - ub = BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA(skA, skC); - println("ub : " + ub); - println("est: " + est); - println("lb : " + lb); - } - - @Test - public void checkNormalReturns2() { // tuple, theta - final UpdatableTupleSketch skA = tupleBldr.build(); //4K - final UpdatableThetaSketch skC = thetaBldr.build(); - final int uA = 10000; - final int uC = 100000; - for (int i = 0; i < uA; i++) { skA.update(i, constSummary); } - for (int i = 0; i < uC; i++) { skC.update(i + (uA / 2)); } - final TupleIntersection inter = new TupleIntersection<>(dsso); - inter.intersect(skA); - inter.intersect(skC, factory.newSummary()); - final TupleSketch skB = inter.getResult(); - - double est = BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skB); - double lb = BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA(skA, skB); - double ub = BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA(skA, skB); - assertTrue(ub > est); - assertTrue(est > lb); - assertEquals(est, 0.5, .03); - println("ub : " + ub); - println("est: " + est); - println("lb : " + lb); - skA.reset(); //skA is now empty - est = BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skB); - lb = BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA(skA, skB); - ub = BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA(skA, skB); - println("ub : " + ub); - println("est: " + est); - println("lb : " + lb); - skC.reset(); //Now both are empty - est = BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skC); - lb = BoundsOnRatiosInTupleSketchedSets.getLowerBoundForBoverA(skA, skC); - ub = BoundsOnRatiosInTupleSketchedSets.getUpperBoundForBoverA(skA, skC); - println("ub : " + ub); - println("est: " + est); - println("lb : " + lb); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkAbnormalReturns1() { // tuple, tuple - final UpdatableTupleSketch skA = tupleBldr.build(); //4K - final UpdatableTupleSketch skC = tupleBldr.build(); - final int uA = 100000; - final int uC = 10000; - for (int i = 0; i < uA; i++) { skA.update(i, constSummary); } - for (int i = 0; i < uC; i++) { skC.update(i + (uA / 2), constSummary); } - BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skC); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkAbnormalReturns2() { // tuple, theta - final UpdatableTupleSketch skA = tupleBldr.build(); //4K - final UpdatableThetaSketch skC = thetaBldr.build(); - final int uA = 100000; - final int uC = 10000; - for (int i = 0; i < uA; i++) { skA.update(i, constSummary); } - for (int i = 0; i < uC; i++) { skC.update(i + (uA / 2)); } - BoundsOnRatiosInTupleSketchedSets.getEstimateOfBoverA(skA, skC); - } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } -} diff --git a/src/test/java/org/apache/datasketches/thetacommon/HashOperationsTest.java b/src/test/java/org/apache/datasketches/thetacommon/HashOperationsTest.java deleted file mode 100644 index e13a0b498..000000000 --- a/src/test/java/org/apache/datasketches/thetacommon/HashOperationsTest.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -import static org.apache.datasketches.hash.MurmurHash3.hash; -import static org.apache.datasketches.thetacommon.HashOperations.checkHashCorruption; -import static org.apache.datasketches.thetacommon.HashOperations.checkThetaCorruption; -import static org.apache.datasketches.thetacommon.HashOperations.continueCondition; -import static org.apache.datasketches.thetacommon.HashOperations.hashArrayInsert; -import static org.apache.datasketches.thetacommon.HashOperations.hashInsertOnly; -import static org.apache.datasketches.thetacommon.HashOperations.hashInsertOnlyMemorySegment; -import static org.apache.datasketches.thetacommon.HashOperations.hashSearch; -import static org.apache.datasketches.thetacommon.HashOperations.hashSearchMemorySegment; -import static org.apache.datasketches.thetacommon.HashOperations.hashSearchOrInsert; -import static org.apache.datasketches.thetacommon.HashOperations.hashSearchOrInsertMemorySegment; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.testng.annotations.Test; - -public class HashOperationsTest { - - //Not otherwise already covered - - @Test(expectedExceptions = SketchesStateException.class) - public void testThetaCorruption1() { - checkThetaCorruption(0); - } - - @Test(expectedExceptions = SketchesStateException.class) - public void testThetaCorruption2() { - checkThetaCorruption(-1); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void testHashCorruption() { - checkHashCorruption(-1); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkHashSearch() { - hashSearch(new long[4], 2, 0); - } - - @Test - public void checkHashArrayInsert() { - final long[] hTable = new long[16]; - final long[] hashIn = new long[1]; - for (int i = 0; i < 8; i++) { - hashIn[0] = i; - final long h = hash(hashIn, 0)[0] >>> 1; - hashInsertOnly(hTable, 4, h); - final int count = hashArrayInsert(hTable, hTable, 4, Long.MAX_VALUE); - assertEquals(count, 0); - } - - } - - @Test - public void testContinueCondtion() { - final long thetaLong = Long.MAX_VALUE / 2; - assertTrue(continueCondition(thetaLong, 0)); - assertTrue(continueCondition(thetaLong, thetaLong)); - assertTrue(continueCondition(thetaLong, thetaLong + 1)); - assertFalse(continueCondition(thetaLong, thetaLong - 1)); - } - - @Test - public void testHashInsertOnlyNoStride() { - final long[] table = new long[32]; - final int index = hashInsertOnly(table, 5, 1); - assertEquals(index, 1); - assertEquals(table[1], 1L); - } - - @Test - public void testHashInsertOnlyWithStride() { - final long[] table = new long[32]; - table[1] = 1; - final int index = hashInsertOnly(table, 5, 1); - assertEquals(index, 2); - assertEquals(table[2], 1L); - } - - @Test - public void testHashInsertOnlyMemorySegmentNoStride() { - final long[] table = new long[32]; - final MemorySegment seg = MemorySegment.ofArray(table); - final int index = hashInsertOnlyMemorySegment(seg, 5, 1, 0); - assertEquals(index, 1); - assertEquals(table[1], 1L); - } - - @Test - public void testHashInsertOnlyMemorySegmentWithStride() { - final long[] table = new long[32]; - table[1] = 1; - final MemorySegment seg = MemorySegment.ofArray(table); - final int index = hashInsertOnlyMemorySegment(seg, 5, 1, 0); - assertEquals(index, 2); - assertEquals(table[2], 1L); - } - - @Test - public void checkFullHeapTableCatchesInfiniteLoop() { - final long[] table = new long[32]; - for (int i = 1; i <= 32; ++i) { - hashInsertOnly(table, 5, i); - } - - // table full; search returns not found, others throw exception - final int retVal = hashSearch(table, 5, 33); - assertEquals(retVal, -1); - - try { - hashInsertOnly(table, 5, 33); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - try { - hashSearchOrInsert(table, 5, 33); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - } - - @Test - public void checkFullDirectTableCatchesInfiniteLoop() { - final long[] table = new long[32]; - final MemorySegment seg = MemorySegment.ofArray(table); - for (int i = 1; i <= 32; ++i) { - hashInsertOnlyMemorySegment(seg, 5, i, 0); - } - - // table full; search returns not found, others throw exception - final int retVal = hashSearchMemorySegment(seg, 5, 33, 0); - assertEquals(retVal, -1); - - try { - hashInsertOnlyMemorySegment(seg, 5, 33, 0); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - try { - hashSearchOrInsertMemorySegment(seg, 5, 33, 0); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - } - - @Test - public void checkFullFastDirectTableCatchesInfiniteLoop() { - final long[] table = new long[32]; - final MemorySegment wseg = MemorySegment.ofArray(table); - - for (int i = 1; i <= 32; ++i) { - hashInsertOnlyMemorySegment(wseg, 5, i, 0); - } - - // table full; throws exception - try { - hashInsertOnlyMemorySegment(wseg, 5, 33, 0); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - - try { - hashSearchOrInsertMemorySegment(wseg, 5, 33, 0); - fail(); - } catch (final SketchesArgumentException e) { - // expected - } - } - - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/thetacommon/QuickSelectTest.java b/src/test/java/org/apache/datasketches/thetacommon/QuickSelectTest.java deleted file mode 100644 index f812a7509..000000000 --- a/src/test/java/org/apache/datasketches/thetacommon/QuickSelectTest.java +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -import static java.lang.String.format; -import static org.apache.datasketches.common.QuickSelect.select; -import static org.apache.datasketches.common.QuickSelect.selectExcludingZeros; -import static org.apache.datasketches.common.QuickSelect.selectIncludingZeros; - -import java.util.Random; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.testng.Assert; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class QuickSelectTest { - private static final String LS = System.getProperty("line.separator"); - private static final Random random = new Random(); // pseudo-random number generator - - //long[] arrays - - @Test - public void checkQuickSelect0Based() { - final int len = 64; - final long[] arr = new long[len]; - for (int i = 0; i < len; i++ ) { - arr[i] = i; - } - for (int pivot = 0; pivot < 64; pivot++ ) { - final long trueVal = pivot; - for (int i = 0; i < 1000; i++ ) { - shuffle(arr); - final long retVal = select(arr, 0, len - 1, pivot); - Assert.assertEquals(retVal, trueVal); - } - } - } - - @Test - public void checkQuickSelect1BasedExcludingZeros() { - final int len = 64; - final int nonZeros = (7 * len) / 8; - final long[] arr = new long[len]; - for (int i = 0; i < nonZeros; i++ ) { - arr[i] = i + 1; - } - final int pivot = len / 2; - final long trueVal = arr[pivot - 1]; - shuffle(arr); - final long retVal = selectExcludingZeros(arr, nonZeros, pivot); - Assert.assertEquals(retVal, trueVal); - } - - @Test - public void checkQuickSelect1BasedExcludingZeros2() { - final int len = 64; - final int nonZeros = 16; - final long[] arr = new long[len]; - for (int i = 0; i < nonZeros; i++ ) { - arr[i] = i + 1; - } - shuffle(arr); - final int pivot = len / 2; - final long retVal = selectExcludingZeros(arr, nonZeros, pivot); - Assert.assertEquals(retVal, 0); - } - - @Test - public void checkQuickSelect1BasedIncludingZeros() { - final int len = 64; - final int zeros = len / 8; - final long[] arr = new long[len]; - for (int i = zeros; i < len; i++ ) { - arr[i] = i + 1; - } - final int pivot = len / 2; - final long trueVal = arr[pivot - 1]; - shuffle(arr); - final long retVal = selectIncludingZeros(arr, pivot); - Assert.assertEquals(retVal, trueVal); - } - - //double[] arrays - - @Test - public void checkQuickSelectDbl0Based() { - final int len = 64; - final double[] arr = new double[len]; - for (int i = 0; i < len; i++ ) { - arr[i] = i; - } - for (int pivot = 0; pivot < 64; pivot++ ) { - final double trueVal = pivot; - for (int i = 0; i < 1000; i++ ) { - shuffle(arr); - final double retVal = select(arr, 0, len - 1, pivot); - Assert.assertEquals(retVal, trueVal, 0.0); - } - } - } - - @Test - public void checkQuickSelectDbl1BasedExcludingZeros() { - final int len = 64; - final int nonZeros = (7 * len) / 8; - final double[] arr = new double[len]; - for (int i = 0; i < nonZeros; i++ ) { - arr[i] = i + 1; - } - final int pivot = len / 2; - final double trueVal = arr[pivot - 1]; - shuffle(arr); - final double retVal = selectExcludingZeros(arr, nonZeros, pivot); - Assert.assertEquals(retVal, trueVal, 0.0); - } - - @Test - public void checkQuickSelectDbl1BasedExcludingZeros2() { - final int len = 64; - final int nonZeros = 16; - final double[] arr = new double[len]; - for (int i = 0; i < nonZeros; i++ ) { - arr[i] = i + 1; - } - shuffle(arr); - final int pivot = len / 2; - final double retVal = selectExcludingZeros(arr, nonZeros, pivot); - Assert.assertEquals(retVal, 0, 0.0); - } - - @Test - public void checkQuickSelectDbl1BasedIncludingZeros() { - final int len = 64; - final int zeros = len / 8; - final double[] arr = new double[len]; - for (int i = zeros; i < len; i++ ) { - arr[i] = i + 1; - } - final int pivot = len / 2; - final double trueVal = arr[pivot - 1]; - shuffle(arr); - final double retVal = selectIncludingZeros(arr, pivot); - Assert.assertEquals(retVal, trueVal, 0.0); - } - - - /** - * Rearrange the elements of an array in random order. - * @param a long array - */ - public static void shuffle(final long[] a) { - final int N = a.length; - for (int i = 0; i < N; i++ ) { - final int r = i + uniform(N - i); // between i and N-1 - final long temp = a[i]; - a[i] = a[r]; - a[r] = temp; - } - } - - /** - * Rearrange the elements of an array in random order. - * @param a double array - */ - public static void shuffle(final double[] a) { - final int N = a.length; - for (int i = 0; i < N; i++ ) { - final int r = i + uniform(N - i); // between i and N-1 - final double temp = a[i]; - a[i] = a[r]; - a[r] = temp; - } - } - - - /** - * Returns an integer uniformly between 0 (inclusive) and n (exclusive) where {@code n > 0} - * - * @param n the upper exclusive bound - * @return random integer - */ - public static int uniform(final int n) { - if (n <= 0) { - throw new SketchesArgumentException("n must be positive"); - } - return random.nextInt(n); - } - - private static String printArr(final long[] arr) { - final StringBuilder sb = new StringBuilder(); - final int len = arr.length; - sb.append(" Base0").append(" Base1").append(" Value").append(LS); - for (int i = 0; i < len; i++ ) { - sb - .append(format("%6d", i)).append(format("%6d", i + 1)).append(format("%6d", arr[i])) - .append(LS); - } - return sb.toString(); - } - - private static String printArr(final double[] arr) { - final StringBuilder sb = new StringBuilder(); - final int len = arr.length; - sb.append(" Base0").append(" Base1").append(" Value").append(LS); - for (int i = 0; i < len; i++ ) { - sb - .append(format("%6d", i)).append(format("%6d", i + 1)).append(format("%9.3f", arr[i])) - .append(LS); - } - return sb.toString(); - } - - //For console testing - static void test1() { - final int len = 16; - final int nonZeros = (3 * len) / 4; - final int zeros = len - nonZeros; - final long[] arr = new long[len]; - for (int i = 0; i < nonZeros; i++ ) { - arr[i] = i + 1; - } - println("Generated Numbers:"); - println(printArr(arr)); - shuffle(arr); - println("Randomized Ordering:"); - println(printArr(arr)); - final int pivot = len / 2; - println("select(...):"); - println("ArrSize : " + len); - println("NonZeros: " + nonZeros); - println("Zeros : " + zeros); - println("Choose pivot at 1/2 array size, pivot: " + pivot); - final long ret = select(arr, 0, len - 1, pivot); - println("Return value of 0-based pivot including zeros:"); - println("select(arr, 0, " + (len - 1) + ", " + pivot + ") => " + ret); - println("0-based index of pivot = pivot = " + (pivot)); - println("Result Array:" + LS); - println(printArr(arr)); - } - - //For console testing - static void test2() { - final int len = 16; - final int nonZeros = (3 * len) / 4; - final int zeros = len - nonZeros; - final long[] arr = new long[len]; - for (int i = 0; i < nonZeros; i++ ) { - arr[i] = i + 1; - } - println("Generated Numbers:"); - println(printArr(arr)); - shuffle(arr); - println("Randomized Ordering:"); - println(printArr(arr)); - final int pivot = len / 2; //= 8 - println("selectDiscountingZeros(...):"); - println("ArrSize : " + len); - println("NonZeros: " + nonZeros); - println("Zeros : " + zeros); - println("Choose pivot at 1/2 array size, pivot= " + pivot); - final long ret = selectExcludingZeros(arr, nonZeros, pivot); - println("Return value of 1-based pivot discounting zeros:"); - println("selectDiscountingZeros(arr, " + nonZeros + ", " + pivot + ") => " + ret); - println("0-based index of pivot= pivot+zeros-1 = " + ((pivot + zeros) - 1)); - println("Result Array:" + LS); - println(printArr(arr)); - } - - //For console testing - static void test3() { - final int len = 16; - final int nonZeros = (3 * len) / 4; - final int zeros = len - nonZeros; - final long[] arr = new long[len]; - for (int i = 0; i < nonZeros; i++ ) { - arr[i] = i + 1; - } - println("Generated Numbers:"); - println(printArr(arr)); - shuffle(arr); - println("Randomized Ordering:"); - println(printArr(arr)); - final int pivot = len / 2; //= 8 - println("selectIncludingZeros(...):"); - println("ArrSize : " + len); - println("NonZeros: " + nonZeros); - println("Zeros : " + zeros); - println("Choose pivot at 1/2 array size, pivot= " + pivot); - final long ret = selectIncludingZeros(arr, pivot); - println("Return value of 1-based pivot including zeros:"); - println("selectIncludingZeros(arr, " + pivot + ") => " + ret); - println("0-based index of pivot= pivot-1 = " + (pivot - 1)); - println("Result Array:" + LS); - println(printArr(arr)); - } - - static void testDbl1() { - final int len = 16; - final int nonZeros = (3 * len) / 4; - final int zeros = len - nonZeros; - final double[] arr = new double[len]; - for (int i = 0; i < nonZeros; i++ ) { - arr[i] = i + 1; - } - println("Generated Numbers:"); - println(printArr(arr)); - shuffle(arr); - println("Randomized Ordering:"); - println(printArr(arr)); - final int pivot = len / 2; - println("select(...):"); - println("ArrSize : " + len); - println("NonZeros: " + nonZeros); - println("Zeros : " + zeros); - println("Choose pivot at 1/2 array size, pivot: " + pivot); - final double ret = select(arr, 0, len - 1, pivot); - println("Return value of 0-based pivot including zeros:"); - println("select(arr, 0, " + (len - 1) + ", " + pivot + ") => " + ret); - println("0-based index of pivot = pivot = " + (pivot)); - println("Result Array:" + LS); - println(printArr(arr)); - } - - //For console testing - static void testDbl2() { - final int len = 16; - final int nonZeros = (3 * len) / 4; - final int zeros = len - nonZeros; - final double[] arr = new double[len]; - for (int i = 0; i < nonZeros; i++ ) { - arr[i] = i + 1; - } - println("Generated Numbers:"); - println(printArr(arr)); - shuffle(arr); - println("Randomized Ordering:"); - println(printArr(arr)); - final int pivot = len / 2; //= 8 - println("selectDiscountingZeros(...):"); - println("ArrSize : " + len); - println("NonZeros: " + nonZeros); - println("Zeros : " + zeros); - println("Choose pivot at 1/2 array size, pivot= " + pivot); - final double ret = selectExcludingZeros(arr, nonZeros, pivot); - println("Return value of 1-based pivot discounting zeros:"); - println("selectDiscountingZeros(arr, " + nonZeros + ", " + pivot + ") => " + ret); - println("0-based index of pivot= pivot+zeros-1 = " + ((pivot + zeros) - 1)); - println("Result Array:" + LS); - println(printArr(arr)); - } - - //For console testing - static void testDbl3() { - final int len = 16; - final int nonZeros = (3 * len) / 4; - final int zeros = len - nonZeros; - final double[] arr = new double[len]; - for (int i = 0; i < nonZeros; i++ ) { - arr[i] = i + 1; - } - println("Generated Numbers:"); - println(printArr(arr)); - shuffle(arr); - println("Randomized Ordering:"); - println(printArr(arr)); - final int pivot = len / 2; //= 8 - println("selectIncludingZeros(...):"); - println("ArrSize : " + len); - println("NonZeros: " + nonZeros); - println("Zeros : " + zeros); - println("Choose pivot at 1/2 array size, pivot= " + pivot); - final double ret = selectIncludingZeros(arr, pivot); - println("Return value of 1-based pivot including zeros:"); - println("selectIncludingZeros(arr, " + pivot + ") => " + ret); - println("0-based index of pivot= pivot-1 = " + (pivot - 1)); - println("Result Array:" + LS); - println(printArr(arr)); - } - - // public static void main(String[] args) { - // println(LS+"==LONGS 1=========="+LS); - // test1(); - // println(LS+"==LONGS 2=========="+LS); - // test2(); - // println(LS+"==LONGS 3=========="+LS); - // test3(); - // println(LS+"==DOUBLES 1========"+LS); - // testDbl1(); - // println(LS+"==DOUBLES 2========"+LS); - // testDbl2(); - // println(LS+"==DOUBLES 3========"+LS); - // testDbl3(); - // - // - // QuickSelectTest qst = new QuickSelectTest(); - // qst.checkQuickSelect0Based(); - // qst.checkQuickSelect1BasedExcludingZeros(); - // qst.checkQuickSelect1BasedExcludingZeros2(); - // qst.checkQuickSelect1BasedIncludingZeros(); - // qst.checkQuickSelectDbl0Based(); - // qst.checkQuickSelectDbl1BasedExcludingZeros(); - // qst.checkQuickSelectDbl1BasedExcludingZeros2(); - // qst.checkQuickSelectDbl1BasedIncludingZeros(); - // - // } - - @Test - public void printlnTest() { - println("PRINTING: " + this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //disable here - } - - /** - * @param d value to print - */ - static void println(final double d) { - //System.out.println(d); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/thetacommon/ThetaUtilTest.java b/src/test/java/org/apache/datasketches/thetacommon/ThetaUtilTest.java deleted file mode 100644 index 2a7628470..000000000 --- a/src/test/java/org/apache/datasketches/thetacommon/ThetaUtilTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.thetacommon; - -import org.apache.datasketches.quantilescommon.QuantilesUtil; -import org.apache.datasketches.thetacommon.ThetaUtil; -import org.testng.Assert; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class ThetaUtilTest { - - @Test - public void checkStartingSubMultiple() { - Assert.assertEquals(ThetaUtil.startingSubMultiple(8, 3, 4), 5); - Assert.assertEquals(ThetaUtil.startingSubMultiple(7, 3, 4), 4); - Assert.assertEquals(ThetaUtil.startingSubMultiple(6, 3, 4), 6); - } - - @Test(expectedExceptions = NullPointerException.class) - public void checkValidateValuesNullException() { - QuantilesUtil.checkDoublesSplitPointsOrder(null); - } - -} - diff --git a/src/test/java/org/apache/datasketches/tuple/CompactSketchWithDoubleSummaryTest.java b/src/test/java/org/apache/datasketches/tuple/CompactSketchWithDoubleSummaryTest.java deleted file mode 100644 index ab855b583..000000000 --- a/src/test/java/org/apache/datasketches/tuple/CompactSketchWithDoubleSummaryTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.CompactTupleSketch; -import org.apache.datasketches.tuple.TupleSketch; -import org.apache.datasketches.tuple.TupleSketchIterator; -import org.apache.datasketches.tuple.UpdatableTupleSketch; -import org.apache.datasketches.tuple.UpdatableTupleSketchBuilder; -import org.apache.datasketches.tuple.adouble.DoubleSummary; -import org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer; -import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; -import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class CompactSketchWithDoubleSummaryTest { - private final DoubleSummary.Mode mode = Mode.Sum; - - @Test - public void emptyFromNonPublicConstructorNullArray() { - CompactTupleSketch sketch = - new CompactTupleSketch<>(null, null, Long.MAX_VALUE, true); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getRetainedEntries(), 0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - TupleSketchIterator it = sketch.iterator(); - Assert.assertNotNull(it); - Assert.assertFalse(it.next()); - sketch.toString(); - } - - @Test - public void emptyFromNonPublicConstructor() { - long[] keys = new long[0]; - DoubleSummary[] summaries = - (DoubleSummary[]) java.lang.reflect.Array.newInstance(DoubleSummary.class, 0); - CompactTupleSketch sketch = - new CompactTupleSketch<>(keys, summaries, Long.MAX_VALUE, true); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getRetainedEntries(), 0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - TupleSketchIterator it = sketch.iterator(); - Assert.assertNotNull(it); - Assert.assertFalse(it.next()); - } - - @Test - public void emptyFromQuickSelectSketch() { - UpdatableTupleSketch us = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - CompactTupleSketch sketch = us.compact(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getRetainedEntries(), 0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - TupleSketchIterator it = sketch.iterator(); - Assert.assertNotNull(it); - Assert.assertFalse(it.next()); - } - - @Test - public void exactModeFromQuickSelectSketch() { - UpdatableTupleSketch us = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - us.update(1, 1.0); - us.update(2, 1.0); - us.update(3, 1.0); - us.update(1, 1.0); - us.update(2, 1.0); - us.update(3, 1.0); - CompactTupleSketch sketch = us.compact(); - Assert.assertFalse(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 3.0); - Assert.assertEquals(sketch.getLowerBound(1), 3.0); - Assert.assertEquals(sketch.getUpperBound(1), 3.0); - Assert.assertEquals(sketch.getRetainedEntries(), 3); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - TupleSketchIterator it = sketch.iterator(); - int count = 0; - while (it.next()) { - Assert.assertEquals(it.getSummary().getValue(), 2.0); - count++; - } - Assert.assertEquals(count, 3); - } - - @Test - public void serializeDeserializeSmallExact() { - UpdatableTupleSketch us = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - us.update("a", 1.0); - us.update("b", 1.0); - us.update("c", 1.0); - CompactTupleSketch sketch1 = us.compact(); - TupleSketch sketch2 = - TupleSketch.heapifySketch(MemorySegment.ofArray(sketch1.toByteArray()), - new DoubleSummaryDeserializer()); - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertFalse(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), 3.0); - Assert.assertEquals(sketch2.getLowerBound(1), 3.0); - Assert.assertEquals(sketch2.getUpperBound(1), 3.0); - Assert.assertEquals(sketch2.getRetainedEntries(), 3); - Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch2.getTheta(), 1.0); - TupleSketchIterator it = sketch2.iterator(); - int count = 0; - while (it.next()) { - Assert.assertEquals(it.getSummary().getValue(), 1.0); - count++; - } - Assert.assertEquals(count, 3); - } - - @Test - public void serializeDeserializeEstimation() throws Exception { - UpdatableTupleSketch us = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - for (int i = 0; i < 8192; i++) { - us.update(i, 1.0); - } - us.trim(); - CompactTupleSketch sketch1 = us.compact(); - byte[] bytes = sketch1.toByteArray(); - - // for binary testing - //TestUtil.writeBytesToFile(bytes, "CompactSketchWithDoubleSummary4K.sk"); - - TupleSketch sketch2 = - TupleSketch.heapifySketch(MemorySegment.ofArray(bytes), new DoubleSummaryDeserializer()); - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertTrue(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), sketch1.getEstimate()); - Assert.assertEquals(sketch2.getThetaLong(), sketch1.getThetaLong()); - TupleSketchIterator it = sketch2.iterator(); - int count = 0; - while (it.next()) { - Assert.assertEquals(it.getSummary().getValue(), 1.0); - count++; - } - Assert.assertEquals(count, 4096); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeWrongType() { - UpdatableTupleSketch us = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - for (int i = 0; i < 8192; i++) { - us.update(i, 1.0); - } - CompactTupleSketch sketch1 = us.compact(); - TupleSketch.heapifyUpdatableSketch(MemorySegment.ofArray(sketch1.toByteArray()), - new DoubleSummaryDeserializer(), - new DoubleSummaryFactory(mode)); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/IntegerSummary.java b/src/test/java/org/apache/datasketches/tuple/IntegerSummary.java deleted file mode 100644 index 68c74b0a5..000000000 --- a/src/test/java/org/apache/datasketches/tuple/IntegerSummary.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ByteArrayUtil; -import org.apache.datasketches.tuple.DeserializeResult; -import org.apache.datasketches.tuple.UpdatableSummary; - -/** - * Summary for generic tuple sketches of type Integer. - * This summary keeps an Integer value. - */ -public class IntegerSummary implements UpdatableSummary { - private int value_; - - /** - * Creates an instance of IntegerSummary with a given starting value. - * @param value starting value - */ - public IntegerSummary(final int value) { - value_ = value; - } - - @Override - public IntegerSummary update(final Integer value) { - value_ += value; - return this; - } - - @Override - public IntegerSummary copy() { - return new IntegerSummary(value_); - } - - /** - * @return current value of the IntegerSummary - */ - public int getValue() { - return value_; - } - - private static final int SERIALIZED_SIZE_BYTES = 4; - private static final int VALUE_INDEX = 0; - - @Override - public byte[] toByteArray() { - final byte[] bytes = new byte[SERIALIZED_SIZE_BYTES]; - ByteArrayUtil.putIntLE(bytes, VALUE_INDEX, value_); - return bytes; - } - - /** - * Creates an instance of the IntegerSummary given a serialized representation - * @param seg MemorySegment object with serialized IntegerSummary - * @return DeserializedResult object, which contains a IntegerSummary object and number of bytes - * read from the MemorySegment - */ - public static DeserializeResult fromMemorySegment(final MemorySegment seg) { - return new DeserializeResult<>(new IntegerSummary(seg.get(JAVA_INT_UNALIGNED, VALUE_INDEX)), SERIALIZED_SIZE_BYTES); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/IntegerSummaryDeserializer.java b/src/test/java/org/apache/datasketches/tuple/IntegerSummaryDeserializer.java deleted file mode 100644 index 56a222758..000000000 --- a/src/test/java/org/apache/datasketches/tuple/IntegerSummaryDeserializer.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.tuple.DeserializeResult; -import org.apache.datasketches.tuple.SummaryDeserializer; - -public class IntegerSummaryDeserializer implements SummaryDeserializer { - - @Override - public DeserializeResult heapifySummary(final MemorySegment seg) { - return IntegerSummary.fromMemorySegment(seg); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/IntegerSummaryFactory.java b/src/test/java/org/apache/datasketches/tuple/IntegerSummaryFactory.java deleted file mode 100644 index 3a61a4aee..000000000 --- a/src/test/java/org/apache/datasketches/tuple/IntegerSummaryFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import org.apache.datasketches.tuple.SummaryFactory; - -/** - * Factory for IntegerSummary. - */ -public class IntegerSummaryFactory implements SummaryFactory { - - @Override - public IntegerSummary newSummary() { - return new IntegerSummary(0); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/JaccardSimilarityTest.java b/src/test/java/org/apache/datasketches/tuple/JaccardSimilarityTest.java deleted file mode 100644 index 4b789a5ce..000000000 --- a/src/test/java/org/apache/datasketches/tuple/JaccardSimilarityTest.java +++ /dev/null @@ -1,459 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import org.apache.datasketches.theta.UpdatableThetaSketch; -import org.apache.datasketches.theta.UpdatableThetaSketchBuilder; -import org.apache.datasketches.tuple.UpdatableTupleSketch; -import org.apache.datasketches.tuple.UpdatableTupleSketchBuilder; -import org.apache.datasketches.tuple.adouble.DoubleSummary; -import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; -import org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations; -import org.testng.annotations.Test; - -import static org.apache.datasketches.tuple.JaccardSimilarity.dissimilarityTest; -import static org.apache.datasketches.tuple.JaccardSimilarity.exactlyEqual; -import static org.apache.datasketches.tuple.JaccardSimilarity.jaccard; -import static org.apache.datasketches.tuple.JaccardSimilarity.similarityTest; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -/** - * @author Lee Rhodes - * @author David Cromberge - */ -public class JaccardSimilarityTest { - private final DoubleSummary.Mode umode = DoubleSummary.Mode.Sum; - private final DoubleSummarySetOperations dsso = new DoubleSummarySetOperations(); - private final DoubleSummaryFactory factory = new DoubleSummaryFactory(umode); - private final UpdatableThetaSketchBuilder thetaBldr = UpdatableThetaSketch.builder(); - private final UpdatableTupleSketchBuilder tupleBldr = new UpdatableTupleSketchBuilder<>(factory); - private final Double constSummary = 1.0; - - @Test - public void checkNullsEmpties1() { // tuple, tuple - int minK = 1 << 12; - double threshold = 0.95; - println("Check nulls & empties, minK: " + minK + "\t Th: " + threshold); - //check both null - double[] jResults = jaccard(null, null, dsso); - boolean state = jResults[1] > threshold; - println("null \t null:\t" + state + "\t" + jaccardString(jResults)); - assertFalse(state); - - state = exactlyEqual(null, null, dsso); - assertFalse(state); - - final UpdatableTupleSketch measured = tupleBldr.setNominalEntries(minK).build(); - final UpdatableTupleSketch expected = tupleBldr.setNominalEntries(minK).build(); - - //check both empty - jResults = jaccard(measured, expected, dsso); - state = jResults[1] > threshold; - println("empty\tempty:\t" + state + "\t" + jaccardString(jResults)); - assertTrue(state); - - state = exactlyEqual(measured, expected, dsso); - assertTrue(state); - - state = exactlyEqual(measured, measured, dsso); - assertTrue(state); - - //adjust one - expected.update(1, constSummary); - jResults = jaccard(measured, expected, dsso); - state = jResults[1] > threshold; - println("empty\t 1:\t" + state + "\t" + jaccardString(jResults)); - assertFalse(state); - - state = exactlyEqual(measured, expected, dsso); - assertFalse(state); - - println(""); - } - - @Test - public void checkNullsEmpties2() { // tuple, theta - int minK = 1 << 12; - double threshold = 0.95; - println("Check nulls & empties, minK: " + minK + "\t Th: " + threshold); - //check both null - double[] jResults = jaccard(null, null, factory.newSummary(), dsso); - boolean state = jResults[1] > threshold; - println("null \t null:\t" + state + "\t" + jaccardString(jResults)); - assertFalse(state); - - state = exactlyEqual(null, null, factory.newSummary(), dsso); - assertFalse(state); - - final UpdatableTupleSketch measured = tupleBldr.setNominalEntries(minK).build(); - final UpdatableThetaSketch expected = thetaBldr.setNominalEntries(minK).build(); - - //check both empty - jResults = jaccard(measured, expected, factory.newSummary(), dsso); - state = jResults[1] > threshold; - println("empty\tempty:\t" + state + "\t" + jaccardString(jResults)); - assertTrue(state); - - state = exactlyEqual(measured, expected, factory.newSummary(), dsso); - assertTrue(state); - - state = exactlyEqual(measured, measured, dsso); - assertTrue(state); - - //adjust one - expected.update(1); - jResults = jaccard(measured, expected, factory.newSummary(), dsso); - state = jResults[1] > threshold; - println("empty\t 1:\t" + state + "\t" + jaccardString(jResults)); - assertFalse(state); - - state = exactlyEqual(measured, expected, factory.newSummary(), dsso); - assertFalse(state); - - println(""); - } - - @Test - public void checkExactMode1() { // tuple, tuple - int k = 1 << 12; - int u = k; - double threshold = 0.9999; - println("Exact Mode, minK: " + k + "\t Th: " + threshold); - - final UpdatableTupleSketch measured = tupleBldr.setNominalEntries(k).build(); - final UpdatableTupleSketch expected = tupleBldr.setNominalEntries(k).build(); - - for (int i = 0; i < (u-1); i++) { //one short - measured.update(i, constSummary); - expected.update(i, constSummary); - } - - double[] jResults = jaccard(measured, expected, dsso); - boolean state = jResults[1] > threshold; - println(state + "\t" + jaccardString(jResults)); - assertTrue(state); - - state = exactlyEqual(measured, expected, dsso); - assertTrue(state); - - measured.update(u-1, constSummary); //now exactly k entries - expected.update(u, constSummary); //now exactly k entries but differs by one - jResults = jaccard(measured, expected, dsso); - state = jResults[1] > threshold; - println(state + "\t" + jaccardString(jResults)); - assertFalse(state); - - state = exactlyEqual(measured, expected, dsso); - assertFalse(state); - - println(""); - } - - @Test - public void checkExactMode2() { // tuple, theta - int k = 1 << 12; - int u = k; - double threshold = 0.9999; - println("Exact Mode, minK: " + k + "\t Th: " + threshold); - - final UpdatableTupleSketch measured = tupleBldr.setNominalEntries(k).build(); - final UpdatableThetaSketch expected = thetaBldr.setNominalEntries(k).build(); - - for (int i = 0; i < (u-1); i++) { //one short - measured.update(i, constSummary); - expected.update(i); - } - - double[] jResults = jaccard(measured, expected, factory.newSummary(), dsso); - boolean state = jResults[1] > threshold; - println(state + "\t" + jaccardString(jResults)); - assertTrue(state); - - state = exactlyEqual(measured, expected, factory.newSummary(), dsso); - assertTrue(state); - - measured.update(u-1, constSummary); //now exactly k entries - expected.update(u); //now exactly k entries but differs by one - jResults = jaccard(measured, expected, factory.newSummary(), dsso); - state = jResults[1] > threshold; - println(state + "\t" + jaccardString(jResults)); - assertFalse(state); - - state = exactlyEqual(measured, expected, factory.newSummary(), dsso); - assertFalse(state); - - println(""); - } - - @Test - public void checkEstMode1() { // tuple, tuple - int k = 1 << 12; - int u = 1 << 20; - double threshold = 0.9999; - println("Estimation Mode, minK: " + k + "\t Th: " + threshold); - - final UpdatableTupleSketch measured = tupleBldr.setNominalEntries(k).build(); - final UpdatableTupleSketch expected = tupleBldr.setNominalEntries(k).build(); - - for (int i = 0; i < u; i++) { - measured.update(i, constSummary); - expected.update(i, constSummary); - } - - double[] jResults = jaccard(measured, expected, dsso); - boolean state = jResults[1] > threshold; - println(state + "\t" + jaccardString(jResults)); - assertTrue(state); - - state = exactlyEqual(measured, expected, dsso); - assertTrue(state); - - for (int i = u; i < (u + 50); i++) { //empirically determined - measured.update(i, constSummary); - } - - jResults = jaccard(measured, expected, dsso); - state = jResults[1] >= threshold; - println(state + "\t" + jaccardString(jResults)); - assertFalse(state); - - state = exactlyEqual(measured, expected, dsso); - assertFalse(state); - - println(""); - } - - @Test - public void checkEstMode2() { // tuple, theta - int k = 1 << 12; - int u = 1 << 20; - double threshold = 0.9999; - println("Estimation Mode, minK: " + k + "\t Th: " + threshold); - - final UpdatableTupleSketch measured = tupleBldr.setNominalEntries(k).build(); - final UpdatableThetaSketch expected = thetaBldr.setNominalEntries(k).build(); - - for (int i = 0; i < u; i++) { - measured.update(i, constSummary); - expected.update(i); - } - - double[] jResults = jaccard(measured, expected, factory.newSummary(), dsso); - boolean state = jResults[1] > threshold; - println(state + "\t" + jaccardString(jResults)); - assertTrue(state); - - state = exactlyEqual(measured, expected, factory.newSummary(), dsso); - assertTrue(state); - - for (int i = u; i < (u + 50); i++) { //empirically determined - measured.update(i, constSummary); - } - - jResults = jaccard(measured, expected, factory.newSummary(), dsso); - state = jResults[1] >= threshold; - println(state + "\t" + jaccardString(jResults)); - assertFalse(state); - - state = exactlyEqual(measured, expected, factory.newSummary(), dsso); - assertFalse(state); - - println(""); - } - - /** - * Enable printing on this test and you will see that the distribution is pretty tight, - * about +/- 0.7%, which is pretty good since the accuracy of the underlying sketch is about - * +/- 1.56%. - */ - @Test - public void checkSimilarity1() { // tuple, tuple - int minK = 1 << 12; - int u1 = 1 << 20; - int u2 = (int) (u1 * 0.95); - double threshold = 0.943; - println("Estimation Mode, minK: " + minK + "\t Th: " + threshold); - - final UpdatableTupleSketch measured = tupleBldr.setNominalEntries(minK).build(); - final UpdatableTupleSketch expected = tupleBldr.setNominalEntries(minK).build(); - - for (int i = 0; i < u1; i++) { - expected.update(i, constSummary); - } - - for (int i = 0; i < u2; i++) { - measured.update(i, constSummary); - } - - double[] jResults = jaccard(measured, expected, dsso); - boolean state = similarityTest(measured, expected, dsso, threshold); - println(state + "\t" + jaccardString(jResults)); - assertTrue(state); - //check identity case - state = similarityTest(measured, measured, dsso, threshold); - assertTrue(state); - } - - /** - * Enable printing on this test and you will see that the distribution is pretty tight, - * about +/- 0.7%, which is pretty good since the accuracy of the underlying sketch is about - * +/- 1.56%. - */ - @Test - public void checkSimilarity2() { // tuple, theta - int minK = 1 << 12; - int u1 = 1 << 20; - int u2 = (int) (u1 * 0.95); - double threshold = 0.943; - println("Estimation Mode, minK: " + minK + "\t Th: " + threshold); - - final UpdatableTupleSketch measured = tupleBldr.setNominalEntries(minK).build(); - final UpdatableThetaSketch expected = thetaBldr.setNominalEntries(minK).build(); - - for (int i = 0; i < u1; i++) { - expected.update(i); - } - - for (int i = 0; i < u2; i++) { - measured.update(i, constSummary); - } - - double[] jResults = jaccard(measured, expected, factory.newSummary(), dsso); - boolean state = similarityTest(measured, expected, factory.newSummary(), dsso, threshold); - println(state + "\t" + jaccardString(jResults)); - assertTrue(state); - //check identity case - state = similarityTest(measured, measured, dsso, threshold); - assertTrue(state); - } - - /** - * Enable printing on this test and you will see that the distribution is much looser, - * about +/- 14%. This is due to the fact that intersections loose accuracy as the ratio of - * intersection to the union becomes a small number. - */ - @Test - public void checkDissimilarity1() { // tuple, tuple - int minK = 1 << 12; - int u1 = 1 << 20; - int u2 = (int) (u1 * 0.05); - double threshold = 0.061; - println("Estimation Mode, minK: " + minK + "\t Th: " + threshold); - - final UpdatableTupleSketch measured = tupleBldr.setNominalEntries(minK).setNominalEntries(minK).build(); - final UpdatableTupleSketch expected = tupleBldr.setNominalEntries(minK).setNominalEntries(minK).build(); - - for (int i = 0; i < u1; i++) { - expected.update(i, constSummary); - } - - for (int i = 0; i < u2; i++) { - measured.update(i, constSummary); - } - - double[] jResults = jaccard(measured, expected, dsso); - boolean state = dissimilarityTest(measured, expected, dsso, threshold); - println(state + "\t" + jaccardString(jResults)); - assertTrue(state); - } - - /** - * Enable printing on this test and you will see that the distribution is much looser, - * about +/- 14%. This is due to the fact that intersections loose accuracy as the ratio of - * intersection to the union becomes a small number. - */ - @Test - public void checkDissimilarity2() { // tuple, theta - int minK = 1 << 12; - int u1 = 1 << 20; - int u2 = (int) (u1 * 0.05); - double threshold = 0.061; - println("Estimation Mode, minK: " + minK + "\t Th: " + threshold); - - final UpdatableTupleSketch measured = tupleBldr.setNominalEntries(minK).setNominalEntries(minK).build(); - final UpdatableThetaSketch expected = thetaBldr.setNominalEntries(minK).build(); - - for (int i = 0; i < u1; i++) { - expected.update(i); - } - - for (int i = 0; i < u2; i++) { - measured.update(i, constSummary); - } - - double[] jResults = jaccard(measured, expected, factory.newSummary(), dsso); - boolean state = dissimilarityTest(measured, expected, factory.newSummary(), dsso, threshold); - println(state + "\t" + jaccardString(jResults)); - assertTrue(state); - } - - private static String jaccardString(double[] jResults) { - double lb = jResults[0]; - double est = jResults[1]; - double ub = jResults[2]; - return lb + "\t" + est + "\t" + ub + "\t" + ((lb/est) - 1.0) + "\t" + ((ub/est) - 1.0); - } - - @Test - public void checkMinK1() { // tuple, tuple - final UpdatableTupleSketch skA = tupleBldr.build(); //4096 - final UpdatableTupleSketch skB = tupleBldr.build(); //4096 - skA.update(1, constSummary); - skB.update(1, constSummary); - double[] result = jaccard(skA, skB, dsso); - println(result[0] + ", " + result[1] + ", " + result[2]); - for (int i = 1; i < 4096; i++) { - skA.update(i, constSummary); - skB.update(i, constSummary); - } - result = jaccard(skA, skB, dsso); - println(result[0] + ", " + result[1] + ", " + result[2]); - } - - @Test - public void checkMinK2() { // tuple, theta - final UpdatableTupleSketch skA = tupleBldr.build(); //4096 - final UpdatableThetaSketch skB = UpdatableThetaSketch.builder().build(); //4096 - skA.update(1, constSummary); - skB.update(1); - double[] result = jaccard(skA, skB, factory.newSummary(), dsso); - println(result[0] + ", " + result[1] + ", " + result[2]); - for (int i = 1; i < 4096; i++) { - skA.update(i, constSummary); - skB.update(i); - } - result = jaccard(skA, skB, factory.newSummary(), dsso); - println(result[0] + ", " + result[1] + ", " + result[2]); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(Object o) { - //System.out.println(o.toString()); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/MiscTest.java b/src/test/java/org/apache/datasketches/tuple/MiscTest.java deleted file mode 100644 index 431dccd94..000000000 --- a/src/test/java/org/apache/datasketches/tuple/MiscTest.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase; -import org.apache.datasketches.tuple.UpdatableTupleSketch; -import org.apache.datasketches.tuple.UpdatableTupleSketchBuilder; -import org.apache.datasketches.tuple.Util; -import org.apache.datasketches.tuple.adouble.DoubleSummary; -import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; -import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class MiscTest { - - @Test - public void checkUpdatableSketchBuilderReset() { - final DoubleSummary.Mode mode = Mode.Sum; - final UpdatableTupleSketchBuilder bldr = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)); - bldr.reset(); - final UpdatableTupleSketch sk = bldr.build(); - assertTrue(sk.isEmpty()); - } - - @Test - public void checkStringToByteArray() { - Util.stringToByteArray(""); - } - - @Test - public void checkDoubleToLongArray() { - final long[] v = Util.doubleToLongArray(-0.0); - assertEquals(v[0], 0); - } - - //@Test - public void checkById() { - final int[] ids = {0,1,2, 5, 6 }; - final int len = ids.length; - for (int i = 0; i < len; i++) { - for (int j = 0; j < len; j++) { - final int id = ids[i] << 3 | ids[j]; - final CornerCase cCase = CornerCase.caseIdToCornerCase(id); - final String interResStr = cCase.getIntersectAction().getActionDescription(); - final String anotbResStr = cCase.getAnotbAction().getActionDescription(); - println(Integer.toOctalString(id) + "\t" + cCase + "\t" + cCase.getCaseDescription() - + "\t" + interResStr + "\t" + anotbResStr); - } - } - } - - @Test - public void checkCopyCtor() { - final DoubleSummary.Mode mode = Mode.Sum; - final UpdatableTupleSketchBuilder bldr = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)); - bldr.reset(); - final UpdatableTupleSketch sk = bldr.build(); - sk.update(1.0, 1.0); - assertEquals(sk.getRetainedEntries(), 1); - final UpdatableTupleSketch sk2 = sk.copy(); - assertEquals(sk2.getRetainedEntries(), 1); - } - - - /** - * - * @param o object to print - */ - private static void println(final Object o) { - //System.out.println(o.toString()); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/ReadOnlyMemorySegmentTest.java b/src/test/java/org/apache/datasketches/tuple/ReadOnlyMemorySegmentTest.java deleted file mode 100644 index 557133b23..000000000 --- a/src/test/java/org/apache/datasketches/tuple/ReadOnlyMemorySegmentTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesReadOnlyException; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class ReadOnlyMemorySegmentTest { - - @Test - public void wrapAndTryUpdatingSketch() { - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch1.update(1, new double[] {1}); - final ArrayOfDoublesUpdatableSketch sketch2 = (ArrayOfDoublesUpdatableSketch) - ArrayOfDoublesSketch.wrapSketch(MemorySegment.ofArray(sketch1.toByteArray())); - Assert.assertEquals(sketch2.getEstimate(), 1.0); - sketch2.toByteArray(); - boolean thrown = false; - try { - sketch2.update(2, new double[] {1}); - } catch (final SketchesReadOnlyException e) { - thrown = true; - } - try { - sketch2.trim(); - } catch (final SketchesReadOnlyException e) { - thrown = true; - } - Assert.assertTrue(thrown); - } - - @Test - public void heapifyAndUpdateSketch() { - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch1.update(1, new double[] {1}); - // downcasting is not recommended, for testing only - final ArrayOfDoublesUpdatableSketch sketch2 = (ArrayOfDoublesUpdatableSketch) - ArrayOfDoublesSketch.heapifySketch(MemorySegment.ofArray(sketch1.toByteArray())); - sketch2.update(2, new double[] {1}); - Assert.assertEquals(sketch2.getEstimate(), 2.0); - } - - @Test - public void wrapAndTryUpdatingUnionEstimationMode() { - final int numUniques = 10000; - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < numUniques; i++) { - sketch1.update(key++, new double[] {1}); - } - final ArrayOfDoublesUnion union1 = new ArrayOfDoublesSetOperationBuilder().buildUnion(); - union1.union(sketch1); - final ArrayOfDoublesUnion union2 = ArrayOfDoublesSketch.wrapUnion(MemorySegment.ofArray(union1.toByteArray()).asReadOnly()); - final ArrayOfDoublesSketch resultSketch = union2.getResult(); - Assert.assertTrue(resultSketch.isEstimationMode()); - Assert.assertEquals(resultSketch.getEstimate(), numUniques, numUniques * 0.04); - - // make sure union update actually needs to modify the union - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < numUniques; i++) { - sketch2.update(key++, new double[] {1}); - } - - boolean thrown = false; - try { - union2.union(sketch2); - } catch (final SketchesReadOnlyException e) { - thrown = true; - } - Assert.assertTrue(thrown); - } - - @Test - public void heapifyAndUpdateUnion() { - final int numUniques = 10000; - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < numUniques; i++) { - sketch1.update(key++, new double[] {1}); - } - final ArrayOfDoublesUnion union1 = new ArrayOfDoublesSetOperationBuilder().buildUnion(); - union1.union(sketch1); - final ArrayOfDoublesUnion union2 = ArrayOfDoublesSketch.heapifyUnion(MemorySegment.ofArray(union1.toByteArray())); - final ArrayOfDoublesSketch resultSketch = union2.getResult(); - Assert.assertTrue(resultSketch.isEstimationMode()); - Assert.assertEquals(resultSketch.getEstimate(), numUniques, numUniques * 0.04); - - // make sure union update actually needs to modify the union - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < numUniques; i++) { - sketch2.update(key++, new double[] {1}); - } - union2.union(sketch2); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/SerializerDeserializerTest.java b/src/test/java/org/apache/datasketches/tuple/SerializerDeserializerTest.java deleted file mode 100644 index 92d18639f..000000000 --- a/src/test/java/org/apache/datasketches/tuple/SerializerDeserializerTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static org.apache.datasketches.common.Util.computeSeedHash; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Family; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.SerializerDeserializer; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class SerializerDeserializerTest { - - @Test - public void validSketchType() { - byte[] bytes = new byte[4]; - bytes[SerializerDeserializer.TYPE_BYTE_OFFSET] = (byte) SerializerDeserializer.SketchType.CompactTupleSketch.ordinal(); - Assert.assertEquals(SerializerDeserializer.getSketchType(MemorySegment.ofArray(bytes)), SerializerDeserializer.SketchType.CompactTupleSketch); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void invalidSketchType() { - byte[] bytes = new byte[4]; - bytes[SerializerDeserializer.TYPE_BYTE_OFFSET] = 33; - SerializerDeserializer.getSketchType(MemorySegment.ofArray(bytes)); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void validateFamilyNotTuple() { - SerializerDeserializer.validateFamily((byte) 1, (byte) 0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void validateFamilyWrongPreambleLength() { - SerializerDeserializer.validateFamily((byte) Family.TUPLE.getID(), (byte) 0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkBadSeedHash() { - computeSeedHash(50541); - } -} diff --git a/src/test/java/org/apache/datasketches/tuple/TupleCrossLanguageTest.java b/src/test/java/org/apache/datasketches/tuple/TupleCrossLanguageTest.java deleted file mode 100644 index 6c182baa2..000000000 --- a/src/test/java/org/apache/datasketches/tuple/TupleCrossLanguageTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES; -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_HISTORICAL_FILES; -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.getFileBytes; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; -import static org.apache.datasketches.common.TestUtil.resPath; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.TestUtil; -import org.apache.datasketches.tuple.adouble.DoubleSummary; -import org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class TupleCrossLanguageTest { - - @Test(groups = {CHECK_CPP_HISTORICAL_FILES}) - public void serialVersion1Compatibility() { - final byte[] byteArr = TestUtil.getFileBytes(resPath, "CompactSketchWithDoubleSummary4K_serialVersion1.sk"); - TupleSketch sketch = TupleSketch.heapifySketch(MemorySegment.ofArray(byteArr), new DoubleSummaryDeserializer()); - Assert.assertTrue(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 8192, 8192 * 0.99); - Assert.assertEquals(sketch.getRetainedEntries(), 4096); - int count = 0; - TupleSketchIterator it = sketch.iterator(); - while (it.next()) { - Assert.assertEquals(it.getSummary().getValue(), 1.0); - count++; - } - Assert.assertEquals(count, 4096); - } - - @Test(groups = {CHECK_CPP_HISTORICAL_FILES}) - public void version2Compatibility() { - final byte[] byteArr = TestUtil.getFileBytes(resPath, "TupleWithTestIntegerSummary4kTrimmedSerVer2.sk"); - TupleSketch sketch1 = TupleSketch.heapifySketch(MemorySegment.ofArray(byteArr), new IntegerSummaryDeserializer()); - - // construct the same way - final int lgK = 12; - final int K = 1 << lgK; - final UpdatableTupleSketchBuilder builder = - new UpdatableTupleSketchBuilder<>(new IntegerSummaryFactory()); - final UpdatableTupleSketch updatableSketch = builder.build(); - for (int i = 0; i < 2 * K; i++) { - updatableSketch.update(i, 1); - } - updatableSketch.trim(); - TupleSketch sketch2 = updatableSketch.compact(); - - Assert.assertEquals(sketch1.getRetainedEntries(), sketch2.getRetainedEntries()); - Assert.assertEquals(sketch1.getThetaLong(), sketch2.getThetaLong()); - Assert.assertEquals(sketch1.isEmpty(), sketch2.isEmpty()); - Assert.assertEquals(sketch1.isEstimationMode(), sketch2.isEstimationMode()); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppIntegerSummary() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "tuple_int_n" + n + "_cpp.sk"); - final TupleSketch sketch = - TupleSketch.heapifySketch(MemorySegment.ofArray(bytes), new IntegerSummaryDeserializer()); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertTrue(n > 1000 ? sketch.isEstimationMode() : !sketch.isEstimationMode()); - assertEquals(sketch.getEstimate(), n, n * 0.03); - final TupleSketchIterator it = sketch.iterator(); - while (it.next()) { - assertTrue(it.getHash() < sketch.getThetaLong()); - assertTrue(it.getSummary().getValue() < n); - } - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateForCppIntegerSummary() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (int n: nArr) { - final UpdatableTupleSketch sk = - new UpdatableTupleSketchBuilder<>(new IntegerSummaryFactory()).build(); - for (int i = 0; i < n; i++) { - sk.update(i, i); - } - putBytesToJavaPath("tuple_int_n" + n + "_java.sk", sk.compact().toByteArray()); - } - } - - @Test(expectedExceptions = SketchesArgumentException.class, groups = {CHECK_CPP_HISTORICAL_FILES}) - public void noSupportHeapifyV0_9_1() throws Exception { - final byte[] byteArr = TestUtil.getFileBytes(resPath, "ArrayOfDoublesUnion_v0.9.1.sk"); - ArrayOfDoublesUnion.heapify(MemorySegment.ofArray(byteArr)); - } - - @Test(expectedExceptions = SketchesArgumentException.class, groups = {CHECK_CPP_HISTORICAL_FILES}) - public void noSupportWrapV0_9_1() throws Exception { - final byte[] byteArr = TestUtil.getFileBytes(resPath, "ArrayOfDoublesUnion_v0.9.1.sk"); - ArrayOfDoublesUnion.wrap(MemorySegment.ofArray(byteArr)); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/TupleExamples2Test.java b/src/test/java/org/apache/datasketches/tuple/TupleExamples2Test.java deleted file mode 100644 index 8d8151187..000000000 --- a/src/test/java/org/apache/datasketches/tuple/TupleExamples2Test.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - - import static org.testng.Assert.assertEquals; - -import org.apache.datasketches.theta.UpdatableThetaSketch; -import org.apache.datasketches.theta.UpdatableThetaSketchBuilder; -import org.apache.datasketches.tuple.adouble.DoubleSummary; -import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode; -import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; -import org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations; -import org.testng.annotations.Test; - - /** - * Tests for Version 2.0.0 - * @author Lee Rhodes - */ - public class TupleExamples2Test { - private final DoubleSummary.Mode umode = Mode.Sum; - private final DoubleSummary.Mode imode = Mode.AlwaysOne; - private final DoubleSummarySetOperations dsso0 = new DoubleSummarySetOperations(); - private final DoubleSummarySetOperations dsso1 = new DoubleSummarySetOperations(umode); - private final DoubleSummarySetOperations dsso2 = new DoubleSummarySetOperations(umode, imode); - private final DoubleSummaryFactory ufactory = new DoubleSummaryFactory(umode); - private final DoubleSummaryFactory ifactory = new DoubleSummaryFactory(imode); - private final UpdatableThetaSketchBuilder thetaBldr = UpdatableThetaSketch.builder(); - private final UpdatableTupleSketchBuilder tupleBldr = - new UpdatableTupleSketchBuilder<>(ufactory); - - - @Test - public void example1() { // stateful: tuple, theta, use dsso2 - //Load source sketches - final UpdatableTupleSketch tupleSk = tupleBldr.build(); - final UpdatableThetaSketch thetaSk = thetaBldr.build(); - for (int i = 1; i <= 12; i++) { - tupleSk.update(i, 1.0); - thetaSk.update(i + 3); - } - - //TupleUnion - final TupleUnion union = new TupleUnion<>(dsso2); - union.union(tupleSk); - union.union(thetaSk, ufactory.newSummary().update(1.0)); - final CompactTupleSketch ucsk = union.getResult(); - int entries = ucsk.getRetainedEntries(); - println("TupleUnion Stateful: tuple, theta: " + entries); - final TupleSketchIterator uiter = ucsk.iterator(); - int counter = 1; - int twos = 0; - int ones = 0; - while (uiter.next()) { - final int i = (int)uiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1 - if (i == 1) { ones++; } - if (i == 2) { twos++; } - } - assertEquals(ones, 6); - assertEquals(twos, 9); - - //TupleIntersection - final TupleIntersection inter = new TupleIntersection<>(dsso2); - inter.intersect(tupleSk); - inter.intersect(thetaSk, ifactory.newSummary().update(1.0)); - final CompactTupleSketch icsk = inter.getResult(); - entries = icsk.getRetainedEntries(); - println("TupleIntersection Stateful: tuple, theta: " + entries); - final TupleSketchIterator iiter = icsk.iterator(); - counter = 1; - while (iiter.next()) { - final int i = (int)iiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 1 - assertEquals(i, 1); - } - } - - @Test - public void example2() { //stateless: tuple1, tuple2, use dsso2 - //Load source sketches - final UpdatableTupleSketch tupleSk1 = tupleBldr.build(); - final UpdatableTupleSketch tupleSk2 = tupleBldr.build(); - - for (int i = 1; i <= 12; i++) { - tupleSk1.update(i, 1.0); - tupleSk2.update(i + 3, 1.0); - } - - //TupleUnion - final TupleUnion union = new TupleUnion<>(dsso2); - final CompactTupleSketch ucsk = union.union(tupleSk1, tupleSk2); - int entries = ucsk.getRetainedEntries(); - println("TupleUnion: " + entries); - final TupleSketchIterator uiter = ucsk.iterator(); - int counter = 1; - int twos = 0; - int ones = 0; - while (uiter.next()) { - final int i = (int)uiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1 - if (i == 1) { ones++; } - if (i == 2) { twos++; } - } - assertEquals(ones, 6); - assertEquals(twos, 9); - - //TupleIntersection - final TupleIntersection inter = new TupleIntersection<>(dsso2); - final CompactTupleSketch icsk = inter.intersect(tupleSk1, tupleSk2); - entries = icsk.getRetainedEntries(); - println("TupleIntersection: " + entries); - final TupleSketchIterator iiter = icsk.iterator(); - counter = 1; - while (iiter.next()) { - final int i = (int)iiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 2 - assertEquals(i, 1); - } - } - - @Test - public void example3() { //stateless: tuple1, tuple2, use dsso2 - //Load source sketches - final UpdatableTupleSketch tupleSk = tupleBldr.build(); - final UpdatableThetaSketch thetaSk = thetaBldr.build(); - for (int i = 1; i <= 12; i++) { - tupleSk.update(i, 1.0); - thetaSk.update(i + 3); - } - - //TupleUnion - final TupleUnion union = new TupleUnion<>(dsso2); - final CompactTupleSketch ucsk = - union.union(tupleSk, thetaSk, ufactory.newSummary().update(1.0)); - int entries = ucsk.getRetainedEntries(); - println("TupleUnion: " + entries); - final TupleSketchIterator uiter = ucsk.iterator(); - int counter = 1; - int twos = 0; - int ones = 0; - while (uiter.next()) { - final int i = (int)uiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1 - if (i == 1) { ones++; } - if (i == 2) { twos++; } - } - assertEquals(ones, 6); - assertEquals(twos, 9); - - //TupleIntersection - final TupleIntersection inter = new TupleIntersection<>(dsso2); - final CompactTupleSketch icsk = - inter.intersect(tupleSk, thetaSk, ufactory.newSummary().update(1.0)); - entries = icsk.getRetainedEntries(); - println("TupleIntersection: " + entries); - final TupleSketchIterator iiter = icsk.iterator(); - counter = 1; - while (iiter.next()) { - final int i = (int)iiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 2 - assertEquals(i, 1); - } - } - - @Test - public void example4() { //stateful: tuple, theta, Mode=sum for both, use dsso0 - //Load source sketches - final UpdatableTupleSketch tupleSk = tupleBldr.build(); - final UpdatableThetaSketch thetaSk = thetaBldr.build(); - for (int i = 1; i <= 12; i++) { - tupleSk.update(i, 1.0); - thetaSk.update(i + 3); - } - - //TupleUnion - final TupleUnion union = new TupleUnion<>(dsso0); - union.union(tupleSk); - union.union(thetaSk, ufactory.newSummary().update(1.0)); - final CompactTupleSketch ucsk = union.getResult(); - int entries = ucsk.getRetainedEntries(); - println("TupleUnion Stateful: tuple, theta: " + entries); - final TupleSketchIterator uiter = ucsk.iterator(); - int counter = 1; - int twos = 0; - int ones = 0; - while (uiter.next()) { - final int i = (int)uiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1 - if (i == 1) { ones++; } - if (i == 2) { twos++; } - } - assertEquals(ones, 6); - assertEquals(twos, 9); - - //TupleIntersection - final TupleIntersection inter = new TupleIntersection<>(dsso0); - inter.intersect(tupleSk); - inter.intersect(thetaSk, ifactory.newSummary().update(1.0)); - final CompactTupleSketch icsk = inter.getResult(); - entries = icsk.getRetainedEntries(); - println("TupleIntersection Stateful: tuple, theta: " + entries); - final TupleSketchIterator iiter = icsk.iterator(); - counter = 1; - while (iiter.next()) { - final int i = (int)iiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 1 - assertEquals(i, 2); - } - } - - @Test - public void example5() { //stateful, tuple, theta, Mode=sum for both, use dsso1 - //Load source sketches - final UpdatableTupleSketch tupleSk = tupleBldr.build(); - final UpdatableThetaSketch thetaSk = thetaBldr.build(); - for (int i = 1; i <= 12; i++) { - tupleSk.update(i, 1.0); - thetaSk.update(i + 3); - } - - //TupleUnion - final TupleUnion union = new TupleUnion<>(dsso1); - union.union(tupleSk); - union.union(thetaSk, ufactory.newSummary().update(1.0)); - final CompactTupleSketch ucsk = union.getResult(); - int entries = ucsk.getRetainedEntries(); - println("TupleUnion Stateful: tuple, theta: " + entries); - final TupleSketchIterator uiter = ucsk.iterator(); - int counter = 1; - int twos = 0; - int ones = 0; - while (uiter.next()) { - final int i = (int)uiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1 - if (i == 1) { ones++; } - if (i == 2) { twos++; } - } - assertEquals(ones, 6); - assertEquals(twos, 9); - - //TupleIntersection - final TupleIntersection inter = new TupleIntersection<>(dsso1); - inter.intersect(tupleSk); - inter.intersect(thetaSk, ifactory.newSummary().update(1.0)); - final CompactTupleSketch icsk = inter.getResult(); - entries = icsk.getRetainedEntries(); - println("TupleIntersection Stateful: tuple, theta: " + entries); - final TupleSketchIterator iiter = icsk.iterator(); - counter = 1; - while (iiter.next()) { - final int i = (int)iiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 1 - assertEquals(i, 2); - } - } - - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //enable/disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/TupleExamplesTest.java b/src/test/java/org/apache/datasketches/tuple/TupleExamplesTest.java deleted file mode 100644 index 726683626..000000000 --- a/src/test/java/org/apache/datasketches/tuple/TupleExamplesTest.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple; - -import static org.testng.Assert.assertEquals; - -import org.apache.datasketches.theta.UpdatableThetaSketch; -import org.apache.datasketches.theta.UpdatableThetaSketchBuilder; -import org.apache.datasketches.tuple.aninteger.IntegerSummary; -import org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode; -import org.apache.datasketches.tuple.aninteger.IntegerSummaryFactory; -import org.apache.datasketches.tuple.aninteger.IntegerSummarySetOperations; -import org.testng.annotations.Test; - -/** - * Tests for Version 2.0.0 - * @author Lee Rhodes - */ -public class TupleExamplesTest { - private final IntegerSummary.Mode umode = Mode.Sum; - private final IntegerSummary.Mode imode = Mode.AlwaysOne; - private final IntegerSummarySetOperations isso = new IntegerSummarySetOperations(umode, imode); - private final IntegerSummaryFactory ufactory = new IntegerSummaryFactory(umode); - private final IntegerSummaryFactory ifactory = new IntegerSummaryFactory(imode); - private final UpdatableThetaSketchBuilder thetaBldr = UpdatableThetaSketch.builder(); - private final UpdatableTupleSketchBuilder tupleBldr = - new UpdatableTupleSketchBuilder<>(ufactory); - - - @Test - public void example1() { - //Load source sketches - final UpdatableTupleSketch tupleSk = tupleBldr.build(); - final UpdatableThetaSketch thetaSk = thetaBldr.build(); - for (int i = 1; i <= 12; i++) { - tupleSk.update(i, 1); - thetaSk.update(i + 3); - } - - //TupleUnion stateful: tuple, theta - final TupleUnion union = new TupleUnion<>(isso); - union.union(tupleSk); - union.union(thetaSk, ufactory.newSummary().update(1)); - final CompactTupleSketch ucsk = union.getResult(); - int entries = ucsk.getRetainedEntries(); - println("TupleUnion Stateful: tuple, theta: " + entries); - final TupleSketchIterator uiter = ucsk.iterator(); - int counter = 1; - int twos = 0; - int ones = 0; - while (uiter.next()) { - final int i = uiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1 - if (i == 1) { ones++; } - if (i == 2) { twos++; } - } - assertEquals(ones, 6); - assertEquals(twos, 9); - - //TupleIntersection stateful: tuple, theta - final TupleIntersection inter = new TupleIntersection<>(isso); - inter.intersect(tupleSk); - inter.intersect(thetaSk, ifactory.newSummary().update(1)); - final CompactTupleSketch icsk = inter.getResult(); - entries = icsk.getRetainedEntries(); - println("TupleIntersection Stateful: tuple, theta: " + entries); - final TupleSketchIterator iiter = icsk.iterator(); - counter = 1; - while (iiter.next()) { - final int i = iiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 1 - assertEquals(i, 1); - } - } - - @Test - public void example2() { - //Load source sketches - final UpdatableTupleSketch tupleSk1 = tupleBldr.build(); - final UpdatableTupleSketch tupleSk2 = tupleBldr.build(); - - for (int i = 1; i <= 12; i++) { - tupleSk1.update(i, 1); - tupleSk2.update(i + 3, 1); - } - - //TupleUnion, stateless: tuple1, tuple2 - final TupleUnion union = new TupleUnion<>(isso); - final CompactTupleSketch ucsk = union.union(tupleSk1, tupleSk2); - int entries = ucsk.getRetainedEntries(); - println("TupleUnion: " + entries); - final TupleSketchIterator uiter = ucsk.iterator(); - int counter = 1; - int twos = 0; - int ones = 0; - while (uiter.next()) { - final int i = uiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1 - if (i == 1) { ones++; } - if (i == 2) { twos++; } - } - assertEquals(ones, 6); - assertEquals(twos, 9); - - //TupleIntersection stateless: tuple1, tuple2 - final TupleIntersection inter = new TupleIntersection<>(isso); - final CompactTupleSketch icsk = inter.intersect(tupleSk1, tupleSk2); - entries = icsk.getRetainedEntries(); - println("TupleIntersection: " + entries); - final TupleSketchIterator iiter = icsk.iterator(); - counter = 1; - while (iiter.next()) { - final int i = iiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 2 - assertEquals(i, 1); - } - } - - @Test - public void example3() { - //Load source sketches - final UpdatableTupleSketch tupleSk = tupleBldr.build(); - final UpdatableThetaSketch thetaSk = thetaBldr.build(); - for (int i = 1; i <= 12; i++) { - tupleSk.update(i, 1); - thetaSk.update(i + 3); - } - - //TupleUnion, stateless: tuple1, tuple2 - final TupleUnion union = new TupleUnion<>(isso); - final CompactTupleSketch ucsk = - union.union(tupleSk, thetaSk, ufactory.newSummary().update(1)); - int entries = ucsk.getRetainedEntries(); - println("TupleUnion: " + entries); - final TupleSketchIterator uiter = ucsk.iterator(); - int counter = 1; - int twos = 0; - int ones = 0; - while (uiter.next()) { - final int i = uiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 2, 6 entries = 1 - if (i == 1) { ones++; } - if (i == 2) { twos++; } - } - assertEquals(ones, 6); - assertEquals(twos, 9); - - //TupleIntersection stateless: tuple1, tuple2 - final TupleIntersection inter = new TupleIntersection<>(isso); - final CompactTupleSketch icsk = - inter.intersect(tupleSk, thetaSk, ufactory.newSummary().update(1)); - entries = icsk.getRetainedEntries(); - println("TupleIntersection: " + entries); - final TupleSketchIterator iiter = icsk.iterator(); - counter = 1; - while (iiter.next()) { - final int i = iiter.getSummary().getValue(); - println(counter++ + ", " + i); //9 entries = 2 - assertEquals(i, 1); - } - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(final String s) { - //System.out.println(s); //enable/disable here - } -} diff --git a/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleAnotBTest.java b/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleAnotBTest.java deleted file mode 100644 index c3b701275..000000000 --- a/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleAnotBTest.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.adouble; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.theta.ThetaSketch; -import org.apache.datasketches.theta.UpdatableThetaSketch; -import org.apache.datasketches.theta.UpdatableThetaSketchBuilder; -import org.apache.datasketches.tuple.TupleAnotB; -import org.apache.datasketches.tuple.CompactTupleSketch; -import org.apache.datasketches.tuple.TupleSketch; -import org.apache.datasketches.tuple.TupleSketchIterator; -import org.apache.datasketches.tuple.UpdatableTupleSketch; -import org.apache.datasketches.tuple.UpdatableTupleSketchBuilder; -import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode; -import org.testng.Assert; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class AdoubleAnotBTest { - private static final DoubleSummary.Mode mode = Mode.Sum; - private final Results results = new Results(); - - private static void threeMethodsWithTheta( - final TupleAnotB aNotB, - final TupleSketch skA, - final TupleSketch skB, - final ThetaSketch skThetaB, - final Results results) - { - CompactTupleSketch result; - - //Stateful, A = Tuple, B = Tuple - if (skA != null) { - try { - aNotB.setA(skA); - aNotB.notB(skB); - result = aNotB.getResult(true); - results.check(result); - } - catch (final SketchesArgumentException e) { } - } - - //Stateless A = Tuple, B = Tuple - if (skA == null || skB == null) { - try { - result = TupleAnotB.aNotB(skA, skB); - fail(); - } - catch (final SketchesArgumentException e) { } - } else { - result = TupleAnotB.aNotB(skA, skB); - results.check(result); - } - - //Stateless A = Tuple, B = Theta - if (skA == null || skThetaB == null) { - try { result = TupleAnotB.aNotB(skA, skThetaB); fail(); } - catch (final SketchesArgumentException e) { } - } else { - result = TupleAnotB.aNotB(skA, skThetaB); - results.check(result); - } - - //Stateful A = Tuple, B = Tuple - if (skA == null) { - try { aNotB.setA(skA); fail(); } - catch (final SketchesArgumentException e) { } - } else { - aNotB.setA(skA); - aNotB.notB(skB); - result = aNotB.getResult(true); - results.check(result); - } - - //Stateful A = Tuple, B = Theta - if (skA == null) { - try { aNotB.setA(skA); fail(); } - catch (final SketchesArgumentException e) { } - } else { - aNotB.setA(skA); - aNotB.notB(skThetaB); - result = aNotB.getResult(false); - results.check(result); - result = aNotB.getResult(true); - results.check(result); - } - } - - private static class Results { - private int retEnt = 0; - private boolean empty = true; - private double expect = 0.0; - private double tol = 0.0; - private double sum = 0.0; - - Results() {} - - Results set(final int retEnt, final boolean empty, - final double expect, final double tol, final double sum) { - this.retEnt = retEnt; //retained Entries - this.empty = empty; - this.expect = expect; //expected estimate - this.tol = tol; //tolerance - this.sum = sum; - return this; - } - - void check(final CompactTupleSketch result) { - assertEquals(result.getRetainedEntries(), retEnt); - assertEquals(result.isEmpty(), empty); - if (result.getTheta() < 1.0) { - final double est = result.getEstimate(); - assertEquals(est, expect, expect * tol); - assertTrue(result.getUpperBound(1) > est); - assertTrue(result.getLowerBound(1) <= est); - } else { - assertEquals(result.getEstimate(), expect, 0.0); - assertEquals(result.getUpperBound(1), expect, 0.0); - assertEquals(result.getLowerBound(1), expect, 0.0); - } - final TupleSketchIterator it = result.iterator(); - while (it.next()) { - Assert.assertEquals(it.getSummary().getValue(), sum); - } - } - } //End class Results - - private static UpdatableTupleSketch buildUpdatableTuple() { - return new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - } - - private static UpdatableThetaSketch buildUpdateTheta() { - return new UpdatableThetaSketchBuilder().build(); - } - - /*****************************************/ - - @Test - public void aNotBNullEmptyCombinations() { - final TupleAnotB aNotB = new TupleAnotB<>(); - // calling getResult() before calling update() should yield an empty set - final CompactTupleSketch result = aNotB.getResult(true); - results.set(0, true, 0.0, 0.0, 0.0).check(result); - - final UpdatableTupleSketch sketch = buildUpdatableTuple(); - final UpdatableThetaSketch skTheta = buildUpdateTheta(); - - threeMethodsWithTheta(aNotB, null, null, null, results); - threeMethodsWithTheta(aNotB, sketch, null, null, results); - threeMethodsWithTheta(aNotB, null, sketch, null, results); - threeMethodsWithTheta(aNotB, sketch, sketch, null, results); - threeMethodsWithTheta(aNotB, null, null, skTheta, results); - threeMethodsWithTheta(aNotB, sketch, null, skTheta, results); - threeMethodsWithTheta(aNotB, null, sketch, skTheta, results); - threeMethodsWithTheta(aNotB, sketch, sketch, skTheta, results); - } - - @Test - public void aNotBCheckDoubleSetAs() { - final UpdatableTupleSketch skA = buildUpdatableTuple(); - skA.update(1, 1.0); - skA.update(2, 1.0); - final UpdatableTupleSketch skA2 = buildUpdatableTuple(); - final TupleAnotB aNotB = new TupleAnotB<>(); - aNotB.setA(skA); - assertEquals(aNotB.getResult(false).isEmpty(), false); - aNotB.setA(skA2); - assertEquals(aNotB.getResult(false).isEmpty(), true); - } - - @Test - public void aNotBEmptyExact() { - final UpdatableTupleSketch sketchA = buildUpdatableTuple(); - final UpdatableTupleSketch sketchB = buildUpdatableTuple(); - sketchB.update(1, 1.0); - sketchB.update(2, 1.0); - final UpdatableThetaSketch skThetaB = buildUpdateTheta(); - skThetaB.update(1); - skThetaB.update(2); - - final TupleAnotB aNotB = new TupleAnotB<>(); - results.set(0, true, 0.0, 0.0, 0.0); - threeMethodsWithTheta(aNotB, sketchA, sketchB, skThetaB, results); - } - - @Test - public void aNotBExactEmpty() { - final UpdatableTupleSketch sketchA = buildUpdatableTuple(); - sketchA.update(1, 1.0); - sketchA.update(2, 1.0); - final UpdatableTupleSketch sketchB = buildUpdatableTuple(); - final UpdatableThetaSketch skThetaB = buildUpdateTheta(); - - final TupleAnotB aNotB = new TupleAnotB<>(); - results.set(2, false, 2.0, 0.0, 1.0); - threeMethodsWithTheta(aNotB, sketchA, sketchB, skThetaB, results); - - // same thing, but compact sketches - threeMethodsWithTheta(aNotB, sketchA.compact(), sketchB.compact(), skThetaB.compact(), results); - } - - @Test - public void aNotBExactOverlap() { - final UpdatableTupleSketch sketchA = buildUpdatableTuple(); - sketchA.update(1, 1.0); - sketchA.update(1, 1.0); - sketchA.update(2, 1.0); - sketchA.update(2, 1.0); - - final UpdatableTupleSketch sketchB = buildUpdatableTuple(); - sketchB.update(2, 1.0); - sketchB.update(2, 1.0); - sketchB.update(3, 1.0); - sketchB.update(3, 1.0); - - final UpdatableThetaSketch skThetaB = buildUpdateTheta(); - skThetaB.update(2); - skThetaB.update(3); - - final TupleAnotB aNotB = new TupleAnotB<>(); - results.set(1, false, 1.0, 0.0, 2.0); - threeMethodsWithTheta(aNotB, sketchA, sketchB, skThetaB, results); - } - - @Test - public void aNotBEstimationOverlap() { - final UpdatableTupleSketch sketchA = buildUpdatableTuple(); - for (int i = 0; i < 8192; i++) { - sketchA.update(i, 1.0); - } - - final UpdatableTupleSketch sketchB = buildUpdatableTuple(); - for (int i = 0; i < 4096; i++) { - sketchB.update(i, 1.0); - } - - final UpdatableThetaSketch skThetaB = buildUpdateTheta(); - for (int i = 0; i < 4096; i++) { - skThetaB.update(i); - } - - final TupleAnotB aNotB = new TupleAnotB<>(); - results.set(2123, false, 4096.0, 0.03, 1.0); - threeMethodsWithTheta(aNotB, sketchA, sketchB, skThetaB, results); - - // same thing, but compact sketches - threeMethodsWithTheta(aNotB, sketchA.compact(), sketchB.compact(), skThetaB.compact(), results); - } - - @Test - public void aNotBEstimationOverlapLargeB() { - final UpdatableTupleSketch sketchA = buildUpdatableTuple(); - for (int i = 0; i < 10_000; i++) { - sketchA.update(i, 1.0); - } - - final UpdatableTupleSketch sketchB = buildUpdatableTuple(); - for (int i = 0; i < 100_000; i++) { - sketchB.update(i + 8000, 1.0); - } - - final UpdatableThetaSketch skThetaB = buildUpdateTheta(); - for (int i = 0; i < 100_000; i++) { - skThetaB.update(i + 8000); - } - - final int expected = 8_000; - final TupleAnotB aNotB = new TupleAnotB<>(); - results.set(376, false, expected, 0.1, 1.0); - threeMethodsWithTheta(aNotB, sketchA, sketchB, skThetaB, results); - - // same thing, but compact sketches - threeMethodsWithTheta(aNotB, sketchA.compact(), sketchB.compact(), skThetaB.compact(), results); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleIntersectionTest.java b/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleIntersectionTest.java deleted file mode 100644 index a01690cf4..000000000 --- a/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleIntersectionTest.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.adouble; - -import static org.testng.Assert.fail; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.SketchesStateException; -import org.apache.datasketches.theta.UpdatableThetaSketch; -import org.apache.datasketches.theta.UpdatableThetaSketchBuilder; -import org.apache.datasketches.tuple.CompactTupleSketch; -import org.apache.datasketches.tuple.TupleIntersection; -import org.apache.datasketches.tuple.TupleSketch; -import org.apache.datasketches.tuple.TupleSketchIterator; -import org.apache.datasketches.tuple.UpdatableTupleSketch; -import org.apache.datasketches.tuple.UpdatableTupleSketchBuilder; -import org.apache.datasketches.tuple.adouble.DoubleSummary; -import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; -import org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations; -import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode; -import org.testng.Assert; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class AdoubleIntersectionTest { - private final DoubleSummary.Mode mode = Mode.Sum; - - @Test - public void intersectionNotEmptyNoEntries() { - final UpdatableTupleSketch sketch1 = - new UpdatableTupleSketchBuilder<> - (new DoubleSummaryFactory(mode)).setSamplingProbability(0.01f).build(); - sketch1.update("a", 1.0); // this happens to get rejected because of sampling with low probability - final TupleIntersection intersection = - new TupleIntersection<>(new DoubleSummarySetOperations(mode, mode)); - intersection.intersect(sketch1); - final CompactTupleSketch result = intersection.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0, 0.0001); - Assert.assertTrue(result.getUpperBound(1) > 0); - } - - @Test - public void intersectionExactWithEmpty() { - final UpdatableTupleSketch sketch1 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - sketch1.update(1, 1.0); - sketch1.update(2, 1.0); - sketch1.update(3, 1.0); - - final TupleSketch sketch2 = TupleSketch.createEmptySketch(); - - final TupleIntersection intersection = - new TupleIntersection<>(new DoubleSummarySetOperations(mode, mode)); - intersection.intersect(sketch1); - intersection.intersect(sketch2); - final CompactTupleSketch result = intersection.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - } - - @Test - public void intersectionExactMode() { - UpdatableTupleSketch sketch1 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - sketch1.update(1, 1.0); - sketch1.update(1, 1.0); - sketch1.update(2, 1.0); - sketch1.update(2, 1.0); - - final UpdatableTupleSketch sketch2 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - sketch2.update(2, 1.0); - sketch2.update(2, 1.0); - sketch2.update(3, 1.0); - sketch2.update(3, 1.0); - - final TupleIntersection intersection = - new TupleIntersection<>(new DoubleSummarySetOperations(mode, mode)); - intersection.intersect(sketch1); - intersection.intersect(sketch2); - final CompactTupleSketch result = intersection.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 1); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), 1.0); - Assert.assertEquals(result.getLowerBound(1), 1.0); - Assert.assertEquals(result.getUpperBound(1), 1.0); - final TupleSketchIterator it = result.iterator(); - Assert.assertTrue(it.next()); - Assert.assertTrue(it.getHash() > 0); - Assert.assertEquals(it.getSummary().getValue(), 4.0); - Assert.assertFalse(it.next()); - - intersection.reset(); - sketch1 = null; - try { intersection.intersect(sketch1); fail();} - catch (final SketchesArgumentException e) { } - -} - - @Test - public void intersectionDisjointEstimationMode() { - int key = 0; - final UpdatableTupleSketch sketch1 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, 1.0); - } - - final UpdatableTupleSketch sketch2 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, 1.0); - } - - final TupleIntersection intersection = - new TupleIntersection<>(new DoubleSummarySetOperations(mode, mode)); - intersection.intersect(sketch1); - intersection.intersect(sketch2); - CompactTupleSketch result = intersection.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertTrue(result.getUpperBound(1) > 0); - - // an intersection with no entries must survive more updates - intersection.intersect(sketch1); - result = intersection.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertTrue(result.getUpperBound(1) > 0); - } - - @Test - public void intersectionEstimationMode() { - int key = 0; - final UpdatableTupleSketch sketch1 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, 1.0); - } - - key -= 4096; // overlap half of the entries - final UpdatableTupleSketch sketch2 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, 1.0); - } - - final TupleIntersection intersection = - new TupleIntersection<>(new DoubleSummarySetOperations(mode, mode)); - intersection.intersect(sketch1); - intersection.intersect(sketch2); - final CompactTupleSketch result = intersection.getResult(); - Assert.assertFalse(result.isEmpty()); - // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries()) - Assert.assertEquals(result.getEstimate(), 4096.0, 4096 * 0.03); - Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate()); - Assert.assertTrue(result.getUpperBound(1) > result.getEstimate()); - final TupleSketchIterator it = result.iterator(); - while (it.next()) { - Assert.assertEquals(it.getSummary().getValue(), 2.0); - } - } - - @Test - public void checkExactIntersectionWithTheta() { - final UpdatableThetaSketch thSkNull = null; - final UpdatableThetaSketch thSkEmpty = new UpdatableThetaSketchBuilder().build(); - final UpdatableThetaSketch thSk10 = new UpdatableThetaSketchBuilder().build(); - final UpdatableThetaSketch thSk15 = new UpdatableThetaSketchBuilder().build(); - for (int i = 0; i < 10; i++) { thSk10.update(i); } - for (int i = 0; i < 10; i++) { thSk15.update(i + 5); } //overlap = 5 - - DoubleSummary dsum = new DoubleSummaryFactory(mode).newSummary(); - final TupleIntersection intersection = - new TupleIntersection<>(new DoubleSummarySetOperations(mode, mode)); - CompactTupleSketch result; - - try { intersection.getResult(); fail(); } - catch (final SketchesStateException e ) { } //OK. - - try { intersection.intersect(thSkNull, dsum); fail(); } - catch (final SketchesArgumentException e) { } //OK - - intersection.intersect(thSkEmpty, dsum); - result = intersection.getResult(); - Assert.assertTrue(result.isEmpty()); //Empty after empty first call - intersection.reset(); - - intersection.intersect(thSk10, dsum); - result = intersection.getResult(); - Assert.assertEquals(result.getEstimate(), 10.0); //Returns valid first call - intersection.reset(); - - intersection.intersect(thSk10, dsum); // Valid first call - intersection.intersect(thSkEmpty, dsum); - result = intersection.getResult(); - Assert.assertTrue(result.isEmpty()); //Returns Empty after empty second call - intersection.reset(); - - intersection.intersect(thSk10, dsum); - intersection.intersect(thSk15, dsum); - result = intersection.getResult(); - Assert.assertEquals(result.getEstimate(), 5.0); //Returns intersection - intersection.reset(); - - dsum = null; - try { intersection.intersect(thSk10, dsum); fail(); } - catch (final SketchesArgumentException e) { } - } - - @Test - public void checkExactIntersectionWithThetaDisjoint() { - final UpdatableThetaSketch thSkA = new UpdatableThetaSketchBuilder().setLogNominalEntries(10).build(); - final UpdatableThetaSketch thSkB = new UpdatableThetaSketchBuilder().setLogNominalEntries(10).build(); - int key = 0; - for (int i = 0; i < 32; i++) { thSkA.update(key++); } - for (int i = 0; i < 32; i++) { thSkB.update(key++); } - - final DoubleSummary dsum = new DoubleSummaryFactory(mode).newSummary(); - final TupleIntersection intersection = - new TupleIntersection<>(new DoubleSummarySetOperations(mode, mode)); - CompactTupleSketch result; - - intersection.intersect(thSkA, dsum); - intersection.intersect(thSkB, dsum); - result = intersection.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 0); - - // an intersection with no entries must survive more updates - intersection.intersect(thSkA, dsum); - result = intersection.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 0); - intersection.reset(); - } - - @Test - public void checkEstimatingIntersectionWithThetaOverlapping() { - final UpdatableThetaSketch thSkA = new UpdatableThetaSketchBuilder().setLogNominalEntries(4).build(); - final UpdatableThetaSketch thSkB = new UpdatableThetaSketchBuilder().setLogNominalEntries(10).build(); - for (int i = 0; i < 64; i++) { thSkA.update(i); } //dense mode, low theta - for (int i = 32; i < 96; i++) { thSkB.update(i); } //exact overlapping - - final DoubleSummary dsum = new DoubleSummaryFactory(mode).newSummary(); - final TupleIntersection intersection = - new TupleIntersection<>(new DoubleSummarySetOperations(mode, mode)); - CompactTupleSketch result; - - intersection.intersect(thSkA, dsum); - intersection.intersect(thSkB, dsum); - result = intersection.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 14); - - thSkB.reset(); - for (int i = 100; i < 164; i++) { thSkB.update(i); } //exact, disjoint - intersection.intersect(thSkB, dsum); //remove existing entries - result = intersection.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 0); - intersection.intersect(thSkB, dsum); - result = intersection.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 0); - } - - @Test - public void intersectionEmpty() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - final TupleIntersection intersection = - new TupleIntersection<>(new DoubleSummarySetOperations(mode, mode)); - intersection.intersect(sketch); - final CompactTupleSketch result = intersection.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleTest.java b/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleTest.java deleted file mode 100644 index 94d25bd7d..000000000 --- a/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleTest.java +++ /dev/null @@ -1,424 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.adouble; - -import static org.testng.Assert.assertEquals; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.TupleSketch; -import org.apache.datasketches.tuple.TupleSketchIterator; -import org.apache.datasketches.tuple.UpdatableTupleSketch; -import org.apache.datasketches.tuple.UpdatableTupleSketchBuilder; -import org.apache.datasketches.tuple.adouble.DoubleTupleSketch; -import org.apache.datasketches.tuple.adouble.DoubleSummary; -import org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer; -import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; -import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class AdoubleTest { - private final DoubleSummary.Mode mode = Mode.Sum; - - @Test - public void isEmpty() { - final int lgK = 12; - final DoubleTupleSketch sketch = new DoubleTupleSketch(lgK, mode); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getTheta(), 1.0); - Assert.assertEquals(sketch.getTheta(), 1.0); - Assert.assertNotNull(sketch.toString()); - final TupleSketchIterator it = sketch.iterator(); - Assert.assertNotNull(it); - Assert.assertFalse(it.next()); - } - - @Test - public void checkLowK() { - final UpdatableTupleSketchBuilder bldr = new UpdatableTupleSketchBuilder<>( - new DoubleSummaryFactory(Mode.Sum)); - bldr.setNominalEntries(16); - final UpdatableTupleSketch sk = bldr.build(); - assertEquals(sk.getLgK(), 4); - } - - @SuppressWarnings("deprecation") - @Test - public void serDeTest() { - final int lgK = 12; - final int K = 1 << lgK; - final DoubleTupleSketch a1Sk = new DoubleTupleSketch(lgK, Mode.AlwaysOne); - final int m = 2 * K; - for (int key = 0; key < m; key++) { - a1Sk.update(key, 1.0); - } - final double est1 = a1Sk.getEstimate(); - final MemorySegment seg = MemorySegment.ofArray(a1Sk.toByteArray()); - final DoubleTupleSketch a1Sk2 = new DoubleTupleSketch(seg, Mode.AlwaysOne); - final double est2 = a1Sk2.getEstimate(); - assertEquals(est1, est2); - } - - @Test - public void checkStringKey() { - final int lgK = 12; - final int K = 1 << lgK; - final DoubleTupleSketch a1Sk1 = new DoubleTupleSketch(lgK, Mode.AlwaysOne); - final int m = K / 2; - for (int key = 0; key < m; key++) { - a1Sk1.update(Integer.toHexString(key), 1.0); - } - assertEquals(a1Sk1.getEstimate(), K / 2.0); - } - - - @Test - public void isEmptyWithSampling() { - final float samplingProbability = 0.1f; - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)) - .setSamplingProbability(samplingProbability).build(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - } - - @Test - public void sampling() { - final float samplingProbability = 0.001f; - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>( - new DoubleSummaryFactory(mode)).setSamplingProbability(samplingProbability).build(); - sketch.update("a", 1.0); - Assert.assertFalse(sketch.isEmpty()); - Assert.assertTrue(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertTrue(sketch.getUpperBound(1) > 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0, 0.0000001); - Assert.assertEquals((float)sketch.getTheta(), samplingProbability); - Assert.assertEquals((float)sketch.getTheta(), samplingProbability); - } - - @Test - public void exactMode() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>( - new DoubleSummaryFactory(mode)).build(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - for (int i = 1; i <= 4096; i++) { - sketch.update(i, 1.0); - } - Assert.assertFalse(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 4096.0); - Assert.assertEquals(sketch.getUpperBound(1), 4096.0); - Assert.assertEquals(sketch.getLowerBound(1), 4096.0); - Assert.assertEquals(sketch.getTheta(), 1.0); - Assert.assertEquals(sketch.getTheta(), 1.0); - - int count = 0; - final TupleSketchIterator it = sketch.iterator(); - while (it.next()) { - Assert.assertEquals(it.getSummary().getValue(), 1.0); - count++; - } - Assert.assertEquals(count, 4096); - - sketch.reset(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getTheta(), 1.0); - Assert.assertEquals(sketch.getTheta(), 1.0); - } - - @Test - // The moment of going into the estimation mode is, to some extent, an implementation detail - // Here we assume that presenting as many unique values as twice the nominal - // size of the sketch will result in estimation mode - public void estimationMode() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>( - new DoubleSummaryFactory(mode)).build(); - Assert.assertEquals(sketch.getEstimate(), 0.0); - for (int i = 1; i <= 8192; i++) { - sketch.update(i, 1.0); - } - Assert.assertTrue(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 8192, 8192 * 0.01); - Assert.assertTrue(sketch.getEstimate() >= sketch.getLowerBound(1)); - Assert.assertTrue(sketch.getEstimate() < sketch.getUpperBound(1)); - - int count = 0; - final TupleSketchIterator it = sketch.iterator(); - while (it.next()) { - Assert.assertEquals(it.getSummary().getValue(), 1.0); - count++; - } - Assert.assertTrue(count >= 4096); - - sketch.reset(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getTheta(), 1.0); - Assert.assertEquals(sketch.getTheta(), 1.0); -} - - @Test - public void estimationModeWithSamplingNoResizing() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>( - new DoubleSummaryFactory(mode)) - .setSamplingProbability(0.5f) - .setResizeFactor(ResizeFactor.X1).build(); - for (int i = 0; i < 16384; i++) { - sketch.update(i, 1.0); - } - Assert.assertTrue(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 16384, 16384 * 0.01); - Assert.assertTrue(sketch.getEstimate() >= sketch.getLowerBound(1)); - Assert.assertTrue(sketch.getEstimate() < sketch.getUpperBound(1)); - } - - @Test - public void updatesOfAllKeyTypes() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - sketch.update(1L, 1.0); - sketch.update(2.0, 1.0); - final byte[] bytes = { 3, 3 }; - sketch.update(bytes, 1.0); - sketch.update(ByteBuffer.wrap(bytes), 1.0); // same as previous - sketch.update(ByteBuffer.wrap(bytes, 0, 1), 1.0); // slice of previous - final int[] ints = { 4 }; - sketch.update(ints, 1.0); - final long[] longs = { 5L }; - sketch.update(longs, 1.0); - sketch.update("a", 1.0); - Assert.assertEquals(sketch.getEstimate(), 7.0); - } - - @Test - public void doubleSummaryDefaultSumMode() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>( - new DoubleSummaryFactory(mode)).build(); - { - sketch.update(1, 1.0); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - final TupleSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 1.0); - Assert.assertFalse(it.next()); - } - { - sketch.update(1, 0.7); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - final TupleSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 1.7); - Assert.assertFalse(it.next()); - } - { - sketch.update(1, 0.8); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - final TupleSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 2.5); - Assert.assertFalse(it.next()); - } - } - - @Test - public void doubleSummaryMinMode() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>( - new DoubleSummaryFactory(DoubleSummary.Mode.Min)).build(); - { - sketch.update(1, 1.0); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - final TupleSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 1.0); - Assert.assertFalse(it.next()); - } - { - sketch.update(1, 0.7); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - final TupleSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 0.7); - Assert.assertFalse(it.next()); - } - { - sketch.update(1, 0.8); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - final TupleSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 0.7); - Assert.assertFalse(it.next()); - } - } - @Test - - public void doubleSummaryMaxMode() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>( - new DoubleSummaryFactory(DoubleSummary.Mode.Max)).build(); - { - sketch.update(1, 1.0); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - final TupleSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 1.0); - Assert.assertFalse(it.next()); - } - { - sketch.update(1, 0.7); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - final TupleSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 1.0); - Assert.assertFalse(it.next()); - } - { - sketch.update(1, 2.0); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - final TupleSketchIterator it = sketch.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 2.0); - Assert.assertFalse(it.next()); - } - } - - @SuppressWarnings("deprecation") - @Test - public void serializeDeserializeExact() throws Exception { - final UpdatableTupleSketch sketch1 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - sketch1.update(1, 1.0); - - final UpdatableTupleSketch sketch2 = TupleSketch.heapifyUpdatableSketch( - MemorySegment.ofArray(sketch1.toByteArray()), - new DoubleSummaryDeserializer(), new DoubleSummaryFactory(mode)); - - Assert.assertEquals(sketch2.getEstimate(), 1.0); - final TupleSketchIterator it = sketch2.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 1.0); - Assert.assertFalse(it.next()); - - // the same key, so still one unique - sketch2.update(1, 1.0); - Assert.assertEquals(sketch2.getEstimate(), 1.0); - - sketch2.update(2, 1.0); - Assert.assertEquals(sketch2.getEstimate(), 2.0); - } - - @SuppressWarnings("deprecation") - @Test - public void serializeDeserializeEstimationNoResizing() throws Exception { - final UpdatableTupleSketch sketch1 = - new UpdatableTupleSketchBuilder<>( - new DoubleSummaryFactory(mode)).setResizeFactor(ResizeFactor.X1).build(); - for (int j = 0; j < 10; j++) { - for (int i = 0; i < 8192; i++) { - sketch1.update(i, 1.0); - } - } - sketch1.trim(); - final byte[] bytes = sketch1.toByteArray(); - - //for binary testing - //TestUtil.writeBytesToFile(bytes, "UpdatableSketchWithDoubleSummary4K.sk"); - - final TupleSketch sketch2 = - TupleSketch.heapifySketch(MemorySegment.ofArray(bytes), new DoubleSummaryDeserializer()); - Assert.assertTrue(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), 8192, 8192 * 0.99); - Assert.assertEquals(sketch1.getTheta(), sketch2.getTheta()); - final TupleSketchIterator it = sketch2.iterator(); - int count = 0; - while (it.next()) { - Assert.assertEquals(it.getSummary().getValue(), 10.0); - count++; - } - Assert.assertEquals(count, 4096); - } - - @SuppressWarnings("deprecation") - @Test - public void serializeDeserializeSampling() throws Exception { - final int sketchSize = 16384; - final int numberOfUniques = sketchSize; - final UpdatableTupleSketch sketch1 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)) - .setNominalEntries(sketchSize).setSamplingProbability(0.5f).build(); - for (int i = 0; i < numberOfUniques; i++) { - sketch1.update(i, 1.0); - } - final TupleSketch sketch2 = TupleSketch.heapifySketch( - MemorySegment.ofArray(sketch1.toByteArray()), new DoubleSummaryDeserializer()); - Assert.assertTrue(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate() / numberOfUniques, 1.0, 0.01); - Assert.assertEquals(sketch2.getRetainedEntries() / (double) numberOfUniques, 0.5, 0.01); - Assert.assertEquals(sketch1.getTheta(), sketch2.getTheta()); - } - - @Test - public void checkUpdatableSketch() { - final DoubleSummaryFactory dsumFact = new DoubleSummaryFactory(mode); - //DoubleSummary dsum = dsumFact.newSummary(); - final UpdatableTupleSketchBuilder bldr = new UpdatableTupleSketchBuilder<>(dsumFact); - final UpdatableTupleSketch usk = bldr.build(); - final byte[] byteArr = new byte[0]; - usk.update(byteArr, 0.0); - final int[] intArr = new int[0]; - usk.update(intArr, 1.0); - final long[] longArr = new long[0]; - usk.update(longArr, 2.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void invalidSamplingProbability() { - new UpdatableTupleSketchBuilder<> - (new DoubleSummaryFactory(mode)).setSamplingProbability(2f).build(); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleUnionTest.java b/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleUnionTest.java deleted file mode 100644 index 08dd421d2..000000000 --- a/src/test/java/org/apache/datasketches/tuple/adouble/AdoubleUnionTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.adouble; - -import static org.testng.Assert.fail; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.theta.UpdatableThetaSketch; -import org.apache.datasketches.theta.UpdatableThetaSketchBuilder; -import org.apache.datasketches.tuple.CompactTupleSketch; -import org.apache.datasketches.tuple.TupleSketchIterator; -import org.apache.datasketches.tuple.TupleUnion; -import org.apache.datasketches.tuple.UpdatableTupleSketch; -import org.apache.datasketches.tuple.UpdatableTupleSketchBuilder; -import org.apache.datasketches.tuple.adouble.DoubleSummary; -import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; -import org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations; -import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode; -import org.testng.Assert; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class AdoubleUnionTest { - private final DoubleSummary.Mode mode = Mode.Sum; - - @Test - public void unionEmptySampling() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).setSamplingProbability(0.01f).build(); - sketch.update(1, 1.0); - Assert.assertEquals(sketch.getRetainedEntries(), 0); // not retained due to low sampling probability - - final TupleUnion union = new TupleUnion<>(new DoubleSummarySetOperations(mode, mode)); - union.union(sketch); - final CompactTupleSketch result = union.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertFalse(result.isEmpty()); - Assert.assertTrue(result.isEstimationMode()); - Assert.assertEquals(result.getEstimate(), 0.0); - } - - @Test - public void unionExactMode() { - final UpdatableTupleSketch sketch1 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - sketch1.update(1, 1.0); - sketch1.update(1, 1.0); - sketch1.update(1, 1.0); - sketch1.update(2, 1.0); - - final UpdatableTupleSketch sketch2 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - sketch2.update(2, 1.0); - sketch2.update(2, 1.0); - sketch2.update(3, 1.0); - sketch2.update(3, 1.0); - sketch2.update(3, 1.0); - - final TupleUnion union = new TupleUnion<>(new DoubleSummarySetOperations(mode, mode)); - union.union(sketch1); - union.union(sketch2); - CompactTupleSketch result = union.getResult(); - Assert.assertEquals(result.getEstimate(), 3.0); - - final TupleSketchIterator it = result.iterator(); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 3.0); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 3.0); - Assert.assertTrue(it.next()); - Assert.assertEquals(it.getSummary().getValue(), 3.0); - Assert.assertFalse(it.next()); - - union.reset(); - result = union.getResult(); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertTrue(result.isEmpty()); - Assert.assertFalse(result.isEstimationMode()); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - Assert.assertEquals(result.getTheta(), 1.0); - } - - @Test - public void unionEstimationMode() { - int key = 0; - final UpdatableTupleSketch sketch1 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, 1.0); - } - - key -= 4096; // overlap half of the entries - final UpdatableTupleSketch sketch2 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, 1.0); - } - - final TupleUnion union = new TupleUnion<>(4096, new DoubleSummarySetOperations(mode, mode)); - union.union(sketch1); - union.union(sketch2); - final CompactTupleSketch result = union.getResult(); - Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01); - Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate()); - Assert.assertTrue(result.getUpperBound(1) > result.getEstimate()); - } - - @Test - public void unionMixedMode() { - int key = 0; - final UpdatableTupleSketch sketch1 = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - for (int i = 0; i < 1000; i++) { - sketch1.update(key++, 1.0); - //System.out.println("theta1=" + sketch1.getTheta() + " " + sketch1.getThetaLong()); - } - - key -= 500; // overlap half of the entries - final UpdatableTupleSketch sketch2 = - new UpdatableTupleSketchBuilder<> - (new DoubleSummaryFactory(mode)).setSamplingProbability(0.2f).build(); - for (int i = 0; i < 20000; i++) { - sketch2.update(key++, 1.0); - //System.out.println("theta2=" + sketch2.getTheta() + " " + sketch2.getThetaLong()); - } - - final TupleUnion union = new TupleUnion<>(4096, new DoubleSummarySetOperations(mode, mode)); - union.union(sketch1); - union.union(sketch2); - final CompactTupleSketch result = union.getResult(); - Assert.assertEquals(result.getEstimate(), 20500.0, 20500 * 0.01); - Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate()); - Assert.assertTrue(result.getUpperBound(1) > result.getEstimate()); - } - - @Test - public void checkUnionUpdateWithTheta() { - final TupleUnion union = new TupleUnion<>(new DoubleSummarySetOperations(mode, mode)); - UpdatableThetaSketch usk = null; - DoubleSummary dsum = null; - - try { union.union(usk, dsum); fail(); } - catch (final SketchesArgumentException e) { } - - usk = new UpdatableThetaSketchBuilder().build(); - try { union.union(usk, dsum); fail(); } - catch (final SketchesArgumentException e) { } - - dsum = new DoubleSummaryFactory(mode).newSummary(); - for (int i = 0; i < 10; i++) { usk.update(i); } - union.union(usk, dsum); - Assert.assertEquals(union.getResult().getEstimate(), 10.0); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/adouble/FilterTest.java b/src/test/java/org/apache/datasketches/tuple/adouble/FilterTest.java deleted file mode 100644 index 269583df4..000000000 --- a/src/test/java/org/apache/datasketches/tuple/adouble/FilterTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.adouble; - -import java.util.Random; - -import org.apache.datasketches.tuple.Filter; -import org.apache.datasketches.tuple.TupleSketch; -import org.apache.datasketches.tuple.UpdatableTupleSketch; -import org.apache.datasketches.tuple.UpdatableTupleSketchBuilder; -import org.apache.datasketches.tuple.adouble.DoubleSummary; -import org.apache.datasketches.tuple.adouble.DoubleSummaryFactory; -import org.apache.datasketches.tuple.adouble.DoubleSummary.Mode; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class FilterTest { - private static final int numberOfElements = 100; - private static final Random random = new Random(1);//deterministic for this class - private final DoubleSummary.Mode mode = Mode.Sum; - - @Test - public void emptySketch() { - final TupleSketch sketch = TupleSketch.createEmptySketch(); - - final Filter filter = new Filter<>(o -> true); - - final TupleSketch filteredSketch = filter.filter(sketch); - - Assert.assertEquals(filteredSketch.getEstimate(), 0.0); - Assert.assertEquals(filteredSketch.getThetaLong(), sketch.getThetaLong()); - Assert.assertTrue(filteredSketch.isEmpty()); - Assert.assertEquals(filteredSketch.getLowerBound(1), 0.0); - Assert.assertEquals(filteredSketch.getUpperBound(1), 0.0); - } - - @Test - public void nullSketch() { - final Filter filter = new Filter<>(o -> true); - - final TupleSketch filteredSketch = filter.filter(null); - - Assert.assertEquals(filteredSketch.getEstimate(), 0.0); - Assert.assertEquals(filteredSketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertTrue(filteredSketch.isEmpty()); - Assert.assertEquals(filteredSketch.getLowerBound(1), 0.0); - Assert.assertEquals(filteredSketch.getUpperBound(1), 0.0); - } - - @Test - public void filledSketchShouldBehaveTheSame() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - - fillSketch(sketch, numberOfElements, 0.0); - - final Filter filter = new Filter<>(o -> true); - - final TupleSketch filteredSketch = filter.filter(sketch); - - Assert.assertEquals(filteredSketch.getEstimate(), sketch.getEstimate()); - Assert.assertEquals(filteredSketch.getThetaLong(), sketch.getThetaLong()); - Assert.assertFalse(filteredSketch.isEmpty()); - Assert.assertEquals(filteredSketch.getLowerBound(1), sketch.getLowerBound(1)); - Assert.assertEquals(filteredSketch.getUpperBound(1), sketch.getUpperBound(1)); - } - - @Test - public void filledSketchShouldFilterOutElements() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - - fillSketch(sketch, numberOfElements, 0.0); - fillSketch(sketch, 2 * numberOfElements, 1.0); - - final Filter filter = new Filter<>(o -> o.getValue() < 0.5); - - final TupleSketch filteredSketch = filter.filter(sketch); - - Assert.assertEquals(filteredSketch.getEstimate(), numberOfElements); - Assert.assertEquals(filteredSketch.getThetaLong(), sketch.getThetaLong()); - Assert.assertFalse(filteredSketch.isEmpty()); - Assert.assertTrue(filteredSketch.getLowerBound(1) <= filteredSketch.getEstimate()); - Assert.assertTrue(filteredSketch.getUpperBound(1) >= filteredSketch.getEstimate()); - } - - @Test - public void filteringInEstimationMode() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>(new DoubleSummaryFactory(mode)).build(); - - final int n = 10000; - fillSketch(sketch, n, 0.0); - fillSketch(sketch, 2 * n, 1.0); - - final Filter filter = new Filter<>(o -> o.getValue() < 0.5); - - final TupleSketch filteredSketch = filter.filter(sketch); - - Assert.assertEquals(filteredSketch.getEstimate(), n, n * 0.05); - Assert.assertEquals(filteredSketch.getThetaLong(), sketch.getThetaLong()); - Assert.assertFalse(filteredSketch.isEmpty()); - Assert.assertTrue(filteredSketch.getLowerBound(1) <= filteredSketch.getEstimate()); - Assert.assertTrue(filteredSketch.getUpperBound(1) >= filteredSketch.getEstimate()); - } - - @Test - public void nonEmptySketchWithNoEntries() { - final UpdatableTupleSketch sketch = - new UpdatableTupleSketchBuilder<>( - new DoubleSummaryFactory(mode)).setSamplingProbability(0.0001f).build(); - sketch.update(0, 0.0); - - Assert.assertFalse(sketch.isEmpty()); - Assert.assertEquals(sketch.getRetainedEntries(), 0); - - final Filter filter = new Filter<>(o -> true); - - final TupleSketch filteredSketch = filter.filter(sketch); - - Assert.assertFalse(filteredSketch.isEmpty()); - Assert.assertEquals(filteredSketch.getEstimate(), sketch.getEstimate()); - Assert.assertEquals(filteredSketch.getThetaLong(), sketch.getThetaLong()); - Assert.assertEquals(filteredSketch.getLowerBound(1), sketch.getLowerBound(1)); - Assert.assertEquals(filteredSketch.getUpperBound(1), sketch.getUpperBound(1)); - } - - private static void fillSketch(final UpdatableTupleSketch sketch, - final int numberOfElements, final Double sketchValue) { - - - for (int cont = 0; cont < numberOfElements; cont++) { - sketch.update(random.nextLong(), sketchValue); - } - } -} diff --git a/src/test/java/org/apache/datasketches/tuple/aninteger/CornerCaseTupleSetOperationsTest.java b/src/test/java/org/apache/datasketches/tuple/aninteger/CornerCaseTupleSetOperationsTest.java deleted file mode 100644 index 56dd73595..000000000 --- a/src/test/java/org/apache/datasketches/tuple/aninteger/CornerCaseTupleSetOperationsTest.java +++ /dev/null @@ -1,630 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.aninteger; - -import static org.apache.datasketches.hash.MurmurHash3.hash; -import static org.testng.Assert.assertTrue; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.theta.UpdatableThetaSketch; -import org.apache.datasketches.theta.UpdatableThetaSketchBuilder; -import org.apache.datasketches.tuple.CompactTupleSketch; -import org.apache.datasketches.tuple.TupleAnotB; -import org.apache.datasketches.tuple.TupleIntersection; -import org.apache.datasketches.tuple.TupleUnion; -import org.testng.annotations.Test; - -public class CornerCaseTupleSetOperationsTest { - - /* Hash Values - * 9223372036854775807 Theta = 1.0 - * - * 6730918654704304314 hash(3L)[0] >>> 1 GT_MIDP - * 4611686018427387904 Theta for p = 0.5f = MIDP - * 2206043092153046979 hash(2L)[0] >>> 1 LT_MIDP_V - * 1498732507761423037 hash(5L)[0] >>> 1 LTLT_MIDP_V - * - * 1206007004353599230 hash(6L)[0] >>> 1 GT_LOWP_V - * 922337217429372928 Theta for p = 0.1f = LOWP - * 593872385995628096 hash(4L)[0] >>> 1 LT_LOWP_V - * 405753591161026837 hash(1L)[0] >>> 1 LTLT_LOWP_V - */ - - private static final long GT_MIDP_V = 3L; - private static final float MIDP_FLT = 0.5f; - - private static final long GT_LOWP_V = 6L; - private static final float LOWP_FLT = 0.1f; - private static final long LT_LOWP_V = 4L; - - - private IntegerSummary.Mode mode = IntegerSummary.Mode.Min; - private IntegerSummary integerSummary = new IntegerSummary(mode); - private IntegerSummarySetOperations setOperations = new IntegerSummarySetOperations(mode, mode); - - private enum SkType { - EMPTY, // { 1.0, 0, T} Bin: 101 Oct: 05 - EXACT, // { 1.0, >0, F} Bin: 110 Oct: 06, specify only value - ESTIMATION, // {<1.0, >0, F} Bin: 010 Oct: 02, specify only value - DEGENERATE // {<1.0, 0, F} Bin: 000 Oct: 0, specify p, value - } - - //================================= - - @Test - public void emptyEmpty() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.EMPTY, 0, 0); - IntegerTupleSketch tupleB = getTupleSketch(SkType.EMPTY, 0, 0); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.EMPTY, 0, 0); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = 1.0; - final int expectedUnionCount = 0; - final boolean expectedUnionEmpty = true; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void emptyExact() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.EMPTY, 0, 0); - IntegerTupleSketch tupleB = getTupleSketch(SkType.EXACT, 0, GT_MIDP_V); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.EXACT, 0, GT_MIDP_V); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = 1.0; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void EmptyDegenerate() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.EMPTY, 0, 0); - IntegerTupleSketch tupleB = getTupleSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 0; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void emptyEstimation() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.EMPTY, 0, 0); - IntegerTupleSketch tupleB = getTupleSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - //================================= - - @Test - public void exactEmpty() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.EXACT, 0, GT_MIDP_V); - IntegerTupleSketch tupleB = getTupleSketch(SkType.EMPTY, 0, 0); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.EMPTY, 0, 0); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 1; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = 1.0; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void exactExact() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.EXACT, 0, GT_MIDP_V); - IntegerTupleSketch tupleB = getTupleSketch(SkType.EXACT, 0, GT_MIDP_V); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.EXACT, 0, GT_MIDP_V); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 1; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = 1.0; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void exactDegenerate() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.EXACT, 0, LT_LOWP_V); - IntegerTupleSketch tupleB = getTupleSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); //entries = 0 - UpdatableThetaSketch thetaB = getThetaSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 1; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void exactEstimation() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.EXACT, 0, LT_LOWP_V); - IntegerTupleSketch tupleB = getTupleSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 1; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - //================================= - - @Test - public void estimationEmpty() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V); - IntegerTupleSketch tupleB = getTupleSketch(SkType.EMPTY, 0, 0); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.EMPTY, 0, 0); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 1; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void estimationExact() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V); - IntegerTupleSketch tupleB = getTupleSketch(SkType.EXACT, 0, LT_LOWP_V); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.EXACT, 0, LT_LOWP_V); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 1; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void estimationDegenerate() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.ESTIMATION, MIDP_FLT, LT_LOWP_V); - IntegerTupleSketch tupleB = getTupleSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 1; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void estimationEstimation() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.ESTIMATION, MIDP_FLT, LT_LOWP_V); - IntegerTupleSketch tupleB = getTupleSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 1; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - //================================= - - @Test - public void degenerateEmpty() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); //entries = 0 - IntegerTupleSketch tupleB = getTupleSketch(SkType.EMPTY, 0, 0); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.EMPTY, 0, 0); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 0; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void degenerateExact() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); //entries = 0 - IntegerTupleSketch tupleB = getTupleSketch(SkType.EXACT, 0, LT_LOWP_V); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.EXACT, 0, LT_LOWP_V); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void degenerateDegenerate() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.DEGENERATE, MIDP_FLT, GT_MIDP_V); //entries = 0 - IntegerTupleSketch tupleB = getTupleSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_V); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 0; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void degenerateEstimation() { - IntegerTupleSketch tupleA = getTupleSketch(SkType.DEGENERATE, MIDP_FLT, GT_MIDP_V); //entries = 0 - IntegerTupleSketch tupleB = getTupleSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V); - UpdatableThetaSketch thetaB = getThetaSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_V); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(tupleA, tupleB, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - //================================= - //================================= - - private void checks( - IntegerTupleSketch tupleA, - IntegerTupleSketch tupleB, - UpdatableThetaSketch thetaB, - double expectedIntersectTheta, - int expectedIntersectCount, - boolean expectedIntersectEmpty, - double expectedAnotbTheta, - int expectedAnotbCount, - boolean expectedAnotbEmpty, - double expectedUnionTheta, - int expectedUnionCount, - boolean expectedUnionEmpty) { - CompactTupleSketch csk; - TupleIntersection inter = new TupleIntersection<>(setOperations); - TupleAnotB anotb = new TupleAnotB<>(); - TupleUnion union = new TupleUnion<>(16, setOperations); - - //TupleIntersection Stateless TupleSketch, TupleSketch Updatable - csk = inter.intersect(tupleA, tupleB); - checkResult("Intersect Stateless TupleSketch, TupleSketch", csk, expectedIntersectTheta, expectedIntersectCount, - expectedIntersectEmpty); - //TupleIntersection Stateless TupleSketch, TupleSketch Compact - csk = inter.intersect(tupleA.compact(), tupleB.compact()); - checkResult("Intersect Stateless TupleSketch, TupleSketch", csk, expectedIntersectTheta, expectedIntersectCount, - expectedIntersectEmpty); - //TupleIntersection Stateless TupleSketch, ThetaSketch Updatable - csk = inter.intersect(tupleA, thetaB, integerSummary); //TupleSketch, ThetaSketch - checkResult("Intersect Stateless TupleSketch, ThetaSketch", csk, expectedIntersectTheta, expectedIntersectCount, - expectedIntersectEmpty); - //TupleIntersection Stateless TupleSketch, ThetaSketch Compact - csk = inter.intersect(tupleA.compact(), thetaB.compact(), integerSummary); - checkResult("Intersect Stateless TupleSketch, ThetaSketch", csk, expectedIntersectTheta, expectedIntersectCount, - expectedIntersectEmpty); - - //TupleAnotB Stateless TupleSketch, TupleSketch Updatable - csk = TupleAnotB.aNotB(tupleA, tupleB); - checkResult("TupleAnotB Stateless TupleSketch, TupleSketch", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - //TupleAnotB Stateless TupleSketch, TupleSketch Compact - csk = TupleAnotB.aNotB(tupleA.compact(), tupleB.compact()); - checkResult("TupleAnotB Stateless TupleSketch, TupleSketch", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - //TupleAnotB Stateless TupleSketch, ThetaSketch Updatable - csk = TupleAnotB.aNotB(tupleA, thetaB); - checkResult("TupleAnotB Stateless TupleSketch, ThetaSketch", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - //TupleAnotB Stateless TupleSketch, ThetaSketch Compact - csk = TupleAnotB.aNotB(tupleA.compact(), thetaB.compact()); - checkResult("TupleAnotB Stateless TupleSketch, ThetaSketch", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - - //TupleAnotB Stateful TupleSketch, TupleSketch Updatable - anotb.setA(tupleA); - anotb.notB(tupleB); - csk = anotb.getResult(true); - checkResult("TupleAnotB Stateful TupleSketch, TupleSketch", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - //TupleAnotB Stateful TupleSketch, TupleSketch Compact - anotb.setA(tupleA.compact()); - anotb.notB(tupleB.compact()); - csk = anotb.getResult(true); - checkResult("TupleAnotB Stateful TupleSketch, TupleSketch", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - //TupleAnotB Stateful TupleSketch, ThetaSketch Updatable - anotb.setA(tupleA); - anotb.notB(thetaB); - csk = anotb.getResult(true); - checkResult("TupleAnotB Stateful TupleSketch, ThetaSketch", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - //TupleAnotB Stateful TupleSketch, ThetaSketch Compact - anotb.setA(tupleA.compact()); - anotb.notB(thetaB.compact()); - csk = anotb.getResult(true); - checkResult("TupleAnotB Stateful TupleSketch, ThetaSketch", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - - //TupleUnion Stateless TupleSketch, TupleSketch Updatable - csk = union.union(tupleA, tupleB); - checkResult("TupleUnion Stateless TupleSketch, TupleSketch", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - //TupleUnion Stateless TupleSketch, TupleSketch Compact - csk = union.union(tupleA.compact(), tupleB.compact()); - checkResult("TupleUnion Stateless TupleSketch, TupleSketch", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - //TupleUnion Stateless TupleSketch, ThetaSketch Updatable - csk = union.union(tupleA, thetaB, integerSummary); - checkResult("TupleUnion Stateless TupleSketch, ThetaSketch", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - //TupleUnion Stateless TupleSketch, ThetaSketch Compact - csk = union.union(tupleA.compact(), thetaB.compact(), integerSummary); - checkResult("TupleUnion Stateless TupleSketch, ThetaSketch", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - - //TupleUnion Stateful TupleSketch, TupleSketch Updatable - union.union(tupleA); - union.union(tupleB); - csk = union.getResult(true); - checkResult("TupleUnion Stateful TupleSketch, TupleSketch", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - //TupleAnotB Stateful TupleSketch, TupleSketch Compact - union.union(tupleA.compact()); - union.union(tupleB.compact()); - csk = union.getResult(true); - checkResult("TupleUnion Stateful TupleSketch, TupleSketch", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - //TupleAnotB Stateful TupleSketch, ThetaSketch Updatable - union.union(tupleA); - union.union(thetaB, integerSummary); - csk = union.getResult(true); - checkResult("TupleUnion Stateful TupleSketch, ThetaSketch", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - //TupleAnotB Stateful TupleSketch, ThetaSketch Compact - union.union(tupleA.compact()); - union.union(thetaB.compact(), integerSummary); - csk = union.getResult(true); - checkResult("TupleUnion Stateful TupleSketch, ThetaSketch", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - - } - - private static void checkResult( - String comment, - CompactTupleSketch csk, - double expectedTheta, - int expectedEntries, - boolean expectedEmpty) { - double actualTheta = csk.getTheta(); - int actualEntries = csk.getRetainedEntries(); - boolean actualEmpty = csk.isEmpty(); - - boolean thetaOk = actualTheta == expectedTheta; - boolean entriesOk = actualEntries == expectedEntries; - boolean emptyOk = actualEmpty == expectedEmpty; - if (!thetaOk || !entriesOk || !emptyOk) { - StringBuilder sb = new StringBuilder(); - sb.append(comment + ": "); - if (!thetaOk) { sb.append("Theta: expected " + expectedTheta + ", got " + actualTheta + "; "); } - if (!entriesOk) { sb.append("Entries: expected " + expectedEntries + ", got " + actualEntries + "; "); } - if (!emptyOk) { sb.append("Empty: expected " + expectedEmpty + ", got " + actualEmpty + "."); } - throw new IllegalArgumentException(sb.toString()); - } - } - - private static IntegerTupleSketch getTupleSketch( - SkType skType, - float p, - long updateKey) { - - IntegerTupleSketch sk; - switch(skType) { - case EMPTY: { // { 1.0, 0, T} p and value are not used - sk = new IntegerTupleSketch(4, 2, 1.0f, IntegerSummary.Mode.Min); - break; - } - case EXACT: { // { 1.0, >0, F} p is not used - sk = new IntegerTupleSketch(4, 2, 1.0f, IntegerSummary.Mode.Min); - sk.update(updateKey, 1); - break; - } - case ESTIMATION: { // {<1.0, >0, F} - checkValidUpdate(p, updateKey); - sk = new IntegerTupleSketch(4, 2, p, IntegerSummary.Mode.Min); - sk.update(updateKey, 1); - break; - } - case DEGENERATE: { // {<1.0, 0, F} - checkInvalidUpdate(p, updateKey); - sk = new IntegerTupleSketch(4, 2, p, IntegerSummary.Mode.Min); - sk.update(updateKey, 1); // > theta - break; - } - - default: { return null; } // should not happen - } - return sk; - } - - //NOTE: p and value arguments are used for every case - private static UpdatableThetaSketch getThetaSketch( - SkType skType, - float p, - long updateKey) { - UpdatableThetaSketchBuilder bldr = new UpdatableThetaSketchBuilder(); - bldr.setLogNominalEntries(4); - bldr.setResizeFactor(ResizeFactor.X4); - - UpdatableThetaSketch sk; - switch(skType) { - case EMPTY: { // { 1.0, 0, T} p and value are not used - sk = bldr.build(); - break; - } - case EXACT: { // { 1.0, >0, F} p is not used - sk = bldr.build(); - sk.update(updateKey); - break; - } - case ESTIMATION: { // {<1.0, >0, F} - checkValidUpdate(p, updateKey); - bldr.setP(p); - sk = bldr.build(); - sk.update(updateKey); - break; - } - case DEGENERATE: { // {<1.0, 0, F} - checkInvalidUpdate(p, updateKey); - bldr.setP(p); - sk = bldr.build(); - sk.update(updateKey); - break; - } - - default: { return null; } // should not happen - } - return sk; - } - - private static void checkValidUpdate(float p, long updateKey) { - assertTrue( getLongHash(updateKey) < (long) (p * Long.MAX_VALUE)); - } - - private static void checkInvalidUpdate(float p, long updateKey) { - assertTrue( getLongHash(updateKey) > (long) (p * Long.MAX_VALUE)); - } - - static long getLongHash(long v) { - return (hash(v, Util.DEFAULT_UPDATE_SEED)[0]) >>> 1; - } -} diff --git a/src/test/java/org/apache/datasketches/tuple/aninteger/EngagementTest.java b/src/test/java/org/apache/datasketches/tuple/aninteger/EngagementTest.java deleted file mode 100644 index cd2a20ea9..000000000 --- a/src/test/java/org/apache/datasketches/tuple/aninteger/EngagementTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.aninteger; - -import static java.lang.Math.exp; -import static java.lang.Math.log; -import static java.lang.Math.round; -import static org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode.AlwaysOne; -import static org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode.Sum; - -import org.apache.datasketches.tuple.CompactTupleSketch; -import org.apache.datasketches.tuple.TupleSketchIterator; -import org.apache.datasketches.tuple.TupleUnion; -import org.apache.datasketches.tuple.aninteger.IntegerTupleSketch; -import org.apache.datasketches.tuple.aninteger.IntegerSummary; -import org.apache.datasketches.tuple.aninteger.IntegerSummarySetOperations; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class EngagementTest { - public static final int numStdDev = 2; - - @Test - public void computeEngagementHistogram() { - final int lgK = 8; //Using a larger sketch >= 9 will produce exact results for this little example - final int K = 1 << lgK; - final int days = 30; - int v = 0; - final IntegerTupleSketch[] skArr = new IntegerTupleSketch[days]; - for (int i = 0; i < days; i++) { - skArr[i] = new IntegerTupleSketch(lgK, AlwaysOne); - } - for (int i = 0; i <= days; i++) { //31 generating indices for symmetry - final int numIds = numIDs(days, i); - final int numDays = numDays(days, i); - final int myV = v++; - for (int d = 0; d < numDays; d++) { - for (int id = 0; id < numIds; id++) { - skArr[d].update(myV + id, 1); - } - } - v += numIds; - } - unionOps(K, Sum, skArr); - } - - private static int numIDs(final int totalDays, final int index) { - final double d = totalDays; - final double i = index; - return (int)round(exp(i * log(d) / d)); - } - - private static int numDays(final int totalDays, final int index) { - final double d = totalDays; - final double i = index; - return (int)round(exp((d - i) * log(d) / d)); - } - - private static void unionOps(final int K, final IntegerSummary.Mode mode, final IntegerTupleSketch ... sketches) { - final IntegerSummarySetOperations setOps = new IntegerSummarySetOperations(mode, mode); - final TupleUnion union = new TupleUnion<>(K, setOps); - final int len = sketches.length; - - for (final IntegerTupleSketch isk : sketches) { - union.union(isk); - } - final CompactTupleSketch result = union.getResult(); - final TupleSketchIterator itr = result.iterator(); - - final int[] numDaysArr = new int[len + 1]; //zero index is ignored - - while (itr.next()) { - //For each unique visitor from the result sketch, get the # days visited - final int numDaysVisited = itr.getSummary().getValue(); - //increment the number of visitors that visited numDays - numDaysArr[numDaysVisited]++; //values range from 1 to 30 - } - - println("\nEngagement Histogram:"); - println("Number of Unique Visitors by Number of Days Visited"); - printf("%12s%12s%12s%12s\n","Days Visited", "Estimate", "LB", "UB"); - int sumVisits = 0; - final double theta = result.getTheta(); - for (int i = 0; i < numDaysArr.length; i++) { - final int visitorsAtDaysVisited = numDaysArr[i]; - if (visitorsAtDaysVisited == 0) { continue; } - sumVisits += visitorsAtDaysVisited * i; - - final double estVisitorsAtDaysVisited = visitorsAtDaysVisited / theta; - final double lbVisitorsAtDaysVisited = result.getLowerBound(numStdDev, visitorsAtDaysVisited); - final double ubVisitorsAtDaysVisited = result.getUpperBound(numStdDev, visitorsAtDaysVisited); - - printf("%12d%12.0f%12.0f%12.0f\n", - i, estVisitorsAtDaysVisited, lbVisitorsAtDaysVisited, ubVisitorsAtDaysVisited); - } - - //The estimate and bounds of the total number of visitors comes directly from the sketch. - final double visitors = result.getEstimate(); - final double lbVisitors = result.getLowerBound(numStdDev); - final double ubVisitors = result.getUpperBound(numStdDev); - printf("\n%12s%12s%12s%12s\n","Totals", "Estimate", "LB", "UB"); - printf("%12s%12.0f%12.0f%12.0f\n", "Visitors", visitors, lbVisitors, ubVisitors); - - //The total number of visits, however, is a scaled metric and takes advantage of the fact that - //the retained entries in the sketch is a uniform random sample of all unique visitors, and - //the the rest of the unique users will likely behave in the same way. - final double estVisits = sumVisits / theta; - final double lbVisits = estVisits * lbVisitors / visitors; - final double ubVisits = estVisits * ubVisitors / visitors; - printf("%12s%12.0f%12.0f%12.0f\n\n", "Visits", estVisits, lbVisits, ubVisits); - } - - /** - * @param o object to print - */ - private static void println(final Object o) { - printf("%s\n", o.toString()); - } - - /** - * @param fmt format - * @param args arguments - */ - private static void printf(final String fmt, final Object ... args) { - //System.out.printf(fmt, args); //Enable/Disable printing here - } -} diff --git a/src/test/java/org/apache/datasketches/tuple/aninteger/IntegerSketchTest.java b/src/test/java/org/apache/datasketches/tuple/aninteger/IntegerSketchTest.java deleted file mode 100644 index 8111eb544..000000000 --- a/src/test/java/org/apache/datasketches/tuple/aninteger/IntegerSketchTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.aninteger; - -import static org.testng.Assert.assertEquals; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.tuple.TupleAnotB; -import org.apache.datasketches.tuple.CompactTupleSketch; -import org.apache.datasketches.tuple.TupleIntersection; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class IntegerSketchTest { - - @SuppressWarnings("deprecation") - @Test - public void serDeTest() { - final int lgK = 12; - final int K = 1 << lgK; - final IntegerSummary.Mode a1Mode = IntegerSummary.Mode.AlwaysOne; - final IntegerTupleSketch a1Sk = new IntegerTupleSketch(lgK, a1Mode); - final int m = 2 * K; - for (int i = 0; i < m; i++) { - a1Sk.update(i, 1); - } - final double est1 = a1Sk.getEstimate(); - final MemorySegment seg = MemorySegment.ofArray(a1Sk.toByteArray()); - final IntegerTupleSketch a1Sk2 = new IntegerTupleSketch(seg, a1Mode); - final double est2 = a1Sk2.getEstimate(); - assertEquals(est1, est2); - } - - @Test - public void intersectTest() { - final int lgK = 12; - final int K = 1 << lgK; - final IntegerSummary.Mode a1Mode = IntegerSummary.Mode.AlwaysOne; - final IntegerTupleSketch a1Sk1 = new IntegerTupleSketch(lgK, a1Mode); - final IntegerTupleSketch a1Sk2 = new IntegerTupleSketch(lgK, a1Mode); - final int m = 2 * K; - for (int i = 0; i < m; i++) { - a1Sk1.update(i, 1); - a1Sk2.update(i + m/2, 1); - } - final TupleIntersection inter = - new TupleIntersection<>(new IntegerSummarySetOperations(a1Mode, a1Mode)); - inter.intersect(a1Sk1); - inter.intersect(a1Sk2); - final CompactTupleSketch csk = inter.getResult(); - assertEquals(csk.getEstimate(), K * 1.0, K * .03); - } - - @Test - public void aNotBTest() { - final int lgK = 4; - final int u = 5; - final IntegerSummary.Mode a1Mode = IntegerSummary.Mode.AlwaysOne; - final IntegerTupleSketch a1Sk1 = new IntegerTupleSketch(lgK, a1Mode); - final IntegerTupleSketch a1Sk2 = null;//new IntegerTupleSketch(lgK, a1Mode); - final TupleAnotB anotb = new TupleAnotB<>(); - for (int i = 0; i < u; i++) { - a1Sk1.update(i, 1); - } - anotb.setA(a1Sk1); - anotb.notB(a1Sk2); - final CompactTupleSketch cSk = anotb.getResult(true); - assertEquals((int)cSk.getEstimate(), u); - } - - @Test - public void checkMinMaxMode() { - final int lgK = 12; - final int K = 1 << lgK; - final IntegerSummary.Mode minMode = IntegerSummary.Mode.Min; - final IntegerSummary.Mode maxMode = IntegerSummary.Mode.Max; - final IntegerTupleSketch a1Sk1 = new IntegerTupleSketch(lgK, minMode); - final IntegerTupleSketch a1Sk2 = new IntegerTupleSketch(lgK, maxMode); - final int m = K / 2; - for (int key = 0; key < m; key++) { - a1Sk1.update(key, 1); - a1Sk1.update(key, 0); - a1Sk1.update(key, 2); - a1Sk2.update(key + m/2, 1); - a1Sk2.update(key + m/2, 0); - a1Sk2.update(key + m/2, 2); - } - final double est1 = a1Sk1.getEstimate(); - final double est2 = a1Sk2.getEstimate(); - assertEquals(est1, est2); - } - - @Test - public void checkStringKey() { - final int lgK = 12; - final int K = 1 << lgK; - final IntegerSummary.Mode a1Mode = IntegerSummary.Mode.AlwaysOne; - final IntegerTupleSketch a1Sk1 = new IntegerTupleSketch(lgK, a1Mode); - final int m = K / 2; - for (int key = 0; key < m; key++) { - a1Sk1.update(Integer.toHexString(key), 1); - } - assertEquals(a1Sk1.getEstimate(), K / 2.0); - } - - /** - * @param o object to print - */ - static void println(final Object o) { - //System.out.println(o.toString()); //Disable - } - - /** - * @param fmt format - * @param args arguments - */ - static void printf(final String fmt, final Object ... args) { - //System.out.printf(fmt, args); //Disable - } -} diff --git a/src/test/java/org/apache/datasketches/tuple/aninteger/MikhailsBugTupleTest.java b/src/test/java/org/apache/datasketches/tuple/aninteger/MikhailsBugTupleTest.java deleted file mode 100644 index 5e08748a2..000000000 --- a/src/test/java/org/apache/datasketches/tuple/aninteger/MikhailsBugTupleTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.aninteger; - -import org.apache.datasketches.tuple.CompactTupleSketch; -import org.apache.datasketches.tuple.TupleIntersection; -import org.apache.datasketches.tuple.TupleAnotB; -import org.testng.annotations.Test; - -/** - * Issue #368, from Mikhail Lavrinovich 12 OCT 2021 - * The failure was TupleAnotB(estimating {<1.0,1,F}, TupleIntersect(estimating{<1.0,1,F}, newDegenerative{<1.0,0,T}, - * Which should be equal to TupleAnotB(estimating{<1.0,1,F}, new{1.0,0,T} = estimating{<1.0, 1, F}. - * The TupleAnotB threw a null pointer exception because it was not properly handling sketches with zero entries. - */ -public class MikhailsBugTupleTest { - - @Test - public void mikhailsBug() { - IntegerTupleSketch x = new IntegerTupleSketch(12, 2, 0.1f, IntegerSummary.Mode.Min); - IntegerTupleSketch y = new IntegerTupleSketch(12, 2, 0.1f, IntegerSummary.Mode.Min); - x.update(1L, 1); - IntegerSummarySetOperations setOperations = - new IntegerSummarySetOperations(IntegerSummary.Mode.Min, IntegerSummary.Mode.Min); - TupleIntersection intersection = new TupleIntersection<>(setOperations); - CompactTupleSketch intersect = intersection.intersect(x, y); - TupleAnotB.aNotB(x, intersect); // NPE was here - } - - //@Test - public void withTuple() { - IntegerTupleSketch x = new IntegerTupleSketch(12, 2, 0.1f, IntegerSummary.Mode.Min); - IntegerTupleSketch y = new IntegerTupleSketch(12, 2, 0.1f, IntegerSummary.Mode.Min); - x.update(1L, 1); - println("Tuple x: Estimating {<1.0,1,F}"); - println(x.toString()); - println("Tuple y: NewDegenerative {<1.0,0,T}"); - println(y.toString()); - IntegerSummarySetOperations setOperations = - new IntegerSummarySetOperations(IntegerSummary.Mode.Min, IntegerSummary.Mode.Min); - TupleIntersection intersection = new TupleIntersection<>(setOperations); - CompactTupleSketch intersect = intersection.intersect(x, y); - println("TupleIntersect(Estimating, NewDegen) = new {1.0, 0, T}"); - println(intersect.toString()); - CompactTupleSketch csk = TupleAnotB.aNotB(x, intersect); - println("TupleAnotB(Estimating, New) = estimating {<1.0, 1, F}"); - println(csk.toString()); - } - - /** - * Println an object - * @param o object to print - */ - private static void println(Object o) { - //System.out.println(o.toString()); //disable here - } -} \ No newline at end of file diff --git a/src/test/java/org/apache/datasketches/tuple/aninteger/ParameterLeakageTest.java b/src/test/java/org/apache/datasketches/tuple/aninteger/ParameterLeakageTest.java deleted file mode 100644 index 988d188dd..000000000 --- a/src/test/java/org/apache/datasketches/tuple/aninteger/ParameterLeakageTest.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.aninteger; - -import static org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode.Min; -import static org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode.Sum; - -import org.apache.datasketches.tuple.CompactTupleSketch; -import org.apache.datasketches.tuple.TupleIntersection; -import org.apache.datasketches.tuple.TupleAnotB; -import org.apache.datasketches.tuple.TupleSketch; -import org.apache.datasketches.tuple.TupleSketchIterator; -import org.apache.datasketches.tuple.TupleUnion; -import org.testng.annotations.Test; - -/** - * These tests check to make sure that no summary objects, which are mutable, and created - * as needed internally within a tuple sketch never leak into the result sketch. - * - * @author Lee Rhodes - * - */ -public class ParameterLeakageTest { - IntegerSummarySetOperations setOps = new IntegerSummarySetOperations(Sum, Min); - - @Test - public void checkUnion() { - IntegerTupleSketch sk1 = new IntegerTupleSketch(4, Sum); - sk1.update(1, 1); - IntegerSummary sk1sum = captureSummaries(sk1)[0]; - - IntegerTupleSketch sk2 = new IntegerTupleSketch(4, Sum); - sk2.update(2, 1); - IntegerSummary sk2sum = captureSummaries(sk2)[0]; - - - TupleUnion union = new TupleUnion<>(setOps); - - CompactTupleSketch csk = union.union(sk1, sk2); - IntegerSummary[] summaries = captureSummaries(csk); - println("TupleUnion Count: " + summaries.length); - - for (IntegerSummary isum : summaries) { - if ((isum == sk1sum) || (isum == sk2sum)) { - throw new IllegalArgumentException("Parameter Leakage"); - } - } - } - - @Test - public void checkIntersectStateless() { - IntegerTupleSketch sk1 = new IntegerTupleSketch(4, Sum); - sk1.update(1, 1); - IntegerSummary sk1sum = captureSummaries(sk1)[0]; - - IntegerTupleSketch sk2 = new IntegerTupleSketch(4, Sum); - sk2.update(1, 1); - IntegerSummary sk2sum = captureSummaries(sk2)[0]; - - TupleIntersection intersect = new TupleIntersection<>(setOps); - - CompactTupleSketch csk = intersect.intersect(sk1, sk2); - IntegerSummary[] summaries = captureSummaries(csk); - println("Intersect Stateless Count: " + summaries.length); - - for (IntegerSummary isum : summaries) { - if ((isum == sk1sum) || (isum == sk2sum)) { - throw new IllegalArgumentException("Parameter Leakage"); - } - } - } - - @Test - public void checkIntersectStateful() { - IntegerTupleSketch sk1 = new IntegerTupleSketch(4, Sum); - sk1.update(1, 1); - IntegerSummary sk1sum = captureSummaries(sk1)[0]; - - IntegerTupleSketch sk2 = new IntegerTupleSketch(4, Sum); - sk2.update(1, 1); - IntegerSummary sk2sum = captureSummaries(sk2)[0]; - - TupleIntersection intersect = new TupleIntersection<>(setOps); - - intersect.intersect(sk1); - intersect.intersect(sk2); - CompactTupleSketch csk = intersect.getResult(); - - IntegerSummary[] summaries = captureSummaries(csk); - println("Intersect Stateful Count: " + summaries.length); - - for (IntegerSummary isum : summaries) { - if ((isum == sk1sum) || (isum == sk2sum)) { - throw new IllegalArgumentException("Parameter Leakage"); - } - } - } - - @Test - public void checkAnotbStateless() { - IntegerTupleSketch sk1 = new IntegerTupleSketch(4, Sum); - sk1.update(1, 1); - CompactTupleSketch csk1 = sk1.compact(); - IntegerSummary sk1sum = captureSummaries(csk1)[0]; - - IntegerTupleSketch sk2 = new IntegerTupleSketch(4, Sum); //EMPTY - - CompactTupleSketch csk = TupleAnotB.aNotB(csk1, sk2); - IntegerSummary[] summaries = captureSummaries(csk); - println("TupleAnotB Stateless Count: " + summaries.length); - - for (IntegerSummary isum : summaries) { - if (isum == sk1sum) { - throw new IllegalArgumentException("Parameter Leakage"); - } - } - } - - @Test - public void checkAnotbStateful() { - IntegerTupleSketch sk1 = new IntegerTupleSketch(4, Sum); - sk1.update(1, 1); - CompactTupleSketch csk1 = sk1.compact(); - IntegerSummary sk1sum = captureSummaries(csk1)[0]; - - IntegerTupleSketch sk2 = new IntegerTupleSketch(4, Sum); //EMPTY - - TupleAnotB anotb = new TupleAnotB<>(); - - anotb.setA(csk1); - anotb.notB(sk2); - - CompactTupleSketch csk = anotb.getResult(true); - IntegerSummary[] summaries = captureSummaries(csk); - println("TupleAnotB Stateful Count: " + summaries.length); - - for (IntegerSummary isum : summaries) { - if (isum == sk1sum) { - throw new IllegalArgumentException("Parameter Leakage"); - } - } - } - - private static IntegerSummary[] captureSummaries(TupleSketch sk) { - int entries = sk.getRetainedEntries(); - IntegerSummary[] intSumArr = new IntegerSummary[entries]; - int cnt = 0; - TupleSketchIterator it = sk.iterator(); - while (it.next()) { - intSumArr[cnt] = it.getSummary(); - cnt++; - } - return intSumArr; - } - - /** - * @param o Object to print - */ - static void println(Object o) { - //System.out.println(o.toString()); //disable - } -} diff --git a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/AodSketchCrossLanguageTest.java b/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/AodSketchCrossLanguageTest.java deleted file mode 100644 index 121b8f52d..000000000 --- a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/AodSketchCrossLanguageTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES; -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.getFileBytes; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; - -/** - * Serialize binary sketches to be tested by C++ code. - * Test deserialization of binary sketches serialized by C++ code. - */ -public class AodSketchCrossLanguageTest { - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingOneValue() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (int n: nArr) { - final ArrayOfDoublesUpdatableSketch sk = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < n; i++) { - sk.update(i, new double[] {i}); - } - putBytesToJavaPath("aod_1_n" + n + "_java.sk", sk.compact().toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingThreeValues() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (int n: nArr) { - final ArrayOfDoublesUpdatableSketch sk = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(3).build(); - for (int i = 0; i < n; i++) { - sk.update(i, new double[] {i, i, i}); - } - putBytesToJavaPath("aod_3_n" + n + "_java.sk", sk.compact().toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingNonEmptyNoEntries() throws IOException { - final ArrayOfDoublesUpdatableSketch sk = - new ArrayOfDoublesUpdatableSketchBuilder().setSamplingProbability(0.01f).build(); - sk.update(1, new double[] {1}); - assertFalse(sk.isEmpty()); - assertEquals(sk.getRetainedEntries(), 0); - putBytesToJavaPath("aod_1_non_empty_no_entries_java.sk", sk.compact().toByteArray()); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppOneValue() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000}; - for (int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "aod_1_n" + n + "_cpp.sk"); - final ArrayOfDoublesSketch sketch = ArrayOfDoublesSketch.wrap(MemorySegment.ofArray(bytes)); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertEquals(sketch.getEstimate(), n, n * 0.03); - assertEquals(sketch.getNumValues(), 1); - final ArrayOfDoublesSketchIterator it = sketch.iterator(); - while (it.next()) { - assertTrue(it.getKey() < sketch.getThetaLong()); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppThreeValues() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10000, 100000, 1000000}; - for (int n: nArr) { - final byte[] bytes = getFileBytes(cppPath, "aod_3_n" + n + "_cpp.sk"); - final ArrayOfDoublesSketch sketch = ArrayOfDoublesSketch.wrap(MemorySegment.ofArray(bytes)); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertEquals(sketch.getEstimate(), n, n * 0.03); - assertEquals(sketch.getNumValues(), 3); - final ArrayOfDoublesSketchIterator it = sketch.iterator(); - while (it.next()) { - assertTrue(it.getKey() < sketch.getThetaLong()); - assertEquals(it.getValues()[0], it.getValues()[1]); - assertEquals(it.getValues()[0], it.getValues()[2]); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppOneValueNonEmptyNoEntries() throws IOException { - final byte[] bytes = getFileBytes(cppPath, "aod_1_non_empty_no_entries_cpp.sk"); - final ArrayOfDoublesSketch sketch = ArrayOfDoublesSketch.wrap(MemorySegment.ofArray(bytes)); - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getRetainedEntries(), 0); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotBTest.java b/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotBTest.java deleted file mode 100644 index 48f60cdcc..000000000 --- a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotBTest.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotB; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCompactSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class ArrayOfDoublesAnotBTest { - - @Test - public void nullOrEmptyInput() { - // calling getResult() before calling update() should yield an empty set - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB(); - ArrayOfDoublesCompactSketch result = aNotB.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - - ArrayOfDoublesSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); - try { - aNotB.update(sketch, null); - fail(); - } catch (SketchesArgumentException e) {} - - try { - aNotB.update(null, sketch); - fail(); - } catch (SketchesArgumentException e) {} - - aNotB.update(sketch, sketch); - result = aNotB.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - } - - @Test - public void emptyA() { - ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketchB.update(1, new double[] {1.0}); - sketchB.update(2, new double[] {1.0}); - sketchB.update(3, new double[] {1.0}); - sketchB.update(4, new double[] {1.0}); - sketchB.update(5, new double[] {1.0}); - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB(); - - ArrayOfDoublesSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().build(); - aNotB.update(sketchA, sketchB); - ArrayOfDoublesCompactSketch result = aNotB.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - } - - @Test - public void emptyB() { - ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketchA.update(1, new double[] {1.0}); - sketchA.update(2, new double[] {1.0}); - sketchA.update(3, new double[] {1.0}); - sketchA.update(4, new double[] {1.0}); - sketchA.update(5, new double[] {1.0}); - ArrayOfDoublesSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().build(); - - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB(); - aNotB.update(sketchA, sketchB); - ArrayOfDoublesCompactSketch result = aNotB.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 5); - Assert.assertEquals(result.getEstimate(), 5.0); - Assert.assertEquals(result.getLowerBound(1), 5.0); - Assert.assertEquals(result.getUpperBound(1), 5.0); - - ArrayOfDoublesSketchIterator it = result.iterator(); - while (it.next()) { - Assert.assertEquals(it.getValues(), new double[] {1}); - } - } - - @Test - public void aSameAsB() { - ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch.update(1, new double[] {1.0}); - sketch.update(2, new double[] {1.0}); - sketch.update(3, new double[] {1.0}); - sketch.update(4, new double[] {1.0}); - sketch.update(5, new double[] {1.0}); - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB(); - aNotB.update(sketch, sketch); - ArrayOfDoublesCompactSketch result = aNotB.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - } - - @Test - public void exactMode() { - ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketchA.update(1, new double[] {1}); - sketchA.update(2, new double[] {1}); - sketchA.update(3, new double[] {1}); - sketchA.update(4, new double[] {1}); - sketchA.update(5, new double[] {1}); - - ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketchB.update(3, new double[] {1}); - sketchB.update(4, new double[] {1}); - sketchB.update(5, new double[] {1}); - sketchB.update(6, new double[] {1}); - sketchB.update(7, new double[] {1}); - - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB(); - aNotB.update(sketchA, sketchB); - ArrayOfDoublesCompactSketch result = aNotB.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 2); - Assert.assertEquals(result.getEstimate(), 2.0); - Assert.assertEquals(result.getLowerBound(1), 2.0); - Assert.assertEquals(result.getUpperBound(1), 2.0); - ArrayOfDoublesSketchIterator it = result.iterator(); - while (it.next()) { - Assert.assertEquals(it.getValues(), new double[] {1}); - } - } - - @Test - public void exactModeTwoDoubles() { - ArrayOfDoublesUpdatableSketchBuilder bldr = new ArrayOfDoublesUpdatableSketchBuilder(); - bldr.setNominalEntries(16); - bldr.setNumberOfValues(2); - bldr.setResizeFactor(ResizeFactor.X1); - - double[] valuesArr1 = {1.0, 2.0}; - double[] valuesArr2 = {2.0, 4.0}; - ArrayOfDoublesUpdatableSketch sketch1 = bldr.build(); - sketch1.update("a", valuesArr1); - sketch1.update("b", valuesArr2); - sketch1.update("c", valuesArr1); - sketch1.update("d", valuesArr1); - ArrayOfDoublesUpdatableSketch sketch2 = bldr.build(); - sketch2.update("c", valuesArr2); - sketch2.update("d", valuesArr2); - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB(); - aNotB.update(sketch1, sketch2); - ArrayOfDoublesCompactSketch result = aNotB.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 2); - double[] resultArr = new double[] {2.0,4.0,1.0,2.0}; //order specific to this test - Assert.assertEquals(result.getValuesAsOneDimension(), resultArr); - } - - @Test - public void exactModeCustomSeed() { - long seed = 1234567890; - ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build(); - sketchA.update(1, new double[] {1}); - sketchA.update(2, new double[] {1}); - sketchA.update(3, new double[] {1}); - sketchA.update(4, new double[] {1}); - sketchA.update(5, new double[] {1}); - - ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build(); - sketchB.update(3, new double[] {1}); - sketchB.update(4, new double[] {1}); - sketchB.update(5, new double[] {1}); - sketchB.update(6, new double[] {1}); - sketchB.update(7, new double[] {1}); - - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().setSeed(seed).buildAnotB(); - aNotB.update(sketchA, sketchB); - ArrayOfDoublesCompactSketch result = aNotB.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 2); - Assert.assertEquals(result.getEstimate(), 2.0); - Assert.assertEquals(result.getLowerBound(1), 2.0); - Assert.assertEquals(result.getUpperBound(1), 2.0); - ArrayOfDoublesSketchIterator it = result.iterator(); - while (it.next()) { - Assert.assertEquals(it.getValues(), new double[] {1}); - } - } - - @Test - public void estimationMode() { - int key = 0; - ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 8192; i++) { - sketchA.update(key++, new double[] {1}); - } - - key -= 4096; // overlap half of the entries - ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 8192; i++) { - sketchB.update(key++, new double[] {1}); - } - - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB(); - aNotB.update(sketchA, sketchB); - ArrayOfDoublesCompactSketch result = aNotB.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), 4096.0, 4096 * 0.03); // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries()) - Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate()); - Assert.assertTrue(result.getUpperBound(1) > result.getEstimate()); - ArrayOfDoublesSketchIterator it = result.iterator(); - while (it.next()) { - Assert.assertEquals(it.getValues(), new double[] {1}); - } - - // same operation, but compact sketches and off-heap result - aNotB.update(sketchA.compact(), sketchB.compact()); - result = aNotB.getResult(MemorySegment.ofArray(new byte[1000000])); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), 4096.0, 4096 * 0.03); // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries()) - Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate()); - Assert.assertTrue(result.getUpperBound(1) > result.getEstimate()); - it = result.iterator(); - while (it.next()) { - Assert.assertEquals(it.getValues(), new double[] {1}); - } - } - - @Test - public void estimationModeLargeB() { - int key = 0; - ArrayOfDoublesUpdatableSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 10000; i++) { - sketchA.update(key++, new double[] {1}); - } - - key -= 2000; // overlap - ArrayOfDoublesUpdatableSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 100000; i++) { - sketchB.update(key++, new double[] {1}); - } - - final int expected = 10000 - 2000; - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB(); - aNotB.update(sketchA, sketchB); - ArrayOfDoublesCompactSketch result = aNotB.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), expected, expected * 0.1); // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries()) - Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate()); - Assert.assertTrue(result.getUpperBound(1) > result.getEstimate()); - ArrayOfDoublesSketchIterator it = result.iterator(); - while (it.next()) { - Assert.assertEquals(it.getValues(), new double[] {1}); - } - - // same operation, but compact sketches and off-heap result - aNotB.update(sketchA.compact(), sketchB.compact()); - result = aNotB.getResult(MemorySegment.ofArray(new byte[1000000])); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), expected, expected * 0.1); // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries()) - Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate()); - Assert.assertTrue(result.getUpperBound(1) > result.getEstimate()); - it = result.iterator(); - while (it.next()) { - Assert.assertEquals(it.getValues(), new double[] {1}); - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void incompatibleSeedA() { - ArrayOfDoublesSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(1).build(); - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB(); - aNotB.update(sketch, null); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void incompatibleSeedB() { - ArrayOfDoublesSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(1).build(); - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().buildAnotB(); - aNotB.update(null, sketch); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void incompatibleSeeds() { - ArrayOfDoublesSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(1).build(); - ArrayOfDoublesSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(2).build(); - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().setSeed(3).buildAnotB(); - aNotB.update(sketchA, sketchB); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void incompatibleNumValues() { - ArrayOfDoublesSketch sketchA = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(1).build(); - ArrayOfDoublesSketch sketchB = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(); - ArrayOfDoublesAnotB aNotB = new ArrayOfDoublesSetOperationBuilder().setSeed(3).buildAnotB(); - aNotB.update(sketchA, sketchB); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCompactSketchTest.java b/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCompactSketchTest.java deleted file mode 100644 index 7bd2ee14b..000000000 --- a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCompactSketchTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static org.testng.Assert.assertEquals; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.Util; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCompactSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; -import org.apache.datasketches.tuple.arrayofdoubles.DirectArrayOfDoublesCompactSketch; -import org.apache.datasketches.tuple.arrayofdoubles.DirectArrayOfDoublesQuickSelectSketchR; -import org.apache.datasketches.tuple.arrayofdoubles.HeapArrayOfDoublesCompactSketch; -import org.apache.datasketches.tuple.arrayofdoubles.HeapArrayOfDoublesQuickSelectSketch; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class ArrayOfDoublesCompactSketchTest { - - @Test - public void heapToDirectExactTwoDoubles() { - ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(); - sketch1.update("a", new double[] {1, 2}); - sketch1.update("b", new double[] {1, 2}); - sketch1.update("c", new double[] {1, 2}); - sketch1.update("d", new double[] {1, 2}); - sketch1.update("a", new double[] {1, 2}); - sketch1.update("b", new double[] {1, 2}); - sketch1.update("c", new double[] {1, 2}); - sketch1.update("d", new double[] {1, 2}); - ArrayOfDoublesCompactSketch csk = sketch1.compact(); - MemorySegment seg = MemorySegment.ofArray(csk.toByteArray()); - ArrayOfDoublesSketch sketch2 = new DirectArrayOfDoublesCompactSketch(seg); - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertFalse(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), 4.0); - Assert.assertEquals(sketch2.getUpperBound(1), 4.0); - Assert.assertEquals(sketch2.getLowerBound(1), 4.0); - Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch2.getTheta(), 1.0); - double[][] values = sketch2.getValues(); - Assert.assertEquals(values.length, 4); - for (double[] array: values) { - Assert.assertEquals(array.length, 2); - Assert.assertEquals(array[0], 2.0); - Assert.assertEquals(array[1], 4.0); - } - } - - @Test - public void directToHeapExactTwoDoubles() { - ArrayOfDoublesUpdatableSketch sketch1 = - new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(MemorySegment.ofArray(new byte[1000000])); - sketch1.update("a", new double[] {1, 2}); - sketch1.update("b", new double[] {1, 2}); - sketch1.update("c", new double[] {1, 2}); - sketch1.update("d", new double[] {1, 2}); - sketch1.update("a", new double[] {1, 2}); - sketch1.update("b", new double[] {1, 2}); - sketch1.update("c", new double[] {1, 2}); - sketch1.update("d", new double[] {1, 2}); - ArrayOfDoublesSketch sketch2 = - new HeapArrayOfDoublesCompactSketch( - MemorySegment.ofArray(sketch1.compact(MemorySegment.ofArray(new byte[1000000])).toByteArray())); - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertFalse(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), 4.0); - Assert.assertEquals(sketch2.getUpperBound(1), 4.0); - Assert.assertEquals(sketch2.getLowerBound(1), 4.0); - Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch2.getTheta(), 1.0); - double[][] values = sketch2.getValues(); - Assert.assertEquals(values.length, 4); - for (double[] array: values) { - Assert.assertEquals(array.length, 2); - Assert.assertEquals(array[0], 2.0); - Assert.assertEquals(array[1], 4.0); - } - } - - @SuppressWarnings("unused") - @Test - public void checkGetValuesAndKeysMethods() { - ArrayOfDoublesUpdatableSketchBuilder bldr = new ArrayOfDoublesUpdatableSketchBuilder(); - bldr.setNominalEntries(16).setNumberOfValues(2); - - HeapArrayOfDoublesQuickSelectSketch hqssk = (HeapArrayOfDoublesQuickSelectSketch) bldr.build(); - hqssk.update("a", new double[] {1, 2}); - hqssk.update("b", new double[] {3, 4}); - hqssk.update("c", new double[] {5, 6}); - hqssk.update("d", new double[] {7, 8}); - final double[][] values = hqssk.getValues(); - final double[] values1d = hqssk.getValuesAsOneDimension(); - final long[] keys = hqssk.getKeys(); - - HeapArrayOfDoublesCompactSketch hcsk = (HeapArrayOfDoublesCompactSketch)hqssk.compact(); - final double[][] values2 = hcsk.getValues(); - final double[] values1d2 = hcsk.getValuesAsOneDimension(); - final long[] keys2 = hcsk.getKeys(); - assertEquals(values2, values); - assertEquals(values1d2, values1d); - assertEquals(keys2, keys); - - MemorySegment hqsskSeg = MemorySegment.ofArray(hqssk.toByteArray()); - - DirectArrayOfDoublesQuickSelectSketchR dqssk = - (DirectArrayOfDoublesQuickSelectSketchR)ArrayOfDoublesSketch.wrap(hqsskSeg, Util.DEFAULT_UPDATE_SEED); - final double[][] values3 = dqssk.getValues(); - final double[] values1d3 = dqssk.getValuesAsOneDimension(); - final long[] keys3 = dqssk.getKeys(); - assertEquals(values3, values); - assertEquals(values1d3, values1d); - assertEquals(keys3, keys); - - MemorySegment hcskSeg = MemorySegment.ofArray(hcsk.toByteArray()); - - DirectArrayOfDoublesCompactSketch dcsk2 = - (DirectArrayOfDoublesCompactSketch)ArrayOfDoublesSketch.wrap(hcskSeg, Util.DEFAULT_UPDATE_SEED); - final double[][] values4 = dqssk.getValues(); - final double[] values1d4 = dqssk.getValuesAsOneDimension(); - final long[] keys4 = dqssk.getKeys(); - assertEquals(values4, values); - assertEquals(values1d4, values1d); - assertEquals(keys4, keys); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesIntersectionTest.java b/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesIntersectionTest.java deleted file mode 100644 index 6a54adbdd..000000000 --- a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesIntersectionTest.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static org.testng.Assert.fail; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCombiner; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCompactSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesIntersection; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class ArrayOfDoublesIntersectionTest { - - private static ArrayOfDoublesCombiner combiner = new ArrayOfDoublesCombiner() { - - @Override - public double[] combine(final double[] a, final double[] b) { - for (int i = 0; i < a.length; i++) { - a[i] += b[i]; - } - return a; - } - }; - - @Test - public void nullInput() { - final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection(); - try { - intersection.intersect(null, null); - fail(); - } catch (SketchesArgumentException e) {} - - } - - @Test - public void empty() { - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection(); - intersection.intersect(sketch1, null); - final ArrayOfDoublesCompactSketch result = intersection.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - Assert.assertEquals(result.getValues().length, 0); - } - - @Test - public void degenerateWithExact() { - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setSamplingProbability(0.01f).build(); - sketch1.update("a", new double[] {1}); // this happens to get rejected because of sampling with low probability - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch2.update(1, new double[] {1}); - - final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection(); - intersection.intersect(sketch1, null); - intersection.intersect(sketch2, null); - final ArrayOfDoublesCompactSketch result = intersection.getResult(); - Assert.assertFalse(result.isEmpty()); //Degenerate - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 184.0); - Assert.assertEquals(result.getValues().length, 0); - } - - @Test - public void heapExactWithEmpty() { - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch1.update(1, new double[] {1}); - sketch1.update(2, new double[] {1}); - sketch1.update(3, new double[] {1}); - - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - - final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection(); - intersection.intersect(sketch1, null); - intersection.intersect(sketch2, null); - final ArrayOfDoublesCompactSketch result = intersection.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - } - - @Test - public void directExactWithEmpty() { - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder() - .build(MemorySegment.ofArray(new byte[1000000])); - sketch1.update(1, new double[] {1}); - sketch1.update(2, new double[] {1}); - sketch1.update(3, new double[] {1}); - - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder() - .build(MemorySegment.ofArray(new byte[1000000])); - - final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder(). - buildIntersection(MemorySegment.ofArray(new byte[1000000])); - intersection.intersect(sketch1, null); - intersection.intersect(sketch2, null); - final ArrayOfDoublesCompactSketch result = intersection.getResult(MemorySegment.ofArray(new byte[1000000])); - Assert.assertTrue(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - } - - @Test - public void heapExactMode() { - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch1.update(1, new double[] {1}); - sketch1.update(1, new double[] {1}); - sketch1.update(2, new double[] {1}); - sketch1.update(2, new double[] {1}); - - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch2.update(2, new double[] {1}); - sketch2.update(2, new double[] {1}); - sketch2.update(3, new double[] {1}); - sketch2.update(3, new double[] {1}); - - final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection(); - intersection.intersect(sketch1, combiner); - intersection.intersect(sketch2, combiner); - ArrayOfDoublesCompactSketch result = intersection.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 1); - Assert.assertEquals(result.getEstimate(), 1.0); - Assert.assertEquals(result.getLowerBound(1), 1.0); - Assert.assertEquals(result.getUpperBound(1), 1.0); - final double[][] values = result.getValues(); - for (int i = 0; i < values.length; i++) { - Assert.assertEquals(values[i][0], 4.0); - } - - intersection.reset(); - try { - intersection.intersect(null, null); - fail(); - } catch (SketchesArgumentException e) { } - } - - @Test - public void heapDisjointEstimationMode() { - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection(); - intersection.intersect(sketch1, combiner); - intersection.intersect(sketch2, combiner); - final ArrayOfDoublesCompactSketch result = intersection.getResult(); - Assert.assertFalse(result.isEmpty()); //Degenerate case - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 3.0); - Assert.assertEquals(result.getValues().length, 0); - Assert.assertTrue(result.thetaLong_ < Long.MAX_VALUE); - } - - @Test - public void directDisjointEstimationMode() { - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder(). - build(MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder(). - build(MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder(). - buildIntersection(MemorySegment.ofArray(new byte[1000000])); - intersection.intersect(sketch1, combiner); - intersection.intersect(sketch2, combiner); - final ArrayOfDoublesCompactSketch result = intersection.getResult(MemorySegment.ofArray(new byte[1000000])); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 0); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getUpperBound(1), 3.0); - Assert.assertEquals(result.getValues().length, 0); - } - - @Test - public void heapEstimationMode() { - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, new double[] {1.0}); - } - - key -= 4096; // overlap half of the entries - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection(); - intersection.intersect(sketch1, combiner); - intersection.intersect(sketch2, combiner); - final ArrayOfDoublesCompactSketch result = intersection.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), 4096.0, 4096 * 0.03); // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries()) - Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate()); - Assert.assertTrue(result.getUpperBound(1) > result.getEstimate()); - final double[][] values = result.getValues(); - for (int i = 0; i < values.length; i++) { - Assert.assertEquals(values[i][0], 2.0); - } - } - - @Test - public void directEstimationMode() { - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, new double[] {1.0}); - } - - key -= 4096; // overlap half of the entries - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().buildIntersection(MemorySegment.ofArray(new byte[1000000])); - intersection.intersect(sketch1, combiner); - intersection.intersect(sketch2, combiner); - final ArrayOfDoublesCompactSketch result = intersection.getResult(MemorySegment.ofArray(new byte[1000000])); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), 4096.0, 4096 * 0.03); // crude estimate of RSE(95%) = 2 / sqrt(result.getRetainedEntries()) - Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate()); - Assert.assertTrue(result.getUpperBound(1) > result.getEstimate()); - final double[][] values = result.getValues(); - for (int i = 0; i < values.length; i++) { - Assert.assertEquals(values[i][0], 2.0); - } - } - - @Test - public void heapExactModeCustomSeed() { - final long seed = 1234567890; - - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build(); - sketch1.update(1, new double[] {1}); - sketch1.update(1, new double[] {1}); - sketch1.update(2, new double[] {1}); - sketch1.update(2, new double[] {1}); - - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build(); - sketch2.update(2, new double[] {1}); - sketch2.update(2, new double[] {1}); - sketch2.update(3, new double[] {1}); - sketch2.update(3, new double[] {1}); - - final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().setSeed(seed).buildIntersection(); - intersection.intersect(sketch1, combiner); - intersection.intersect(sketch2, combiner); - final ArrayOfDoublesCompactSketch result = intersection.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getRetainedEntries(), 1); - Assert.assertEquals(result.getEstimate(), 1.0); - Assert.assertEquals(result.getLowerBound(1), 1.0); - Assert.assertEquals(result.getUpperBound(1), 1.0); - final double[][] values = result.getValues(); - for (int i = 0; i < values.length; i++) { - Assert.assertEquals(values[i][0], 4.0); - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void incompatibleSeeds() { - final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(1).build(); - final ArrayOfDoublesIntersection intersection = new ArrayOfDoublesSetOperationBuilder().setSeed(2).buildIntersection(); - intersection.intersect(sketch, combiner); - } -} diff --git a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesQuickSelectSketchTest.java b/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesQuickSelectSketchTest.java deleted file mode 100644 index a54c12d20..000000000 --- a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesQuickSelectSketchTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesQuickSelectSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class ArrayOfDoublesQuickSelectSketchTest { - - @Test(expectedExceptions = SketchesArgumentException.class) - public void invalidSamplingProbability() { - new ArrayOfDoublesUpdatableSketchBuilder().setSamplingProbability(2f); - } - - @Test - public void heapToDirectExactTwoDoubles() { - double[] valuesArr = {1.0, 2.0}; - ArrayOfDoublesUpdatableSketch sketch1 = - new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(); - sketch1.update("a", valuesArr); - sketch1.update("b", valuesArr); - sketch1.update("c", valuesArr); - sketch1.update("d", valuesArr); - sketch1.update("a", valuesArr); - noopUpdates(sketch1, valuesArr); - ArrayOfDoublesUpdatableSketch sketch2 = ArrayOfDoublesUpdatableSketch.wrap(MemorySegment.ofArray(sketch1.toByteArray())); - sketch2.update("b", valuesArr); - sketch2.update("c", valuesArr); - sketch2.update("d", valuesArr); - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertFalse(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), 4.0); - Assert.assertEquals(sketch2.getUpperBound(1), 4.0); - Assert.assertEquals(sketch2.getLowerBound(1), 4.0); - Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch2.getTheta(), 1.0); - double[][] values = sketch2.getValues(); - Assert.assertEquals(values.length, 4); - for (double[] array: values) { - Assert.assertEquals(array.length, 2); - Assert.assertEquals(array[0], 2.0); - Assert.assertEquals(array[1], 4.0); - } - } - - @Test - public void heapToDirectWithSeed() { - long seed = 1; - double[] values = {1.0}; - - ArrayOfDoublesUpdatableSketch sketch1 = - new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build(); - sketch1.update("a", values); - sketch1.update("b", values); - sketch1.update("c", values); - - ArrayOfDoublesUpdatableSketch sketch2 = ArrayOfDoublesUpdatableSketch.wrap(MemorySegment.ofArray(sketch1.toByteArray()), seed); - sketch2.update("b", values); - sketch2.update("c", values); - sketch2.update("d", values); - - Assert.assertEquals(sketch2.getEstimate(), 4.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInsertExceptions() { - ArrayOfDoublesUpdatableSketch sketch1 = - new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(); - sketch1.update("a", new double[] {1.0}); - } - - @Test - public void directToHeapExactTwoDoubles() { - double[] valuesArr = {1.0, 2.0}; - ArrayOfDoublesUpdatableSketch sketch1 = - new ArrayOfDoublesUpdatableSketchBuilder(). - setNumberOfValues(2).build(MemorySegment.ofArray(new byte[1000000])); - sketch1.update("a", valuesArr); - sketch1.update("b", valuesArr); - sketch1.update("c", valuesArr); - sketch1.update("d", valuesArr); - sketch1.update("a", valuesArr); - noopUpdates(sketch1, valuesArr); - ArrayOfDoublesUpdatableSketch sketch2 = ArrayOfDoublesUpdatableSketch.heapify(MemorySegment.ofArray(sketch1.toByteArray())); - sketch2.update("b", valuesArr); - sketch2.update("c", valuesArr); - sketch2.update("d", valuesArr); - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertFalse(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), 4.0); - Assert.assertEquals(sketch2.getUpperBound(1), 4.0); - Assert.assertEquals(sketch2.getLowerBound(1), 4.0); - Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch2.getTheta(), 1.0); - double[][] values = sketch2.getValues(); - Assert.assertEquals(values.length, 4); - for (double[] array: values) { - Assert.assertEquals(array.length, 2); - Assert.assertEquals(array[0], 2.0); - Assert.assertEquals(array[1], 4.0); - } - } - - @Test - public void directToHeapWithSeed() { - long seed = 1; - double[] values = {1.0}; - - ArrayOfDoublesUpdatableSketch sketch1 = - new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build( - MemorySegment.ofArray(new byte[1000000])); - sketch1.update("a", values); - sketch1.update("b", values); - sketch1.update("c", values); - - ArrayOfDoublesUpdatableSketch sketch2 = ArrayOfDoublesUpdatableSketch.heapify(MemorySegment.ofArray(sketch1.toByteArray()), seed); - sketch2.update("b", values); - sketch2.update("c", values); - sketch2.update("d", values); - - Assert.assertEquals(sketch2.getEstimate(), 4.0); - } - - @Test - public void maxBytes() { - Assert.assertEquals(ArrayOfDoublesQuickSelectSketch.getMaxBytes(1024, 2), 49184); - } - - private static void noopUpdates(ArrayOfDoublesUpdatableSketch sketch, double[] valuesArr) { - byte[] byteArr = null; - sketch.update(byteArr, valuesArr); - byteArr = new byte[0]; - sketch.update(byteArr, valuesArr); - int[] intArr = null; - sketch.update(intArr, valuesArr); - intArr = new int[0]; - sketch.update(intArr, valuesArr); - long[] longArr = null; - sketch.update(longArr, valuesArr); - longArr = new long[0]; - sketch.update(longArr, valuesArr); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUnionTest.java b/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUnionTest.java deleted file mode 100644 index 3ba169673..000000000 --- a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUnionTest.java +++ /dev/null @@ -1,520 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.lang.foreign.MemorySegment; -import java.util.Arrays; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCompactSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class ArrayOfDoublesUnionTest { - - @Test - public void heapExactMode() { - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch1.update(1, new double[] {1.0}); - sketch1.update(1, new double[] {1.0}); - sketch1.update(1, new double[] {1.0}); - sketch1.update(2, new double[] {1.0}); - - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch2.update(2, new double[] {1.0}); - sketch2.update(2, new double[] {1.0}); - sketch2.update(3, new double[] {1.0}); - sketch2.update(3, new double[] {1.0}); - sketch2.update(3, new double[] {1.0}); - - final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().buildUnion(); - union.union(sketch1); - union.union(sketch2); - final int maxBytes = ArrayOfDoublesUnion.getMaxBytes( - ArrayOfDoublesSetOperationBuilder.DEFAULT_NOMINAL_ENTRIES, - ArrayOfDoublesSetOperationBuilder.DEFAULT_NUMBER_OF_VALUES); - Assert.assertEquals(maxBytes, 131120); // 48 bytes preamble + 2 * nominal entries * (key size + value size) - ArrayOfDoublesCompactSketch result = union.getResult(); - Assert.assertEquals(result.getEstimate(), 3.0); - double[][] values = result.getValues(); - Assert.assertEquals(values[0][0], 3.0); - Assert.assertEquals(values[1][0], 3.0); - Assert.assertEquals(values[2][0], 3.0); - - final MemorySegment wseg = MemorySegment.ofArray(union.toByteArray()); - final ArrayOfDoublesUnion wrappedUnion = ArrayOfDoublesSketch.wrapUnion(wseg); - result = wrappedUnion.getResult(); - Assert.assertEquals(result.getEstimate(), 3.0); - values = result.getValues(); - Assert.assertEquals(values[0][0], 3.0); - Assert.assertEquals(values[1][0], 3.0); - Assert.assertEquals(values[2][0], 3.0); - - - union.reset(); - result = union.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertFalse(result.isEstimationMode()); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getTheta(), 1.0); - } - - @Test - public void heapEstimationMode() { - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, new double[] {1.0}); - } - - key -= 4096; // overlap half of the entries - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().buildUnion(); - union.union(sketch1); - union.union(sketch2); - ArrayOfDoublesCompactSketch result = union.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertTrue(result.isEstimationMode()); - Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01); - - union.reset(); - result = union.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertFalse(result.isEstimationMode()); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getTheta(), 1.0); - } - - @Test - public void heapEstimationModeFullOverlapTwoValuesAndDownsizing() { - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, new double[] {1.0, 2.0}); - } - - key = 0; // full overlap - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, new double[] {1.0, 2.0}); - } - - final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().setNumberOfValues(2).setNominalEntries(1024).buildUnion(); - union.union(sketch1); - union.union(sketch2); - final ArrayOfDoublesCompactSketch result = union.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertTrue(result.isEstimationMode()); - Assert.assertEquals(result.getEstimate(), 8192.0, 8192 * 0.01); - Assert.assertEquals(result.getRetainedEntries(), 1024); // union was downsampled - - final ArrayOfDoublesSketchIterator it = result.iterator(); - final double[] expected = {2, 4}; - while (it.next()) { - Assert.assertEquals(it.getValues(), expected, Arrays.toString(it.getValues()) + " != " + Arrays.toString(expected)); - } - } - - @Test - public void heapMixedMode() { - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 1000; i++) { - sketch1.update(key++, new double[] {1.0}); - } - - key -= 500; // overlap half of the entries - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().setSamplingProbability(0.2f).build(); - for (int i = 0; i < 20000; i++) { - sketch2.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().buildUnion(); - union.union(sketch1); - union.union(sketch2); - final ArrayOfDoublesCompactSketch result = union.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertTrue(result.isEstimationMode()); - Assert.assertEquals(result.getEstimate(), 20500.0, 20500 * 0.01); - } - - @Test - public void heapSerializeDeserialize() { - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, new double[] {1.0}); - } - - key -= 4096; // overlap half of the entries - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesUnion union1 = new ArrayOfDoublesSetOperationBuilder().buildUnion(); - union1.union(sketch1); - union1.union(sketch2); - - final ArrayOfDoublesUnion union2 = ArrayOfDoublesUnion.heapify(MemorySegment.ofArray(union1.toByteArray())); - ArrayOfDoublesCompactSketch result = union2.getResult(); - Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01); - - union2.reset(); - result = union2.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertFalse(result.isEstimationMode()); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getTheta(), 1.0); - final double[][] values = result.getValues(); - for (int i = 0; i < values.length; i++) { - Assert.assertEquals(values[i][0], 2.0); - } - } - - @Test - public void heapSerializeDeserializeWithSeed() { - final long seed = 1; - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build(); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, new double[] {1.0}); - } - - key -= 4096; // overlap half of the entries - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed).build(); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesUnion union1 = new ArrayOfDoublesSetOperationBuilder().setSeed(seed).buildUnion(); - union1.union(sketch1); - union1.union(sketch2); - - final ArrayOfDoublesUnion union2 = ArrayOfDoublesUnion.heapify(MemorySegment.ofArray(union1.toByteArray()), seed); - final ArrayOfDoublesCompactSketch result = union2.getResult(); - Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01); - } - - @Test - public void directSerializeDeserialize() { - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build( - MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, new double[] {1.0}); - } - - key -= 4096; // overlap half of the entries - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build( - MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesUnion union1 = new ArrayOfDoublesSetOperationBuilder().buildUnion( - MemorySegment.ofArray(new byte[1000000])); - union1.union(sketch1); - union1.union(sketch2); - - final ArrayOfDoublesUnion union2 = ArrayOfDoublesUnion.wrap(MemorySegment.ofArray(union1.toByteArray())); - ArrayOfDoublesCompactSketch result = union2.getResult(MemorySegment.ofArray(new byte[1000000])); - Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01); - - union2.reset(); - result = union2.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertFalse(result.isEstimationMode()); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getTheta(), 1.0); - final double[][] values = result.getValues(); - for (int i = 0; i < values.length; i++) { - Assert.assertEquals(values[i][0], 2.0); - } - } - - @Test - public void directSerializeDeserializeWithSeed() { - final long seed = 1; - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed) - .build(MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, new double[] {1.0}); - } - - key -= 4096; // overlap half of the entries - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(seed) - .build(MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesUnion union1 = new ArrayOfDoublesSetOperationBuilder().setSeed(seed) - .buildUnion(MemorySegment.ofArray(new byte[1000000])); - union1.union(sketch1); - union1.union(sketch2); - - final ArrayOfDoublesUnion union2 = ArrayOfDoublesUnion.wrap(MemorySegment.ofArray(union1.toByteArray()), seed); - final ArrayOfDoublesCompactSketch result = union2.getResult(MemorySegment.ofArray(new byte[1000000])); - Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01); - } - - @Test - public void directExactMode() { - final ArrayOfDoublesUpdatableSketch sketch1 = - new ArrayOfDoublesUpdatableSketchBuilder().build(MemorySegment.ofArray(new byte[1000000])); - sketch1.update(1, new double[] {1.0}); - sketch1.update(1, new double[] {1.0}); - sketch1.update(1, new double[] {1.0}); - sketch1.update(2, new double[] {1.0}); - - final ArrayOfDoublesUpdatableSketch sketch2 = - new ArrayOfDoublesUpdatableSketchBuilder().build(MemorySegment.ofArray(new byte[1000000])); - sketch2.update(2, new double[] {1.0}); - sketch2.update(2, new double[] {1.0}); - sketch2.update(3, new double[] {1.0}); - sketch2.update(3, new double[] {1.0}); - sketch2.update(3, new double[] {1.0}); - - final ArrayOfDoublesUnion union = - new ArrayOfDoublesSetOperationBuilder().buildUnion(MemorySegment.ofArray(new byte[1000000])); - union.union(sketch1); - union.union(sketch2); - ArrayOfDoublesCompactSketch result = union.getResult(MemorySegment.ofArray(new byte[1000000])); - Assert.assertEquals(result.getEstimate(), 3.0); - final double[][] values = result.getValues(); - Assert.assertEquals(values[0][0], 3.0); - Assert.assertEquals(values[1][0], 3.0); - Assert.assertEquals(values[2][0], 3.0); - - union.reset(); - result = union.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertFalse(result.isEstimationMode()); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getTheta(), 1.0); - } - - @Test - public void directEstimationMode() { - int key = 0; - final ArrayOfDoublesUpdatableSketch sketch1 = - new ArrayOfDoublesUpdatableSketchBuilder().build(MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < 8192; i++) { - sketch1.update(key++, new double[] {1.0}); - } - - key -= 4096; // overlap half of the entries - final ArrayOfDoublesUpdatableSketch sketch2 = - new ArrayOfDoublesUpdatableSketchBuilder().build(MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < 8192; i++) { - sketch2.update(key++, new double[] {1.0}); - } - - final ArrayOfDoublesUnion union = - new ArrayOfDoublesSetOperationBuilder().buildUnion(MemorySegment.ofArray(new byte[1000000])); - union.union(sketch1); - union.union(sketch2); - ArrayOfDoublesCompactSketch result = union.getResult(MemorySegment.ofArray(new byte[1000000])); - Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01); - - union.reset(); - result = union.getResult(); - Assert.assertTrue(result.isEmpty()); - Assert.assertFalse(result.isEstimationMode()); - Assert.assertEquals(result.getEstimate(), 0.0); - Assert.assertEquals(result.getUpperBound(1), 0.0); - Assert.assertEquals(result.getLowerBound(1), 0.0); - Assert.assertEquals(result.getTheta(), 1.0); - } - - @Test - public void heapToDirect() { - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch1.update(1, new double[] {1.0}); - sketch1.update(1, new double[] {1.0}); - sketch1.update(1, new double[] {1.0}); - sketch1.update(2, new double[] {1.0}); - - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch2.update(2, new double[] {1.0}); - sketch2.update(2, new double[] {1.0}); - sketch2.update(3, new double[] {1.0}); - sketch2.update(3, new double[] {1.0}); - sketch2.update(3, new double[] {1.0}); - - final ArrayOfDoublesUnion heapUnion = new ArrayOfDoublesSetOperationBuilder().buildUnion(); - heapUnion.union(sketch1); - - final ArrayOfDoublesUnion directUnion = - ArrayOfDoublesUnion.wrap(MemorySegment.ofArray(heapUnion.toByteArray())); - directUnion.union(sketch2); //throws - - final ArrayOfDoublesCompactSketch result = directUnion.getResult(MemorySegment.ofArray(new byte[1000000])); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), 3.0); - final double[][] values = result.getValues(); - Assert.assertEquals(values.length, 3); - Assert.assertEquals(values[0][0], 3.0); - Assert.assertEquals(values[1][0], 3.0); - Assert.assertEquals(values[2][0], 3.0); - } - - @Test - public void directToHeap() { - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch1.update(1, new double[] {1.0}); - sketch1.update(1, new double[] {1.0}); - sketch1.update(1, new double[] {1.0}); - sketch1.update(2, new double[] {1.0}); - - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch2.update(2, new double[] {1.0}); - sketch2.update(2, new double[] {1.0}); - sketch2.update(3, new double[] {1.0}); - sketch2.update(3, new double[] {1.0}); - sketch2.update(3, new double[] {1.0}); - - final ArrayOfDoublesUnion directUnion = - new ArrayOfDoublesSetOperationBuilder().buildUnion(MemorySegment.ofArray(new byte[1000000])); - directUnion.union(sketch1); - - final ArrayOfDoublesUnion heapUnion = ArrayOfDoublesUnion.heapify(MemorySegment.ofArray(directUnion.toByteArray())); - heapUnion.union(sketch2); - - final ArrayOfDoublesCompactSketch result = heapUnion.getResult(); - Assert.assertFalse(result.isEmpty()); - Assert.assertEquals(result.getEstimate(), 3.0); - final double[][] values = result.getValues(); - Assert.assertEquals(values.length, 3); - Assert.assertEquals(values[0][0], 3.0); - Assert.assertEquals(values[1][0], 3.0); - Assert.assertEquals(values[2][0], 3.0); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void incompatibleSeeds() { - final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setSeed(1).build(); - final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().setSeed(2).buildUnion(); - union.union(sketch); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void incompatibleInputSketchFewerValues() { - final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); - final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().setNumberOfValues(2).buildUnion(); - union.union(sketch); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void incompatibleInputSketchMoreValues() { - final ArrayOfDoublesUpdatableSketch sketch = - new ArrayOfDoublesUpdatableSketchBuilder().setNumberOfValues(2).build(); - final ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().buildUnion(); - union.union(sketch); - } - - @Test - public void directDruidUsageOneSketch() { - final MemorySegment seg = MemorySegment.ofArray(new byte[1_000_000]); - new ArrayOfDoublesSetOperationBuilder().buildUnion(seg); // just set up MemorySegment to wrap later - - final int n = 100_000; // estimation mode - final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < n; i++) { - sketch.update(i, new double[] {1.0}); - } - sketch.trim(); // pretend this is a result from a union - - // as Druid wraps MemorySegment - MemorySegment seg2 = MemorySegment.ofArray(new byte[1_000_000]); - ArrayOfDoublesCompactSketch dcsk = sketch.compact(seg2); - ArrayOfDoublesUnion union = ArrayOfDoublesSketch.wrapUnion(seg); //empty union - union.union(dcsk); - //ArrayOfDoublesSketches.wrapUnion(seg).union(sketch.compact(MemorySegment.ofArray(new byte[1_000_000]))); - - final ArrayOfDoublesSketch result = ArrayOfDoublesUnion.wrap(seg).getResult(); - Assert.assertEquals(result.getEstimate(), sketch.getEstimate());//expected [98045.91060164096] but found [4096.0] - Assert.assertEquals(result.isEstimationMode(), sketch.isEstimationMode()); - } - - @Test - public void directDruidUsageTwoSketches() { - final MemorySegment seg = MemorySegment.ofArray(new byte[1000000]); - new ArrayOfDoublesSetOperationBuilder().buildUnion(seg); // just set up MemorySegment to wrap later - - int key = 0; - - final int n1 = 100000; // estimation mode - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < n1; i++) { - sketch1.update(key++, new double[] {1.0}); - } - // as Druid wraps MemorySegment - ArrayOfDoublesSketch.wrapUnion(seg).union(sketch1.compact(MemorySegment.ofArray(new byte[1000000]))); - - final int n2 = 1000000; // estimation mode - final ArrayOfDoublesUpdatableSketch sketch2 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < n2; i++) { - sketch2.update(key++, new double[] {1.0}); - } - // as Druid wraps MemorySegment - ArrayOfDoublesSketch.wrapUnion(seg).union(sketch2.compact(MemorySegment.ofArray(new byte[1000000]))); - - // build one sketch that must be the same as union - key = 0; // reset to have the same keys - final int n = n1 + n2; - final ArrayOfDoublesUpdatableSketch expected = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < n; i++) { - expected.update(key++, new double[] {1.0}); - } - expected.trim(); // union result is trimmed, so we need to trim this sketch for valid comparison - - final ArrayOfDoublesSketch result = ArrayOfDoublesUnion.wrap(seg).getResult(); - Assert.assertEquals(result.getEstimate(), expected.getEstimate()); - Assert.assertEquals(result.isEstimationMode(), expected.isEstimationMode()); - Assert.assertEquals(result.getUpperBound(1), expected.getUpperBound(1)); - Assert.assertEquals(result.getLowerBound(1), expected.getLowerBound(1)); - Assert.assertEquals(result.getRetainedEntries(), expected.getRetainedEntries()); - Assert.assertEquals(result.getNumValues(), expected.getNumValues()); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/CornerCaseArrayOfDoublesSetOperationsTest.java b/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/CornerCaseArrayOfDoublesSetOperationsTest.java deleted file mode 100644 index 02c56fd96..000000000 --- a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/CornerCaseArrayOfDoublesSetOperationsTest.java +++ /dev/null @@ -1,581 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import static org.apache.datasketches.common.Util.zeroPad; -import static org.apache.datasketches.hash.MurmurHash3.hash; -import static org.testng.Assert.assertTrue; - -import org.apache.datasketches.common.Util; -import org.testng.annotations.Test; - -public class CornerCaseArrayOfDoublesSetOperationsTest { - //Stateful TupleIntersection with intersect(sketch A, combiner), followed by getResult() - //Essentially Stateless TupleAnotB with update(TupleSketch A, TupleSketch B), followed by getResult() - //Stateful TupleUnion with union(TupleSketch A), followed by getResult() - - /* Hashes and Hash Equivalents - * Top8bits Hex Decimal - * MAX: 01111111, 7fffffffffffffff, 9223372036854775807 - * GT_MIDP: 01011101, 5d6906dac1b340ba, 6730918654704304314 3L - * MIDP_THETALONG:01000000, 4000000000000000, 4611686018427387904 - * GT_LOWP: 00010000, 10bc98fb132116fe, 1206007004353599230 6L - * LOWP_THETALONG:00010000, 1000000000000000, 1152921504606846976 - * LT_LOWP: 00001000, 83ddbc9e12ede40, 593872385995628096 4L - */ - - - private static final float MIDP_FLT = 0.5f; - private static final float LOWP_FLT = 0.125f; - private static final long GT_MIDP_KEY = 3L; - private static final long GT_LOWP_KEY = 6L; - private static final long LT_LOWP_KEY = 4L; - - private static final long MAX_LONG = Long.MAX_VALUE; - - private static final long HASH_GT_MIDP = getLongHash(GT_MIDP_KEY); - private static final long MIDP_THETALONG = (long)(MAX_LONG * MIDP_FLT); - - private static final long HASH_GT_LOWP = getLongHash(GT_LOWP_KEY); - private static final long LOWP_THETALONG = (long)(MAX_LONG * LOWP_FLT); - private static final long HASH_LT_LOWP = getLongHash(LT_LOWP_KEY); - - private static final String LS = System.getProperty("line.separator"); - - private enum SkType { - EMPTY, // { 1.0, 0, T} Bin: 101 Oct: 05 - EXACT, // { 1.0, >0, F} Bin: 110 Oct: 06, specify only value - ESTIMATION, // {<1.0, >0, F} Bin: 010 Oct: 02, specify only value - DEGENERATE // {<1.0, 0, F} Bin: 000 Oct: 0, specify p, value - } - - private static class MinCombiner implements ArrayOfDoublesCombiner { - MinCombiner() {} - - @Override - public double[] combine(double[] a, double[] b) { - return new double[] { Math.min(a[0], b[0]) }; - } - } - - private static MinCombiner minCombiner = new MinCombiner(); - - //=================================f - - @Test - public void emptyEmpty() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EMPTY, 0, 0); - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EMPTY, 0, 0); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = 1.0; - final int expectedUnionCount = 0; - final boolean expectedUnionEmpty = true; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void emptyExact() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EMPTY, 0, 0); - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EXACT, 0, GT_MIDP_KEY); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = 1.0; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void emptyDegenerate() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EMPTY, 0, 0); - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_KEY); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 0; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void emptyEstimation() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EMPTY, 0, 0); - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_KEY); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - //================================= - - @Test - public void exactEmpty() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EXACT, 0, GT_MIDP_KEY); - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EMPTY, 0, 0); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 1; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = 1.0; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void exactExact() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EXACT, 0, GT_MIDP_KEY); - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EXACT, 0, GT_MIDP_KEY); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 1; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = 1.0; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = true; - final double expectedUnionTheta = 1.0; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void exactDegenerate() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EXACT, 0, LT_LOWP_KEY); - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_KEY); //entries = 0 - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 1; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void exactEstimation() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.EXACT, 0, LT_LOWP_KEY); - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_KEY); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 1; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - //================================= - - @Test - public void estimationEmpty() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_KEY); - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EMPTY, 0, 0); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 1; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void estimationExact() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_KEY); - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EXACT, 0, LT_LOWP_KEY); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 1; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void estimationDegenerate() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.ESTIMATION, MIDP_FLT, LT_LOWP_KEY); - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_KEY); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 1; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void estimationEstimation() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.ESTIMATION, MIDP_FLT, LT_LOWP_KEY); - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_KEY); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 1; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - //================================= - - @Test - public void degenerateEmpty() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_KEY); //entries = 0 - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EMPTY, 0, 0); - final double expectedIntersectTheta = 1.0; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = true; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 0; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void degenerateExact() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_KEY); //entries = 0 - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.EXACT, 0, LT_LOWP_KEY); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void degenerateDegenerate() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.DEGENERATE, MIDP_FLT, GT_MIDP_KEY); //entries = 0 - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.DEGENERATE, LOWP_FLT, GT_LOWP_KEY); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 0; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - @Test - public void degenerateEstimation() { - ArrayOfDoublesUpdatableSketch thetaA = getSketch(SkType.DEGENERATE, MIDP_FLT, GT_MIDP_KEY); //entries = 0 - ArrayOfDoublesUpdatableSketch thetaB = getSketch(SkType.ESTIMATION, LOWP_FLT, LT_LOWP_KEY); - final double expectedIntersectTheta = LOWP_FLT; - final int expectedIntersectCount = 0; - final boolean expectedIntersectEmpty = false; - final double expectedAnotbTheta = LOWP_FLT; - final int expectedAnotbCount = 0; - final boolean expectedAnotbEmpty = false; - final double expectedUnionTheta = LOWP_FLT; - final int expectedUnionCount = 1; - final boolean expectedUnionEmpty = false; - - checks(thetaA, thetaB, - expectedIntersectTheta, expectedIntersectCount, expectedIntersectEmpty, - expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty, - expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - //================================= - //================================= - - private static void checks( - ArrayOfDoublesUpdatableSketch tupleA, - ArrayOfDoublesUpdatableSketch tupleB, - double expectedIntersectTheta, - int expectedIntersectCount, - boolean expectedIntersectEmpty, - double expectedAnotbTheta, - int expectedAnotbCount, - boolean expectedAnotbEmpty, - double expectedUnionTheta, - int expectedUnionCount, - boolean expectedUnionEmpty) { - ArrayOfDoublesCompactSketch csk; - ArrayOfDoublesIntersection inter = new ArrayOfDoublesSetOperationBuilder().buildIntersection(); - ArrayOfDoublesAnotB anotb = new ArrayOfDoublesSetOperationBuilder().buildAnotB(); - ArrayOfDoublesUnion union = new ArrayOfDoublesSetOperationBuilder().buildUnion(); - - //TupleIntersection Tuple, Tuple Updatable Stateful - inter.intersect(tupleA, minCombiner); - inter.intersect(tupleB, minCombiner); - csk = inter.getResult(); - inter.reset(); - checkResult("Intersect Stateless Theta, Theta", csk, expectedIntersectTheta, expectedIntersectCount, - expectedIntersectEmpty); - //TupleIntersection Tuple, Tuple Compact Stateful - inter.intersect(tupleA.compact(), minCombiner); - inter.intersect(tupleB.compact(), minCombiner); - csk = inter.getResult(); - inter.reset(); - checkResult("Intersect Stateless Theta, Theta", csk, expectedIntersectTheta, expectedIntersectCount, - expectedIntersectEmpty); - - //TupleAnotB Stateless Tuple, Tuple Updatable - anotb.update(tupleA, tupleB); - csk = anotb.getResult(); - checkResult("TupleAnotB Stateless Theta, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - //TupleAnotB Stateless Tuple, Tuple Compact - anotb.update(tupleA, tupleB); - csk = anotb.getResult(); - checkResult("TupleAnotB Stateless Theta, Theta", csk, expectedAnotbTheta, expectedAnotbCount, expectedAnotbEmpty); - - //TupleUnion Stateful Tuple, Tuple Updatable - union.union(tupleA); - union.union(tupleB); - csk = union.getResult(); - union.reset(); - checkResult("TupleUnion Stateless Theta, Theta", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - //TupleUnion Stateful Tuple, Tuple Compact - union.union(tupleA.compact()); - union.union(tupleB.compact()); - csk = union.getResult(); - union.reset(); - checkResult("TupleUnion Stateless Theta, Theta", csk, expectedUnionTheta, expectedUnionCount, expectedUnionEmpty); - } - - private static void checkResult( - String comment, - ArrayOfDoublesCompactSketch csk, - double expectedTheta, - int expectedEntries, - boolean expectedEmpty) { - double actualTheta = csk.getTheta(); - int actualEntries = csk.getRetainedEntries(); - boolean actualEmpty = csk.isEmpty(); - - boolean thetaOk = actualTheta == expectedTheta; - boolean entriesOk = actualEntries == expectedEntries; - boolean emptyOk = actualEmpty == expectedEmpty; - if (!thetaOk || !entriesOk || !emptyOk) { - StringBuilder sb = new StringBuilder(); - sb.append(comment + ": "); - if (!thetaOk) { sb.append("Theta: expected " + expectedTheta + ", got " + actualTheta + "; "); } - if (!entriesOk) { sb.append("Entries: expected " + expectedEntries + ", got " + actualEntries + "; "); } - if (!emptyOk) { sb.append("Empty: expected " + expectedEmpty + ", got " + actualEmpty + "."); } - throw new IllegalArgumentException(sb.toString()); - } - } - - private static ArrayOfDoublesUpdatableSketch getSketch( - SkType skType, - float p, - long updateKey) { - - ArrayOfDoublesUpdatableSketchBuilder bldr = new ArrayOfDoublesUpdatableSketchBuilder(); - bldr.setNominalEntries(16); - //Assume defaults: 1 double value, resize factor, seed - double[] summaryVal = {1.0}; - - ArrayOfDoublesUpdatableSketch sk; - switch(skType) { - case EMPTY: { // { 1.0, 0, T} p and value are not used - sk = bldr.build(); - break; - } - case EXACT: { // { 1.0, >0, F} p is not used - sk = bldr.build(); - sk.update(updateKey, summaryVal); - break; - } - case ESTIMATION: { // {<1.0, >0, F} - checkValidUpdate(p, updateKey); - bldr.setSamplingProbability(p); - sk = bldr.build(); - sk.update(updateKey, summaryVal); - break; - } - case DEGENERATE: { // {<1.0, 0, F} - checkInvalidUpdate(p, updateKey); - bldr.setSamplingProbability(p); - sk = bldr.build(); - sk.update(updateKey, summaryVal); // > theta - break; - } - - default: { return null; } // should not happen - } - return sk; - } - - private static void checkValidUpdate(float p, long updateKey) { - assertTrue( getLongHash(updateKey) < (long) (p * Long.MAX_VALUE)); - } - - private static void checkInvalidUpdate(float p, long updateKey) { - assertTrue( getLongHash(updateKey) > (long) (p * Long.MAX_VALUE)); - } - - //******************************************* - //Helper functions for setting the hash values - - //@Test - public void printTable() { - println(" Top8bits Hex Decimal"); - printf("MAX: %8s, %16x, %19d" + LS, getTop8(MAX_LONG), MAX_LONG, MAX_LONG); - printf("GT_MIDP: %8s, %16x, %19d" + LS, getTop8(HASH_GT_MIDP), HASH_GT_MIDP, HASH_GT_MIDP); - printf("MIDP_THETALONG:%8s, %16x, %19d" + LS, getTop8(MIDP_THETALONG), MIDP_THETALONG, MIDP_THETALONG); - printf("GT_LOWP: %8s, %16x, %19d" + LS, getTop8(HASH_GT_LOWP), HASH_GT_LOWP, HASH_GT_LOWP); - printf("LOWP_THETALONG:%8s, %16x, %19d" + LS, getTop8(LOWP_THETALONG), LOWP_THETALONG, LOWP_THETALONG); - printf("LT_LOWP: %8s, %16x, %19d" + LS, getTop8(HASH_LT_LOWP), HASH_LT_LOWP, HASH_LT_LOWP); - println(LS +"Doubles"); - - println(LS + "Longs"); - for (long v = 1L; v < 10; v++) { - long hash = (hash(v, Util.DEFAULT_UPDATE_SEED)[0]) >>> 1; - printLong(v, hash); - } - } - - static long getLongHash(long v) { - return (hash(v, Util.DEFAULT_UPDATE_SEED)[0]) >>> 1; - } - - static void printLong(long v, long hash) { - System.out.printf(" %8d, %8s, %16x, %19d" + LS,v, getTop8(hash), hash, hash); - } - - static String getTop8(final long v) { - int i = (int) (v >>> 56); - String s = Integer.toBinaryString(i); - return zeroPad(s, 8); - } - - private static void println(Object o) { - System.out.println(o.toString()); - } - - private static void printf(String fmt, Object ...args) { - System.out.printf(fmt, args); - } -} - diff --git a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesCompactSketchTest.java b/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesCompactSketchTest.java deleted file mode 100644 index 229e44e52..000000000 --- a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesCompactSketchTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.common.Util; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCompactSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class DirectArrayOfDoublesCompactSketchTest { - - @Test - public void emptyFromQuickSelectSketch() { - ArrayOfDoublesUpdatableSketch us = - new ArrayOfDoublesUpdatableSketchBuilder().build(MemorySegment.ofArray(new byte[1000000])); - ArrayOfDoublesCompactSketch sketch = us.compact(MemorySegment.ofArray(new byte[1000000])); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getRetainedEntries(), 0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - Assert.assertNotNull(sketch.getValues()); - Assert.assertEquals(sketch.getValues().length, 0); - ArrayOfDoublesSketchIterator it = sketch.iterator(); - while (it.next()) { - Assert.fail("empty sketch expected"); - } - } - - @Test - public void exactModeFromQuickSelectSketch() { - ArrayOfDoublesUpdatableSketch us = - new ArrayOfDoublesUpdatableSketchBuilder().build(MemorySegment.ofArray(new byte[1000000])); - us.update(1, new double[] {1.0}); - us.update(2, new double[] {1.0}); - us.update(3, new double[] {1.0}); - us.update(1, new double[] {1.0}); - us.update(2, new double[] {1.0}); - us.update(3, new double[] {1.0}); - ArrayOfDoublesCompactSketch sketch = us.compact(MemorySegment.ofArray(new byte[1000000])); - Assert.assertFalse(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 3.0); - Assert.assertEquals(sketch.getLowerBound(1), 3.0); - Assert.assertEquals(sketch.getUpperBound(1), 3.0); - Assert.assertEquals(sketch.getRetainedEntries(), 3); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - Assert.assertEquals(sketch.getSeedHash(), Util.computeSeedHash(Util.DEFAULT_UPDATE_SEED)); - double[][] values = sketch.getValues(); - Assert.assertEquals(values.length, 3); - for (double[] array: values) { - Assert.assertEquals(array[0], 2.0); - } - } - - @Test - public void serializeDeserializeSmallExact() { - ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(MemorySegment.ofArray(new byte[1000000])); - us.update("a", new double[] {1.0}); - us.update("b", new double[] {1.0}); - us.update("c", new double[] {1.0}); - ArrayOfDoublesCompactSketch sketch1 = us.compact(MemorySegment.ofArray(new byte[1000000])); - ArrayOfDoublesSketch sketch2 = ArrayOfDoublesSketch.wrapSketch(MemorySegment.ofArray(sketch1.toByteArray())); - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertFalse(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), 3.0); - Assert.assertEquals(sketch2.getLowerBound(1), 3.0); - Assert.assertEquals(sketch2.getUpperBound(1), 3.0); - Assert.assertEquals(sketch2.getRetainedEntries(), 3); - Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch2.getTheta(), 1.0); - double[][] values = sketch2.getValues(); - Assert.assertEquals(values.length, 3); - for (double[] array: values) { - Assert.assertEquals(array[0], 1.0); - } - } - - @Test - public void serializeDeserializeEstimation() { - ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < 8192; i++) { - us.update(i, new double[] {1.0}); - } - ArrayOfDoublesCompactSketch sketch1 = us.compact(MemorySegment.ofArray(new byte[1000000])); - ArrayOfDoublesSketch sketch2 = ArrayOfDoublesSketch.wrapSketch(MemorySegment.ofArray(sketch1.toByteArray())); - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertTrue(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), sketch1.getEstimate()); - Assert.assertEquals(sketch2.getThetaLong(), sketch1.getThetaLong()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeWithWrongSeed() { - ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < 8192; i++) { - us.update(i, new double[] {1.0}); - } - ArrayOfDoublesCompactSketch sketch1 = us.compact(MemorySegment.ofArray(new byte[1000000])); - ArrayOfDoublesSketch.wrapSketch(MemorySegment.ofArray(sketch1.toByteArray()), 123); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void fromQuickSelectSketchNotEnoughMemorySegment() { - ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(MemorySegment.ofArray(new byte[1000000])); - us.update(1, new double[] {1.0}); - us.compact(MemorySegment.ofArray(new byte[39])); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketchTest.java b/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketchTest.java deleted file mode 100644 index 781f3893b..000000000 --- a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketchTest.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.lang.foreign.MemorySegment; -import java.nio.ByteBuffer; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; -import org.apache.datasketches.tuple.arrayofdoubles.DirectArrayOfDoublesQuickSelectSketch; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class DirectArrayOfDoublesQuickSelectSketchTest { - @Test - public void isEmpty() { - final ArrayOfDoublesUpdatableSketch sketch = - new ArrayOfDoublesUpdatableSketchBuilder(). - build(MemorySegment.ofArray(new byte[1000000])); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - final ArrayOfDoublesSketchIterator it = sketch.iterator(); - while (it.next()) { - Assert.fail("empty sketch expected"); - } - } - - @Test - public void isEmptyWithSampling() { - final float samplingProbability = 0.1f; - final ArrayOfDoublesUpdatableSketch sketch = - new ArrayOfDoublesUpdatableSketchBuilder(). - setSamplingProbability(samplingProbability). - build(MemorySegment.ofArray(new byte[1000000])); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertTrue(((DirectArrayOfDoublesQuickSelectSketch)sketch).isInSamplingMode()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - } - - @Test - // very low probability of being sampled - // once the an input value is chosen so that it is rejected, the test will continue to work - // unless the hash function and the seed are the same - public void sampling() { - final float samplingProbability = 0.001f; - final ArrayOfDoublesUpdatableSketch sketch = - new ArrayOfDoublesUpdatableSketchBuilder(). - setSamplingProbability(samplingProbability). - build(MemorySegment.ofArray(new byte[1000000])); - sketch.update("a", new double[] {1.0}); - Assert.assertFalse(sketch.isEmpty()); - Assert.assertTrue(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertTrue(sketch.getUpperBound(1) > 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0, 0.0000001); - Assert.assertEquals( - (float)(sketch.getThetaLong() / (double) Long.MAX_VALUE), samplingProbability); - Assert.assertEquals((float)sketch.getTheta(), samplingProbability); - } - - @Test - public void exactMode() { - final ArrayOfDoublesUpdatableSketch sketch = - new ArrayOfDoublesUpdatableSketchBuilder(). - build(MemorySegment.ofArray(new byte[1000000])); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - for (int i = 0; i < 4096; i++) { - sketch.update(i, new double[] {1.0}); - } - Assert.assertFalse(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 4096.0); - Assert.assertEquals(sketch.getUpperBound(1), 4096.0); - Assert.assertEquals(sketch.getLowerBound(1), 4096.0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - - final double[][] values = sketch.getValues(); - Assert.assertEquals(values.length, 4096); - int count = 0; - for (int i = 0; i < values.length; i++) { - if (values[i] != null) { - count++; - } - } - Assert.assertEquals(count, 4096); - for (int i = 0; i < 4096; i++) { - Assert.assertEquals(values[i][0], 1.0); - } - - sketch.reset(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - final ArrayOfDoublesSketchIterator it = sketch.iterator(); - while (it.next()) { - Assert.fail("empty sketch expected"); - } - } - - @Test - // The moment of going into the estimation mode is, to some extent, an implementation detail - // Here we assume that presenting as many unique values as twice the nominal size of the sketch - // will result in estimation mode - public void estimationMode() { - final ArrayOfDoublesUpdatableSketch sketch = - new ArrayOfDoublesUpdatableSketchBuilder(). - build(MemorySegment.ofArray(new byte[4096 * 2 * 16 + 32])); - Assert.assertEquals(sketch.getEstimate(), 0.0); - for (int i = 1; i <= 8192; i++) { - sketch.update(i, new double[] {1.0}); - } - Assert.assertTrue(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 8192, 8192 * 0.01); - Assert.assertTrue(sketch.getEstimate() >= sketch.getLowerBound(1)); - Assert.assertTrue(sketch.getEstimate() < sketch.getUpperBound(1)); - - final double[][] values = sketch.getValues(); - Assert.assertTrue(values.length >= 4096); - int count = 0; - for (final double[] array: values) { - if (array != null) { - count++; - Assert.assertEquals(array.length, 1); - Assert.assertEquals(array[0], 1.0); - } - } - Assert.assertEquals(count, values.length); - - sketch.reset(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - Assert.assertEquals(sketch.getSamplingProbability(), 1.0F); - final ArrayOfDoublesSketchIterator it = sketch.iterator(); - while (it.next()) { - Assert.fail("empty sketch expected"); - } - } - - @Test - public void updatesOfAllKeyTypes() { - final ArrayOfDoublesUpdatableSketch sketch = - new ArrayOfDoublesUpdatableSketchBuilder(). - build(MemorySegment.ofArray(new byte[1000000])); - sketch.update(1L, new double[] {1.0}); - sketch.update(2.0, new double[] {1.0}); - final byte[] bytes = new byte[] {3, 4}; - sketch.update(bytes, new double[] {1.0}); - sketch.update(ByteBuffer.wrap(bytes), new double[] {1.0}); // same as previous - sketch.update(ByteBuffer.wrap(bytes, 0, 1), new double[] {1.0}); // slice - sketch.update(new int[] {4}, new double[] {1.0}); - sketch.update(new long[] {5L}, new double[] {1.0}); - sketch.update("a", new double[] {1.0}); - Assert.assertEquals(sketch.getEstimate(), 7.0); - } - - @Test - public void doubleSum() { - final ArrayOfDoublesUpdatableSketch sketch = - new ArrayOfDoublesUpdatableSketchBuilder(). - build(MemorySegment.ofArray(new byte[1000000])); - sketch.update(1, new double[] {1.0}); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - Assert.assertEquals(sketch.getValues()[0][0], 1.0); - sketch.update(1, new double[] {0.7}); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - Assert.assertEquals(sketch.getValues()[0][0], 1.7); - sketch.update(1, new double[] {0.8}); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - Assert.assertEquals(sketch.getValues()[0][0], 2.5); - } - - @Test - public void serializeDeserializeExact() throws Exception { - final ArrayOfDoublesUpdatableSketch sketch1 = - new ArrayOfDoublesUpdatableSketchBuilder(). - build(MemorySegment.ofArray(new byte[1000000])); - sketch1.update(1, new double[] {1.0}); - - final ArrayOfDoublesUpdatableSketch sketch2 = ArrayOfDoublesUpdatableSketch.wrap(MemorySegment.ofArray(sketch1.toByteArray())); - - Assert.assertEquals(sketch2.getEstimate(), 1.0); - final double[][] values = sketch2.getValues(); - Assert.assertEquals(values.length, 1); - Assert.assertEquals(values[0][0], 1.0); - - // the same key, so still one unique - sketch2.update(1, new double[] {1.0}); - Assert.assertEquals(sketch2.getEstimate(), 1.0); - - sketch2.update(2, new double[] {1.0}); - Assert.assertEquals(sketch2.getEstimate(), 2.0); - } - - @Test - public void serializeDeserializeEstimationNoResize() throws Exception { - final ArrayOfDoublesUpdatableSketch sketch1 = - new ArrayOfDoublesUpdatableSketchBuilder().setResizeFactor(ResizeFactor.X1). - build(MemorySegment.ofArray(new byte[1000000])); - for (int j = 0; j < 10; j++) { - for (int i = 0; i < 8192; i++) { - sketch1.update(i, new double[] {1.0}); - } - } - final byte[] byteArray = sketch1.toByteArray(); - - //for visual testing - //TestUtil.writeBytesToFile(byteArray, "ArrayOfDoublesQuickSelectSketch4K.data"); - - final ArrayOfDoublesSketch sketch2 = ArrayOfDoublesSketch.wrap(MemorySegment.ofArray(byteArray)); - Assert.assertTrue(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), 8192, 8192 * 0.99); - Assert.assertEquals(sketch1.getTheta(), sketch2.getTheta()); - final double[][] values = sketch2.getValues(); - Assert.assertTrue(values.length >= 4096); - for (final double[] array: values) { - Assert.assertEquals(array[0], 10.0); - } - } - - @Test - public void serializeDeserializeSampling() { - final int sketchSize = 16384; - final int numberOfUniques = sketchSize; - final ArrayOfDoublesUpdatableSketch sketch1 = - new ArrayOfDoublesUpdatableSketchBuilder(). - setNominalEntries(sketchSize).setSamplingProbability(0.5f). - build(MemorySegment.ofArray(new byte[1000000])); - for (int i = 0; i < numberOfUniques; i++) { - sketch1.update(i, new double[] {1.0}); - } - final ArrayOfDoublesSketch sketch2 = - ArrayOfDoublesSketch.wrap(MemorySegment.ofArray(sketch1.toByteArray())); - Assert.assertTrue(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate() / numberOfUniques, 1.0, 0.01); - Assert.assertEquals(sketch2.getRetainedEntries() / (double) numberOfUniques, 0.5, 0.01); - Assert.assertEquals(sketch1.getTheta(), sketch2.getTheta()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void memorySegmentNotLargeEnough() { - new ArrayOfDoublesUpdatableSketchBuilder(). - setNominalEntries(32).build(MemorySegment.ofArray(new byte[1055])); - } -} diff --git a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesCompactSketchTest.java b/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesCompactSketchTest.java deleted file mode 100644 index 69228c515..000000000 --- a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesCompactSketchTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCompactSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class HeapArrayOfDoublesCompactSketchTest { - - @Test - public void emptyFromQuickSelectSketch() { - ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(); - ArrayOfDoublesCompactSketch sketch = us.compact(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getRetainedEntries(), 0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - Assert.assertNotNull(sketch.getValues()); - Assert.assertEquals(sketch.getValues().length, 0); - ArrayOfDoublesSketchIterator it = sketch.iterator(); - while (it.next()) { - Assert.fail("empty sketch expected"); - } - } - - @Test - public void exactModeFromQuickSelectSketch() { - ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(); - us.update(1, new double[] {1.0}); - us.update(2, new double[] {1.0}); - us.update(3, new double[] {1.0}); - us.update(1, new double[] {1.0}); - us.update(2, new double[] {1.0}); - us.update(3, new double[] {1.0}); - ArrayOfDoublesCompactSketch sketch = us.compact(); - Assert.assertFalse(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 3.0); - Assert.assertEquals(sketch.getLowerBound(1), 3.0); - Assert.assertEquals(sketch.getUpperBound(1), 3.0); - Assert.assertEquals(sketch.getRetainedEntries(), 3); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - double[][] values = sketch.getValues(); - Assert.assertEquals(values.length, 3); - for (double[] array: values) { - Assert.assertEquals(array[0], 2.0); - } - } - - @Test - public void serializeDeserializeSmallExact() { - ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(); - us.update("a", new double[] {1.0}); - us.update("b", new double[] {1.0}); - us.update("c", new double[] {1.0}); - ArrayOfDoublesCompactSketch sketch1 = us.compact(); - ArrayOfDoublesSketch sketch2 = - ArrayOfDoublesSketch.heapifySketch(MemorySegment.ofArray(sketch1.toByteArray())); - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertFalse(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), 3.0); - Assert.assertEquals(sketch2.getLowerBound(1), 3.0); - Assert.assertEquals(sketch2.getUpperBound(1), 3.0); - Assert.assertEquals(sketch2.getRetainedEntries(), 3); - Assert.assertEquals(sketch2.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch2.getTheta(), 1.0); - double[][] values = sketch2.getValues(); - Assert.assertEquals(values.length, 3); - for (double[] array: values) { - Assert.assertEquals(array[0], 1.0); - } - } - - @Test - public void serializeDeserializeEstimation() { - ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 8192; i++) { - us.update(i, new double[] {1.0}); - } - MemorySegment wseg = MemorySegment.ofArray(us.toByteArray()); - ArrayOfDoublesUpdatableSketch wrappedUS = ArrayOfDoublesSketch.wrapUpdatableSketch(wseg); - Assert.assertFalse(wrappedUS.isEmpty()); - Assert.assertTrue(wrappedUS.isEstimationMode()); - Assert.assertEquals(wrappedUS.getEstimate(), us.getEstimate()); - Assert.assertEquals(wrappedUS.getThetaLong(), us.getThetaLong()); - - ArrayOfDoublesUpdatableSketch heapUS = ArrayOfDoublesSketch.heapifyUpdatableSketch(wseg); - Assert.assertFalse(heapUS.isEmpty()); - Assert.assertTrue(heapUS.isEstimationMode()); - Assert.assertEquals(heapUS.getEstimate(), us.getEstimate()); - Assert.assertEquals(heapUS.getThetaLong(), us.getThetaLong()); - - ArrayOfDoublesCompactSketch sketch1 = us.compact(); - ArrayOfDoublesSketch sketch2 = - ArrayOfDoublesSketch.heapifySketch(MemorySegment.ofArray(sketch1.toByteArray())); - Assert.assertFalse(sketch2.isEmpty()); - Assert.assertTrue(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), sketch1.getEstimate()); - Assert.assertEquals(sketch2.getThetaLong(), sketch1.getThetaLong()); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void deserializeWithWrongSeed() { - ArrayOfDoublesUpdatableSketch us = new ArrayOfDoublesUpdatableSketchBuilder().build(); - for (int i = 0; i < 8192; i++) { - us.update(i, new double[] {1.0}); - } - ArrayOfDoublesCompactSketch sketch1 = us.compact(); - MemorySegment seg = MemorySegment.ofArray(sketch1.toByteArray()); - ArrayOfDoublesSketch.heapifySketch(seg, 123); - } -} diff --git a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesQuickSelectSketchTest.java b/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesQuickSelectSketchTest.java deleted file mode 100644 index 9fe991b36..000000000 --- a/src/test/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesQuickSelectSketchTest.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.arrayofdoubles; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch; -import org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class HeapArrayOfDoublesQuickSelectSketchTest { - @Test - public void isEmpty() { - final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - final ArrayOfDoublesSketchIterator it = sketch.iterator(); - while (it.next()) { - Assert.fail("empty sketch expected"); - } - Assert.assertNotNull(sketch.toString()); - } - - @Test - public void isEmptyWithSampling() { - final float samplingProbability = 0.1f; - final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setSamplingProbability(samplingProbability).build(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - } - - @Test - public void sampling() { - final float samplingProbability = 0.001f; - final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().setSamplingProbability(samplingProbability).build(); - sketch.update("a", new double[] {1.0}); - Assert.assertFalse(sketch.isEmpty()); - Assert.assertTrue(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertTrue(sketch.getUpperBound(1) > 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0, 0.0000001); - Assert.assertEquals((float)(sketch.getThetaLong() / (double) Long.MAX_VALUE), samplingProbability); - Assert.assertEquals((float)sketch.getTheta(), samplingProbability); - } - - @Test - public void exactMode() { - final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - for (int i = 1; i <= 4096; i++) { - sketch.update(i, new double[] {1.0}); - } - Assert.assertFalse(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 4096.0); - Assert.assertEquals(sketch.getUpperBound(1), 4096.0); - Assert.assertEquals(sketch.getLowerBound(1), 4096.0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - - final double[][] values = sketch.getValues(); - Assert.assertEquals(values.length, 4096); - int count = 0; - for (int i = 0; i < values.length; i++) { - if (values[i] != null) { - count++; - } - } - Assert.assertEquals(count, 4096); - for (int i = 0; i < 4096; i++) { - Assert.assertEquals(values[i][0], 1.0); - } - - sketch.reset(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - final ArrayOfDoublesSketchIterator it = sketch.iterator(); - while (it.next()) { - Assert.fail("empty sketch expected"); - } - } - - @Test - // The moment of going into the estimation mode is, to some extent, an implementation detail - // Here we assume that presenting as many unique values as twice the nominal size of the sketch will result in estimation mode - public void estimationMode() { - final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); - Assert.assertEquals(sketch.getEstimate(), 0.0); - for (int i = 1; i <= 8192; i++) { - sketch.update(i, new double[] {1.0}); - } - Assert.assertTrue(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 8192, 8192 * 0.01); - Assert.assertTrue(sketch.getEstimate() >= sketch.getLowerBound(1)); - Assert.assertTrue(sketch.getEstimate() < sketch.getUpperBound(1)); - Assert.assertTrue(sketch.getRetainedEntries() > 4096); - sketch.trim(); - Assert.assertEquals(sketch.getRetainedEntries(), 4096); - - final double[][] values = sketch.getValues(); - int count = 0; - for (final double[] array: values) { - if (array != null) { - count++; - Assert.assertEquals(array.length, 1); - Assert.assertEquals(array[0], 1.0); - } - } - Assert.assertEquals(count, values.length); - - sketch.reset(); - Assert.assertTrue(sketch.isEmpty()); - Assert.assertFalse(sketch.isEstimationMode()); - Assert.assertEquals(sketch.getEstimate(), 0.0); - Assert.assertEquals(sketch.getUpperBound(1), 0.0); - Assert.assertEquals(sketch.getLowerBound(1), 0.0); - Assert.assertEquals(sketch.getThetaLong(), Long.MAX_VALUE); - Assert.assertEquals(sketch.getTheta(), 1.0); - final ArrayOfDoublesSketchIterator it = sketch.iterator(); - while (it.next()) { - Assert.fail("empty sketch expected"); - } - } - - @Test - public void updatesOfAllKeyTypes() { - final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch.update(1L, new double[] {1.0}); - sketch.update(2.0, new double[] {1.0}); - sketch.update(new byte[] {3}, new double[] {1.0}); - sketch.update(new int[] {4}, new double[] {1.0}); - sketch.update(new long[] {5L}, new double[] {1.0}); - sketch.update("a", new double[] {1.0}); - Assert.assertEquals(sketch.getEstimate(), 6.0); - } - - @Test - public void doubleSum() { - final ArrayOfDoublesUpdatableSketch sketch = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch.update(1, new double[] {1.0}); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - Assert.assertEquals(sketch.getValues()[0][0], 1.0); - sketch.update(1, new double[] {0.7}); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - Assert.assertEquals(sketch.getValues()[0][0], 1.7); - sketch.update(1, new double[] {0.8}); - Assert.assertEquals(sketch.getRetainedEntries(), 1); - Assert.assertEquals(sketch.getValues()[0][0], 2.5); - } - - @Test - public void serializeDeserializeExact() { - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().build(); - sketch1.update(1, new double[] {1.0}); - - final ArrayOfDoublesUpdatableSketch sketch2 = ArrayOfDoublesUpdatableSketch.heapify(MemorySegment.ofArray(sketch1.toByteArray())); - - Assert.assertEquals(sketch2.getEstimate(), 1.0); - final double[][] values = sketch2.getValues(); - Assert.assertEquals(values.length, 1); - Assert.assertEquals(values[0][0], 1.0); - - // the same key, so still one unique - sketch2.update(1, new double[] {1.0}); - Assert.assertEquals(sketch2.getEstimate(), 1.0); - - sketch2.update(2, new double[] {1.0}); - Assert.assertEquals(sketch2.getEstimate(), 2.0); - } - - @Test - public void serializeDeserializeEstimationNoResize() throws Exception { - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder(). - setResizeFactor(ResizeFactor.X1).build(); - for (int j = 0; j < 10; j++) { - for (int i = 0; i < 8192; i++) { - sketch1.update(i, new double[] {1.0}); - } - } - final byte[] byteArray = sketch1.toByteArray(); - - //for visual testing - //TestUtil.writeBytesToFile(byteArray, "ArrayOfDoublesQuickSelectSketch4K.data"); - - final ArrayOfDoublesSketch sketch2 = ArrayOfDoublesSketch.heapify(MemorySegment.ofArray(byteArray)); - Assert.assertTrue(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate(), 8192, 8192 * 0.99); - Assert.assertEquals(sketch1.getTheta(), sketch2.getTheta()); - final double[][] values = sketch2.getValues(); - Assert.assertTrue(values.length >= 4096); - for (final double[] array: values) { - Assert.assertEquals(array[0], 10.0); - } - } - - @Test - public void serializeDeserializeSampling() { - final int sketchSize = 16384; - final int numberOfUniques = sketchSize; - final ArrayOfDoublesUpdatableSketch sketch1 = new ArrayOfDoublesUpdatableSketchBuilder().setNominalEntries(sketchSize).setSamplingProbability(0.5f).build(); - for (int i = 0; i < numberOfUniques; i++) { - sketch1.update(i, new double[] {1.0}); - } - final ArrayOfDoublesSketch sketch2 = ArrayOfDoublesSketch.heapify(MemorySegment.ofArray(sketch1.toByteArray())); - Assert.assertTrue(sketch2.isEstimationMode()); - Assert.assertEquals(sketch2.getEstimate() / numberOfUniques, 1.0, 0.01); - Assert.assertEquals(sketch2.getRetainedEntries() / (double) numberOfUniques, 0.5, 0.01); - Assert.assertEquals(sketch1.getTheta(), sketch2.getTheta()); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/strings/AosSketchCrossLanguageTest.java b/src/test/java/org/apache/datasketches/tuple/strings/AosSketchCrossLanguageTest.java deleted file mode 100644 index 8a1bf4187..000000000 --- a/src/test/java/org/apache/datasketches/tuple/strings/AosSketchCrossLanguageTest.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.strings; - -import static org.apache.datasketches.common.TestUtil.CHECK_CPP_FILES; -import static org.apache.datasketches.common.TestUtil.GENERATE_JAVA_FILES; -import static org.apache.datasketches.common.TestUtil.cppPath; -import static org.apache.datasketches.common.TestUtil.putBytesToJavaPath; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.lang.foreign.MemorySegment; -import java.nio.file.Files; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.datasketches.common.ResizeFactor; -import org.apache.datasketches.tuple.TupleSketch; -import org.apache.datasketches.tuple.TupleSketchIterator; -import org.testng.annotations.Test; - -/** - * Serialize binary sketches to be tested by other language code. - * Test deserialization of binary sketches serialized by other language code. - */ -public class AosSketchCrossLanguageTest { - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingOneString() throws IOException { - int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (int n : nArr) { - ArrayOfStringsTupleSketch sk = new ArrayOfStringsTupleSketch(); - for (int i = 0; i < n; i++) { - sk.update(new String[] {String.valueOf(i)}, new String[] {"value" + i}); - } - putBytesToJavaPath("aos_1_n" + n + "_java.sk", sk.compact().toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingThreeStrings() throws IOException { - int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (int n : nArr) { - ArrayOfStringsTupleSketch sk = new ArrayOfStringsTupleSketch(); - for (int i = 0; i < n; i++) { - sk.update(new String[] {String.valueOf(i)}, new String[] {"a" + i, "b" + i, "c" + i}); - } - putBytesToJavaPath("aos_3_n" + n + "_java.sk", sk.compact().toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingNonEmptyNoEntries() throws IOException { - ArrayOfStringsTupleSketch sk = new ArrayOfStringsTupleSketch(12, - ResizeFactor.X8, 0.01f); - sk.update(new String[] {"key1"}, new String[] {"value1"}); - assertFalse(sk.isEmpty()); - assertEquals(sk.getRetainedEntries(), 0); - putBytesToJavaPath("aos_1_non_empty_no_entries_java.sk", sk.compact().toByteArray()); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingMultiKeyStrings() throws IOException { - int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (int n : nArr) { - ArrayOfStringsTupleSketch sk = new ArrayOfStringsTupleSketch(); - for (int i = 0; i < n; i++) { - sk.update(new String[] {"key" + i, "subkey" + (i % 10)}, new String[] {"value" + i}); - } - putBytesToJavaPath("aos_multikey_n" + n + "_java.sk", sk.compact().toByteArray()); - } - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingUnicodeStrings() throws IOException { - ArrayOfStringsTupleSketch sk = new ArrayOfStringsTupleSketch(); - - sk.update(new String[]{"키", "열쇠"}, new String[]{"밸류", "값"}); - sk.update(new String[]{"🔑", "🗝️"}, new String[]{"📦", "🎁"}); - sk.update(new String[]{"ключ1", "ключ2"}, new String[]{"ценить1", "ценить2"}); - - assertFalse(sk.isEmpty()); - assertEquals(sk.getRetainedEntries(), 3); - - putBytesToJavaPath("aos_unicode_java.sk", sk.compact().toByteArray()); - } - - @Test(groups = {GENERATE_JAVA_FILES}) - public void generateBinariesForCompatibilityTestingEmptyStrings() throws IOException { - ArrayOfStringsTupleSketch sk = new ArrayOfStringsTupleSketch(); - - sk.update(new String[]{""}, new String[]{"empty_key_value"}); - sk.update(new String[]{"empty_value_key"}, new String[]{""}); - sk.update(new String[]{"", ""}, new String[]{"", ""}); - - assertFalse(sk.isEmpty()); - assertEquals(sk.getRetainedEntries(), 3); - - putBytesToJavaPath("aos_empty_strings_java.sk", sk.compact().toByteArray()); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppOneString() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (int n : nArr) { - final byte[] bytes = Files.readAllBytes(cppPath.resolve("aos_1_n" + n + "_cpp.sk")); - final TupleSketch sketch = ArrayOfStringsTupleSketch.heapifySketch(MemorySegment.ofArray(bytes), new ArrayOfStringsSummaryDeserializer()); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertEquals(sketch.getEstimate(), n, n * 0.03); - assertTrue(n > 1000? sketch.isEstimationMode() : !sketch.isEstimationMode()); - - final TupleSketchIterator it = sketch.iterator(); - while (it.next()) { - assertTrue(it.getHash() < sketch.getThetaLong()); - final String[] summary = it.getSummary().getValue(); - assertEquals(summary.length, 1); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppThreeStrings() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (int n : nArr) { - final byte[] bytes = Files.readAllBytes(cppPath.resolve("aos_3_n" + n + "_cpp.sk")); - final TupleSketch sketch = ArrayOfStringsTupleSketch.heapifySketch(MemorySegment.ofArray(bytes), new ArrayOfStringsSummaryDeserializer()); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertEquals(sketch.getEstimate(), n, n * 0.03); - assertTrue(n > 1000? sketch.isEstimationMode() : !sketch.isEstimationMode()); - - final TupleSketchIterator it = sketch.iterator(); - while (it.next()) { - assertTrue(it.getHash() < sketch.getThetaLong()); - final String[] summary = it.getSummary().getValue(); - assertEquals(summary.length, 3); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppOneStringNonEmptyNoEntries() throws IOException { - final byte[] bytes = Files.readAllBytes(cppPath.resolve("aos_1_non_empty_no_entries_cpp.sk")); - final TupleSketch sketch = ArrayOfStringsTupleSketch.heapifySketch(MemorySegment.ofArray(bytes), new ArrayOfStringsSummaryDeserializer()); - - assertFalse(sketch.isEmpty()); - assertEquals(sketch.getRetainedEntries(), 0); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppMultiKeyStrings() throws IOException { - final int[] nArr = {0, 1, 10, 100, 1000, 10_000, 100_000, 1_000_000}; - for (int n : nArr) { - final byte[] bytes = Files.readAllBytes(cppPath.resolve("aos_multikey_n" + n + "_cpp.sk")); - final TupleSketch sketch = ArrayOfStringsTupleSketch.heapifySketch(MemorySegment.ofArray(bytes), new ArrayOfStringsSummaryDeserializer()); - assertTrue(n == 0 ? sketch.isEmpty() : !sketch.isEmpty()); - assertEquals(sketch.getEstimate(), n, n * 0.03); - assertTrue(n > 1000? sketch.isEstimationMode() : !sketch.isEstimationMode()); - - final TupleSketchIterator it = sketch.iterator(); - while (it.next()) { - assertTrue(it.getHash() < sketch.getThetaLong()); - final String[] summary = it.getSummary().getValue(); - assertEquals(summary.length, 1); - } - } - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppUnicodeStrings() throws IOException { - final byte[] bytes = Files.readAllBytes(cppPath.resolve("aos_unicode_cpp.sk")); - final TupleSketch sketch = ArrayOfStringsTupleSketch.heapifySketch(MemorySegment.ofArray(bytes), new ArrayOfStringsSummaryDeserializer()); - assertFalse(sketch.isEmpty()); - assertFalse(sketch.isEstimationMode()); - assertEquals(sketch.getEstimate(), 3.0); - - final Set> summaries = getSummaries(sketch); - assertTrue(summaries.contains(Arrays.asList("밸류", "값"))); - assertTrue(summaries.contains(Arrays.asList("📦", "🎁"))); - assertTrue(summaries.contains(Arrays.asList("ценить1", "ценить2"))); - } - - @Test(groups = {CHECK_CPP_FILES}) - public void deserializeFromCppEmptyStrings() throws IOException { - final byte[] bytes = Files.readAllBytes(cppPath.resolve("aos_empty_strings_cpp.sk")); - final TupleSketch sketch = ArrayOfStringsTupleSketch.heapifySketch(MemorySegment.ofArray(bytes), new ArrayOfStringsSummaryDeserializer()); - assertFalse(sketch.isEmpty()); - assertFalse(sketch.isEstimationMode()); - assertEquals(sketch.getEstimate(), 3.0); - - final Set> summaries = getSummaries(sketch); - assertTrue(summaries.contains(Arrays.asList("empty_key_value"))); - assertTrue(summaries.contains(Arrays.asList(""))); - assertTrue(summaries.contains(Arrays.asList("", ""))); - } - - private static Set> getSummaries(final TupleSketch sketch) { - final Set> summaries = new HashSet<>(); - final TupleSketchIterator it = sketch.iterator(); - while (it.next()) { - assertTrue(it.getHash() < sketch.getThetaLong()); - summaries.add(Arrays.asList(it.getSummary().getValue())); - } - return summaries; - } -} diff --git a/src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSketchTest.java b/src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSketchTest.java deleted file mode 100644 index b9aaf576e..000000000 --- a/src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSketchTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.strings; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.apache.datasketches.tuple.TupleAnotB; -import org.apache.datasketches.tuple.CompactTupleSketch; -import org.apache.datasketches.tuple.TupleIntersection; -import org.apache.datasketches.tuple.TupleSketchIterator; -import org.apache.datasketches.tuple.TupleUnion; -import org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch; -import org.apache.datasketches.tuple.strings.ArrayOfStringsSummary; -import org.apache.datasketches.tuple.strings.ArrayOfStringsSummarySetOperations; -import org.testng.annotations.Test; - -/** - * @author Lee Rhodes - */ -public class ArrayOfStringsSketchTest { - private static final String LS = System.getProperty("line.separator"); - - @SuppressWarnings("deprecation") - @Test - public void checkSketch() { - ArrayOfStringsTupleSketch sketch1 = new ArrayOfStringsTupleSketch(); - String[][] strArrArr = {{"a","b"},{"c","d"},{"e","f"}}; - int len = strArrArr.length; - for (int i = 0; i < len; i++) { - sketch1.update(i, strArrArr[i]); - } - println("Sketch1"); - printSummaries(sketch1.iterator()); - - sketch1.update(0, strArrArr[0]); //insert duplicate - println("Sketch1 updated with a duplicate"); - printSummaries(sketch1.iterator()); - - MemorySegment wseg = MemorySegment.ofArray(sketch1.toByteArray()); - ArrayOfStringsTupleSketch sketch2 = new ArrayOfStringsTupleSketch(wseg); - println("Sketch2 = Sketch1 via SerDe"); - printSummaries(sketch2.iterator()); - checkSummariesEqual(sketch1, sketch2); - - String[] strArr3 = {"g", "h" }; - sketch2.update(3, strArr3); - println("Sketch2 with a new row"); - printSummaries(sketch2.iterator()); - - TupleUnion union = new TupleUnion<>(new ArrayOfStringsSummarySetOperations()); - union.union(sketch1); - union.union(sketch2); - CompactTupleSketch csk = union.getResult(); - println("Result of union of Sketch1, Sketch2"); - printSummaries(csk.iterator()); - assertEquals(csk.getRetainedEntries(), 4); - - TupleIntersection inter = - new TupleIntersection<>(new ArrayOfStringsSummarySetOperations()); - inter.intersect(sketch1); - inter.intersect(sketch2); - csk = inter.getResult(); - println("Intersect Sketch1, Sketch2"); - printSummaries(csk.iterator()); - assertEquals(csk.getRetainedEntries(), 3); - - TupleAnotB aNotB = new TupleAnotB<>(); - aNotB.setA(sketch2); - aNotB.notB(sketch1); - csk = aNotB.getResult(true); - println("AnotB(Sketch2, Sketch1)"); - printSummaries(csk.iterator()); - assertEquals(csk.getRetainedEntries(), 1); - - } - - private static void checkSummariesEqual(ArrayOfStringsTupleSketch sk1, ArrayOfStringsTupleSketch sk2) { - TupleSketchIterator it1 = sk1.iterator(); - TupleSketchIterator it2 = sk2.iterator(); - while(it1.next() && it2.next()) { - ArrayOfStringsSummary sum1 = it1.getSummary(); - ArrayOfStringsSummary sum2 = it2.getSummary(); - assertTrue(sum1.equals(sum2)); - } - } - - static void printSummaries(TupleSketchIterator it) { - while (it.next()) { - String[] strArr = it.getSummary().getValue(); - for (String s : strArr) { - print(s + ", "); - } - println(""); - } - println(""); - } - - @Test - public void checkCopyCtor() { - ArrayOfStringsTupleSketch sk1 = new ArrayOfStringsTupleSketch(); - String[][] strArrArr = {{"a","b"},{"c","d"},{"e","f"}}; - int len = strArrArr.length; - for (int i = 0; i < len; i++) { - sk1.update(i, strArrArr[i]); - } - assertEquals(sk1.getRetainedEntries(), 3); - final ArrayOfStringsTupleSketch sk2 = sk1.copy(); - assertEquals(sk2.getRetainedEntries(), 3); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(String s) { - print(s + LS); - } - - /** - * @param s value to print - */ - static void print(String s) { - //System.out.print(s); //disable here - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryTest.java b/src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryTest.java deleted file mode 100644 index 1b1d94bed..000000000 --- a/src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.strings; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.lang.foreign.MemorySegment; - -import org.testng.annotations.Test; -import org.apache.datasketches.common.SketchesArgumentException; -import org.apache.datasketches.tuple.DeserializeResult; -import org.apache.datasketches.tuple.strings.ArrayOfStringsSummary; -import org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryDeserializer; - -/** - * @author Lee Rhodes - */ -public class ArrayOfStringsSummaryTest { - - @Test - public void checkToByteArray() { - String[] strArr = new String[] {"abcd", "abcd", "abcd"}; - ArrayOfStringsSummary nsum = new ArrayOfStringsSummary(strArr); - ArrayOfStringsSummary copy = nsum.copy(); - assertTrue(copy.equals(nsum)); - byte[] out = nsum.toByteArray(); - - MemorySegment seg = MemorySegment.ofArray(out); - ArrayOfStringsSummary nsum2 = new ArrayOfStringsSummary(seg); - String[] nodesArr = nsum2.getValue(); - for (String s : nodesArr) { - println(s); - } - - println("\nfromMemorySegment(seg)"); - DeserializeResult dres = ArrayOfStringsSummaryDeserializer.fromMemorySegment(seg); - ArrayOfStringsSummary nsum3 = dres.getObject(); - nodesArr = nsum3.getValue(); - for (String s : nodesArr) { - println(s); - } - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkNumNodes() { - ArrayOfStringsSummary.checkNumNodes(200); - } - - @Test(expectedExceptions = SketchesArgumentException.class) - public void checkInBytes() { - MemorySegment seg = MemorySegment.ofArray(new byte[100]); - ArrayOfStringsSummary.checkInBytes(seg, 200); - } - - @SuppressWarnings("unlikely-arg-type") - @Test - public void checkHashCode() { - String[] strArr = new String[] {"abcd", "abcd", "abcd"}; - ArrayOfStringsSummary sum1 = new ArrayOfStringsSummary(strArr); - ArrayOfStringsSummary sum2 = new ArrayOfStringsSummary(strArr); - int hc1 = sum1.hashCode(); - int hc2 = sum2.hashCode(); - assertEquals(hc1, hc2); - assertTrue(sum1.equals(sum2)); - assertFalse(sum1.equals(hc2)); - assertFalse(sum1.equals(null)); - } - - @Test - public void printlnTest() { - println("PRINTING: "+this.getClass().getName()); - } - - /** - * @param s value to print - */ - static void println(String s) { - //System.out.println(s); - } - -} diff --git a/src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummary_Issue699.java b/src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummary_Issue699.java deleted file mode 100644 index 7e68fc1de..000000000 --- a/src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummary_Issue699.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.datasketches.tuple.strings; - -import static org.apache.datasketches.common.Util.LS; - -import org.apache.datasketches.theta.UpdatableThetaSketch; -import org.apache.datasketches.tuple.TupleSketchIterator; -import org.apache.datasketches.tuple.TupleUnion; -import org.testng.annotations.Test; - -public class ArrayOfStringsSummary_Issue699 { - UpdatableThetaSketch thetaSk = UpdatableThetaSketch.builder().build(); - ArrayOfStringsTupleSketch tupleSk = new ArrayOfStringsTupleSketch(); - TupleUnion union = new TupleUnion<>(new ArrayOfStringsSummarySetOperations()); - - @Test - void go() { - thetaSk.update("a"); - thetaSk.update("b"); - thetaSk.update("c"); - - tupleSk.update("a", new String[] {"x", "y"}); - tupleSk.update("b", new String[] {"z"}); - tupleSk.update("e", new String[] {"x", "z"}); - - println("Print Tuple Summary before union"); - printSummaries(tupleSk.iterator()); - - union.union(tupleSk); - union.union(thetaSk, new ArrayOfStringsSummary()); //enable this or the next - //union.union(thetaSk, new ArrayOfStringsSummary(new String[] {"u", "v"})); //optional association - - println("Print Tuple Summary after union"); - printSummaries(union.getResult().iterator()); - } - - @Test - void checkCopy() { - ArrayOfStringsSummary aoss = new ArrayOfStringsSummary(); - aoss.copy(); //if null this will throw - } - - @Test - void checkToByteArray() { - ArrayOfStringsSummary aoss = new ArrayOfStringsSummary(); - byte[] bytes = aoss.toByteArray(); - println("byte[].length = " + bytes.length); - } - - - static void printSummaries(TupleSketchIterator it) { - while (it.next()) { - String[] strArr = it.getSummary().getValue(); - if (strArr.length == 0) { print("-"); } //illustrates an empty string array - for (String s : strArr) { - print(s + ", "); - } - println(""); - } - println(""); - } - - private static void println(Object o) { - print(o + LS); - } - - private static void print(Object o) { - //System.out.print(o.toString()); - } -} diff --git a/src/test/resources/ArrayOfDoublesUnion_v0.9.1.sk b/src/test/resources/ArrayOfDoublesUnion_v0.9.1.sk deleted file mode 100644 index b8e3d5812..000000000 Binary files a/src/test/resources/ArrayOfDoublesUnion_v0.9.1.sk and /dev/null differ diff --git a/src/test/resources/CompactSketchWithDoubleSummary4K_serialVersion1.sk b/src/test/resources/CompactSketchWithDoubleSummary4K_serialVersion1.sk deleted file mode 100644 index de5fa5e5f..000000000 Binary files a/src/test/resources/CompactSketchWithDoubleSummary4K_serialVersion1.sk and /dev/null differ diff --git a/src/test/resources/GettysburgAddress.txt b/src/test/resources/GettysburgAddress.txt deleted file mode 100644 index 3969d1766..000000000 --- a/src/test/resources/GettysburgAddress.txt +++ /dev/null @@ -1,7 +0,0 @@ -Abraham Lincoln's Gettysburg Address: - - Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. - - Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. - - But, in a larger sense, we can not dedicate —- we can not consecrate —- we can not hallow —- this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -— that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion -— that we here highly resolve that these dead shall not have died in vain -— that this nation, under God, shall have a new birth of freedom -— and that government of the people, by the people, for the people, shall not perish from the earth. diff --git a/src/test/resources/Qk128_n1000_v0.3.0.sk b/src/test/resources/Qk128_n1000_v0.3.0.sk deleted file mode 100644 index 72db1047b..000000000 Binary files a/src/test/resources/Qk128_n1000_v0.3.0.sk and /dev/null differ diff --git a/src/test/resources/Qk128_n1000_v0.6.0.sk b/src/test/resources/Qk128_n1000_v0.6.0.sk deleted file mode 100644 index dd6e72d06..000000000 Binary files a/src/test/resources/Qk128_n1000_v0.6.0.sk and /dev/null differ diff --git a/src/test/resources/Qk128_n1000_v0.8.0.sk b/src/test/resources/Qk128_n1000_v0.8.0.sk deleted file mode 100644 index f9166bbcf..000000000 Binary files a/src/test/resources/Qk128_n1000_v0.8.0.sk and /dev/null differ diff --git a/src/test/resources/Qk128_n1000_v0.8.3.sk b/src/test/resources/Qk128_n1000_v0.8.3.sk deleted file mode 100644 index 6cadb2d5b..000000000 Binary files a/src/test/resources/Qk128_n1000_v0.8.3.sk and /dev/null differ diff --git a/src/test/resources/Qk128_n50_v0.3.0.sk b/src/test/resources/Qk128_n50_v0.3.0.sk deleted file mode 100644 index 4667596fa..000000000 Binary files a/src/test/resources/Qk128_n50_v0.3.0.sk and /dev/null differ diff --git a/src/test/resources/Qk128_n50_v0.6.0.sk b/src/test/resources/Qk128_n50_v0.6.0.sk deleted file mode 100644 index a2334e40d..000000000 Binary files a/src/test/resources/Qk128_n50_v0.6.0.sk and /dev/null differ diff --git a/src/test/resources/Qk128_n50_v0.8.0.sk b/src/test/resources/Qk128_n50_v0.8.0.sk deleted file mode 100644 index 83cc21dd1..000000000 Binary files a/src/test/resources/Qk128_n50_v0.8.0.sk and /dev/null differ diff --git a/src/test/resources/Qk128_n50_v0.8.3.sk b/src/test/resources/Qk128_n50_v0.8.3.sk deleted file mode 100644 index 597cd60d7..000000000 Binary files a/src/test/resources/Qk128_n50_v0.8.3.sk and /dev/null differ diff --git a/src/test/resources/TupleWithTestIntegerSummary4kTrimmedSerVer2.sk b/src/test/resources/TupleWithTestIntegerSummary4kTrimmedSerVer2.sk deleted file mode 100644 index 41374f74b..000000000 Binary files a/src/test/resources/TupleWithTestIntegerSummary4kTrimmedSerVer2.sk and /dev/null differ diff --git a/src/test/resources/kll_double_n1.sk b/src/test/resources/kll_double_n1.sk deleted file mode 100644 index fd2fc1b9d..000000000 Binary files a/src/test/resources/kll_double_n1.sk and /dev/null differ diff --git a/src/test/resources/kll_sketch_double_one_item_v1.sk b/src/test/resources/kll_sketch_double_one_item_v1.sk deleted file mode 100644 index 358b60384..000000000 Binary files a/src/test/resources/kll_sketch_double_one_item_v1.sk and /dev/null differ diff --git a/src/test/resources/kll_sketch_float_one_item_v1.sk b/src/test/resources/kll_sketch_float_one_item_v1.sk deleted file mode 100644 index 450770253..000000000 Binary files a/src/test/resources/kll_sketch_float_one_item_v1.sk and /dev/null differ diff --git a/src/test/resources/tdigest_ref_k100_n10000_double.sk b/src/test/resources/tdigest_ref_k100_n10000_double.sk deleted file mode 100644 index f6f4510ed..000000000 Binary files a/src/test/resources/tdigest_ref_k100_n10000_double.sk and /dev/null differ diff --git a/src/test/resources/tdigest_ref_k100_n10000_float.sk b/src/test/resources/tdigest_ref_k100_n10000_float.sk deleted file mode 100644 index 16d798111..000000000 Binary files a/src/test/resources/tdigest_ref_k100_n10000_float.sk and /dev/null differ diff --git a/src/test/resources/testng.xml b/src/test/resources/testng.xml deleted file mode 100644 index a0e30835e..000000000 --- a/src/test/resources/testng.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - diff --git a/target/javadoc-bundle-options/javadoc-options-javadoc-resources.xml b/target/javadoc-bundle-options/javadoc-options-javadoc-resources.xml new file mode 100644 index 000000000..ec75cc594 --- /dev/null +++ b/target/javadoc-bundle-options/javadoc-options-javadoc-resources.xml @@ -0,0 +1,11 @@ + + + + + + + + + true + src/main/javadoc + diff --git a/target/maven-javadoc-plugin-stale-data.txt b/target/maven-javadoc-plugin-stale-data.txt new file mode 100644 index 000000000..4d31d6635 --- /dev/null +++ b/target/maven-javadoc-plugin-stale-data.txt @@ -0,0 +1,81 @@ +-J-Duser.language= +-J-Duser.country= +-J-Xmx4g +-J-Duser.language=en +-J-Duser.country=US +-J-Dfile.encoding=UTF-8 +@options +@packages +-encoding +'UTF-8' +-overview +'/Users/lrhodes/dev/git/Apache/datasketches-java25/src/main/javadoc/overview.html' +-public +--release +25 +-sourcepath +'/Users/lrhodes/dev/git/Apache/datasketches-java25/src/main/java:/Users/lrhodes/dev/git/Apache/datasketches-java25/src/main/javadoc' +-author +-bottom +'Copyright © 2015–2026. All rights reserved.' +-charset +'UTF-8' +-d +'/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs' +-docencoding +'UTF-8' +-docfilessubdirs +-Xdoclint:all,-missing +-doctitle +'datasketches-java 9.0.1-SNAPSHOT API' +-use +-version +-windowtitle +'datasketches-java 9.0.1-SNAPSHOT API' +org.apache.datasketches.filters.bloomfilter +org.apache.datasketches.filters +org.apache.datasketches.tdigest +org.apache.datasketches.hll +org.apache.datasketches.hash +org.apache.datasketches.tuple.adouble +org.apache.datasketches.tuple +org.apache.datasketches.tuple.strings +org.apache.datasketches.tuple.aninteger +org.apache.datasketches.tuple.arrayofdoubles +org.apache.datasketches.hllmap +org.apache.datasketches.frequencies +org.apache.datasketches.count +org.apache.datasketches.fdt +org.apache.datasketches.kll +org.apache.datasketches.sampling +org.apache.datasketches.partitions +org.apache.datasketches.req +org.apache.datasketches.common +org.apache.datasketches.common.positional +org.apache.datasketches.thetacommon +org.apache.datasketches.quantilescommon +org.apache.datasketches.cpc +org.apache.datasketches.theta +org.apache.datasketches +org.apache.datasketches.quantiles +/Users/lrhodes/dev/git/Apache/datasketches-java25/src/main/java/.DS_Store = 1757454157708 +/Users/lrhodes/dev/git/Apache/datasketches-java25/src/main/java = 1747084663648 +/Users/lrhodes/dev/git/Apache/datasketches-java25/src/main/javadoc/overview.html = 1770495384208 +/Users/lrhodes/dev/git/Apache/datasketches-java25/src/main/javadoc = 1770495384208 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/constant-values.html = 1772501221865 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/tag-search-index.js = 1772501222007 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/overview-tree.html = 1772501221969 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/module-search-index.js = 1772501222005 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/index.html = 1772501221972 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/package-search-index.js = 1772501222005 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/serialized-form.html = 1772501221872 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/index-all.html = 1772501222034 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/allpackages-index.html = 1772501222005 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/deprecated-list.html = 1772501221969 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/member-search-index.js = 1772501222007 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/overview-summary.html = 1772501222035 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/help-doc.html = 1772501222036 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/element-list = 1772501221832 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/search.html = 1772501222035 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/allclasses-index.html = 1772501222004 +/Users/lrhodes/dev/git/Apache/datasketches-java25/target/site/apidocs/type-search-index.js = 1772501222005 diff --git a/target/rat.txt b/target/rat.txt new file mode 100644 index 000000000..33249a61b --- /dev/null +++ b/target/rat.txt @@ -0,0 +1,4139 @@ +***************************************************** +Summary +***************************************************** +Generated at: 2026-03-03T13:43:44-08:00 + by Apache Creadur RAT::Core 0.17 (Apache Software Foundation) + +----------------------------------------------------- +Counters +----------------------------------------------------- + (Entries starting with '!' exceed the minimum or maximum values) + Approved: 612 A count of approved licenses. + Archives: 0 A count of archive files. + Binaries: 3 A count of binary files. + Document types: 3 A count of distinct document types. + Ignored: 541 A count of ignored files. + License categories: 1 A count of distinct license categories. + License names: 1 A count of distinct license names. + Notices: 0 A count of notice files. + Standards: 612 A count of standard files. + Unapproved: 0 A count of unapproved licenses. + Unknown: 0 A count of unknown file types. + + +----------------------------------------------------- +Licenses detected +----------------------------------------------------- + +Apache License 2.0: 612 + +----------------------------------------------------- +License Categories detected +----------------------------------------------------- + +AL : 612 + +----------------------------------------------------- +Document Types detected +----------------------------------------------------- + +BINARY: 3 +IGNORED: 541 +STANDARD: 612 + +***************************************************** +Detail +***************************************************** + + Documents with unapproved licenses will start with a '!' + The first character on the next line identifies the document type. + + char type + A Archive file + B Binary file + I Ignored file + N Notice file + S Standard file + U Unknown file. + + /.DS_Store + I application/octet-stream + + /.asf.yaml + I text/x-yaml + + /.checkstyle + I application/octet-stream + + /.classpath + I text/plain + + /.editorconfig + I application/octet-stream + + /.git + I application/octet-stream (directory) + + /.gitattributes + I application/octet-stream + + /.github + I application/octet-stream (directory) + + /.gitignore + I application/octet-stream + + /.mvn + I application/octet-stream (directory) + + /.project + I text/plain + + /.settings + I application/octet-stream (directory) + + /.vscode + I application/octet-stream (directory) + + /LICENSE + I text/plain + + /NOTICE + I text/plain + + /README.md + S text/x-web-markdown UTF-8 + AL AL2.0 Apache License 2.0 + + /pom.xml + S application/xml ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /serialization_test_data/.DS_Store + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_1_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_1_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_1_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_1_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_1_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_1_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_1_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_1_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_1_non_empty_no_entries_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_3_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_3_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_3_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_3_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_3_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_3_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_3_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/aod_3_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/bf_n0_h3_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/bf_n0_h5_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/bf_n10000_h3_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/bf_n10000_h5_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/bf_n2000000_h3_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/bf_n2000000_h5_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/bf_n30000000_h3_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/bf_n30000000_h5_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/cpc_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/cpc_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/cpc_n20000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/cpc_n2000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/cpc_n200_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_long_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_long_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_long_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_long_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_long_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_long_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_long_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_long_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_string_ascii_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_string_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_string_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_string_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_string_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_string_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_string_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_string_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_string_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/frequent_string_utf8_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll4_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll4_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll4_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll4_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll4_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll4_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll4_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll4_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll6_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll6_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll6_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll6_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll6_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll6_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll6_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll6_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll8_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll8_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll8_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll8_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll8_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll8_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll8_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/hll8_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_double_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_double_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_double_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_double_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_double_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_double_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_double_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_double_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_float_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_float_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_float_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_float_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_float_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_float_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_float_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_float_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_string_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_string_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_string_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_string_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_string_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_string_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_string_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/kll_string_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_double_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_double_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_double_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_double_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_double_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_double_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_double_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_double_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_string_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_string_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_string_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_string_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_string_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_string_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_string_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/quantiles_string_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/req_float_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/req_float_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/req_float_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/req_float_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/req_float_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/req_float_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/req_float_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/req_float_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_buf_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_buf_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_buf_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_buf_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_buf_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_buf_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_buf_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_buf_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_double_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_buf_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_buf_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_buf_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_buf_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_buf_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_buf_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_buf_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_buf_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tdigest_float_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_compressed_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_compressed_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_compressed_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_compressed_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_compressed_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_compressed_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/theta_non_empty_no_entries_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tuple_int_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tuple_int_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tuple_int_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tuple_int_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tuple_int_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tuple_int_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tuple_int_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/tuple_int_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/varopt_sketch_long_n0_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/varopt_sketch_long_n1000000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/varopt_sketch_long_n100000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/varopt_sketch_long_n10000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/varopt_sketch_long_n1000_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/varopt_sketch_long_n100_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/varopt_sketch_long_n10_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/varopt_sketch_long_n1_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/varopt_sketch_long_sampling_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/varopt_sketch_string_exact_cpp.sk + I application/octet-stream + + /serialization_test_data/cpp_generated_files/varopt_union_double_sampling_cpp.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/cpc_n0_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/cpc_n100_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/cpc_n20000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/cpc_n2000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/cpc_n200_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/cpc_negative_one_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll4_n0_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll4_n1000000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll4_n100000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll4_n10000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll4_n1000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll4_n100_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll4_n10_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll4_n1_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll6_n0_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll6_n1000000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll6_n100000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll6_n10000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll6_n1000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll6_n100_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll6_n10_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll6_n1_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll8_n0_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll8_n1000000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll8_n100000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll8_n10000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll8_n1000_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll8_n100_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll8_n10_go.sk + I application/octet-stream + + /serialization_test_data/go_generated_files/hll8_n1_go.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/.DS_Store + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_1_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_1_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_1_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_1_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_1_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_1_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_1_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_1_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_1_non_empty_no_entries_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_3_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_3_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_3_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_3_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_3_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_3_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_3_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aod_3_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_1_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_1_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_1_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_1_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_1_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_1_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_1_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_1_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_1_non_empty_no_entries_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_3_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_3_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_3_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_3_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_3_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_3_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_3_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_3_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_empty_strings_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_multikey_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_multikey_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_multikey_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_multikey_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_multikey_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_multikey_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_multikey_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_multikey_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/aos_unicode_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/bf_n0_h3_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/bf_n0_h5_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/bf_n10000_h3_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/bf_n10000_h5_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/bf_n2000000_h3_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/bf_n2000000_h5_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/bf_n30000000_h3_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/bf_n30000000_h5_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/cpc_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/cpc_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/cpc_n20000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/cpc_n2000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/cpc_n200_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/cpc_negative_one_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_long_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_long_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_long_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_long_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_long_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_long_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_long_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_long_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_string_ascii_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_string_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_string_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_string_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_string_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_string_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_string_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_string_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_string_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/frequent_string_utf8_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll4_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll4_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll4_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll4_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll4_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll4_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll4_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll4_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll6_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll6_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll6_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll6_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll6_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll6_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll6_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll6_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll8_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll8_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll8_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll8_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll8_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll8_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll8_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/hll8_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_double_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_double_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_double_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_double_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_double_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_double_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_double_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_double_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_float_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_float_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_float_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_float_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_float_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_float_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_float_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_float_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_long_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_long_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_long_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_long_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_long_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_long_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_long_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_long_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_string_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_string_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_string_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_string_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_string_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_string_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_string_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/kll_string_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_double_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_double_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_double_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_double_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_double_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_double_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_double_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_double_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_string_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_string_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_string_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_string_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_string_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_string_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_string_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/quantiles_string_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/req_float_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/req_float_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/req_float_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/req_float_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/req_float_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/req_float_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/req_float_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/req_float_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_double_empty_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_double_exact_n100_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_double_exact_n10_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_double_exact_n128_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_double_exact_n1_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_double_exact_n32_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_double_sampling_n1000_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_double_sampling_n1000_k32_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_double_sampling_n1000_k64_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_long_empty_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_long_exact_n100_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_long_exact_n10_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_long_exact_n128_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_long_exact_n1_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_long_exact_n32_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_long_sampling_n1000_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_long_sampling_n1000_k32_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_long_sampling_n1000_k64_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_string_empty_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_string_exact_n100_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_string_exact_n10_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_string_exact_n128_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_string_exact_n1_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_string_exact_n32_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_string_sampling_n1000_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_string_sampling_n1000_k32_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_string_sampling_n1000_k64_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_double_empty_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n100_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n10_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n128_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n1_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_double_exact_n32_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_double_sampling_n1000_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_double_sampling_n1000_maxk32_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_double_sampling_n1000_maxk64_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_long_empty_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n100_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n10_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n128_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n1_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_long_exact_n32_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_long_sampling_n1000_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_long_sampling_n1000_maxk32_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_long_sampling_n1000_maxk64_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_string_empty_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n100_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n10_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n128_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n1_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_string_exact_n32_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_string_sampling_n1000_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_string_sampling_n1000_maxk32_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_items_union_string_sampling_n1000_maxk64_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_empty_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_exact_n100_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_exact_n10_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_exact_n128_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_exact_n1_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_exact_n32_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_sampling_n1000_k128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_sampling_n1000_k32_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_sampling_n1000_k64_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_union_empty_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_union_exact_n100_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_union_exact_n10_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_union_exact_n128_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_union_exact_n1_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_union_exact_n32_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_union_sampling_n1000_maxk128_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_union_sampling_n1000_maxk32_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/reservoir_longs_union_sampling_n1000_maxk64_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tdigest_double_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tdigest_double_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tdigest_double_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tdigest_double_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tdigest_double_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tdigest_double_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tdigest_double_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tdigest_double_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_compressed_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_compressed_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_compressed_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_compressed_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_compressed_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_compressed_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/theta_non_empty_no_entries_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tuple_int_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tuple_int_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tuple_int_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tuple_int_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tuple_int_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tuple_int_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tuple_int_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/tuple_int_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/varopt_sketch_long_n0_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/varopt_sketch_long_n1000000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/varopt_sketch_long_n100000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/varopt_sketch_long_n10000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/varopt_sketch_long_n1000_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/varopt_sketch_long_n100_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/varopt_sketch_long_n10_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/varopt_sketch_long_n1_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/varopt_sketch_long_sampling_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/varopt_sketch_string_exact_java.sk + I application/octet-stream + + /serialization_test_data/java_generated_files/varopt_union_double_sampling_java.sk + I application/octet-stream + + /src/.DS_Store + I application/octet-stream + + /src/main/.DS_Store + I application/octet-stream + + /src/main/java/.DS_Store + I application/octet-stream + + /src/main/java/org/.DS_Store + I application/octet-stream + + /src/main/java/org/apache/.DS_Store + I application/octet-stream + + /src/main/java/org/apache/datasketches/.DS_Store + I application/octet-stream + + /src/main/java/org/apache/datasketches/common/ArrayOfBooleansSerDe.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/ArrayOfDoublesSerDe.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/ArrayOfItemsSerDe.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/ArrayOfLongsSerDe.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/ArrayOfNumbersSerDe.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/ArrayOfStringsSerDe.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/ArrayOfUtf16StringsSerDe.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/BoundsOnBinomialProportions.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/BoundsOnRatiosInSampledSets.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/ByteArrayUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/Family.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/MemorySegmentRequest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/MemorySegmentRequestExample.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/MemorySegmentStatus.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/QuickSelect.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/ResizeFactor.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/SketchesArgumentException.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/SketchesException.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/SketchesNotSupportedException.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/SketchesReadOnlyException.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/SketchesStateException.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/SpecialValueLayouts.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/SuppressFBWarnings.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/Util.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/positional/PositionInvariantsException.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/positional/Positional.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/positional/PositionalImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/positional/PositionalSegment.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/positional/PositionalSegmentImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/common/positional/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/count/CountMinSketch.java + S text/x-java-source UTF-8 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/count/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/BitMatrix.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/CompressedState.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/CompressionCharacterization.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/CompressionData.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/CpcCompression.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/CpcConfidence.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/CpcSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/CpcUnion.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/CpcUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/CpcWrapper.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/Flavor.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/Format.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/IconEstimator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/IconPolynomialCoefficients.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/MergingValidation.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/PairTable.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/PreambleUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/QuickMergingValidation.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/RuntimeAsserts.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/StreamingValidation.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/TestUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/cpc/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/fdt/FdtSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/fdt/Group.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/fdt/PostProcessor.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/fdt/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/filters/.DS_Store + I application/octet-stream + + /src/main/java/org/apache/datasketches/filters/bloomfilter/BitArray.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/filters/bloomfilter/BloomFilter.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/filters/bloomfilter/BloomFilterBuilder.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/filters/bloomfilter/DirectBitArray.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/filters/bloomfilter/DirectBitArrayR.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/filters/bloomfilter/HeapBitArray.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/filters/bloomfilter/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/filters/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/frequencies/ErrorType.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/frequencies/FrequentItemsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/frequencies/FrequentLongsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/frequencies/PreambleUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/frequencies/ReversePurgeItemHashMap.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/frequencies/ReversePurgeLongHashMap.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/frequencies/Util.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/frequencies/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hash/.DS_Store + I application/octet-stream + + /src/main/java/org/apache/datasketches/hash/MurmurHash3.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hash/MurmurHash3FFM.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hash/XxHash.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hash/XxHash64.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hash/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/AbstractCoupons.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/AbstractHllArray.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/AuxHashMap.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/BaseHllSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/CompositeInterpolationXTable.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/Conversions.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/CouponHashSet.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/CouponList.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/CouponMapping.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/CubicInterpolation.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/CurMode.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/DirectAuxHashMap.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/DirectCouponHashSet.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/DirectCouponList.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/DirectHll4Array.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/DirectHll6Array.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/DirectHll8Array.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/DirectHllArray.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/HarmonicNumbers.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/HeapAuxHashMap.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/Hll4Array.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/Hll4Update.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/Hll6Array.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/Hll8Array.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/HllArray.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/HllEstimators.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/HllPairIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/HllSketch.java + S text/x-java-source UTF-8 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/HllSketchImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/HllUnion.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/HllUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/IntArrayPairIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/IntMemorySegmentPairIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/PairIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/PreambleUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/RelativeErrorTables.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/TgtHllType.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/ToByteArrayImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hll/doc-files/HLL_HIP_K12T20U20.png + B image/png + + /src/main/java/org/apache/datasketches/hll/doc-files/HLL_UnionTime4_6_8_Java_CPP.png + B image/png + + /src/main/java/org/apache/datasketches/hll/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hllmap/CouponHashMap.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hllmap/CouponTraverseMap.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hllmap/CouponsIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hllmap/HllMap.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hllmap/Map.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hllmap/SingleCouponMap.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hllmap/UniqueCountMap.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/hllmap/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllDirectCompactItemsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllDirectDoublesSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllDirectFloatsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllDirectLongsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllDoublesHelper.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllDoublesSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllDoublesSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllFloatsHelper.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllFloatsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllFloatsSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllHeapDoublesSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllHeapFloatsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllHeapItemsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllHeapLongsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllHelper.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllItemsHelper.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllItemsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllItemsSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllLongsHelper.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllLongsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllLongsSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllMemorySegmentValidate.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllPreambleUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/KllSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/kll/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/partitions/BoundsRule.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/partitions/Partitioner.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/partitions/SketchFillRequest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/partitions/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/.DS_Store + I application/octet-stream + + /src/main/java/org/apache/datasketches/quantiles/ClassicUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/CompactQuantilesDoublesSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/DirectCompactDoublesSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/DirectDoublesSketchAccessor.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/DirectUpdateDoublesSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/DoublesArrayAccessor.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/DoublesBufferAccessor.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/DoublesByteArrayImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/DoublesMergeImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/DoublesSketchAccessor.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/DoublesUpdateImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/DoublesUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/HeapCompactDoublesSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/HeapDoublesSketchAccessor.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/HeapUpdateDoublesSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/ItemsByteArrayImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/ItemsMergeImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/ItemsUpdateImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/ItemsUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/PreambleUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesSketchBuilder.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesUnion.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesUnionBuilder.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/QuantilesDoublesUnionImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/QuantilesItemsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/QuantilesItemsSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/QuantilesItemsUnion.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/UpdatableQuantilesDoublesSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantiles/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/BinarySearch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/DoublesSketchSortedView.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/DoublesSortedView.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/DoublesSortedViewIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/FloatsSketchSortedView.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/FloatsSortedView.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/FloatsSortedViewIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/GenericInequalitySearch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/GenericPartitionBoundaries.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/GenericSortedView.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/GenericSortedViewIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/IncludeMinMax.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/InequalitySearch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/ItemsSketchSortedView.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/KolmogorovSmirnov.java + S text/x-java-source UTF-8 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/LongsSketchSortedView.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/LongsSortedView.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/LongsSortedViewIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/PartitioningFeature.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/QuantileSearchCriteria.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/QuantilesAPI.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/QuantilesDoublesAPI.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/QuantilesDoublesSketchIteratorAPI.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/QuantilesFloatsAPI.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/QuantilesFloatsSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/QuantilesGenericAPI.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/QuantilesGenericSketchIteratorAPI.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/QuantilesLongsAPI.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/QuantilesLongsSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/QuantilesSketchIteratorAPI.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/QuantilesUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/SketchPartitionLimits.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/SortedView.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/SortedViewIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/quantilescommon/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/req/BaseReqSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/req/FloatBuffer.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/req/ReqCompactor.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/req/ReqDebug.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/req/ReqSerDe.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/req/ReqSketch.java + S text/x-java-source UTF-8 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/req/ReqSketchBuilder.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/req/ReqSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/req/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/EbppsItemsSample.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/EbppsItemsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/PreambleUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/ReservoirItemsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/ReservoirItemsUnion.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/ReservoirLongsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/ReservoirLongsUnion.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/ReservoirSize.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/SampleSubsetSummary.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/SamplingUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/VarOptItemsSamples.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/VarOptItemsSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/VarOptItemsUnion.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/sampling/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tdigest/BinarySearch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tdigest/Sort.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tdigest/TDigestDouble.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tdigest/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/.DS_Store + I application/octet-stream + + /src/main/java/org/apache/datasketches/theta/BitPacking.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/BytesCompactCompressedHashIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/BytesCompactHashIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/CompactOperations.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/CompactThetaSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ConcurrentBackgroundThetaPropagation.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ConcurrentDirectQuickSelectSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ConcurrentHeapQuickSelectSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ConcurrentHeapThetaBuffer.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ConcurrentPropagationService.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ConcurrentSharedThetaSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/DirectCompactCompressedSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/DirectCompactSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/DirectQuickSelectSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/DirectQuickSelectSketchR.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/EmptyCompactSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/HashIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/HeapAlphaSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/HeapCompactHashIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/HeapCompactSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/HeapHashIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/HeapQuickSelectSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/HeapUpdateSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/JaccardSimilarity.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/MemorySegmentCompactCompressedHashIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/MemorySegmentHashIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/PreambleUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/Rebuilder.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/SingleItemSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ThetaAnotB.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ThetaAnotBimpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ThetaIntersection.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ThetaIntersectionImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ThetaSetOperation.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ThetaSetOperationBuilder.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ThetaSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ThetaUnion.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/ThetaUnionImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/UpdatableThetaSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/UpdatableThetaSketchBuilder.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/UpdateReturnState.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/WrappedCompactCompressedSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/WrappedCompactSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/theta/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/thetacommon/BinomialBoundsN.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInThetaSketchedSets.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInTupleSketchedSets.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/thetacommon/EquivTables.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/thetacommon/HashOperations.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/thetacommon/SetOperationCornerCases.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/thetacommon/ThetaUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/thetacommon/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/.DS_Store + I application/octet-stream + + /src/main/java/org/apache/datasketches/tuple/CompactTupleSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/DeserializeResult.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/Filter.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/HashTables.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/JaccardSimilarity.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/QuickSelectSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/SerializerDeserializer.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/Summary.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/SummaryDeserializer.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/SummaryFactory.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/SummarySetOperations.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/TupleAnotB.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/TupleIntersection.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/TupleSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/TupleSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/TupleUnion.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/UpdatableSummary.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/UpdatableTupleSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/UpdatableTupleSketchBuilder.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/Util.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummary.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummaryDeserializer.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummaryFactory.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/adouble/DoubleSummarySetOperations.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/adouble/DoubleTupleSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/adouble/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummary.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummaryDeserializer.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummaryFactory.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/aninteger/IntegerSummarySetOperations.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/aninteger/IntegerTupleSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/aninteger/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotB.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotBImpl.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCombiner.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCompactSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesIntersection.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesQuickSelectSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSetOperationBuilder.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUnion.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketchBuilder.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesCompactSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesIntersection.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketchR.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesUnion.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesUnionR.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HashTables.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesCompactSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesIntersection.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesQuickSelectSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesSketchIterator.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesUnion.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/arrayofdoubles/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummary.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryDeserializer.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryFactory.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummarySetOperations.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/strings/ArrayOfStringsTupleSketch.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/java/org/apache/datasketches/tuple/strings/package-info.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/javadoc/overview.html + S text/html ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/main/javadoc/resources/dictionary.html + S text/html ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/.DS_Store + I application/octet-stream + + /src/test/java/.DS_Store + I application/octet-stream + + /src/test/java/org/.DS_Store + I application/octet-stream + + /src/test/java/org/apache/.DS_Store + I application/octet-stream + + /src/test/java/org/apache/datasketches/.DS_Store + I application/octet-stream + + /src/test/java/org/apache/datasketches/common/.DS_Store + I application/octet-stream + + /src/test/java/org/apache/datasketches/common/ArrayOfXSerDeTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/common/BoundsOnBinomialProportionsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/common/BoundsOnRatiosInSampledSetsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/common/ByteArrayUtilTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/common/FamilyTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/common/Shuffle.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/common/ShuffleTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/common/SketchesExceptionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/common/TestUtil.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/common/UtilTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/common/positional/PositionalSegmentTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/common/positional/PositionalTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/count/CountMinSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/cpc/CompressedStateTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/cpc/CompressionDataTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/cpc/CpcCompressionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/cpc/CpcSketchCrossLanguageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/cpc/CpcSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/cpc/CpcUnionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/cpc/CpcWrapperTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/cpc/IconEstimatorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/cpc/PairTableTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/cpc/PreambleUtilTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/cpc/RuntimeAssertsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/cpc/TestAllTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/fdt/FdtSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/fdt/GroupTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/filters/.DS_Store + I application/octet-stream + + /src/test/java/org/apache/datasketches/filters/bloomfilter/BloomFilterBuilderTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/filters/bloomfilter/BloomFilterCrossLanguageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/filters/bloomfilter/BloomFilterTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/filters/bloomfilter/DirectBitArrayRTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/filters/bloomfilter/DirectBitArrayTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/filters/bloomfilter/HeapBitArrayTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/frequencies/DistTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/frequencies/FrequentItemsSketchCrossLanguageTest.java + S text/x-java-source UTF-8 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/frequencies/HashMapStressTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/frequencies/ItemsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/frequencies/LongsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/frequencies/ReversePurgeLongHashMapTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/frequencies/SerDeCompatibilityTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hash/.DS_Store + I application/octet-stream + + /src/test/java/org/apache/datasketches/hash/MurmurHash3FFMTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hash/MurmurHash3FFMbTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hash/MurmurHash3Test.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hash/XxHash64LoopingTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hash/XxHash64Test.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/AuxHashMapTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/BaseHllSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/CouponListTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/CrossCountingTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/DirectAuxHashMapTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/DirectCouponListTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/DirectHllSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/DirectUnionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/HllArrayTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/HllSketchCrossLanguageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/HllSketchMergeOrderTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/HllSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/IsomorphicTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/PreambleUtilTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/SizeAndModeTransitions.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/TablesTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/ToFromByteArrayTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/UnionCaseTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hll/UnionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hllmap/CouponHashMapTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hllmap/CouponTraverseMapTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hllmap/HllMapTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hllmap/SingleCouponMapTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/hllmap/UniqueCountMapTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllCrossLanguageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDirectCompactDoublesSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDirectCompactFloatsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDirectCompactItemsSketchIteratorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDirectCompactItemsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDirectCompactLongsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDirectDoublesSketchIteratorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDirectDoublesSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDirectFloatsSketchIteratorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDirectFloatsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDirectLongsSketchIteratorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDirectLongsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDoublesSketchIteratorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDoublesSketchSerDeTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDoublesSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllDoublesValidationTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllFloatsSketchIteratorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllFloatsSketchSerDeTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllFloatsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllFloatsValidationTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllHelperTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllItemsSketchSerDeTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllItemsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllItemsSketchiteratorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllLongsSketchIteratorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllLongsSketchSerDeTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllLongsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllMemorySegmentRequestApp.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllMemoryValidateTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllMiscDirectDoublesTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllMiscDirectFloatsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllMiscDirectLongsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllMiscDoublesTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllMiscFloatsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllMiscItemsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllMiscLongsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/kll/KllSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/partitions/ClassicPartitionsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/partitions/ItemsSketchFillRequestLongAsString.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/partitions/KllItemsSketchFillRequestLongAsString.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/partitions/KllPartitionsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/partitions/PartitionResults.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/AccuracyTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/ClassicQuantilesMemorySegmentRequestApp.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/CustomQuantilesTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/DebugUnionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/DirectCompactDoublesSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/DirectQuantilesMemoryRequestTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/DirectUpdateDoublesSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/DoublesMiscTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/DoublesSketchBuilderTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/DoublesSketchIteratorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/DoublesSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/DoublesUnionBuilderTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/DoublesUnionImplTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/DoublesUtilTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/HeapCompactDoublesSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/HeapUpdateDoublesSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/ItemsSketchIteratorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/ItemsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/ItemsUnionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/PreambleUtilTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/QuantilesSketchCrossLanguageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/SerDeCompatibilityTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantiles/UtilTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantilescommon/CrossCheckQuantilesTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantilescommon/GenericInequalitySearchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantilescommon/IncludeMinMaxTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantilescommon/InequalitySearchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantilescommon/KolmogorovSmirnovTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantilescommon/LinearRanksAndQuantiles.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantilescommon/LongsAsOrderableStrings.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantilescommon/PartitionBoundariesTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/quantilescommon/QuantilesUtilTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/req/ReqCompactorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/req/ReqDebugImplTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/req/ReqFloatBufferTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/req/ReqSketchBuilderTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/req/ReqSketchCrossLanguageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/req/ReqSketchOtherTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/req/ReqSketchSortedViewTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/req/ReqSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/sampling/EbppsItemsSampleTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/sampling/EbppsItemsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/sampling/ReservoirCrossLanguageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/sampling/ReservoirItemsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/sampling/ReservoirItemsUnionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/sampling/ReservoirLongsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/sampling/ReservoirLongsUnionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/sampling/ReservoirSizeTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/sampling/VarOptCrossLanguageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/sampling/VarOptItemsSamplesTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/sampling/VarOptItemsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/sampling/VarOptItemsUnionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tdigest/SortTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tdigest/TDigestCrossLanguageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tdigest/TDigestDoubleTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/.DS_Store + I application/octet-stream + + /src/test/java/org/apache/datasketches/theta/AnotBimplTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/BitPackingTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/CompactSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/ConcurrentDirectQuickSelectSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/ConcurrentHeapQuickSelectSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/CornerCaseThetaSetOperationsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/DirectIntersectionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/DirectQuickSelectSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/DirectUnionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/EmptyTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/ExamplesTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/HeapAlphaSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/HeapIntersectionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/HeapQuickSelectSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/HeapUnionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/HeapifyWrapSerVer3Test.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/IteratorTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/JaccardSimilarityTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/PairwiseSetOperationsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/PreambleUtilTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/ReadOnlyMemorySegmentTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/SetOperationTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/SetOpsCornerCasesTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/SingleItemSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/SketchMiscTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/SketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/ThetaSketchCrossLanguageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/UnionImplTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/theta/UpdateSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/thetacommon/BinomialBoundsNTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInThetaSketchedSetsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/thetacommon/BoundsOnRatiosInTupleSketchedSetsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/thetacommon/HashOperationsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/thetacommon/QuickSelectTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/thetacommon/ThetaUtilTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/.DS_Store + I application/octet-stream + + /src/test/java/org/apache/datasketches/tuple/CompactSketchWithDoubleSummaryTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/IntegerSummary.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/IntegerSummaryDeserializer.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/IntegerSummaryFactory.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/JaccardSimilarityTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/MiscTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/ReadOnlyMemorySegmentTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/SerializerDeserializerTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/TupleCrossLanguageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/TupleExamples2Test.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/TupleExamplesTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/adouble/AdoubleAnotBTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/adouble/AdoubleIntersectionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/adouble/AdoubleTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/adouble/AdoubleUnionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/adouble/FilterTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/aninteger/CornerCaseTupleSetOperationsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/aninteger/EngagementTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/aninteger/IntegerSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/aninteger/MikhailsBugTupleTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/aninteger/ParameterLeakageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/arrayofdoubles/AodSketchCrossLanguageTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotBTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCompactSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesIntersectionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesQuickSelectSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUnionTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/arrayofdoubles/CornerCaseArrayOfDoublesSetOperationsTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesCompactSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/arrayofdoubles/DirectArrayOfDoublesQuickSelectSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesCompactSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/arrayofdoubles/HeapArrayOfDoublesQuickSelectSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/strings/AosSketchCrossLanguageTest.java + S text/x-java-source UTF-8 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSketchTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryTest.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/java/org/apache/datasketches/tuple/strings/ArrayOfStringsSummary_Issue699.java + S text/x-java-source ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /src/test/resources/ArrayOfDoublesUnion_v0.9.1.sk + I application/octet-stream + + /src/test/resources/CompactSketchWithDoubleSummary4K_serialVersion1.sk + I application/octet-stream + + /src/test/resources/Qk128_n1000_v0.3.0.sk + I application/octet-stream + + /src/test/resources/Qk128_n1000_v0.6.0.sk + I application/octet-stream + + /src/test/resources/Qk128_n1000_v0.8.0.sk + I application/octet-stream + + /src/test/resources/Qk128_n1000_v0.8.3.sk + I application/octet-stream + + /src/test/resources/Qk128_n50_v0.3.0.sk + I application/octet-stream + + /src/test/resources/Qk128_n50_v0.6.0.sk + I application/octet-stream + + /src/test/resources/Qk128_n50_v0.8.0.sk + I application/octet-stream + + /src/test/resources/Qk128_n50_v0.8.3.sk + I application/octet-stream + + /src/test/resources/TupleWithTestIntegerSummary4kTrimmedSerVer2.sk + I application/octet-stream + + /src/test/resources/kll_double_n1.sk + I application/octet-stream + + /src/test/resources/kll_sketch_double_one_item_v1.sk + I application/octet-stream + + /src/test/resources/kll_sketch_float_one_item_v1.sk + I application/octet-stream + + /src/test/resources/tdigest_ref_k100_n10000_double.sk + I application/octet-stream + + /src/test/resources/tdigest_ref_k100_n10000_float.sk + I application/octet-stream + + /target + I application/octet-stream (directory) + + /tools/FindBugsExcludeFilter.xml + S application/xml ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /tools/ManualJavadocsDeploy.sh + B application/x-sh + + /tools/SketchesCheckstyle.xml + S application/xml ISO-8859-1 + AL AL2.0 Apache License 2.0 + + /tools/testng.xml + S application/xml ISO-8859-1 + AL AL2.0 Apache License 2.0 + + diff --git a/target/site/apidocs/allclasses-index.html b/target/site/apidocs/allclasses-index.html new file mode 100644 index 000000000..3a70e530d --- /dev/null +++ b/target/site/apidocs/allclasses-index.html @@ -0,0 +1,993 @@ + + + + +All Classes and Interfaces (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

All Classes and Interfaces

+
+
+
+
+
+
Class
+
Description
+ +
+
Methods of serializing and deserializing arrays of Boolean as a bit array.
+
+ +
+
Computes a set difference of two tuple sketches of type ArrayOfDoubles
+
+ +
+
Computes a set difference, A-AND-NOT-B, of two ArrayOfDoublesSketches.
+
+ +
+
Combines two arrays of double values for use with ArrayOfDoubles tuple sketches
+
+ +
+
Top level compact tuple sketch of type ArrayOfDoubles.
+
+ +
+
Computes the intersection of two or more tuple sketches of type ArrayOfDoubles.
+
+ +
+
Methods of serializing and deserializing arrays of Double.
+
+ +
+
Builds set operations object for tuple sketches of type ArrayOfDoubles.
+
+ +
+
The base class for the tuple sketch of type ArrayOfDoubles, where an array of double values +is associated with each key.
+
+ +
+
Interface for iterating over tuple sketches of type ArrayOfDoubles
+
+ +
+
The base class for unions of tuple sketches of type ArrayOfDoubles.
+
+ +
+
The top level for updatable tuple sketches of type ArrayOfDoubles.
+
+ +
+
For building a new ArrayOfDoublesUpdatableSketch
+
+ +
+
Base class for serializing and deserializing custom types.
+
+ +
+
Methods of serializing and deserializing arrays of Long.
+
+ +
+
Methods of serializing and deserializing arrays of the object version of primitive types of +Number.
+
+ +
+
Methods of serializing and deserializing arrays of String.
+
+ +
+
Implements UpdatableSummary<String[]>
+
+ +
+
Implements SummaryDeserializer<ArrayOfStringsSummary>
+
+ +
+
Implements SummaryFactory<ArrayOfStringsSummary>
+
+ +
+
Implements SummarySetOperations<ArrayOfStringsSummary>
+
+ +
+
Extends UpdatableTupleSketch<String[], ArrayOfStringsSummary>
+
+ +
+
Methods of serializing and deserializing arrays of String.
+
+ +
+
Contains common equality binary search algorithms.
+
+ +
+
Algorithms with logarithmic complexity for searching in an array.
+
+ +
+
This class enables the estimation of error bounds given a sample set size, the sampling +probability theta, the number of standard deviations and a simple noDataSeen flag.
+
+ +
+
A Bloom filter is a data structure that can be used for probabilistic +set membership.
+
+ +
+
This class provides methods to help estimate the correct parameters when +creating a Bloom filter, and methods to create the filter using those values.
+
+ +
+
Confidence intervals for binomial proportions.
+
+ +
+
This class is used to compute the bounds on the estimate of the ratio |B| / |A|, where: + +|A| is the unknown size of a set A of unique identifiers. +|B| is the unknown size of a subset B of A. +a = |SA| is the observed size of a sample of A +that was obtained by Bernoulli sampling with a known inclusion probability f. +b = |SA ∩ B| is the observed size of a subset +of SA. +
+
+ +
+
This class is used to compute the bounds on the estimate of the ratio B / A, where: + +A is a Theta Sketch of population PopA. +B is a Theta Sketch of population PopB that is a subset of A, +obtained by an intersection of A with some other Theta Sketch C, +which acts like a predicate or selection clause. +The estimate of the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(A, B). +The Upper Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(A, B). +The Lower Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(A, B). + +Note: The theta of A cannot be greater than the theta of B.
+
+ +
+
This class is used to compute the bounds on the estimate of the ratio B / A, where: + +A is a Tuple Sketch of population PopA. +B is a Tuple or Theta Sketch of population PopB that is a subset of A, +obtained by an intersection of A with some other Tuple or Theta Sketch C, +which acts like a predicate or selection clause. +The estimate of the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(A, B). +The Upper Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(A, B). +The Lower Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(A, B). + +Note: The theta of A cannot be greater than the theta of B.
+
+ +
+
This instructs the user about which of the upper and lower bounds of a partition definition row +should be included with the returned data.
+
+ +
+
Useful methods for byte arrays.
+
+ +
+
Utilities for the classic quantiles sketches and independent of the type.
+
+ +
+
Compact sketches are inherently read only.
+
+ +
+
The parent class of all the CompactThetaSketches.
+
+ +
+
CompactTupleSketches are never created directly.
+
+ +
+
This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing.
+
+ +
+
Java implementation of the CountMin sketch data structure of Cormode and Muthukrishnan.
+
+ +
+
This is a unique-counting sketch that implements the +Compressed Probabilistic Counting (CPC, a.k.a FM85) algorithms developed by Kevin Lang in +his paper +Back to the Future: an Even More Nearly +Optimal Cardinality Estimation Algorithm.
+
+ +
+
The union (merge) operation for the CPC sketches.
+
+ +
+
This provides a read-only view of a serialized image of a CpcSketch, which can be +on-heap or off-heap represented as a MemorySegment object, or on-heap represented as a byte array.
+
+ +
+
Returns an object and its size in bytes as a result of a deserialize operation
+
+ +
+
This class can maintain the BitArray object off-heap.
+
+ +
+
The SortedView of the Quantiles Classic QuantilesDoublesSketch and the KllDoublesSketch.
+
+ +
+
The Sorted View for quantile sketches of primitive type double.
+
+ +
+
Iterator over quantile sketches of primitive type double.
+
+ +
+
Summary for generic tuple sketches of type Double.
+
+ +
+
The aggregation modes for this Summary
+
+ +
+
Implements SummaryDeserializer<DoubleSummary>
+
+ +
+
Factory for DoubleSummary.
+
+ +
+
Methods for defining how unions and intersections of two objects of type DoubleSummary +are performed.
+
+ +
+
Extends UpdatableTupleSketch<Double, DoubleSummary>
+
+ +
+
An implementation of an Exact and Bounded Sampling Proportional to Size sketch.
+
+ +
+
Specifies one of two types of error regions of the statistical classification Confusion Matrix +that can be excluded from a returned sample of Frequent Items.
+
+ +
+
Defines the various families of sketch and set operation classes.
+
+ +
+
A Frequent Distinct Tuples sketch.
+
+ +
+
Class for filtering entries from a TupleSketch given a Summary
+
+ +
+
The SortedView for the KllFloatsSketch and the ReqSketch.
+
+ +
+
The Sorted View for quantiles of primitive type float.
+
+ +
+
Iterator over quantile sketches of primitive type float.
+
+ +
+
This sketch is based on the paper https://arxiv.org/abs/1705.07001 +("A High-Performance Algorithm for Identifying Frequent Items in Data Streams" +by Daniel Anderson, Pryce Bevan, Kevin Lang, Edo Liberty, Lee Rhodes, and Justin Thaler) +and is useful for tracking approximate frequencies of items of type <T> +with optional associated counts (<T> item, long count) that are members of a +multiset of such items.
+
+ +
+
Row class that defines the return values from a getFrequentItems query.
+
+ +
+
This sketch is based on the paper https://arxiv.org/abs/1705.07001 +("A High-Performance Algorithm for Identifying Frequent Items in Data Streams" +by Daniel Anderson, Pryce Bevan, Kevin Lang, Edo Liberty, Lee Rhodes, and Justin Thaler) +and is useful for tracking approximate frequencies of long items with optional +associated counts (long item, long count) that are members of a multiset of +such items.
+
+ +
+
Row class that defines the return values from a getFrequentItems query.
+
+ +
+
This provides efficient, unique and unambiguous binary searching for inequality comparison criteria +for ordered arrays of values that may include duplicate values.
+
+ +
+
The enumerator of inequalities
+
+ +
+
This defines the returned results of the getParitionBoundaries() function and +includes the basic methods needed to construct actual partitions.
+
+ +
+
The Sorted View for quantiles of generic type.
+
+ +
+
Iterator over quantile sketches of generic type.
+
+ +
+
Defines a Group from a Frequent Distinct Tuple query.
+
+ +
+
This is used to iterate over the retained hash values of the Theta sketch.
+
+ +
+
Helper class for the common hash table methods.
+
+ +
+
The HllSketch is actually a collection of compact implementations of Phillipe Flajolet’s HyperLogLog (HLL) +sketch but with significantly improved error behavior and excellent speed performance.
+
+ +
+
This performs union operations for all HllSketches.
+
+ +
+
This class reinserts the min and max values into the sorted view arrays as required.
+
+ +
+
A simple structure to hold a pair of arrays
+
+ +
+
A simple structure to hold a pair of arrays
+
+ +
+
A simple structure to hold a pair of arrays
+
+ +
+
A simple structure to hold a pair of arrays
+
+ +
+
This provides efficient, unique and unambiguous binary searching for inequality comparison criteria +for ordered arrays of values that may include duplicate values.
+
+ +
+
Summary for generic tuple sketches of type Integer.
+
+ +
+
The aggregation modes for this Summary
+
+ +
+
Implements SummaryDeserializer<IntegerSummary>
+
+ +
+
Factory for IntegerSummary.
+
+ +
+
Methods for defining how unions and intersections of two objects of type IntegerSummary +are performed.
+
+ +
+
Extends UpdatableTupleSketch<Integer, IntegerSummary>
+
+ +
+
The SortedView for the KllItemsSketch and the classic QuantilesItemsSketch.
+
+ +
+
Jaccard similarity of two ThetaSketches.
+
+ +
+
Jaccard similarity of two TupleSketches, or alternatively, of a TupleSketch and a ThetaSketch.
+
+ +
+
This variation of the KllSketch implements primitive doubles.
+
+ +
+
Iterator over KllDoublesSketch.
+
+ +
+
This variation of the KllSketch implements primitive floats.
+
+ +
+
Iterator over KllFloatsSketch.
+
+ +
+
This variation of the KllSketch implements generic data types.
+
+ +
+
Iterator over KllItemsSketch.
+
+ +
+
This variation of the KllSketch implements primitive longs.
+
+ +
+
Iterator over KllLongsSketch.
+
+ +
+
This class is the root of the KLL sketch class hierarchy.
+
+ +
+
Used primarily to define the structure of the serialized sketch.
+
+ +
+
Used to define the variable type of the current instance of this class.
+
+ +
+
The base implementation for the KLL sketch iterator hierarchy used for viewing the +non-ordered quantiles retained by a sketch.
+
+ +
+
Kolmogorov-Smirnov Test +See Kolmogorov–Smirnov Test
+
+ +
+
The SortedView of the KllLongsSketch.
+
+ +
+
The Sorted View for quantile sketches of primitive type long.
+
+ +
+
Iterator over quantile sketches of primitive type long.
+
+ +
+
This is a callback interface to provide a means to request a new MemorySegment of a specified size.
+
+ +
+
A convenience class that implements a default implementation.
+
+ +
+
This is an example of a possible implementation of the MemorySegmentRequest interface +where all requested segments are allocated off-heap.
+
+ +
+
Methods for inquiring the status of a backing MemorySegment.
+
+ +
+
This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing.
+
+ +
+
The MurmurHash3 is a fast, non-cryptographic, 128-bit hash function that has +excellent avalanche and 2-way bit independence properties.
+
+ +
+
The MurmurHash3 is a fast, non-cryptographic, 128-bit hash function that has +excellent avalanche and 2-way bit independence properties.
+
+ +
+
A partitioning process that can partition very large data sets into thousands +of partitions of approximately the same size.
+
+ +
+
Defines a row for List of PartitionBounds.
+
+ +
+
Holds data for a Stack element
+
+ +
+
This enables the special functions for performing efficient partitioning of massive data.
+
+ +
+
Defines the relative positional API.
+
+ +
+
Defines the API for relative positional access to a MemorySegment.
+
+ +
+
Position operation violation.
+
+ +
+
This processes the contents of a FDT sketch to extract the +primary keys with the most frequent unique combinations of the non-primary dimensions.
+
+ +
+
This is a stochastic streaming sketch that enables near-real time analysis of the +approximate distribution of items from a very large stream in a single pass, requiring only +that the items are comparable.
+
+ +
+
The Quantiles API for item type double.
+
+ +
+
This is an implementation of the Low Discrepancy Mergeable Quantiles Sketch, using doubles, + described in section 3.2 of the journal version of the paper "Mergeable Summaries" + by Agarwal, Cormode, Huang, Phillips, Wei, and Yi:
+
+ +
+
For building a new quantiles QuantilesDoublesSketch.
+
+ +
+
Iterator over QuantilesDoublesSketch.
+
+ +
+
The quantiles sketch iterator for primitive type double.
+
+ +
+
The API for Union operations for QuantilesDoublesSketches
+
+ +
+
For building a new QuantilesDoublesSketch Union operation.
+
+ +
+
These search criteria are used by the KLL, REQ and Classic Quantiles sketches in the DataSketches library.
+
+ +
+
The Quantiles API for item type float.
+
+ +
+
The quantiles sketch iterator for primitive type float.
+
+ +
+
The Quantiles API for item type generic.
+
+ +
+
The quantiles sketch iterator for generic types.
+
+ +
+
This is an implementation of the Low Discrepancy Mergeable Quantiles Sketch, using generic items, +described in section 3.2 of the journal version of the paper "Mergeable Summaries" +by Agarwal, Cormode, Huang, Phillips, Wei, and Yi:
+
+ +
+
Iterator over QuantilesItemsSketch.
+
+ +
+
The API for Union operations for generic QuantilesItemsSketches
+
+ +
+
The Quantiles API for item type long.
+
+ +
+
The quantiles sketch iterator for primitive type long.
+
+ +
+
This is the base API for the iterator hierarchy used for viewing the +non-ordered quantiles retained by the classic Quantiles* sketches and KLL sketches, for example.
+
+ +
+
Utilities for the quantiles sketches.
+
+ +
+
This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing.
+
+ +
+
QuickSelect algorithm improved from Sedgewick.
+
+ +
+
The signaling interface that allows comprehensive analysis of the ReqSketch and ReqCompactor +while eliminating code clutter in the main classes.
+
+ +
+
This Relative Error Quantiles Sketch is the Java implementation based on the paper +"Relative Error Streaming Quantiles" by Graham Cormode, Zohar Karnin, Edo Liberty, +Justin Thaler, Pavel Veselý, and loosely derived from a Python prototype written by Pavel Veselý.
+
+ +
+
For building a new ReqSketch
+
+ +
+
Iterator over all retained items of the ReqSketch.
+
+ +
+
This sketch provides a reservoir sample over an input stream of items.
+
+ +
+
Class to union reservoir samples of generic items.
+
+ +
+
This sketch provides a reservoir sample over an input stream of longs.
+
+ +
+
Class to union reservoir samples of longs.
+
+ +
+
For the Families that accept this configuration parameter, it controls the size multiple that +affects how fast the internal cache grows, when more space is required.
+
+ +
+
A simple object o capture the results of a subset sum query on a sampling sketch.
+
+ +
+
Multipurpose serializer-deserializer for a collection of sketches defined by the enum.
+
+ +
+
Defines the sketch classes that this SerializerDeserializer can handle.
+
+ +
+
Simplifies and speeds up set operations by resolving specific corner cases.
+
+ +
+
A not B actions
+
+ +
+
List of corner cases
+
+ +
+
Intersection actions
+
+ +
+
List of union actions
+
+ +
+
Illegal Arguments Exception class for the library
+
+ +
+
Exception class for the library
+
+ +
+
This operation or mode is not supported.
+
+ +
+
Write operation attempted on a read-only class.
+
+ +
+
Illegal State Exception class for the library
+
+ +
+
This is a callback request to the data source to fill a quantiles sketch, +which is returned to the caller.
+
+ +
+
This defines the methods required to compute the partition limits.
+
+ +
+
Specialized sorting algorithm that can sort one array and permute another array the same way.
+
+ +
+
This is the base interface for the Sorted View interface hierarchy and defines the methods that are type independent.
+
+ +
+
This is the base interface for the SortedViewIterator hierarchy used with a SortedView obtained +from a quantile-type sketch.
+
+ +
+
Value Layouts for Non-native Endianness
+
+ +
+
This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing.
+
+ +
+
Interface for user-defined Summary, which is associated with every hash in a tuple sketch
+
+ +
+
Interface for deserializing user-defined Summary
+
+ +
+
Interface for user-defined SummaryFactory
+
+ +
+
This is to provide methods of producing unions and intersections of two Summary objects.
+
+ +
+
Used to suppress SpotBug warnings.
+
+ +
+
t-Digest for estimating quantiles and ranks.
+
+ +
+
Utility methods for Test
+
+ +
+
Specifies the target type of HLL sketch to be created.
+
+ +
+
Computes a set difference, A-AND-NOT-B, of two ThetaSketches.
+
+ +
+
The API for intersection operations
+
+ +
+
The parent API for all Set Operations
+
+ +
+
For building a new ThetaSetOperation.
+
+ +
+
The top-level class for all theta sketches.
+
+ +
+
Compute the union of two or more theta sketches.
+
+ +
+
Utility methods for the Theta Family of sketches
+
+ +
+
Computes a set difference, A-AND-NOT-B, of two generic TupleSketches.
+
+ +
+
Computes an intersection of two or more generic TupleSketches or generic TupleSketches +combined with ThetaSketches.
+
+ +
+
The top-level class for all Tuple sketches.
+
+ +
+
Iterator over a generic tuple sketch
+
+ +
+
Compute the union of two or more generic tuple sketches or generic TupleSketches combined with +ThetaSketches.
+
+ +
+
This is a real-time, key-value HLL mapping sketch that tracks approximate unique counts of +identifiers (the values) associated with each key.
+
+ +
+
Extends QuantilesDoubleSketch
+
+ +
+
Interface for updating user-defined Summary
+
+ +
+
The parent class for the UpdatableThetaSketch families, such as QuickSelectThetaSketch and AlphaSketch.
+
+ +
+
For building a new UpdatableThetaSketch.
+
+ +
+
An extension of QuickSelectSketch<S>, which can be updated with many types of keys.
+
+ +
+
For building a new generic tuple UpdatableTupleSketch
+
+ + + +
+
Common utility functions.
+
+ +
+
Common utility functions for Tuples
+
+ +
+
This class provides access to the samples contained in a VarOptItemsSketch.
+
+ +
+
This sketch provides a variance optimal sample over an input stream of weighted items.
+
+ +
+
Provides a unioning operation over varopt sketches.
+
+ +
+
The XxHash is a fast, non-cryptographic, 64-bit hash function that has +excellent avalanche and 2-way bit independence properties.
+
+ +
+
The XxHash is a fast, non-cryptographic, 64-bit hash function that has +excellent avalanche and 2-way bit independence properties.
+
+
+
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/allpackages-index.html b/target/site/apidocs/allpackages-index.html new file mode 100644 index 000000000..d864d0585 --- /dev/null +++ b/target/site/apidocs/allpackages-index.html @@ -0,0 +1,183 @@ + + + + +All Packages (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

All Packages

+
+
Package Summary
+
+
Package
+
Description
+ +
+
This package is the parent package for all sketch families and common code areas.
+
+ +
+
This package is for common classes that may be used across all the sketch families.
+
+ +
+
This package provides the classes that define and implement a relative positional API.
+
+ +
+
This package in intended for implementations of the the Count Sketch and the Count-min Sketch both of which can be used to estimate +frequency-moments of a stream of distinct elements.
+
+ +
+
Compressed Probabilistic Counting sketch family
+
+ +
+
Frequent Distinct Tuples Sketch
+
+ +
+
The filters package contains data structures used to determine +approximate set-membership.
+
+ +
+
BloomFilter package
+
+ +
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+ +
+
The hash package contains a high-performing and extended Java implementations +of Austin Appleby's 128-bit MurmurHash3 hash function originally coded in C.
+
+ +
+
The DataSketches™ HllSketch family package
+
+ +
+
The hllmap package contains a space efficient HLL mapping sketch of keys to approximate unique +count of identifiers.
+
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+ +
+
t-Digest for estimating quantiles and ranks.
+
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+ +
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/constant-values.html b/target/site/apidocs/constant-values.html new file mode 100644 index 000000000..ef5d3ee13 --- /dev/null +++ b/target/site/apidocs/constant-values.html @@ -0,0 +1,248 @@ + + + + +Constant Field Values (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Constant Field Values

+
+
+

org.apache.*

+ +
    +
  • +
    org.apache.datasketches.cpc.CpcSketch
    +
    +
    Modifier and Type
    +
    Constant Field
    +
    Value
    +
    public static final int
    + +
    11
    +
    +
  • +
+
    +
  • +
    org.apache.datasketches.hll.HllSketch
    +
    +
    Modifier and Type
    +
    Constant Field
    +
    Value
    +
    public static final int
    + +
    12
    +
    +
  • +
+
    +
  • +
    org.apache.datasketches.kll.KllSketch
    +
    +
    Modifier and Type
    +
    Constant Field
    +
    Value
    +
    public static final int
    + +
    200
    +
    public static final int
    + +
    65535
    +
    +
  • +
+ +
    +
  • +
    org.apache.datasketches.tdigest.TDigestDouble
    +
    +
    Modifier and Type
    +
    Constant Field
    +
    Value
    +
    public static final short
    + +
    200
    +
    +
  • +
+ + +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/deprecated-list.html b/target/site/apidocs/deprecated-list.html new file mode 100644 index 000000000..4ef815db4 --- /dev/null +++ b/target/site/apidocs/deprecated-list.html @@ -0,0 +1,112 @@ + + + + +Deprecated List (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Deprecated API

+
+

Contents

+ + + +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/element-list b/target/site/apidocs/element-list new file mode 100644 index 000000000..5a14b5449 --- /dev/null +++ b/target/site/apidocs/element-list @@ -0,0 +1,26 @@ +org.apache.datasketches +org.apache.datasketches.common +org.apache.datasketches.common.positional +org.apache.datasketches.count +org.apache.datasketches.cpc +org.apache.datasketches.fdt +org.apache.datasketches.filters +org.apache.datasketches.filters.bloomfilter +org.apache.datasketches.frequencies +org.apache.datasketches.hash +org.apache.datasketches.hll +org.apache.datasketches.hllmap +org.apache.datasketches.kll +org.apache.datasketches.partitions +org.apache.datasketches.quantiles +org.apache.datasketches.quantilescommon +org.apache.datasketches.req +org.apache.datasketches.sampling +org.apache.datasketches.tdigest +org.apache.datasketches.theta +org.apache.datasketches.thetacommon +org.apache.datasketches.tuple +org.apache.datasketches.tuple.adouble +org.apache.datasketches.tuple.aninteger +org.apache.datasketches.tuple.arrayofdoubles +org.apache.datasketches.tuple.strings diff --git a/target/site/apidocs/help-doc.html b/target/site/apidocs/help-doc.html new file mode 100644 index 000000000..df187d818 --- /dev/null +++ b/target/site/apidocs/help-doc.html @@ -0,0 +1,236 @@ + + + + +API Help (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+

JavaDoc Help

+
+
+

Navigation

+Starting from the Overview page, you can browse the documentation using the links in each page, and in the navigation bar at the top of each page. The Index and Search box allow you to navigate to specific declarations and summary pages, including: All Packages, All Classes and Interfaces + +
+

Keyboard Navigation

+

Documentation pages provide keyboard shortcuts to facilitate access to common navigation tasks.

+
    +
  • Type +/ + to access the search input field in any page.
  • +
  • Type +. + to access the filter input field in the sidebar of class pages.
  • +
  • Type +Esc + to clear the input and release keyboard focus in any input field.
  • +
  • Type +Tab +/ + +/ + + to select list items after entering a search term in a search or filter input field.
  • +
  • Type + +/ + + to switch between tabs in tabbed summary tables.
  • +
+
+
+
+
+

Kinds of Pages

+The following sections describe the different kinds of pages in this collection. +
+

Overview

+

The Overview page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.

+
+
+

Package

+

Each package has a page that contains a list of its classes and interfaces, with a summary for each. These pages may contain the following categories:

+
    +
  • Interfaces
  • +
  • Classes
  • +
  • Enum Classes
  • +
  • Exception Classes
  • +
  • Annotation Interfaces
  • +
+
+
+

Class or Interface

+

Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a declaration and description, member summary tables, and detailed member descriptions. Entries in each of these sections are omitted if they are empty or not applicable.

+
    +
  • Class Inheritance Diagram
  • +
  • Direct Subclasses
  • +
  • All Known Subinterfaces
  • +
  • All Known Implementing Classes
  • +
  • Class or Interface Declaration
  • +
  • Class or Interface Description
  • +
+
+
    +
  • Nested Class Summary
  • +
  • Enum Constant Summary
  • +
  • Field Summary
  • +
  • Property Summary
  • +
  • Constructor Summary
  • +
  • Method Summary
  • +
  • Required Element Summary
  • +
  • Optional Element Summary
  • +
+
+
    +
  • Enum Constant Details
  • +
  • Field Details
  • +
  • Property Details
  • +
  • Constructor Details
  • +
  • Method Details
  • +
  • Element Details
  • +
+

Note: Annotation interfaces have required and optional elements, but not methods. Only enum classes have enum constants. The components of a record class are displayed as part of the declaration of the record class. Properties are a feature of JavaFX.

+

The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.

+
+
+

Other Files

+

Packages and modules may contain pages with additional information related to the declarations nearby.

+
+
+

Use

+

Each documented package, class or interface has its own Use page, which lists packages, classes, interfaces, methods, constructors and fields that use any part of that package, class or interface. Given a class or interface A, its Use page includes subclasses or subinterfaces of A, fields declared as A, methods that return A, methods and constructors with parameters of type A, and subclasses or subinterfaces with parameters of type A. You can access this page by first going to the package, class or interface, then clicking on the USE link in the navigation bar.

+
+
+

Tree (Class Hierarchy)

+

There is a Class Hierarchy page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. Classes are organized by inheritance structure starting with java.lang.Object. Interfaces do not inherit from java.lang.Object.

+
    +
  • When viewing the Overview page, clicking on TREE displays the hierarchy for all packages.
  • +
  • When viewing a particular package, class or interface page, clicking on TREE displays the hierarchy for only that package.
  • +
+
+
+

Deprecated API

+

The Deprecated API page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to shortcomings, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.

+
+
+

Constant Field Values

+

The Constant Field Values page lists the static final fields and their values.

+
+
+

Serialized Form

+

Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to those who implement rather than use the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See Also" section of the class description.

+
+
+

All Packages

+

The All Packages page contains an alphabetic index of all packages contained in the documentation.

+
+
+

All Classes and Interfaces

+

The All Classes and Interfaces page contains an alphabetic index of all classes and interfaces contained in the documentation, including annotation interfaces, enum classes, and record classes.

+
+
+

Index

+

The Index contains an alphabetic index of all classes, interfaces, constructors, methods, and fields in the documentation, as well as summary pages such as All Packages, All Classes and Interfaces.

+
+
+
+
+

Release Details

+

The details for each module, package, class or interface normally include the release in which the declaration was introduced.

+

When a member is added after the initial introduction of the enclosing class or interface, the details of the member include the release in which it was introduced.

+

Some summary pages (New API, Deprecated) allow you to filter the contents of the page according to the release in which the declaration was introduced or deprecated.

+
+
+This help file applies to API documentation generated by the standard doclet. +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/index-all.html b/target/site/apidocs/index-all.html new file mode 100644 index 000000000..de6d83c6b --- /dev/null +++ b/target/site/apidocs/index-all.html @@ -0,0 +1,9335 @@ + + + + +Index (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Index

+
+A B C D E F G H I J K L M N O P Q R S T U V W X Z 
All Classes and Interfaces|All Packages|Constant Field Values|Serialized Form +

A

+
+
A_NOT_B - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The A and not B family is an operation for the Theta Sketch Framework of sketches.
+
+
Advanced Estimation Algorithms for Optimum Accuracy - Section in package org.apache.datasketches.hll
+
 
+
alignedHeapSegment(int, boolean) - Static method in class org.apache.datasketches.common.Util
+
+
Request a new heap MemorySegment with the given capacityBytes and either 8-byte aligned or one byte aligned.
+
+
ALPHA - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The Alpha Sketch family is a member of the Theta Sketch Framework of sketches and is best +suited for real-time processes where both the updating of the sketch and getting the estimate +is performed directly on the sketch.
+
+
AlwaysOne - Enum constant in enum class org.apache.datasketches.tuple.adouble.DoubleSummary.Mode
+
+
The aggregation mode is always one.
+
+
AlwaysOne - Enum constant in enum class org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode
+
+
The aggregation mode is always one.
+
+
aNotB(ThetaSketch, ThetaSketch) - Method in class org.apache.datasketches.theta.ThetaAnotB
+
+
Perform A-and-not-B set operation on the two given sketches and return the result as an +ordered CompactThetaSketch on the heap.
+
+
aNotB(ThetaSketch, ThetaSketch, boolean, MemorySegment) - Method in class org.apache.datasketches.theta.ThetaAnotB
+
+
Perform A-and-not-B set operation on the two given sketches and return the result as a +CompactThetaSketch.
+
+
aNotB(TupleSketch, ThetaSketch) - Static method in class org.apache.datasketches.tuple.TupleAnotB
+
+
Returns the A-and-not-B set operation on a TupleSketch and a ThetaSketch.
+
+
aNotB(TupleSketch, TupleSketch) - Static method in class org.apache.datasketches.tuple.TupleAnotB
+
+
Returns the A-and-not-B set operation on the two given TupleSketches.
+
+
approximateLowerBoundOnP(long, long, double) - Static method in class org.apache.datasketches.common.BoundsOnBinomialProportions
+
+
Computes lower bound of approximate Clopper-Pearson confidence interval for a binomial +proportion.
+
+
approximateUpperBoundOnP(long, long, double) - Static method in class org.apache.datasketches.common.BoundsOnBinomialProportions
+
+
Computes upper bound of approximate Clopper-Pearson confidence interval for a binomial +proportion.
+
+
approxNumDeltaItems - Variable in class org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow
+
+
The approximate number of items represented by this partition description row.
+
+
ArrayOfBooleansSerDe - Class in org.apache.datasketches.common
+
+
Methods of serializing and deserializing arrays of Boolean as a bit array.
+
+
ArrayOfBooleansSerDe() - Constructor for class org.apache.datasketches.common.ArrayOfBooleansSerDe
+
+
No argument constructor.
+
+
ArrayOfDoublesAnotB - Class in org.apache.datasketches.tuple.arrayofdoubles
+
+
Computes a set difference of two tuple sketches of type ArrayOfDoubles
+
+
ArrayOfDoublesAnotBImpl - Class in org.apache.datasketches.tuple.arrayofdoubles
+
+
Computes a set difference, A-AND-NOT-B, of two ArrayOfDoublesSketches.
+
+
ArrayOfDoublesCombiner - Interface in org.apache.datasketches.tuple.arrayofdoubles
+
+
Combines two arrays of double values for use with ArrayOfDoubles tuple sketches
+
+
ArrayOfDoublesCompactSketch - Class in org.apache.datasketches.tuple.arrayofdoubles
+
+
Top level compact tuple sketch of type ArrayOfDoubles.
+
+
ArrayOfDoublesCompactSketch - Enum constant in enum class org.apache.datasketches.tuple.SerializerDeserializer.SketchType
+
+
ArrayOfDoublesCompactSketch
+
+
ArrayOfDoublesIntersection - Class in org.apache.datasketches.tuple.arrayofdoubles
+
+
Computes the intersection of two or more tuple sketches of type ArrayOfDoubles.
+
+
ArrayOfDoublesQuickSelectSketch - Enum constant in enum class org.apache.datasketches.tuple.SerializerDeserializer.SketchType
+
+
ArrayOfDoublesQuickSelectSketch
+
+
ArrayOfDoublesSerDe - Class in org.apache.datasketches.common
+
+
Methods of serializing and deserializing arrays of Double.
+
+
ArrayOfDoublesSerDe() - Constructor for class org.apache.datasketches.common.ArrayOfDoublesSerDe
+
+
No argument constructor.
+
+
ArrayOfDoublesSetOperationBuilder - Class in org.apache.datasketches.tuple.arrayofdoubles
+
+
Builds set operations object for tuple sketches of type ArrayOfDoubles.
+
+
ArrayOfDoublesSetOperationBuilder() - Constructor for class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder
+
+
Creates an instance of the builder with default parameters
+
+
ArrayOfDoublesSketch - Class in org.apache.datasketches.tuple.arrayofdoubles
+
+
The base class for the tuple sketch of type ArrayOfDoubles, where an array of double values +is associated with each key.
+
+
ArrayOfDoublesSketchIterator - Interface in org.apache.datasketches.tuple.arrayofdoubles
+
+
Interface for iterating over tuple sketches of type ArrayOfDoubles
+
+
ArrayOfDoublesUnion - Class in org.apache.datasketches.tuple.arrayofdoubles
+
+
The base class for unions of tuple sketches of type ArrayOfDoubles.
+
+
ArrayOfDoublesUnion - Enum constant in enum class org.apache.datasketches.tuple.SerializerDeserializer.SketchType
+
+
ArrayOfDoublesUnion
+
+
ArrayOfDoublesUpdatableSketch - Class in org.apache.datasketches.tuple.arrayofdoubles
+
+
The top level for updatable tuple sketches of type ArrayOfDoubles.
+
+
ArrayOfDoublesUpdatableSketchBuilder - Class in org.apache.datasketches.tuple.arrayofdoubles
+
+
For building a new ArrayOfDoublesUpdatableSketch
+
+
ArrayOfDoublesUpdatableSketchBuilder() - Constructor for class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder
+
+
Creates an instance of builder with default parameters
+
+
ArrayOfItemsSerDe<T> - Class in org.apache.datasketches.common
+
+
Base class for serializing and deserializing custom types.
+
+
ArrayOfItemsSerDe() - Constructor for class org.apache.datasketches.common.ArrayOfItemsSerDe
+
+
No argument constructor.
+
+
ArrayOfLongsSerDe - Class in org.apache.datasketches.common
+
+
Methods of serializing and deserializing arrays of Long.
+
+
ArrayOfLongsSerDe() - Constructor for class org.apache.datasketches.common.ArrayOfLongsSerDe
+
+
No argument constructor.
+
+
ArrayOfNumbersSerDe - Class in org.apache.datasketches.common
+
+
Methods of serializing and deserializing arrays of the object version of primitive types of +Number.
+
+
ArrayOfNumbersSerDe() - Constructor for class org.apache.datasketches.common.ArrayOfNumbersSerDe
+
+
No argument constructor.
+
+
ArrayOfStringsSerDe - Class in org.apache.datasketches.common
+
+
Methods of serializing and deserializing arrays of String.
+
+
ArrayOfStringsSerDe() - Constructor for class org.apache.datasketches.common.ArrayOfStringsSerDe
+
+
No argument constructor.
+
+
ArrayOfStringsSummary - Class in org.apache.datasketches.tuple.strings
+
+
Implements UpdatableSummary<String[]>
+
+
ArrayOfStringsSummaryDeserializer - Class in org.apache.datasketches.tuple.strings
+
+
Implements SummaryDeserializer<ArrayOfStringsSummary>
+
+
ArrayOfStringsSummaryDeserializer() - Constructor for class org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryDeserializer
+
+
No argument constructor.
+
+
ArrayOfStringsSummaryFactory - Class in org.apache.datasketches.tuple.strings
+
+
Implements SummaryFactory<ArrayOfStringsSummary>
+
+
ArrayOfStringsSummaryFactory() - Constructor for class org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryFactory
+
+
No argument constructor.
+
+
ArrayOfStringsSummarySetOperations - Class in org.apache.datasketches.tuple.strings
+
+
Implements SummarySetOperations<ArrayOfStringsSummary>
+
+
ArrayOfStringsSummarySetOperations() - Constructor for class org.apache.datasketches.tuple.strings.ArrayOfStringsSummarySetOperations
+
+
No argument constructor.
+
+
ArrayOfStringsTupleSketch - Class in org.apache.datasketches.tuple.strings
+
+
Extends UpdatableTupleSketch<String[], ArrayOfStringsSummary>
+
+
ArrayOfStringsTupleSketch() - Constructor for class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Constructs new sketch with default K = 4096 (lgK = 12), default ResizeFactor=X8, +and default p = 1.0.
+
+
ArrayOfStringsTupleSketch(int) - Constructor for class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Constructs new sketch with default ResizeFactor=X8, default p = 1.0 and given lgK.
+
+
ArrayOfStringsTupleSketch(int, ResizeFactor, float) - Constructor for class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Constructs new sketch with given ResizeFactor, p and lgK.
+
+
ArrayOfStringsTupleSketch(MemorySegment) - Constructor for class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Deprecated. +
As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Heapifying a CompactTupleSketch is not deprecated.
+
+
+
ArrayOfStringsTupleSketch(ArrayOfStringsTupleSketch) - Constructor for class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Copy Constructor
+
+
ArrayOfUtf16StringsSerDe - Class in org.apache.datasketches.common
+
+
Methods of serializing and deserializing arrays of String.
+
+
ArrayOfUtf16StringsSerDe() - Constructor for class org.apache.datasketches.common.ArrayOfUtf16StringsSerDe
+
+
No argument constructor.
+
+
asSlice() - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Returns a slice of this PositionalSegment at the current position.
+
+
+

B

+
+
BinarySearch - Class in org.apache.datasketches.quantilescommon
+
+
Contains common equality binary search algorithms.
+
+
BinarySearch - Class in org.apache.datasketches.tdigest
+
+
Algorithms with logarithmic complexity for searching in an array.
+
+
BinarySearch() - Constructor for class org.apache.datasketches.quantilescommon.BinarySearch
+
+
No argument constructor.
+
+
BinarySearch() - Constructor for class org.apache.datasketches.tdigest.BinarySearch
+
+
No argument constructor.
+
+
BinomialBoundsN - Class in org.apache.datasketches.thetacommon
+
+
This class enables the estimation of error bounds given a sample set size, the sampling +probability theta, the number of standard deviations and a simple noDataSeen flag.
+
+
bitAt(long, int) - Static method in class org.apache.datasketches.common.Util
+
+
Returns a one if the bit at bitPos is a one, otherwise zero.
+
+
BloomFilter - Class in org.apache.datasketches.filters.bloomfilter
+
+
A Bloom filter is a data structure that can be used for probabilistic +set membership.
+
+
BLOOMFILTER - Enum constant in enum class org.apache.datasketches.common.Family
+
+
Bloom Filter
+
+
BloomFilterBuilder - Class in org.apache.datasketches.filters.bloomfilter
+
+
This class provides methods to help estimate the correct parameters when +creating a Bloom filter, and methods to create the filter using those values.
+
+
BloomFilterBuilder() - Constructor for class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
No argument constructor.
+
+
BoundsOnBinomialProportions - Class in org.apache.datasketches.common
+
+
Confidence intervals for binomial proportions.
+
+
BoundsOnRatiosInSampledSets - Class in org.apache.datasketches.common
+
+
This class is used to compute the bounds on the estimate of the ratio |B| / |A|, where: + +|A| is the unknown size of a set A of unique identifiers. +|B| is the unknown size of a subset B of A. +a = |SA| is the observed size of a sample of A +that was obtained by Bernoulli sampling with a known inclusion probability f. +b = |SA ∩ B| is the observed size of a subset +of SA. +
+
+
BoundsOnRatiosInThetaSketchedSets - Class in org.apache.datasketches.thetacommon
+
+
This class is used to compute the bounds on the estimate of the ratio B / A, where: + +A is a Theta Sketch of population PopA. +B is a Theta Sketch of population PopB that is a subset of A, +obtained by an intersection of A with some other Theta Sketch C, +which acts like a predicate or selection clause. +The estimate of the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(A, B). +The Upper Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(A, B). +The Lower Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(A, B). + +Note: The theta of A cannot be greater than the theta of B.
+
+
BoundsOnRatiosInTupleSketchedSets - Class in org.apache.datasketches.thetacommon
+
+
This class is used to compute the bounds on the estimate of the ratio B / A, where: + +A is a Tuple Sketch of population PopA. +B is a Tuple or Theta Sketch of population PopB that is a subset of A, +obtained by an intersection of A with some other Tuple or Theta Sketch C, +which acts like a predicate or selection clause. +The estimate of the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(A, B). +The Upper Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(A, B). +The Lower Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(A, B). + +Note: The theta of A cannot be greater than the theta of B.
+
+
BoundsRule - Enum Class in org.apache.datasketches.partitions
+
+
This instructs the user about which of the upper and lower bounds of a partition definition row +should be included with the returned data.
+
+
build() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketchBuilder
+
+
Returns an UpdatableQuantilesDoublesSketch with the current configuration of this Builder.
+
+
build() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnionBuilder
+
+
Returns a new empty Union object with the current configuration of this Builder.
+
+
build() - Method in class org.apache.datasketches.req.ReqSketchBuilder
+
+
Returns a new ReqSketch with the current configuration of the builder.
+
+
build() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns an UpdatableThetaSketch with the current configuration of this Builder.
+
+
build() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder
+
+
Returns an ArrayOfDoublesUpdatableSketch with the current configuration of this Builder.
+
+
build() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketchBuilder
+
+
Returns an UpdatableTupleSketch with the current configuration of this Builder.
+
+
build(MemorySegment) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketchBuilder
+
+
Returns a UpdatableQuantilesDoublesSketch with the current configuration of this builder +and the specified backing destination MemorySegment store that can grow.
+
+
build(MemorySegment) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns an UpdatableThetaSketch with the current configuration of this Builder +with the specified backing destination MemorySegment store.
+
+
build(MemorySegment) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder
+
+
Returns an ArrayOfDoublesUpdatableSketch with the current configuration of this Builder.
+
+
build(MemorySegment, MemorySegmentRequest) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketchBuilder
+
+
Returns a UpdatableQuantilesDoublesSketch with the current configuration of this builder +and the specified backing destination MemorySegment store that can grow.
+
+
build(MemorySegment, MemorySegmentRequest) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnionBuilder
+
+
Returns a new empty Union object with the current configuration of this Builder +and the specified backing destination MemorySegment store.
+
+
build(Family) - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Returns a ThetaSetOperation with the current configuration of this Builder and the given Family.
+
+
build(Family, MemorySegment) - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Returns a ThetaSetOperation with the current configuration of this Builder, the given Family +and the given destination MemorySegment.
+
+
buildAnotB() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder
+
+
Creates an instance of ArrayOfDoublesAnotB based on the current configuration of the builder.
+
+
buildANotB() - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Convenience method, returns a configured ThetaSetOperation ANotB with +Default Update Seed
+
+
builder() - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Returns a new builder
+
+
builder() - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Returns a new UnionBuilder
+
+
builder() - Static method in class org.apache.datasketches.req.ReqSketch
+
+
Returns a new ReqSketchBuilder
+
+
builder() - Static method in class org.apache.datasketches.theta.ThetaSetOperation
+
+
Makes a new builder
+
+
builder() - Static method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Returns a new builder
+
+
buildIntersection() - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Convenience method, returns a configured ThetaIntersection with +Default Nominal Entries
+
+
buildIntersection() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder
+
+
Creates an instance of ArrayOfDoublesIntersection based on the current configuration of the +builder.
+
+
buildIntersection(MemorySegment) - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Convenience method, returns a configured ThetaIntersection with +Default Nominal Entries +and the given destination MemorySegment.
+
+
buildIntersection(MemorySegment) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder
+
+
Creates an instance of ArrayOfDoublesIntersection in the given MemorySegment and based on the +current configuration of the builder.
+
+
buildLocal(UpdatableThetaSketch) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns a local, on-heap, concurrent UpdatableThetaSketch to be used as a per-thread local buffer +along with the given concurrent shared UpdatableThetaSketch and the current configuration of this +Builder.
+
+
buildShared() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns an on-heap concurrent shared UpdatableThetaSketch with the current configuration of the +Builder.
+
+
buildShared(MemorySegment) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns a concurrent shared UpdatableThetaSketch with the current +configuration of the Builder and the given destination MemorySegment.
+
+
buildSharedFromSketch(UpdatableThetaSketch, MemorySegment) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns a direct (potentially off-heap) concurrent shared UpdatableThetaSketch with the current +configuration of the Builder, the data from the given sketch, and the given destination +MemorySegment.
+
+
buildUnion() - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Convenience method, returns a configured ThetaSetOperation ThetaUnion with +Default Nominal Entries
+
+
buildUnion() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder
+
+
Creates an instance of ArrayOfDoublesUnion based on the current configuration of the builder.
+
+
buildUnion(MemorySegment) - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Convenience method, returns a configured ThetaSetOperation ThetaUnion with +Default Nominal Entries +and the given destination MemorySegment.
+
+
buildUnion(MemorySegment) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder
+
+
Creates an instance of ArrayOfDoublesUnion based on the current configuration of the builder +and the given destination MemorySegment.
+
+
ByteArrayUtil - Class in org.apache.datasketches.common
+
+
Useful methods for byte arrays.
+
+
ByteArrayUtil() - Constructor for class org.apache.datasketches.common.ByteArrayUtil
+
+
No argument constructor.
+
+
bytesToInt(byte[]) - Static method in class org.apache.datasketches.common.Util
+
+
Returns an int extracted from a Little-Endian byte array.
+
+
bytesToLong(byte[]) - Static method in class org.apache.datasketches.common.Util
+
+
Returns a long extracted from a Little-Endian byte array.
+
+
bytesToString(byte[], boolean, boolean, String) - Static method in class org.apache.datasketches.common.Util
+
+
Returns a string view of a byte array
+
+
+

C

+
+
caseIdToCornerCase(int) - Static method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Converts caseId to CornerCaseId
+
+
ceilingMultiple2expK(long, int) - Static method in class org.apache.datasketches.common.Util
+
+
This is a long integer equivalent to Math.ceil(n / (double)(1 << k)) +where: 0 < k ≤ 6 and n is a non-negative long.
+
+
ceilingPowerBaseOfDouble(double, double) - Static method in class org.apache.datasketches.common.Util
+
+
Returns the ceiling of a given n given a base, where the ceiling is an integral power of the base.
+
+
ceilingPowerOf2(int) - Static method in class org.apache.datasketches.common.Util
+
+
Computes the int ceiling power of 2 within the range [1, 2^30].
+
+
ceilingPowerOf2(long) - Static method in class org.apache.datasketches.common.Util
+
+
Computes the long ceiling power of 2 within the range [1, 2^62].
+
+
characterPad(String, int, char, boolean) - Static method in class org.apache.datasketches.common.Util
+
+
Prepend or postpend the given string with the given character to fill the given field length.
+
+
checkBounds(long, long, long) - Static method in class org.apache.datasketches.common.Util
+
+
Check the requested offset and length against the allocated size.
+
+
checkDoublesSplitPointsOrder(double[]) - Static method in class org.apache.datasketches.quantilescommon.QuantilesUtil
+
+
Checks the sequential validity of the given array of double values.
+
+
checkFamilyID(int) - Method in enum class org.apache.datasketches.common.Family
+
+
Checks the given Family ID
+
+
checkFloatsSplitPointsOrder(float[]) - Static method in class org.apache.datasketches.quantilescommon.QuantilesUtil
+
+
Checks the sequential validity of the given array of float values.
+
+
checkHashCorruption(long) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
Checks that the given hash value is not negative.
+
+
checkIfMultipleOf8AndGT0(long, String) - Static method in class org.apache.datasketches.common.Util
+
+
Checks if parameter v is a multiple of 8 and greater than zero.
+
+
checkIfPowerOf2(long, String) - Static method in class org.apache.datasketches.common.Util
+
+
Checks the given long argument if it is a positive integer power of 2.
+
+
checkLongsSplitPointsOrder(long[]) - Static method in class org.apache.datasketches.quantilescommon.QuantilesUtil
+
+
Checks the sequential validity of the given array of double values.
+
+
checkNomLongs(int) - Static method in class org.apache.datasketches.thetacommon.ThetaUtil
+
+
Checks that the given nomLongs is within bounds and returns the Log2 of the ceiling power of 2 +of the given nomLongs.
+
+
checkNormalizedRankBounds(double) - Static method in class org.apache.datasketches.quantilescommon.QuantilesUtil
+
+
Checks that the given normalized rank: 0 ≤ nRank ≤ 1.0.
+
+
checkProbability(double, String) - Static method in class org.apache.datasketches.common.Util
+
+
Checks the given parameter to make sure it is positive and between 0.0 inclusive and 1.0 +inclusive.
+
+
checkSeedHashes(short, short) - Static method in class org.apache.datasketches.common.Util
+
+
Check if the two seed hashes are equal.
+
+
checkThetaCorruption(long) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
Checks that the given theta is not negative nor zero.
+
+
ClassicUtil - Class in org.apache.datasketches.quantiles
+
+
Utilities for the classic quantiles sketches and independent of the type.
+
+
cleanup() - Method in class org.apache.datasketches.common.MemorySegmentRequestExample
+
+
This closes any unclosed, off-heap MemorySegments and removes all mappings from the map.
+
+
clear(MemorySegment) - Static method in class org.apache.datasketches.common.Util
+
+
Clears all bytes of this MemorySegment to zero.
+
+
clear(MemorySegment, long, long) - Static method in class org.apache.datasketches.common.Util
+
+
Clears a portion of this MemorySegment to zero.
+
+
clearBits(MemorySegment, long, byte) - Static method in class org.apache.datasketches.common.Util
+
+
Clears the bits defined by the bitMask
+
+
combine(double[], double[]) - Method in interface org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCombiner
+
+
Method of combining two arrays of double values
+
+
compact() - Method in class org.apache.datasketches.quantiles.UpdatableQuantilesDoublesSketch
+
+
Returns a CompactQuantilesDoublesSketch of this class
+
+
compact() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Converts this sketch to a ordered CompactThetaSketch.
+
+
compact() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Returns this sketch in compact form, which is immutable.
+
+
compact() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Gets an on-heap compact representation of the sketch
+
+
compact() - Method in class org.apache.datasketches.tuple.CompactTupleSketch
+
 
+
compact() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Converts the current state of the sketch into a compact sketch
+
+
compact() - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
+
Converts the current state of the sketch into a compact sketch
+
+
compact() - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Converts the current state of the sketch into a compact sketch
+
+
compact() - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
+
Converts the current state of the sketch into a compact sketch
+
+
compact() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Converts the current state of the sketch into a compact sketch
+
+
compact() - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Converts this TupleSketch to a CompactTupleSketch on the Java heap.
+
+
compact(boolean, MemorySegment) - Method in class org.apache.datasketches.theta.CompactThetaSketch
+
 
+
compact(boolean, MemorySegment) - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Convert this sketch to a CompactThetaSketch.
+
+
compact(boolean, MemorySegment) - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
 
+
compact(MemorySegment) - Method in class org.apache.datasketches.quantiles.UpdatableQuantilesDoublesSketch
+
+
Returns a compact version of this sketch.
+
+
compact(MemorySegment) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Returns this sketch in compact form, which is immutable.
+
+
compact(MemorySegment) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Gets an off-heap compact representation of the sketch using the given MemorySegment
+
+
COMPACT - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The Compact Sketch family is a member of the Theta Sketch Framework of sketches.
+
+
COMPACT_EMPTY - Enum constant in enum class org.apache.datasketches.kll.KllSketch.SketchStructure
+
+
Compact Empty Structure
+
+
COMPACT_FULL - Enum constant in enum class org.apache.datasketches.kll.KllSketch.SketchStructure
+
+
Compact Full Preamble Structure
+
+
COMPACT_SINGLE - Enum constant in enum class org.apache.datasketches.kll.KllSketch.SketchStructure
+
+
Compact Single Item Structure
+
+
CompactQuantilesDoublesSketch - Class in org.apache.datasketches.quantiles
+
+
Compact sketches are inherently read only.
+
+
CompactThetaSketch - Class in org.apache.datasketches.theta
+
+
The parent class of all the CompactThetaSketches.
+
+
CompactThetaSketch() - Constructor for class org.apache.datasketches.theta.CompactThetaSketch
+
+
No argument constructor.
+
+
CompactTupleSketch<S> - Class in org.apache.datasketches.tuple
+
+
CompactTupleSketches are never created directly.
+
+
CompactTupleSketch - Enum constant in enum class org.apache.datasketches.tuple.SerializerDeserializer.SketchType
+
+
CompactTupleSketch
+
+
compareTo(Group) - Method in class org.apache.datasketches.fdt.Group
+
 
+
compareTo(FrequentItemsSketch.Row) - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch.Row
+
+
This compareTo is strictly limited to the Row.getEstimate() value and does not imply any +ordering whatsoever to the other elements of the row: item and upper and lower bounds.
+
+
compareTo(FrequentLongsSketch.Row) - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch.Row
+
+
This compareTo is strictly limited to the Row.getEstimate() value and does not imply any +ordering whatsoever to the other elements of the row: item and upper and lower bounds.
+
+
Composite Estimator - Section in package org.apache.datasketches.hll
+
 
+
CompressionCharacterization - Class in org.apache.datasketches.cpc
+
+
This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing.
+
+
CompressionCharacterization(int, int, int, int, int, int, int, PrintStream, PrintWriter) - Constructor for class org.apache.datasketches.cpc.CompressionCharacterization
+
+
Only used in test.
+
+
computeBytesNeeded(int) - Static method in class org.apache.datasketches.common.ArrayOfBooleansSerDe
+
+
Computes number of bytes needed for packed bit encoding of the array of booleans.
+
+
computeKSDelta(QuantilesDoublesAPI, QuantilesDoublesAPI) - Static method in class org.apache.datasketches.quantilescommon.KolmogorovSmirnov
+
+
Computes the raw delta between two QuantilesDoublesAPI sketches for the kolmogorovSmirnovTest(...) method.
+
+
computeKSDelta(QuantilesFloatsAPI, QuantilesFloatsAPI) - Static method in class org.apache.datasketches.quantilescommon.KolmogorovSmirnov
+
+
Computes the raw delta between two QuantilesFloatsAPI sketches for the kolmogorovSmirnovTest(...) method.
+
+
computeKSThreshold(QuantilesAPI, QuantilesAPI, double) - Static method in class org.apache.datasketches.quantilescommon.KolmogorovSmirnov
+
+
Computes the adjusted delta height threshold for the kolmogorovSmirnovTest(...) method.
+
+
computeSeedHash(long) - Static method in class org.apache.datasketches.common.Util
+
+
Computes and checks the 16-bit seed hash from the given long seed.
+
+
ConcurrentBufferInserted - Enum constant in enum class org.apache.datasketches.theta.UpdateReturnState
+
+
The hash was inserted into the local concurrent buffer, +but has not yet been propagated to the concurrent shared sketch.
+
+
ConcurrentPropagated - Enum constant in enum class org.apache.datasketches.theta.UpdateReturnState
+
+
The hash has been propagated to the concurrent shared sketch.
+
+
continueCondition(long, long) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
Return true (continue) if hash is greater than or equal to thetaLong, or if hash == 0, +or if hash == Long.MAX_VALUE.
+
+
convertToHashTable(long[], int, long, double) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
Converts the given array to a hash table.
+
+
copy() - Method in class org.apache.datasketches.fdt.FdtSketch
+
 
+
copy() - Method in class org.apache.datasketches.hll.HllSketch
+
+
Return a copy of this sketch onto the Java heap.
+
+
copy() - Method in class org.apache.datasketches.tuple.adouble.DoubleSummary
+
 
+
copy() - Method in class org.apache.datasketches.tuple.aninteger.IntegerSummary
+
 
+
copy() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsSummary
+
 
+
copy() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
 
+
copy() - Method in interface org.apache.datasketches.tuple.Summary
+
+
Deep copy.
+
+
copy() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
 
+
copyAs(TgtHllType) - Method in class org.apache.datasketches.hll.HllSketch
+
+
Return a deep copy of this sketch onto the Java heap with the specified TgtHllType.
+
+
copyBytes(byte[], int, byte[], int, int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Copies bytes from source to target with offsets on both the source and target.
+
+
copySummaryArray(S[]) - Static method in class org.apache.datasketches.tuple.Util
+
+
Will copy compact summary arrays as well as hashed summary tables (with nulls).
+
+
count(long[], long) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
Counts the cardinality of the given source array.
+
+
COUNTMIN - Enum constant in enum class org.apache.datasketches.common.Family
+
+
CountMin Sketch
+
+
CountMinSketch - Class in org.apache.datasketches.count
+
+
Java implementation of the CountMin sketch data structure of Cormode and Muthukrishnan.
+
+
countPart(long[], int, long) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
Counts the cardinality of the first Log2 values of the given source array.
+
+
CPC - Enum constant in enum class org.apache.datasketches.common.Family
+
+
Compressed Probabilistic Counting (CPC) Sketch
+
+
CpcSketch - Class in org.apache.datasketches.cpc
+
+
This is a unique-counting sketch that implements the +Compressed Probabilistic Counting (CPC, a.k.a FM85) algorithms developed by Kevin Lang in +his paper +Back to the Future: an Even More Nearly +Optimal Cardinality Estimation Algorithm.
+
+
CpcSketch() - Constructor for class org.apache.datasketches.cpc.CpcSketch
+
+
Constructor with default log_base2 of k
+
+
CpcSketch(int) - Constructor for class org.apache.datasketches.cpc.CpcSketch
+
+
Constructor with log_base2 of k.
+
+
CpcSketch(int, long) - Constructor for class org.apache.datasketches.cpc.CpcSketch
+
+
Constructor with log_base2 of k and seed.
+
+
CpcUnion - Class in org.apache.datasketches.cpc
+
+
The union (merge) operation for the CPC sketches.
+
+
CpcUnion() - Constructor for class org.apache.datasketches.cpc.CpcUnion
+
+
Construct this unioning object with the default LgK and the default update seed.
+
+
CpcUnion(int) - Constructor for class org.apache.datasketches.cpc.CpcUnion
+
+
Construct this unioning object with LgK and the default update seed.
+
+
CpcUnion(int, long) - Constructor for class org.apache.datasketches.cpc.CpcUnion
+
+
Construct this unioning object with LgK and a given seed.
+
+
CpcWrapper - Class in org.apache.datasketches.cpc
+
+
This provides a read-only view of a serialized image of a CpcSketch, which can be +on-heap or off-heap represented as a MemorySegment object, or on-heap represented as a byte array.
+
+
CpcWrapper(byte[]) - Constructor for class org.apache.datasketches.cpc.CpcWrapper
+
+
Construct a read-only view of the given byte array that contains a CpcSketch.
+
+
CpcWrapper(MemorySegment) - Constructor for class org.apache.datasketches.cpc.CpcWrapper
+
+
Construct a read-only view of the given MemorySegment that contains a CpcSketch
+
+
createByAccuracy(long, double) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using a random base seed for the hash function.
+
+
createByAccuracy(long, double, long) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using the provided base seed for the hash function.
+
+
createBySize(long, int) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Creates a BloomFilter with given number of bits and number of hash functions, +using a random base seed for the hash function.
+
+
createBySize(long, int, long) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Creates a BloomFilter with given number of bits and number of hash functions, +using the provided base seed for the hash function.
+
+
createCornerCaseId(long, int, boolean, long, int, boolean) - Static method in class org.apache.datasketches.thetacommon.SetOperationCornerCases
+
+
Creates the CornerCase ID
+
+
createEmptySketch() - Static method in class org.apache.datasketches.tuple.TupleSketch
+
+
Creates an empty CompactTupleSketch.
+
+
cumWeights - Variable in class org.apache.datasketches.quantilescommon.IncludeMinMax.DoublesPair
+
+
the array of associated cumulative weights
+
+
cumWeights - Variable in class org.apache.datasketches.quantilescommon.IncludeMinMax.FloatsPair
+
+
The array of associated cumulative weights
+
+
cumWeights - Variable in class org.apache.datasketches.quantilescommon.IncludeMinMax.ItemsPair
+
+
The array of associated cumulative weights
+
+
cumWeights - Variable in class org.apache.datasketches.quantilescommon.IncludeMinMax.LongsPair
+
+
the array of associated cumulative weights
+
+
+

D

+
+
Default() - Constructor for class org.apache.datasketches.common.MemorySegmentRequest.Default
+
+
No argument constructor that creates the target for the static member DEFAULT.
+
+
DEFAULT - Static variable in interface org.apache.datasketches.common.MemorySegmentRequest
+
+
Create Default as static member.
+
+
DEFAULT_HLL_TYPE - Static variable in class org.apache.datasketches.hll.HllSketch
+
+
The default HLL-TYPE is HLL_4
+
+
DEFAULT_K - Static variable in class org.apache.datasketches.kll.KllSketch
+
+
The default K
+
+
DEFAULT_K - Static variable in class org.apache.datasketches.tdigest.TDigestDouble
+
+
the default value of K if one is not specified
+
+
DEFAULT_LG_K - Static variable in class org.apache.datasketches.cpc.CpcSketch
+
+
The default Log_base2 of K
+
+
DEFAULT_LG_K - Static variable in class org.apache.datasketches.hll.HllSketch
+
+
The default Log_base2 of K
+
+
DEFAULT_NOMINAL_ENTRIES - Static variable in class org.apache.datasketches.thetacommon.ThetaUtil
+
+
The default nominal entries is provided as a convenience for those cases where the +nominal sketch size in number of entries is not provided.
+
+
DEFAULT_NOMINAL_ENTRIES - Static variable in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder
+
+
Default Nominal Entries (a.k.a.
+
+
DEFAULT_NUMBER_OF_VALUES - Static variable in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder
+
+
Default number of values
+
+
DEFAULT_UPDATE_SEED - Static variable in class org.apache.datasketches.common.Util
+
+
The seed 9001 used in the sketch update methods is a prime number that +was chosen very early on in experimental testing.
+
+
Degen_Degen - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Degen_Degen
+
+
Degen_Empty - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Degen_Empty
+
+
Degen_Estimation - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Degen_Estimation
+
+
Degen_Exact - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Degen_Exact
+
+
DEGEN_MIN_0_F - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction
+
+
Degenerate{MinTheta, 0, F}
+
+
DEGEN_MIN_0_F - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.IntersectAction
+
+
Degenerate{MinTheta, 0, F}
+
+
DEGEN_MIN_0_F - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Degenerate{MinTheta, 0, F}
+
+
DEGEN_THA_0_F - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction
+
+
Degenerate{ThetaA, 0, F}
+
+
DEGEN_THA_0_F - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Degenerate{ThetaA, 0, F}
+
+
DEGEN_THB_0_F - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Degenerate{ThetaB, 0, F}
+
+
desc(double[], int, int, double, int) - Method in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Optional call that describes the details of the results of the search.
+
+
desc(float[], int, int, float, int) - Method in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Optional call that describes the details of the results of the search.
+
+
desc(long[], int, int, double, int) - Method in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Optional call that describes the details of the results of the search.
+
+
desc(long[], int, int, long, int) - Method in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Optional call that describes the details of the results of the search.
+
+
deserialize(byte[], long) - Static method in class org.apache.datasketches.count.CountMinSketch
+
+
Deserializes a CountMinSketch from the provided byte array.
+
+
deserializeFromMemorySegment(MemorySegment, int) - Method in class org.apache.datasketches.common.ArrayOfBooleansSerDe
+
 
+
deserializeFromMemorySegment(MemorySegment, int) - Method in class org.apache.datasketches.common.ArrayOfDoublesSerDe
+
 
+
deserializeFromMemorySegment(MemorySegment, int) - Method in class org.apache.datasketches.common.ArrayOfItemsSerDe
+
+
Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
+
+
deserializeFromMemorySegment(MemorySegment, int) - Method in class org.apache.datasketches.common.ArrayOfLongsSerDe
+
 
+
deserializeFromMemorySegment(MemorySegment, int) - Method in class org.apache.datasketches.common.ArrayOfNumbersSerDe
+
 
+
deserializeFromMemorySegment(MemorySegment, int) - Method in class org.apache.datasketches.common.ArrayOfStringsSerDe
+
 
+
deserializeFromMemorySegment(MemorySegment, int) - Method in class org.apache.datasketches.common.ArrayOfUtf16StringsSerDe
+
 
+
deserializeFromMemorySegment(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfBooleansSerDe
+
 
+
deserializeFromMemorySegment(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfDoublesSerDe
+
 
+
deserializeFromMemorySegment(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfItemsSerDe
+
+
Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
+
+
deserializeFromMemorySegment(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfLongsSerDe
+
 
+
deserializeFromMemorySegment(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfNumbersSerDe
+
 
+
deserializeFromMemorySegment(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfStringsSerDe
+
 
+
deserializeFromMemorySegment(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfUtf16StringsSerDe
+
 
+
DeserializeResult<T> - Class in org.apache.datasketches.tuple
+
+
Returns an object and its size in bytes as a result of a deserialize operation
+
+
DeserializeResult(T, int) - Constructor for class org.apache.datasketches.tuple.DeserializeResult
+
+
Creates an instance.
+
+
DirectBitArrayR - Class in org.apache.datasketches.filters.bloomfilter
+
+
This class can maintain the BitArray object off-heap.
+
+
dissimilarityTest(ThetaSketch, ThetaSketch, double) - Static method in class org.apache.datasketches.theta.JaccardSimilarity
+
+
Tests dissimilarity of a measured ThetaSketch against an expected ThetaSketch.
+
+
dissimilarityTest(TupleSketch, ThetaSketch, S, SummarySetOperations, double) - Static method in class org.apache.datasketches.tuple.JaccardSimilarity
+
+
Tests dissimilarity of a measured TupleSketch against an expected ThetaSketch.
+
+
dissimilarityTest(TupleSketch, TupleSketch, SummarySetOperations, double) - Static method in class org.apache.datasketches.tuple.JaccardSimilarity
+
+
Tests dissimilarity of a measured TupleSketch against an expected TupleSketch.
+
+
DoublesPair(double[], long[]) - Constructor for class org.apache.datasketches.quantilescommon.IncludeMinMax.DoublesPair
+
+
Constructor.
+
+
DoublesSketchSortedView - Class in org.apache.datasketches.quantilescommon
+
+
The SortedView of the Quantiles Classic QuantilesDoublesSketch and the KllDoublesSketch.
+
+
DoublesSketchSortedView(double[], long[], QuantilesDoublesAPI) - Constructor for class org.apache.datasketches.quantilescommon.DoublesSketchSortedView
+
+
Construct from elements, also used in testing.
+
+
DoublesSortedView - Interface in org.apache.datasketches.quantilescommon
+
+
The Sorted View for quantile sketches of primitive type double.
+
+
DoublesSortedViewIterator - Class in org.apache.datasketches.quantilescommon
+
+
Iterator over quantile sketches of primitive type double.
+
+
DoublesSortedViewIterator(double[], long[]) - Constructor for class org.apache.datasketches.quantilescommon.DoublesSortedViewIterator
+
+
Constructor.
+
+
DoubleSummary - Class in org.apache.datasketches.tuple.adouble
+
+
Summary for generic tuple sketches of type Double.
+
+
DoubleSummary(DoubleSummary.Mode) - Constructor for class org.apache.datasketches.tuple.adouble.DoubleSummary
+
+
Creates an instance of DoubleSummary with a given mode.
+
+
DoubleSummary.Mode - Enum Class in org.apache.datasketches.tuple.adouble
+
+
The aggregation modes for this Summary
+
+
DoubleSummaryDeserializer - Class in org.apache.datasketches.tuple.adouble
+
+
Implements SummaryDeserializer<DoubleSummary>
+
+
DoubleSummaryDeserializer() - Constructor for class org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer
+
+
No argument constructor.
+
+
DoubleSummaryFactory - Class in org.apache.datasketches.tuple.adouble
+
+
Factory for DoubleSummary.
+
+
DoubleSummaryFactory(DoubleSummary.Mode) - Constructor for class org.apache.datasketches.tuple.adouble.DoubleSummaryFactory
+
+
Creates an instance of DoubleSummaryFactory with a given mode
+
+
DoubleSummarySetOperations - Class in org.apache.datasketches.tuple.adouble
+
+
Methods for defining how unions and intersections of two objects of type DoubleSummary +are performed.
+
+
DoubleSummarySetOperations() - Constructor for class org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations
+
+
Creates an instance with default mode of sum for both union and intersection.
+
+
DoubleSummarySetOperations(DoubleSummary.Mode) - Constructor for class org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations
+
+
Creates an instance given a DoubleSummary update mode where the mode is the same for both +union and intersection.
+
+
DoubleSummarySetOperations(DoubleSummary.Mode, DoubleSummary.Mode) - Constructor for class org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations
+
+
Creates an instance with two modes.
+
+
doubleToLongArray(double) - Static method in class org.apache.datasketches.tuple.Util
+
+
Converts a double to a long[].
+
+
DoubleTupleSketch - Class in org.apache.datasketches.tuple.adouble
+
+
Extends UpdatableTupleSketch<Double, DoubleSummary>
+
+
DoubleTupleSketch(int, int, float, DoubleSummary.Mode) - Constructor for class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
+
Creates this sketch with the following parameters:
+
+
DoubleTupleSketch(int, DoubleSummary.Mode) - Constructor for class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
+
Constructs this sketch with given lgK.
+
+
DoubleTupleSketch(MemorySegment, DoubleSummary.Mode) - Constructor for class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
+
Deprecated. +
As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Heapifying a CompactTupleSketch is not deprecated.
+
+
+
downSample(int) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
From an existing sketch, this creates a new sketch that can have a smaller K.
+
+
downSample(QuantilesDoublesSketch, int, MemorySegment, MemorySegmentRequest) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
From an source sketch, create a new sketch that must have a smaller K.
+
+
+

E

+
+
EBPPS - Enum constant in enum class org.apache.datasketches.common.Family
+
+
Exact and Bounded, Probability Proportional to Size (EBPPS)
+
+
EbppsItemsSketch<T> - Class in org.apache.datasketches.sampling
+
+
An implementation of an Exact and Bounded Sampling Proportional to Size sketch.
+
+
EbppsItemsSketch(int) - Constructor for class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Constructor
+
+
emitAdjSecSizeNumSec(byte) - Method in interface org.apache.datasketches.req.ReqDebug
+
+
Emit adjusting section size and number of sections.
+
+
emitAllHorizList() - Method in interface org.apache.datasketches.req.ReqDebug
+
+
Emit all horizontal lists
+
+
emitCompactingStart(byte) - Method in interface org.apache.datasketches.req.ReqDebug
+
+
Emit Compaction Start.
+
+
emitCompactionDetail(int, int, int, int, boolean) - Method in interface org.apache.datasketches.req.ReqDebug
+
+
Emit Compaction details.
+
+
emitCompactionDone(byte) - Method in interface org.apache.datasketches.req.ReqDebug
+
+
Emit compaction done and number of compactions so far.
+
+
emitCompressDone() - Method in interface org.apache.datasketches.req.ReqDebug
+
+
Emit compress done.
+
+
emitMustAddCompactor() - Method in interface org.apache.datasketches.req.ReqDebug
+
+
Emit Must add compactor
+
+
emitNewCompactor(byte) - Method in interface org.apache.datasketches.req.ReqDebug
+
+
Emit new compactor configuration
+
+
emitStart(ReqSketch) - Method in interface org.apache.datasketches.req.ReqDebug
+
+
Emit the start signal
+
+
emitStartCompress() - Method in interface org.apache.datasketches.req.ReqDebug
+
+
Emit Start Compress
+
+
EMPTY_1_0_T - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction
+
+
Empty{1.0, 0, T}
+
+
EMPTY_1_0_T - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.IntersectAction
+
+
Empty{1.0, 0, T
+
+
EMPTY_1_0_T - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Empty{1.0, 0, T}
+
+
Empty_Degen - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Empty Degen
+
+
Empty_Empty - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Empty Empty
+
+
Empty_Estimation - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Empty Estimation
+
+
Empty_Exact - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Empty Exact
+
+
EMPTY_MSG - Static variable in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
The sketch must not be empty for this operation.
+
+
EQ - Enum constant in enum class org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality
+
+
Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the adjacent pair of +values {A,B} such that A ≤ V ≤ B.
+
+
EQ - Enum constant in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the adjacent pair of +values {A,B} such that A ≤ V ≤ B.
+
+
equalContents(MemorySegment, long, MemorySegment, long, long) - Static method in class org.apache.datasketches.common.Util
+
+
Returns true if both segments have the same content for the specified region.
+
+
equalContents(MemorySegment, MemorySegment) - Static method in class org.apache.datasketches.common.Util
+
+
Returns true if both segments have the same contents and the same length.
+
+
equallySpacedDoubles(int) - Static method in class org.apache.datasketches.quantilescommon.QuantilesUtil
+
+
Returns an array of (num + 1) values that define equally sized intervals between 0.0, inclusive, and 1.0, +inclusive.
+
+
equallySpacedLongs(long, long, int) - Static method in class org.apache.datasketches.quantilescommon.QuantilesUtil
+
+
Returns an array of (num + 1) longs that define, approximately, equally spaced intervals between the given +max, inclusive, and min, inclusive.
+
+
equals(Object) - Method in class org.apache.datasketches.fdt.Group
+
 
+
equals(Object) - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch.Row
+
+
This equals is computed only from the Row.getEstimate() value and does not imply equality +of the other items within the row: item and upper and lower bounds.
+
+
equals(Object) - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch.Row
+
+
This equals is computed only from the Row.getEstimate() value and does not imply equality +of the other items within the row: item and upper and lower bounds.
+
+
equals(Object) - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsSummary
+
 
+
erf(double) - Static method in class org.apache.datasketches.common.BoundsOnBinomialProportions
+
+
Computes an approximation to the erf() function.
+
+
ErrorType - Enum Class in org.apache.datasketches.frequencies
+
+
Specifies one of two types of error regions of the statistical classification Confusion Matrix +that can be excluded from a returned sample of Frequent Items.
+
+
estimateSubsetSum(Predicate) - Method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Computes an estimated subset sum from the entire stream for objects matching a given +predicate.
+
+
estimateSubsetSum(Predicate) - Method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Computes an estimated subset sum from the entire stream for objects matching a given +predicate.
+
+
estimateSubsetSum(Predicate) - Method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Computes an estimated subset sum from the entire stream for objects matching a given +predicate.
+
+
estimateUnknownP(long, long) - Static method in class org.apache.datasketches.common.BoundsOnBinomialProportions
+
+
Computes an estimate of an unknown binomial proportion.
+
+
Estimation_Degen - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Estimation_Degen
+
+
Estimation_Empty - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Estimation_Empty
+
+
Estimation_Estimation - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Estimation_Estimation
+
+
Estimation_Exact - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Estimation_Exact
+
+
evenlyLogSpaced(double, double, int) - Static method in class org.apache.datasketches.quantilescommon.QuantilesUtil
+
+
Returns a double array of values between min and max inclusive where the log of the +returned values are evenly spaced.
+
+
evenlySpacedDoubles(double, double, int) - Static method in class org.apache.datasketches.quantilescommon.QuantilesUtil
+
+
Returns a double array of evenly spaced values between value1, inclusive, and value2 inclusive.
+
+
evenlySpacedFloats(float, float, int) - Static method in class org.apache.datasketches.quantilescommon.QuantilesUtil
+
+
Returns a float array of evenly spaced values between value1, inclusive, and value2 inclusive.
+
+
Exact_Degen - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Exact Degen
+
+
Exact_Empty - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Exact Empty
+
+
Exact_Estimation - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Exact Estimation
+
+
Exact_Exact - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Exact Exact
+
+
exactLog2OfInt(int) - Static method in class org.apache.datasketches.common.Util
+
+
Returns the log2 of the given int value if it is an exact power of 2 and greater than zero.
+
+
exactLog2OfInt(int, String) - Static method in class org.apache.datasketches.common.Util
+
+
Returns the log2 of the given int value if it is an exact power of 2 and greater than zero.
+
+
exactLog2OfLong(long) - Static method in class org.apache.datasketches.common.Util
+
+
Returns the log2 of the given long value if it is an exact power of 2 and greater than zero.
+
+
exactLog2OfLong(long, String) - Static method in class org.apache.datasketches.common.Util
+
+
Returns the log2 of the given long value if it is an exact power of 2 and greater than zero.
+
+
exactlyEqual(ThetaSketch, ThetaSketch) - Static method in class org.apache.datasketches.theta.JaccardSimilarity
+
+
Returns true if the two given sketches have exactly the same hash values and the same +theta values.
+
+
exactlyEqual(TupleSketch, ThetaSketch, S, SummarySetOperations) - Static method in class org.apache.datasketches.tuple.JaccardSimilarity
+
+
Returns true if the two given sketches have exactly the same hash values and the same +theta values.
+
+
exactlyEqual(TupleSketch, TupleSketch, SummarySetOperations) - Static method in class org.apache.datasketches.tuple.JaccardSimilarity
+
+
Returns true if the two given sketches have exactly the same hash values and the same +theta values.
+
+
EXCLUSIVE - Enum constant in enum class org.apache.datasketches.quantilescommon.QuantileSearchCriteria
+
+
Definition of EXCLUSIVE getQuantile(r) search:
+Given rank r, return the quantile of the smallest rank that is +strictly greater than r.
+
+
+

F

+
+
Family - Enum Class in org.apache.datasketches.common
+
+
Defines the various families of sketch and set operation classes.
+
+
fastWrap(MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaUnion
+
+
Wrap a ThetaUnion object around a ThetaUnion MemorySegment object containing data.
+
+
fastWrap(MemorySegment, long) - Static method in class org.apache.datasketches.theta.ThetaUnion
+
+
Wrap a ThetaUnion object around a ThetaUnion MemorySegment object containing data.
+
+
FdtSketch - Class in org.apache.datasketches.fdt
+
+
A Frequent Distinct Tuples sketch.
+
+
FdtSketch(double, double) - Constructor for class org.apache.datasketches.fdt.FdtSketch
+
+
Create a new instance of Frequent Distinct Tuples sketch with a size determined by the given +threshold and rse.
+
+
FdtSketch(int) - Constructor for class org.apache.datasketches.fdt.FdtSketch
+
+
Create new instance of Frequent Distinct Tuples sketch with the given +Log-base2 of required nominal entries.
+
+
FdtSketch(FdtSketch) - Constructor for class org.apache.datasketches.fdt.FdtSketch
+
+
Copy Constructor
+
+
fill(MemorySegment, long, long, byte) - Static method in class org.apache.datasketches.common.Util
+
+
Fills a portion of this Memory region to the given byte value.
+
+
filter(TupleSketch) - Method in class org.apache.datasketches.tuple.Filter
+
+
Filters elements on the provided TupleSketch
+
+
Filter<T> - Class in org.apache.datasketches.tuple
+
+
Class for filtering entries from a TupleSketch given a Summary
+
+
Filter(Predicate) - Constructor for class org.apache.datasketches.tuple.Filter
+
+
Filter constructor with a Predicate
+
+
find(double[], int, int, double) - Static method in class org.apache.datasketches.quantilescommon.BinarySearch
+
+
Binary Search for the index of the exact double value in the given search range.
+
+
find(double[], int, int, double, InequalitySearch) - Static method in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Binary Search for the index of the double value in the given search range that satisfies +the given InequalitySearch criterion.
+
+
find(float[], int, int, float) - Static method in class org.apache.datasketches.quantilescommon.BinarySearch
+
+
Binary Search for the index of the exact float value in the given search range.
+
+
find(float[], int, int, float, InequalitySearch) - Static method in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Binary Search for the index of the float value in the given search range that satisfies +the given InequalitySearch criterion.
+
+
find(long[], int, int, double, InequalitySearch) - Static method in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Binary Search for the index of the double value in the given search range that satisfies +the given InequalitySearch criterion.
+
+
find(long[], int, int, long) - Static method in class org.apache.datasketches.quantilescommon.BinarySearch
+
+
Binary Search for the index of the exact long value in the given search range.
+
+
find(long[], int, int, long, InequalitySearch) - Static method in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Binary Search for the index of the long value in the given search range that satisfies +the given InequalitySearch criterion.
+
+
find(T[], int, int, T, GenericInequalitySearch.Inequality, Comparator) - Static method in class org.apache.datasketches.quantilescommon.GenericInequalitySearch
+
+
Binary Search for the index of the generic value in the given search range that satisfies +the given Inequality criterion.
+
+
FloatsPair(float[], long[]) - Constructor for class org.apache.datasketches.quantilescommon.IncludeMinMax.FloatsPair
+
+
Constructor.
+
+
FloatsSketchSortedView - Class in org.apache.datasketches.quantilescommon
+
+
The SortedView for the KllFloatsSketch and the ReqSketch.
+
+
FloatsSketchSortedView(float[], long[], QuantilesFloatsAPI) - Constructor for class org.apache.datasketches.quantilescommon.FloatsSketchSortedView
+
+
Construct Sorted View.
+
+
FloatsSortedView - Interface in org.apache.datasketches.quantilescommon
+
+
The Sorted View for quantiles of primitive type float.
+
+
FloatsSortedViewIterator - Class in org.apache.datasketches.quantilescommon
+
+
Iterator over quantile sketches of primitive type float.
+
+
FloatsSortedViewIterator(float[], long[]) - Constructor for class org.apache.datasketches.quantilescommon.FloatsSortedViewIterator
+
+
Constructor.
+
+
floorPowerBaseOfDouble(double, double) - Static method in class org.apache.datasketches.common.Util
+
+
Computes the floor of a given n given base, where the floor is an integral power of the base.
+
+
floorPowerOf2(int) - Static method in class org.apache.datasketches.common.Util
+
+
Computes the floor power of 2 given n is in the range [1, 2^31-1].
+
+
floorPowerOf2(long) - Static method in class org.apache.datasketches.common.Util
+
+
Computes the floor power of 2 given n is in the range [1, 2^63-1].
+
+
FREQUENCY - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The Frequency family of sketches.
+
+
FrequentItemsSketch<T> - Class in org.apache.datasketches.frequencies
+
+
This sketch is based on the paper https://arxiv.org/abs/1705.07001 +("A High-Performance Algorithm for Identifying Frequent Items in Data Streams" +by Daniel Anderson, Pryce Bevan, Kevin Lang, Edo Liberty, Lee Rhodes, and Justin Thaler) +and is useful for tracking approximate frequencies of items of type <T> +with optional associated counts (<T> item, long count) that are members of a +multiset of such items.
+
+
FrequentItemsSketch(int) - Constructor for class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Construct this sketch with the parameter maxMapSize and the default initialMapSize (8).
+
+
FrequentItemsSketch.Row<T> - Class in org.apache.datasketches.frequencies
+
+
Row class that defines the return values from a getFrequentItems query.
+
+
FrequentLongsSketch - Class in org.apache.datasketches.frequencies
+
+
This sketch is based on the paper https://arxiv.org/abs/1705.07001 +("A High-Performance Algorithm for Identifying Frequent Items in Data Streams" +by Daniel Anderson, Pryce Bevan, Kevin Lang, Edo Liberty, Lee Rhodes, and Justin Thaler) +and is useful for tracking approximate frequencies of long items with optional +associated counts (long item, long count) that are members of a multiset of +such items.
+
+
FrequentLongsSketch(int) - Constructor for class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Construct this sketch with the parameter maxMapSize and the default initialMapSize (8).
+
+
FrequentLongsSketch.Row - Class in org.apache.datasketches.frequencies
+
+
Row class that defines the return values from a getFrequentItems query.
+
+
fromMemorySegment(MemorySegment) - Static method in class org.apache.datasketches.tuple.adouble.DoubleSummary
+
+
Creates an instance of the DoubleSummary given a serialized representation
+
+
fromMemorySegment(MemorySegment) - Static method in class org.apache.datasketches.tuple.aninteger.IntegerSummary
+
+
Creates an instance of the IntegerSummary given a serialized representation
+
+
fromOrdinal(int) - Static method in enum class org.apache.datasketches.hll.TgtHllType
+
+
Convert the typeId to the enum type
+
+
FULL_ANOTB - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction
+
+
Full AnotB
+
+
FULL_INTERSECT - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.IntersectAction
+
+
Full Intersect
+
+
FULL_UNION - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Full Union
+
+
+

G

+
+
GE - Enum constant in enum class org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality
+
+
Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the lowest adjacent pair of +values {A,B} such that A < V ≤ B.
+Let low = index of the lowest value in the range.
+Let high = index of the highest value in the range.
+
+
GE - Enum constant in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the lowest adjacent pair of +values {A,B} such that A < V ≤ B.
+Let low = index of the lowest value in the range.
+Let high = index of the highest value in the range.
+
+
GenericInequalitySearch - Class in org.apache.datasketches.quantilescommon
+
+
This provides efficient, unique and unambiguous binary searching for inequality comparison criteria +for ordered arrays of values that may include duplicate values.
+
+
GenericInequalitySearch() - Constructor for class org.apache.datasketches.quantilescommon.GenericInequalitySearch
+
+
No argument constructor.
+
+
GenericInequalitySearch.Inequality - Enum Class in org.apache.datasketches.quantilescommon
+
+
The enumerator of inequalities
+
+
GenericPartitionBoundaries<T> - Class in org.apache.datasketches.quantilescommon
+
+
This defines the returned results of the getParitionBoundaries() function and +includes the basic methods needed to construct actual partitions.
+
+
GenericPartitionBoundaries(long, T[], long[], double[], T, T, QuantileSearchCriteria) - Constructor for class org.apache.datasketches.quantilescommon.GenericPartitionBoundaries
+
+
Constructor.
+
+
GenericSortedView<T> - Interface in org.apache.datasketches.quantilescommon
+
+
The Sorted View for quantiles of generic type.
+
+
GenericSortedViewIterator<T> - Class in org.apache.datasketches.quantilescommon
+
+
Iterator over quantile sketches of generic type.
+
+
GenericSortedViewIterator(T[], long[]) - Constructor for class org.apache.datasketches.quantilescommon.GenericSortedViewIterator
+
+
Constructor
+
+
get() - Method in interface org.apache.datasketches.theta.HashIterator
+
+
Gets the hash value
+
+
getActionDescription() - Method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction
+
+
Gets the action description
+
+
getActionDescription() - Method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.IntersectAction
+
+
Gets the Action Description
+
+
getActionDescription() - Method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Gets the action description
+
+
getActionId() - Method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction
+
+
Gets the Action ID
+
+
getActionId() - Method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.IntersectAction
+
+
Gets the Action ID
+
+
getActionId() - Method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Gets the action ID
+
+
getActiveEntries() - Method in class org.apache.datasketches.hllmap.UniqueCountMap
+
+
Returns the number of active, unique keys across all internal maps
+
+
getAnotbAction() - Method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Gets the AnotB action
+
+
getAprioriError(int, long) - Static method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns the estimated a priori error given the maxMapSize for the sketch and the +estimatedTotalStreamWeight.
+
+
getAprioriError(int, long) - Static method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns the estimated a priori error given the maxMapSize for the sketch and the +estimatedTotalStreamWeight.
+
+
getAverageSketchBytesPerKey() - Method in class org.apache.datasketches.hllmap.UniqueCountMap
+
+
Returns the average bytes storage per key that is dedicated to sketching the unique counts.
+
+
getBitsUsed() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Returns the number of bits in the BloomFilter that are set to 1.
+
+
getBoolean() - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the boolean value at the current position.
+
+
getBoolean(long) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the boolean value at the given offset.
+
+
getBoundaries() - Method in class org.apache.datasketches.quantilescommon.GenericPartitionBoundaries
+
+
Gets an ordered array of boundaries that sequentially define the upper and lower boundaries of partitions.
+
+
getByte() - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the byte value at the current position.
+
+
getByte(long) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the byte value at the given offset.
+
+
getByteArray(byte[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the byte array at the current position.
+
+
getBytes() - Method in enum class org.apache.datasketches.kll.KllSketch.SketchType
+
+
Gets the item size in bytes.
+
+
getC() - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Returns the expected number of samples returned upon a call to +getResult().
+
+
getCapacity() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Returns the total number of bits in the BloomFilter.
+
+
getCaseDescription() - Method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Gets the case description
+
+
getCDF(double[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
This is equivalent to getCDF(splitPoints, INCLUSIVE)
+
+
getCDF(double[]) - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Returns an approximation to the Cumulative Distribution Function (CDF), which is the +cumulative analog of the PMF, of the input stream given a set of split points.
+
+
getCDF(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
 
+
getCDF(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getCDF(double[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.DoublesSortedView
+
+
Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getCDF(double[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getCDF(float[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
This is equivalent to getCDF(splitPoints, INCLUSIVE)
+
+
getCDF(float[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
 
+
getCDF(float[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.FloatsSortedView
+
+
Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getCDF(float[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getCDF(float[], QuantileSearchCriteria) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getCDF(long[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
This is equivalent to getCDF(splitPoints, INCLUSIVE)
+
+
getCDF(long[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
 
+
getCDF(long[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.LongsSortedView
+
+
Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getCDF(long[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getCDF(T[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
This is equivalent to getCDF(splitPoints, INCLUSIVE)
+
+
getCDF(T[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getCDF(T[], QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getCDF(T[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.GenericSortedView
+
+
Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getCDF(T[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getChar() - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the char value at the current position.
+
+
getChar(long) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the char value at the given offset.
+
+
getCharArray(char[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the char array at the current position.
+
+
getClassOfT() - Method in class org.apache.datasketches.common.ArrayOfBooleansSerDe
+
 
+
getClassOfT() - Method in class org.apache.datasketches.common.ArrayOfDoublesSerDe
+
 
+
getClassOfT() - Method in class org.apache.datasketches.common.ArrayOfItemsSerDe
+
+
Returns the concrete class of type T
+
+
getClassOfT() - Method in class org.apache.datasketches.common.ArrayOfLongsSerDe
+
 
+
getClassOfT() - Method in class org.apache.datasketches.common.ArrayOfNumbersSerDe
+
 
+
getClassOfT() - Method in class org.apache.datasketches.common.ArrayOfStringsSerDe
+
 
+
getClassOfT() - Method in class org.apache.datasketches.common.ArrayOfUtf16StringsSerDe
+
 
+
getClassOfT() - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getClassOfT() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getClassOfT() - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Returns the sketch item class
+
+
getCompactBytes() - Method in class org.apache.datasketches.theta.CompactThetaSketch
+
 
+
getCompactBytes() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns the number of storage bytes required for this ThetaSketch if its current state were +compacted.
+
+
getCompactBytes() - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
 
+
getCompactSerialiedSizeBytes(int, long) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Returns the number of bytes a QuantilesDoublesSketch would require to store in compact form +given k and n.
+
+
getCompactSerializationBytes() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
getCompactSerializationBytes() - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
getCompactSketchMaxBytes(int) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns the maximum number of storage bytes required for a CompactThetaSketch given the configured +log_base2 of the number of nominal entries, which is a power of 2.
+
+
getComparator() - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getComparator() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getComparator() - Method in interface org.apache.datasketches.quantilescommon.GenericSortedView
+
+
Gets the Comparator for this generic type.
+
+
getComparator() - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
getComparator() - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Returns the Comparator of T
+
+
getCompositeEstimate() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
getCompositeEstimate() - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
getConCurLgNominalEntries() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns local Log-base 2 Nominal Entries for the concurrent local sketch
+
+
getCount() - Method in class org.apache.datasketches.fdt.Group
+
+
Returns the count
+
+
getCountLessThanThetaLong(long) - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Gets the number of hash values less than the given theta expressed as a long.
+
+
getCountLessThanThetaLong(long) - Method in class org.apache.datasketches.tuple.CompactTupleSketch
+
 
+
getCountLessThanThetaLong(long) - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
 
+
getCountLessThanThetaLong(long) - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
 
+
getCountLessThanThetaLong(long) - Method in class org.apache.datasketches.fdt.FdtSketch
+
 
+
getCountLessThanThetaLong(long) - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
 
+
getCountLessThanThetaLong(long) - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
 
+
getCountLessThanThetaLong(long) - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Gets the number of hash values less than the given theta expressed as a long.
+
+
getCumulativeWeight() - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Returns the cumulative weight of items processed by the sketch.
+
+
getCumulativeWeights() - Method in class org.apache.datasketches.quantilescommon.DoublesSketchSortedView
+
 
+
getCumulativeWeights() - Method in class org.apache.datasketches.quantilescommon.FloatsSketchSortedView
+
 
+
getCumulativeWeights() - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
getCumulativeWeights() - Method in class org.apache.datasketches.quantilescommon.LongsSketchSortedView
+
 
+
getCumulativeWeights() - Method in interface org.apache.datasketches.quantilescommon.SortedView
+
+
Returns the array of cumulative weights from the sketch.
+
+
getCurrentBytes() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns the number of storage bytes required for this sketch in its current state.
+
+
getCurrentBytes() - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Returns the number of storage bytes required for this union in its current state.
+
+
getCurrentBytes() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCompactSketch
+
 
+
getCurrentBytes() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
For compact sketches this is the same as getMaxBytes().
+
+
getCurrentCapacity() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Get current capacity
+
+
getCurrentCapacity() - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
+
Get current capacity
+
+
getCurrentCapacity() - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Get current capacity
+
+
getCurrentCapacity() - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
+
Get current capacity
+
+
getCurrentCapacity() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Get current capacity
+
+
getCurrentCompactSerializedSizeBytes() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Returns the current number of bytes this sketch would require to store in the compact MemorySegment Format.
+
+
getCurrentMapCapacity() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns the current number of counters the sketch is configured to support.
+
+
getCurrentMapCapacity() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns the current number of counters the sketch is configured to support.
+
+
getCurrentUpdatableSerializedSizeBytes() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Returns the current number of bytes this sketch would require to store in the updatable MemorySegment Format.
+
+
getDouble() - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the double value at the current position.
+
+
getDouble(long) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the double value at the given offset.
+
+
getDoubleArray(double[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the double array at the current position.
+
+
getDoubleBE(byte[], int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Get a double from the given byte array starting at the given offset +in big endian order.
+
+
getDoubleLE(byte[], int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Get a double from the given byte array starting at the given offset +in little endian order.
+
+
getEffectiveK() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Returns the effective k of this Union.
+
+
getEffectiveK() - Method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Returns the effective k of this Union.
+
+
getEnd() - Method in interface org.apache.datasketches.common.positional.Positional
+
+
Gets the end position
+
+
getEpsilon(int) - Static method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns epsilon used to compute a priori error.
+
+
getEpsilon(int) - Static method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns epsilon used to compute a priori error.
+
+
getEstimate() - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Returns the best estimate of the cardinality of the sketch.
+
+
getEstimate() - Method in class org.apache.datasketches.cpc.CpcWrapper
+
+
Returns the best estimate of the cardinality of the sketch.
+
+
getEstimate() - Method in class org.apache.datasketches.fdt.Group
+
+
Returns the estimate
+
+
getEstimate() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch.Row
+
+
Returns the estimate
+
+
getEstimate() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch.Row
+
+
Returns the estimate
+
+
getEstimate() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
getEstimate() - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
getEstimate() - Method in class org.apache.datasketches.sampling.SampleSubsetSummary
+
+
Returns the unique count estimate
+
+
getEstimate() - Method in class org.apache.datasketches.theta.CompactThetaSketch
+
 
+
getEstimate() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Gets the unique count estimate.
+
+
getEstimate() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Estimates the cardinality of the set (number of unique values presented to the sketch)
+
+
getEstimate() - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Estimates the cardinality of the set (number of unique values presented to the sketch)
+
+
getEstimate(byte[]) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the estimated frequency for the given item.
+
+
getEstimate(byte[]) - Method in class org.apache.datasketches.hllmap.UniqueCountMap
+
+
Retrieves the current estimate of unique count for a given key.
+
+
getEstimate(int) - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Gets the estimate of the true distinct population of subset tuples represented by the count +of entries in a subset of the total retained entries of the sketch.
+
+
getEstimate(long) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the estimated frequency for the given item.
+
+
getEstimate(long) - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Gets the estimate of the frequency of the given item.
+
+
getEstimate(MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Gets the estimate from the given MemorySegment
+
+
getEstimate(String) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the estimated frequency for the given item.
+
+
getEstimate(T) - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Gets the estimate of the frequency of the given item.
+
+
getEstimateOfA(long, double) - Static method in class org.apache.datasketches.common.BoundsOnRatiosInSampledSets
+
+
Return the estimate of A.
+
+
getEstimateOfB(long, double) - Static method in class org.apache.datasketches.common.BoundsOnRatiosInSampledSets
+
+
Return the estimate of B.
+
+
getEstimateOfBoverA(long, long) - Static method in class org.apache.datasketches.common.BoundsOnRatiosInSampledSets
+
+
Return the estimate of b over a
+
+
getEstimateOfBoverA(ThetaSketch, ThetaSketch) - Static method in class org.apache.datasketches.thetacommon.BoundsOnRatiosInThetaSketchedSets
+
+
Gets the estimate for B over A
+
+
getEstimateOfBoverA(TupleSketch, ThetaSketch) - Static method in class org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets
+
+
Gets the estimate for B over A
+
+
getEstimateOfBoverA(TupleSketch, TupleSketch) - Static method in class org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets
+
+
Gets the estimate for B over A
+
+
getFamily() - Static method in class org.apache.datasketches.cpc.CpcSketch
+
+
Return the DataSketches identifier for this CPC family of sketches.
+
+
getFamily() - Static method in class org.apache.datasketches.cpc.CpcUnion
+
+
Return the DataSketches identifier for this CPC family of sketches.
+
+
getFamily() - Static method in class org.apache.datasketches.cpc.CpcWrapper
+
+
Return the DataSketches identifier for this CPC family of sketches.
+
+
getFamily() - Method in class org.apache.datasketches.theta.CompactThetaSketch
+
 
+
getFamily() - Method in class org.apache.datasketches.theta.ThetaAnotB
+
 
+
getFamily() - Method in class org.apache.datasketches.theta.ThetaIntersection
+
 
+
getFamily() - Method in class org.apache.datasketches.theta.ThetaSetOperation
+
+
Gets the Family of this ThetaSetOperation
+
+
getFamily() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns the Family that this sketch belongs to
+
+
getFamily() - Method in class org.apache.datasketches.theta.ThetaUnion
+
 
+
getFamily() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns the local Family
+
+
getFamilyName() - Method in enum class org.apache.datasketches.common.Family
+
+
Returns the name for this family
+
+
getFillPercentage() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Returns the percentage of all bits in the BloomFilter set to 1.
+
+
getFloat() - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the float value at the current position.
+
+
getFloat(long) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the float value at the given offset.
+
+
getFloatArray(float[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the float array at the current position.
+
+
getFloatBE(byte[], int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Get a float from the given byte array starting at the given offset +in big endian order.
+
+
getFloatLE(byte[], int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Get a float from the given byte array starting at the given offset +in little endian order.
+
+
getFraction() - Method in class org.apache.datasketches.fdt.Group
+
+
Returns the fraction for this group
+
+
getFrequentItems(long, ErrorType) - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns an array of Rows that include frequent items, estimates, upper and lower bounds +given a threshold and an ErrorCondition.
+
+
getFrequentItems(long, ErrorType) - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns an array of Rows that include frequent items, estimates, upper and lower bounds +given a threshold and an ErrorCondition.
+
+
getFrequentItems(ErrorType) - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns an array of Rows that include frequent items, estimates, upper and lower bounds +given an ErrorCondition and the default threshold.
+
+
getFrequentItems(ErrorType) - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns an array of Rows that include frequent items, estimates, upper and lower bounds +given an ErrorCondition and the default threshold.
+
+
getGroupCount() - Method in class org.apache.datasketches.fdt.PostProcessor
+
+
Returns the number of groups in the final sketch.
+
+
getGroupList(int[], int, int) - Method in class org.apache.datasketches.fdt.PostProcessor
+
+
Return the most frequent Groups associated with Primary Keys based on the size of the groups.
+
+
getHash() - Method in class org.apache.datasketches.tuple.TupleSketchIterator
+
+
Gets the hash from the current entry in the sketch, which is a hash +of the original key passed to update().
+
+
getHeader() - Method in class org.apache.datasketches.fdt.Group
+
+
Returns the descriptive header
+
+
getHighRankAccuracy() - Method in class org.apache.datasketches.req.ReqSketchBuilder
+
+
Gets the builder configured High Rank Accuracy.
+
+
getHighRankAccuracyMode() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getId() - Method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Gets the case ID
+
+
getID() - Method in enum class org.apache.datasketches.common.Family
+
+
Returns the byte ID for this family
+
+
getInstance(long) - Static method in interface org.apache.datasketches.common.positional.Positional
+
+
Gets an instance of this Positional.
+
+
getInstance(Class, int, Comparator) - Static method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Obtains a new instance of an QuantilesItemsSketch using the given k.
+
+
getInstance(Class, int, Comparator) - Static method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Create an instance of QuantilesItemsUnion
+
+
getInstance(Class, Comparator) - Static method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Obtains a new instance of an QuantilesItemsSketch using the DEFAULT_K.
+
+
getInstance(Class, Comparator) - Static method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Create an instance of QuantilesItemsUnion with the default k.
+
+
getInstance(MemorySegment) - Static method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
+
+
getInstance(MemorySegment, ArrayOfItemsSerDe) - Static method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
+
+
getInstance(String) - Static method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns a sketch instance of this class from the given String, +which must be a String representation of this sketch class.
+
+
getInt() - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the int value at the current position.
+
+
getInt(long) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the int value at the given offset.
+
+
getIntArray(int[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the int array at the current position.
+
+
getIntBE(byte[], int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Get a int from the given byte array starting at the given offset +in big endian order.
+
+
getIntersectAction() - Method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Gets the intersect action
+
+
getIntLE(byte[], int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Get a int from the given byte array starting at the given offset +in little endian order.
+
+
getItem() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch.Row
+
+
Returns an item of type T
+
+
getItem() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch.Row
+
+
Returns item of type long
+
+
getItem() - Method in class org.apache.datasketches.sampling.VarOptItemsSamples.WeightedSample
+
+
Accesses the iterator's current object
+
+
getK() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getK() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketchBuilder
+
+
Gets the current configured k
+
+
getK() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getK() - Method in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Gets the user configured parameter k, which controls the accuracy of the sketch +and its memory space usage.
+
+
getK() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getK() - Method in class org.apache.datasketches.req.ReqSketchBuilder
+
+
Gets the builder configured k.
+
+
getK() - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Returns the configured maximum sample size.
+
+
getK() - Method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Returns the sketch's value of k, the maximum number of samples stored in the +reservoir.
+
+
getK() - Method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Returns the sketch's value of k, the maximum number of samples stored in the reservoir.
+
+
getK() - Method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Returns the sketch's value of k, the maximum number of samples stored in the +sketch.
+
+
getK() - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Returns parameter k (compression) that was used to configure this TDigest
+
+
getKey() - Method in interface org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator
+
+
Gets a key from the current entry in the sketch, which is a hash +of the original key passed to update().
+
+
getKeyUsageBytes() - Method in class org.apache.datasketches.hllmap.UniqueCountMap
+
+
Returns total bytes used for key storage
+
+
getKFromEpsilon(double, boolean) - Static method in class org.apache.datasketches.kll.KllSketch
+
+
Gets the approximate k to use given epsilon, the normalized rank error.
+
+
getKFromEpsilon(double, boolean) - Static method in class org.apache.datasketches.quantiles.ClassicUtil
+
+
Used by Classic Quantiles.
+
+
getKFromEpsilon(double, boolean) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Gets the approximate k to use given epsilon, the normalized rank error.
+
+
getKFromEpsilon(double, boolean) - Static method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Gets the approximate k to use given epsilon, the normalized rank error.
+
+
getLgConfigK() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
getLgConfigK() - Method in class org.apache.datasketches.hll.HllUnion
+
+
Gets the effective lgConfigK for the HllUnion operator, which may be less than +lgMaxK.
+
+
getLgK() - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Return the parameter LgK.
+
+
getLgK() - Method in class org.apache.datasketches.cpc.CpcUnion
+
+
Returns the current value of Log_base2 of K.
+
+
getLgK() - Method in class org.apache.datasketches.cpc.CpcWrapper
+
+
Returns the configured Log_base2 of K of this sketch.
+
+
getLgK() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Get log_base2 of Nominal Entries
+
+
getLgK() - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
+
Get log_base2 of Nominal Entries
+
+
getLgK() - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Get log_base2 of Nominal Entries
+
+
getLgK() - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
+
Get log_base2 of Nominal Entries
+
+
getLgK() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Get log_base2 of Nominal Entries
+
+
getLgNominalEntries() - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Returns Log-base 2 Nominal Entries
+
+
getLgNominalEntries() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns the local Log-base 2 Nominal Entries
+
+
getLgNomLongs() - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Gets the Log base 2 of the configured nominal entries
+
+
getLong() - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the long value at the current position.
+
+
getLong(long) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the long value at the given offset.
+
+
getLongArray(long[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the long array at the current position.
+
+
getLongBE(byte[], int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Get a long from the source byte array starting at the given offset +in big endian order.
+
+
getLongLE(byte[], int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Get a long from the given byte array starting at the given offset +in little endian order.
+
+
getLowerBound() - Method in class org.apache.datasketches.fdt.Group
+
+
Returns the lower bound
+
+
getLowerBound() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch.Row
+
+
Returns the lower bound
+
+
getLowerBound() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch.Row
+
+
Returns the lower bound
+
+
getLowerBound() - Method in class org.apache.datasketches.sampling.SampleSubsetSummary
+
+
Returns the lower bound
+
+
getLowerBound(byte[]) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the lower bound of the estimated frequency for the given item.
+
+
getLowerBound(byte[]) - Method in class org.apache.datasketches.hllmap.UniqueCountMap
+
+
Returns the lower bound cardinality with respect to UniqueCountMap.getEstimate(byte[]) associated +with the given key.
+
+
getLowerBound(int) - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Returns the best estimate of the lower bound of the confidence interval given kappa, +the number of standard deviations from the mean.
+
+
getLowerBound(int) - Method in class org.apache.datasketches.cpc.CpcWrapper
+
+
Returns the best estimate of the lower bound of the confidence interval given kappa, +the number of standard deviations from the mean.
+
+
getLowerBound(int) - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
getLowerBound(int) - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
getLowerBound(int) - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Gets the approximate lower error bound given the specified number of Standard Deviations.
+
+
getLowerBound(int) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Gets the approximate lower error bound given the specified number of Standard Deviations.
+
+
getLowerBound(int) - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Gets the approximate lower error bound given the specified number of Standard Deviations.
+
+
getLowerBound(int, int) - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Gets the estimate of the lower bound of the true distinct population represented by the count +of entries in a subset of the total retained entries of the sketch.
+
+
getLowerBound(int, MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Gets the approximate lower error bound from a valid MemorySegment image of a ThetaSketch +given the specified number of Standard Deviations.
+
+
getLowerBound(long) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the lower bound of the estimated frequency for the given item.
+
+
getLowerBound(long) - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Gets the guaranteed lower bound frequency of the given item, which can never be +negative.
+
+
getLowerBound(long, double, int, boolean) - Static method in class org.apache.datasketches.thetacommon.BinomialBoundsN
+
+
Returns the approximate lower bound value
+
+
getLowerBound(String) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the lower bound of the estimated frequency for the given item.
+
+
getLowerBound(T) - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Gets the guaranteed lower bound frequency of the given item, which can never be +negative.
+
+
getLowerBoundForBoverA(long, long, double) - Static method in class org.apache.datasketches.common.BoundsOnRatiosInSampledSets
+
+
Return the approximate lower bound based on a 95% confidence interval
+
+
getLowerBoundForBoverA(ThetaSketch, ThetaSketch) - Static method in class org.apache.datasketches.thetacommon.BoundsOnRatiosInThetaSketchedSets
+
+
Gets the approximate lower bound for B over A based on a 95% confidence interval
+
+
getLowerBoundForBoverA(TupleSketch, ThetaSketch) - Static method in class org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets
+
+
Gets the approximate lower bound for B over A based on a 95% confidence interval
+
+
getLowerBoundForBoverA(TupleSketch, TupleSketch) - Static method in class org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets
+
+
Gets the approximate lower bound for B over A based on a 95% confidence interval
+
+
getMaxAnotBResultBytes(int) - Static method in class org.apache.datasketches.theta.ThetaSetOperation
+
+
Returns the maximum number of bytes for the returned CompactThetaSketch, given the +value of nomEntries of the first sketch A of ThetaAnotB.
+
+
getMaxBytes() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCompactSketch
+
 
+
getMaxBytes() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Returns the maximum number of bytes for this sketch when serialized.
+
+
getMaxBytes(int, int) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion
+
+
Returns maximum required storage bytes given nomEntries and numValues
+
+
getMaxCompactSketchBytes(int) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns the maximum number of storage bytes required for a CompactThetaSketch with the given +number of actual entries.
+
+
getMaxConcurrencyError() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Gets the local Maximum Concurrency Error
+
+
getMaximumError() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns an upper bound on the maximum error of getEstimate(item) for any item.
+
+
getMaximumError() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns an upper bound on the maximum error of getEstimate(item) for any item.
+
+
getMaximumMapCapacity() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns the maximum number of counters the sketch is configured to support.
+
+
getMaximumMapCapacity() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns the maximum number of counters the sketch is configured to support.
+
+
getMaxIntersectionBytes(int) - Static method in class org.apache.datasketches.theta.ThetaSetOperation
+
+
Returns the maximum required storage bytes given a nomEntries parameter for intersection +operations
+
+
getMaxItem() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getMaxItem() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getMaxItem() - Method in class org.apache.datasketches.quantilescommon.DoublesSketchSortedView
+
 
+
getMaxItem() - Method in interface org.apache.datasketches.quantilescommon.DoublesSortedView
+
+
Returns the maximum item of the stream.
+
+
getMaxItem() - Method in class org.apache.datasketches.quantilescommon.FloatsSketchSortedView
+
 
+
getMaxItem() - Method in interface org.apache.datasketches.quantilescommon.FloatsSortedView
+
+
Returns the maximum item of the stream.
+
+
getMaxItem() - Method in class org.apache.datasketches.quantilescommon.GenericPartitionBoundaries
+
+
Returns the maximum item of the stream.
+
+
getMaxItem() - Method in interface org.apache.datasketches.quantilescommon.GenericSortedView
+
+
Returns the maximum item of the stream.
+
+
getMaxItem() - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
getMaxItem() - Method in class org.apache.datasketches.quantilescommon.LongsSketchSortedView
+
 
+
getMaxItem() - Method in interface org.apache.datasketches.quantilescommon.LongsSortedView
+
+
Returns the maximum item of the stream.
+
+
getMaxItem() - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Returns the maximum item of the stream.
+
+
getMaxItem() - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Returns the maximum item of the stream.
+
+
getMaxItem() - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Returns the maximum item of the stream.
+
+
getMaxItem() - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Returns the maximum item of the stream.
+
+
getMaxItem() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getMaxK() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Returns the configured maxK of this Union.
+
+
getMaxK() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnionBuilder
+
+
Gets the current configured maxK
+
+
getMaxK() - Method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Returns the configured maxK of this Union.
+
+
getMaxK() - Method in class org.apache.datasketches.sampling.ReservoirItemsUnion
+
+
Returns the maximum allowed reservoir capacity in this union.
+
+
getMaxK() - Method in class org.apache.datasketches.sampling.ReservoirLongsUnion
+
+
Returns the maximum allowed reservoir capacity in this union.
+
+
getMaxNumLocalThreads() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Gets the local Maximum Number of Local Threads.
+
+
getMaxPartitions() - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
getMaxPartitions() - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
 
+
getMaxPartitions() - Method in interface org.apache.datasketches.quantilescommon.SketchPartitionLimits
+
+
Gets the maximum number of partitions this sketch will support based on the configured size K +and the number of retained values of this sketch.
+
+
getMaxPreLongs() - Method in enum class org.apache.datasketches.common.Family
+
+
Returns the maximum preamble size for this family in longs
+
+
getMaxSerializationBytes(int) - Static method in class org.apache.datasketches.hll.HllUnion
+
+
Returns the maximum size in bytes that this HllUnion operator can grow to given a lgK.
+
+
getMaxSerializedBytes(int) - Static method in class org.apache.datasketches.cpc.CpcSketch
+
+
The actual size of a compressed CPC sketch has a small random variance, but the following +empirically measured size should be large enough for at least 99.9 percent of sketches.
+
+
getMaxSerializedSizeBytes(int, long, KllSketch.SketchType, boolean) - Static method in class org.apache.datasketches.kll.KllSketch
+
+
Returns upper bound on the serialized size of a KllSketch given the following parameters.
+
+
getMaxUnionBytes() - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Returns the maximum required storage bytes for this union.
+
+
getMaxUnionBytes(int) - Static method in class org.apache.datasketches.theta.ThetaSetOperation
+
+
Returns the maximum required storage bytes given a nomEntries parameter for ThetaUnion operations
+
+
getMaxUpdatableSerializationBytes(int, TgtHllType) - Static method in class org.apache.datasketches.hll.HllSketch
+
+
Returns the maximum size in bytes that this sketch can grow to given lgConfigK.
+
+
getMaxUpdateSketchBytes(int) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns the maximum number of storage bytes required for an UpdatableThetaSketch with the given +number of nominal entries (power of 2).
+
+
getMaxValue() - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Returns maximum value seen by TDigest
+
+
getMemorySegment() - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Returns the underlying MemorySegment.
+
+
getMemorySegmentRequest() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns the local MemorySegmentRequest
+
+
getMinItem() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getMinItem() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getMinItem() - Method in class org.apache.datasketches.quantilescommon.DoublesSketchSortedView
+
 
+
getMinItem() - Method in interface org.apache.datasketches.quantilescommon.DoublesSortedView
+
+
Returns the minimum item of the stream.
+
+
getMinItem() - Method in class org.apache.datasketches.quantilescommon.FloatsSketchSortedView
+
 
+
getMinItem() - Method in interface org.apache.datasketches.quantilescommon.FloatsSortedView
+
+
Returns the minimum item of the stream.
+
+
getMinItem() - Method in class org.apache.datasketches.quantilescommon.GenericPartitionBoundaries
+
+
Returns the minimum item of the stream.
+
+
getMinItem() - Method in interface org.apache.datasketches.quantilescommon.GenericSortedView
+
+
Returns the minimum item of the stream.
+
+
getMinItem() - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
getMinItem() - Method in class org.apache.datasketches.quantilescommon.LongsSketchSortedView
+
 
+
getMinItem() - Method in interface org.apache.datasketches.quantilescommon.LongsSortedView
+
+
Returns the minimum item of the stream.
+
+
getMinItem() - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Returns the minimum item of the stream.
+
+
getMinItem() - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Returns the minimum item of the stream.
+
+
getMinItem() - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Returns the minimum item of the stream.
+
+
getMinItem() - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Returns the minimum item of the stream.
+
+
getMinItem() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getMinPartitionSizeItems() - Method in interface org.apache.datasketches.quantilescommon.SketchPartitionLimits
+
+
Gets the minimum partition size in items this sketch will support based on the configured size K of this +sketch and the number of retained values of this sketch.
+
+
getMinPreLongs() - Method in enum class org.apache.datasketches.common.Family
+
+
Returns the minimum preamble size for this family in longs
+
+
getMinValue() - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Returns minimum value seen by TDigest
+
+
getN() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getN() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getN() - Method in class org.apache.datasketches.quantilescommon.DoublesSketchSortedView
+
 
+
getN() - Method in class org.apache.datasketches.quantilescommon.FloatsSketchSortedView
+
 
+
getN() - Method in class org.apache.datasketches.quantilescommon.GenericPartitionBoundaries
+
+
Gets the length of the input stream offered to the underlying sketch.
+
+
getN() - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
getN() - Method in class org.apache.datasketches.quantilescommon.LongsSketchSortedView
+
 
+
getN() - Method in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Gets the length of the input stream offered to the sketch..
+
+
getN() - Method in interface org.apache.datasketches.quantilescommon.SketchPartitionLimits
+
+
Gets the length of the input stream offered to the sketch..
+
+
getN() - Method in interface org.apache.datasketches.quantilescommon.SortedView
+
+
Returns the total number of items presented to the sourcing sketch.
+
+
getN() - Method in class org.apache.datasketches.quantilescommon.SortedViewIterator
+
+
Gets the total count of all items presented to the sketch.
+
+
getN() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getN() - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Returns the number of items processed by the sketch, regardless +of item weight.
+
+
getN() - Method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Returns the number of items processed from the input stream
+
+
getN() - Method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Returns the number of items processed from the input stream
+
+
getN() - Method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Returns the number of items processed from the input stream
+
+
getName() - Method in enum class org.apache.datasketches.kll.KllSketch.SketchType
+
+
Get the name of the associated sketch
+
+
getNaturalRank() - Method in class org.apache.datasketches.quantilescommon.SortedViewIterator
+
+
Gets the natural rank at the current index.
+
+
getNaturalRank(double, long, QuantileSearchCriteria) - Static method in class org.apache.datasketches.quantilescommon.QuantilesUtil
+
+
Computes the closest Natural Rank from a given Normalized Rank
+
+
getNaturalRank(QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.SortedViewIterator
+
+
Gets the natural rank at the current index (or previous index) based on the chosen search criterion.
+
+
getNaturalRanks() - Method in class org.apache.datasketches.quantilescommon.GenericPartitionBoundaries
+
+
Gets an ordered array of natural ranks of the associated array of partition boundaries utilizing +a specified search criterion.
+
+
getNominalEntries() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Gets the configured nominal number of entries
+
+
getNominalEntries() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Get configured nominal number of entries
+
+
getNominalEntries() - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
+
Get configured nominal number of entries
+
+
getNominalEntries() - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Get configured nominal number of entries
+
+
getNominalEntries() - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
+
Get configured nominal number of entries
+
+
getNominalEntries() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Get configured nominal number of entries
+
+
getNormalizedRank() - Method in class org.apache.datasketches.quantilescommon.SortedViewIterator
+
+
Gets the normalized rank at the current index.
+
+
getNormalizedRank(QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.SortedViewIterator
+
+
Gets the normalized rank at the current index (or previous index) +based on the chosen search criterion.
+
+
getNormalizedRankError(boolean) - Method in class org.apache.datasketches.kll.KllSketch
+
 
+
getNormalizedRankError(boolean) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getNormalizedRankError(boolean) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getNormalizedRankError(boolean) - Method in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Gets the approximate rank error of this sketch normalized as a fraction between zero and one.
+
+
getNormalizedRankError(boolean) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getNormalizedRankError(int, boolean) - Static method in class org.apache.datasketches.kll.KllSketch
+
+
Gets the normalized rank error given k and pmf.
+
+
getNormalizedRankError(int, boolean) - Static method in class org.apache.datasketches.quantiles.ClassicUtil
+
+
Used by Classic Quantiles.
+
+
getNormalizedRankError(int, boolean) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Gets the normalized rank error given k and pmf.
+
+
getNormalizedRankError(int, boolean) - Static method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Gets the normalized rank error given k and pmf.
+
+
getNormalizedRanks() - Method in class org.apache.datasketches.quantilescommon.GenericPartitionBoundaries
+
+
Gets an ordered array of normalized ranks of the associated array of partition boundaries utilizing +a specified search criterion.
+
+
getNumActiveItems() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns the number of active items in the sketch.
+
+
getNumActiveItems() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns the number of active items in the sketch.
+
+
getNumBuckets_() - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the number of buckets per hash function.
+
+
getNumDeltaItems() - Method in class org.apache.datasketches.quantilescommon.GenericPartitionBoundaries
+
+
Gets the number of items to be included for each partition as an array.
+
+
getNumHashes() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Returns the configured number of hash functions for this BloomFilter
+
+
getNumHashes_() - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the number of hash functions used in this sketch.
+
+
getNumPartitions() - Method in class org.apache.datasketches.quantilescommon.GenericPartitionBoundaries
+
+
Gets the number of partitions
+
+
getNumPoolThreads() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Gets the local number of background pool threads used for propagation in the concurrent sketches.
+
+
getNumRetained() - Method in class org.apache.datasketches.kll.KllSketch
+
 
+
getNumRetained() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getNumRetained() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getNumRetained() - Method in class org.apache.datasketches.quantilescommon.DoublesSketchSortedView
+
 
+
getNumRetained() - Method in class org.apache.datasketches.quantilescommon.FloatsSketchSortedView
+
 
+
getNumRetained() - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
getNumRetained() - Method in class org.apache.datasketches.quantilescommon.LongsSketchSortedView
+
 
+
getNumRetained() - Method in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Gets the number of quantiles retained by the sketch.
+
+
getNumRetained() - Method in interface org.apache.datasketches.quantilescommon.SortedView
+
+
Gets the number of quantiles retained by this sorted view.
+
+
getNumRetained() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getNumSamples() - Method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Returns the current number of items in the reservoir, which may be smaller than the +reservoir capacity.
+
+
getNumSamples() - Method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Returns the current number of items in the reservoir, which may be smaller than the reservoir +capacity.
+
+
getNumSamples() - Method in class org.apache.datasketches.sampling.VarOptItemsSamples
+
+
Returns the length Copies items and weights from the sketch, if necessary, and returns the +length of +any +resulting array.
+
+
getNumSamples() - Method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Returns the current number of items in the sketch, which may be smaller than the +sketch capacity.
+
+
getNumValues() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Returns number of double values associated with each key
+
+
getObject() - Method in class org.apache.datasketches.tuple.DeserializeResult
+
+
Returns Deserialized object
+
+
getP() - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Returns the pre-sampling probability p
+
+
getP() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns the local upfront uniform pre-sampling probability p
+
+
getPartitionBoundariesFromNumParts(int) - Method in interface org.apache.datasketches.quantilescommon.PartitioningFeature
+
+
This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition.
+
+
getPartitionBoundariesFromNumParts(int, QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getPartitionBoundariesFromNumParts(int, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getPartitionBoundariesFromNumParts(int, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
getPartitionBoundariesFromNumParts(int, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.PartitioningFeature
+
+
This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition.
+
+
getPartitionBoundariesFromPartSize(long) - Method in interface org.apache.datasketches.quantilescommon.PartitioningFeature
+
+
This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition.
+
+
getPartitionBoundariesFromPartSize(long, QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getPartitionBoundariesFromPartSize(long, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getPartitionBoundariesFromPartSize(long, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
getPartitionBoundariesFromPartSize(long, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.PartitioningFeature
+
+
This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition.
+
+
getPMF(double[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
This is equivalent to getPMF(splitPoints, INCLUSIVE)
+
+
getPMF(double[]) - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Returns an approximation to the Probability Mass Function (PMF) of the input stream +given a set of split points.
+
+
getPMF(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
 
+
getPMF(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getPMF(double[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.DoublesSortedView
+
+
Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getPMF(double[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getPMF(float[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
This is equivalent to getPMF(splitPoints, INCLUSIVE)
+
+
getPMF(float[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
 
+
getPMF(float[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.FloatsSortedView
+
+
Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getPMF(float[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getPMF(float[], QuantileSearchCriteria) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getPMF(long[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
This is equivalent to getPMF(splitPoints, INCLUSIVE)
+
+
getPMF(long[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
 
+
getPMF(long[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.LongsSortedView
+
+
Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getPMF(long[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getPMF(T[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
This is equivalent to getPMF(splitPoints, INCLUSIVE)
+
+
getPMF(T[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getPMF(T[], QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getPMF(T[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.GenericSortedView
+
+
Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getPMF(T[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
+
+
getPosition() - Method in interface org.apache.datasketches.common.positional.Positional
+
+
Gets the current position
+
+
getPostProcessor() - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Returns the PostProcessor that enables multiple queries against the sketch results.
+
+
getPostProcessor(Group, char) - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Returns the PostProcessor that enables multiple queries against the sketch results.
+
+
getPreInts() - Method in enum class org.apache.datasketches.kll.KllSketch.SketchStructure
+
+
gets the Preamble Integers for this Structure.
+
+
getPrimaryKey() - Method in class org.apache.datasketches.fdt.Group
+
+
Gets the primary key of type String
+
+
getPropagateOrderedCompact() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Gets the local Propagate Ordered Compact flag used with concurrent sketches.
+
+
getQuantile() - Method in class org.apache.datasketches.kll.KllDoublesSketchIterator
+
 
+
getQuantile() - Method in class org.apache.datasketches.kll.KllFloatsSketchIterator
+
 
+
getQuantile() - Method in class org.apache.datasketches.kll.KllItemsSketchIterator
+
 
+
getQuantile() - Method in class org.apache.datasketches.kll.KllLongsSketchIterator
+
 
+
getQuantile() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketchIterator
+
 
+
getQuantile() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketchIterator
+
 
+
getQuantile() - Method in class org.apache.datasketches.quantilescommon.DoublesSortedViewIterator
+
+
Gets the quantile at the current index.
+
+
getQuantile() - Method in class org.apache.datasketches.quantilescommon.FloatsSortedViewIterator
+
+
Gets the quantile at the current index.
+
+
getQuantile() - Method in class org.apache.datasketches.quantilescommon.GenericSortedViewIterator
+
+
Gets the quantile at the current index +This is equivalent to getQuantile(INCLUSIVE).
+
+
getQuantile() - Method in class org.apache.datasketches.quantilescommon.LongsSortedViewIterator
+
+
Gets the quantile at the current index.
+
+
getQuantile() - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIteratorAPI
+
+
Gets the double quantile at the current index.
+
+
getQuantile() - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator
+
+
Gets the float quantile at the current index.
+
+
getQuantile() - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI
+
+
Gets the generic quantile at the current index.
+
+
getQuantile() - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsSketchIterator
+
+
Gets the long quantile at the current index.
+
+
getQuantile() - Method in class org.apache.datasketches.req.ReqSketchIterator
+
 
+
getQuantile(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
This is equivalent to getQuantile(rank, INCLUSIVE)
+
+
getQuantile(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
This is equivalent to getQuantile(rank, INCLUSIVE)
+
+
getQuantile(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
This is equivalent to getQuantile(rank, INCLUSIVE)
+
+
getQuantile(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
This is equivalent to getQuantile(rank, INCLUSIVE)
+
+
getQuantile(double) - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Compute approximate quantile value corresponding to the given normalized rank
+
+
getQuantile(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
 
+
getQuantile(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
 
+
getQuantile(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getQuantile(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
 
+
getQuantile(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getQuantile(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getQuantile(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.DoublesSketchSortedView
+
 
+
getQuantile(double, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.DoublesSortedView
+
+
Gets the approximate quantile of the given normalized rank and the given search criterion.
+
+
getQuantile(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.FloatsSketchSortedView
+
 
+
getQuantile(double, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.FloatsSortedView
+
+
Gets the approximate quantile of the given normalized rank and the given search criterion.
+
+
getQuantile(double, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.GenericSortedView
+
+
Gets the approximate quantile of the given normalized rank and the given search criterion.
+
+
getQuantile(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
getQuantile(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.LongsSketchSortedView
+
 
+
getQuantile(double, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.LongsSortedView
+
+
Gets the approximate quantile of the given normalized rank and the given search criterion.
+
+
getQuantile(double, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Gets the approximate quantile of the given normalized rank and the given search criterion.
+
+
getQuantile(double, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Gets the approximate quantile of the given normalized rank and the given search criterion.
+
+
getQuantile(double, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Gets the approximate quantile of the given normalized rank and the given search criterion.
+
+
getQuantile(double, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Gets the approximate quantile of the given normalized rank and the given search criterion.
+
+
getQuantile(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getQuantile(QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.GenericSortedViewIterator
+
+
Gets the quantile at the current index (or previous index) +based on the chosen search criterion.
+
+
getQuantileLowerBound(double) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
+
+
getQuantileLowerBound(double) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
+
+
getQuantileLowerBound(double) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getQuantileLowerBound(double) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
+
+
getQuantileLowerBound(double) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
+
+
getQuantileLowerBound(double) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getQuantileLowerBound(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
+
+
getQuantileLowerBound(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
+
+
getQuantileLowerBound(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
+
+
getQuantileLowerBound(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
+
+
getQuantileLowerBound(double) - Method in class org.apache.datasketches.req.ReqSketch
+
+
Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
+
+
getQuantileLowerBound(double, int) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getQuantiles() - Method in class org.apache.datasketches.quantilescommon.DoublesSketchSortedView
+
 
+
getQuantiles() - Method in interface org.apache.datasketches.quantilescommon.DoublesSortedView
+
+
Returns an array of all retained quantiles by the sketch.
+
+
getQuantiles() - Method in class org.apache.datasketches.quantilescommon.FloatsSketchSortedView
+
 
+
getQuantiles() - Method in interface org.apache.datasketches.quantilescommon.FloatsSortedView
+
+
Returns an array of all retained quantiles by the sketch.
+
+
getQuantiles() - Method in interface org.apache.datasketches.quantilescommon.GenericSortedView
+
+
Returns the full array of quantiles.
+
+
getQuantiles() - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
getQuantiles() - Method in class org.apache.datasketches.quantilescommon.LongsSketchSortedView
+
 
+
getQuantiles() - Method in interface org.apache.datasketches.quantilescommon.LongsSortedView
+
+
Returns an array of all retained quantiles by the sketch.
+
+
getQuantiles(double[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
This is equivalent to getQuantiles(ranks, INCLUSIVE)
+
+
getQuantiles(double[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
This is equivalent to getQuantiles(ranks, INCLUSIVE)
+
+
getQuantiles(double[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
This is equivalent to getQuantiles(ranks, INCLUSIVE)
+
+
getQuantiles(double[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
This is equivalent to getQuantiles(ranks, INCLUSIVE)
+
+
getQuantiles(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
 
+
getQuantiles(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
 
+
getQuantiles(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getQuantiles(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
 
+
getQuantiles(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getQuantiles(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getQuantiles(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
+
Gets an array of quantiles corresponding to the given array of ranks.
+
+
getQuantiles(double[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Gets an array of quantiles from the given array of normalized ranks.
+
+
getQuantiles(double[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Gets an array of quantiles from the given array of normalized ranks.
+
+
getQuantiles(double[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Gets an array of quantiles from the given array of normalized ranks.
+
+
getQuantiles(double[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Gets an array of quantiles from the given array of normalized ranks.
+
+
getQuantiles(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getQuantileUpperBound(double) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
+
+
getQuantileUpperBound(double) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
+
+
getQuantileUpperBound(double) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getQuantileUpperBound(double) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
+
+
getQuantileUpperBound(double) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
+
+
getQuantileUpperBound(double) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getQuantileUpperBound(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
+
+
getQuantileUpperBound(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
+
+
getQuantileUpperBound(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
+
+
getQuantileUpperBound(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
+
+
getQuantileUpperBound(double) - Method in class org.apache.datasketches.req.ReqSketch
+
+
Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
+
+
getQuantileUpperBound(double, int) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getRange(T, T, BoundsRule) - Method in interface org.apache.datasketches.partitions.SketchFillRequest
+
+
This is a callback request to the data source to fill a quantiles sketch +with a range of data between upper and lower bounds.
+
+
getRank(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
This is equivalent to getRank(quantile, INCLUSIVE)
+
+
getRank(double) - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Compute approximate normalized rank of the given value.
+
+
getRank(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
 
+
getRank(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getRank(double, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.DoublesSketchSortedView
+
 
+
getRank(double, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.DoublesSortedView
+
+
Gets the normalized rank corresponding to the given a quantile.
+
+
getRank(double, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Gets the normalized rank corresponding to the given a quantile.
+
+
getRank(float) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
This is equivalent to getRank(quantile, INCLUSIVE)
+
+
getRank(float, QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
 
+
getRank(float, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.FloatsSketchSortedView
+
 
+
getRank(float, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.FloatsSortedView
+
+
Gets the normalized rank corresponding to the given a quantile.
+
+
getRank(float, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Gets the normalized rank corresponding to the given a quantile.
+
+
getRank(float, QuantileSearchCriteria) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getRank(long) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
This is equivalent to getRank(quantile, INCLUSIVE)
+
+
getRank(long, QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
 
+
getRank(long, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.LongsSketchSortedView
+
 
+
getRank(long, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.LongsSortedView
+
+
Gets the normalized rank corresponding to the given a quantile.
+
+
getRank(long, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Gets the normalized rank corresponding to the given a quantile.
+
+
getRank(T) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
This is equivalent to getRank(T quantile, INCLUSIVE)
+
+
getRank(T, QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getRank(T, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getRank(T, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.GenericSortedView
+
+
Gets the normalized rank corresponding to the given a quantile.
+
+
getRank(T, QuantileSearchCriteria) - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
getRank(T, QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Gets the normalized rank corresponding to the given a quantile.
+
+
getRankLowerBound(double) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankLowerBound(double) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankLowerBound(double) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
+
Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankLowerBound(double) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankLowerBound(double) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankLowerBound(double) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getRankLowerBound(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankLowerBound(double) - Method in class org.apache.datasketches.req.ReqSketch
+
+
Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankLowerBound(double, int) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getRanks(double[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
This is equivalent to getRanks(quantiles, INCLUSIVE)
+
+
getRanks(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
 
+
getRanks(double[], QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getRanks(double[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
+
+
getRanks(float[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
This is equivalent to getRanks(quantiles, INCLUSIVE)
+
+
getRanks(float[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
 
+
getRanks(float[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
+
+
getRanks(float[], QuantileSearchCriteria) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getRanks(long[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
This is equivalent to getRanks(quantiles, INCLUSIVE)
+
+
getRanks(long[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
 
+
getRanks(long[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
+
+
getRanks(T[]) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
This is equivalent to getRanks(quantiles, INCLUSIVE)
+
+
getRanks(T[], QuantileSearchCriteria) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getRanks(T[], QuantileSearchCriteria) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getRanks(T[], QuantileSearchCriteria) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
+
+
getRankUpperBound(double) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankUpperBound(double) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankUpperBound(double) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
+
Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankUpperBound(double) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankUpperBound(double) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankUpperBound(double) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getRankUpperBound(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankUpperBound(double) - Method in class org.apache.datasketches.req.ReqSketch
+
+
Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
+
+
getRankUpperBound(double, int) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getRelativeError() - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the relative error of the sketch.
+
+
getRelErr(boolean, boolean, int, int) - Static method in class org.apache.datasketches.hll.HllSketch
+
+
Gets the current (approximate) Relative Error (RE) asymptotic values given several +parameters.
+
+
getRelErr(boolean, boolean, int, int) - Static method in class org.apache.datasketches.hll.HllUnion
+
+
Gets the current (approximate) Relative Error (RE) asymptotic values given several +parameters.
+
+
getRemaining() - Method in interface org.apache.datasketches.common.positional.Positional
+
+
The number of elements remaining between the current position and the end position
+
+
getReqDebug() - Method in class org.apache.datasketches.req.ReqSketchBuilder
+
+
Gets the builder configured ReqDebug
+
+
getResizeFactor() - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Returns the Resize Factor
+
+
getResizeFactor() - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Returns the configured ResizeFactor
+
+
getResizeFactor() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns the local Resize Factor
+
+
getResizeFactor() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Gets the configured resize factor
+
+
getResizeFactor() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Get configured resize factor
+
+
getResizeFactor() - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
+
Get configured resize factor
+
+
getResizeFactor() - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Get configured resize factor
+
+
getResizeFactor() - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
+
Get configured resize factor
+
+
getResizeFactor() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Get configured resize factor
+
+
getResult() - Method in class org.apache.datasketches.cpc.CpcUnion
+
+
Returns the result of union operations as a CPC sketch.
+
+
getResult() - Method in class org.apache.datasketches.hll.HllUnion
+
+
Return the result of this HllUnion operator as an HLL_4 sketch.
+
+
getResult() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Gets the result of this Union as an UpdatableQuantilesDoublesSketch, which enables further update +operations on the resulting sketch.
+
+
getResult() - Method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Gets the result of this Union operation as a copy of the internal state.
+
+
getResult() - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Returns a copy of the current sample.
+
+
getResult() - Method in class org.apache.datasketches.sampling.ReservoirItemsUnion
+
+
Returns a sketch representing the current state of the union.
+
+
getResult() - Method in class org.apache.datasketches.sampling.ReservoirLongsUnion
+
+
Returns a sketch representing the current state of the union.
+
+
getResult() - Method in class org.apache.datasketches.sampling.VarOptItemsUnion
+
+
Gets the varopt sketch resulting from the union of any input sketches.
+
+
getResult() - Method in class org.apache.datasketches.theta.ThetaIntersection
+
+
Gets the result of this operation as an ordered CompactThetaSketch on the Java heap.
+
+
getResult() - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Gets the result of this operation as an ordered CompactThetaSketch on the Java heap.
+
+
getResult() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotB
+
+
Gets the result of this operation in the form of a ArrayOfDoublesCompactSketch
+
+
getResult() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotBImpl
+
 
+
getResult() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesIntersection
+
+
Gets the internal set as an on-heap compact sketch.
+
+
getResult() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion
+
+
Returns the resulting union in the form of a compact sketch
+
+
getResult() - Method in class org.apache.datasketches.tuple.TupleIntersection
+
+
Gets the internal set as an unordered CompactTupleSketch
+
+
getResult() - Method in class org.apache.datasketches.tuple.TupleUnion
+
+
Gets the result of a sequence of stateful union operations as an unordered CompactTupleSketch
+
+
getResult(boolean) - Method in class org.apache.datasketches.theta.ThetaAnotB
+
+
Gets the result of the multistep, stateful operation ThetaAnotB that have been executed with calls +to ThetaAnotB.setA(ThetaSketch) and (ThetaAnotB.notB(ThetaSketch) or +ThetaAnotB.notB(org.apache.datasketches.theta.ThetaSketch)).
+
+
getResult(boolean) - Method in class org.apache.datasketches.tuple.TupleAnotB
+
+
Gets the result of the multistep, stateful operation TupleAnotB that have been executed with calls +to TupleAnotB.setA(TupleSketch) and (TupleAnotB.notB(TupleSketch) or +TupleAnotB.notB(ThetaSketch)).
+
+
getResult(boolean) - Method in class org.apache.datasketches.tuple.TupleUnion
+
+
Gets the result of a sequence of stateful union operations as an unordered CompactTupleSketch.
+
+
getResult(boolean, MemorySegment) - Method in class org.apache.datasketches.theta.ThetaIntersection
+
+
Gets the result of this operation as a CompactThetaSketch in the given dstSeg.
+
+
getResult(boolean, MemorySegment) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Gets the result of this operation as a CompactThetaSketch of the chosen form.
+
+
getResult(boolean, MemorySegment, boolean) - Method in class org.apache.datasketches.theta.ThetaAnotB
+
+
Gets the result of the multistep, stateful operation ThetaAnotB that have been executed with calls +to ThetaAnotB.setA(ThetaSketch) and (ThetaAnotB.notB(ThetaSketch) or +ThetaAnotB.notB(org.apache.datasketches.theta.ThetaSketch)).
+
+
getResult(int[], int, int, char) - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Returns an ordered List of Groups of the most frequent distinct population of subset tuples +represented by the count of entries of each group.
+
+
getResult(MemorySegment) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotB
+
+
Gets the result of this operation in the form of a ArrayOfDoublesCompactSketch
+
+
getResult(MemorySegment) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotBImpl
+
 
+
getResult(MemorySegment) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesIntersection
+
+
Gets the result of stateful intersections so far.
+
+
getResult(MemorySegment) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion
+
+
Returns the resulting union in the form of a compact sketch
+
+
getResult(MemorySegment, MemorySegmentRequest) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Places the result of this Union into the provided MemorySegment as an UpdatableQuantilesDoublesSketch, +which enables further update operations on the resulting sketch.
+
+
getResult(TgtHllType) - Method in class org.apache.datasketches.hll.HllUnion
+
+
Return the result of this HllUnion operator with the specified TgtHllType
+
+
getResultAndReset() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Gets the result of this Union as an UpdatableQuantilesDoublesSketch, which enables further update +operations on the resulting sketch.
+
+
getResultAndReset() - Method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Gets the sketch result of this Union operation and resets this Union to the virgin state.
+
+
getRetainedEntries() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns the number of valid entries that have been retained by the sketch.
+
+
getRetainedEntries() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Returns number of retained entries
+
+
getRetainedEntries() - Method in class org.apache.datasketches.tuple.CompactTupleSketch
+
 
+
getRetainedEntries() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
 
+
getRetainedEntries() - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
 
+
getRetainedEntries() - Method in class org.apache.datasketches.fdt.FdtSketch
+
 
+
getRetainedEntries() - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
 
+
getRetainedEntries() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
 
+
getRetainedEntries() - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Returns number of retained entries
+
+
getRetainedEntries(boolean) - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns the number of entries that have been retained by the sketch.
+
+
getRetainedEntries(MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns the number of valid entries that have been retained by the sketch from the given MemorySegment
+
+
getRF(int) - Static method in enum class org.apache.datasketches.common.ResizeFactor
+
+
Returns the Resize Factor given the Log-base 2 of the Resize Factor
+
+
getRowHeader() - Static method in class org.apache.datasketches.frequencies.FrequentItemsSketch.Row
+
+
Returns the descriptive row header
+
+
getRowHeader() - Static method in class org.apache.datasketches.frequencies.FrequentLongsSketch.Row
+
+
Returns the descriptive row header
+
+
getRse() - Method in class org.apache.datasketches.fdt.Group
+
+
Returns the RSE
+
+
getRSE(int, double, boolean, long) - Static method in class org.apache.datasketches.req.ReqSketch
+
+
Returns an a priori estimate of relative standard error (RSE, expressed as a number in [0,1]).
+
+
getSamples() - Method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Returns a copy of the items in the reservoir, or null if empty.
+
+
getSamples() - Method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Returns a copy of the items in the reservoir.
+
+
getSamples(Class) - Method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Returns a copy of the items in the reservoir as members of Class clazz, or null +if empty.
+
+
getSamplingProbability() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Gets the configured sampling probability
+
+
getSamplingProbability() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Get configured sampling probability
+
+
getSamplingProbability() - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
+
Get configured sampling probability
+
+
getSamplingProbability() - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Get configured sampling probability
+
+
getSamplingProbability() - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
+
Get configured sampling probability
+
+
getSamplingProbability() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Get configured sampling probability
+
+
getSearchCriteria() - Method in class org.apache.datasketches.quantilescommon.GenericPartitionBoundaries
+
+
Gets the search criteria specified for the source sketch
+
+
getSeed() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Returns the hash seed for this BloomFilter.
+
+
getSeed() - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Returns the seed
+
+
getSeed() - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Gets the configured seed
+
+
getSeed() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Returns the local long seed value that is required by the hashing function.
+
+
getSeed_() - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the hash seed used by this sketch.
+
+
getSerializationVersion() - Static method in class org.apache.datasketches.hll.HllSketch
+
+
Returns the current serialization version.
+
+
getSerializationVersion() - Static method in class org.apache.datasketches.hll.HllUnion
+
+
Returns the current serialization version.
+
+
getSerializationVersion(MemorySegment) - Static method in class org.apache.datasketches.hll.HllSketch
+
+
Returns the current serialization version of the given MemorySegment.
+
+
getSerializationVersion(MemorySegment) - Static method in class org.apache.datasketches.hll.HllUnion
+
+
Returns the current serialization version of the given MemorySegment.
+
+
getSerializationVersion(MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns the serialization version from the given MemorySegment
+
+
getSerializedFilterSize(long) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Returns the minimum MemorySegment size, in bytes, needed for a serialized BloomFilter with the given number of bits.
+
+
getSerializedFilterSizeByAccuracy(long, double) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Returns the minimum MemorySegment size, in bytes, needed for a serialized BloomFilter with an optimal number of bits +and hash functions for the given inputs.
+
+
getSerializedSize(long) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Returns the serialized length of a non-empty BloomFilter of the given size, in bytes
+
+
getSerializedSizeBytes() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Returns the length of this BloomFilter when serialized, in bytes
+
+
getSerializedSizeBytes() - Method in class org.apache.datasketches.kll.KllSketch
+
+
Returns the current number of bytes this Sketch would require if serialized in compact form.
+
+
getSerializedSizeBytes() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getSerializedSizeBytes() - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Returns the current number of bytes this Sketch would require if serialized.
+
+
getSerializedSizeBytes() - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Returns the current number of bytes this Sketch would require if serialized.
+
+
getSerializedSizeBytes() - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Returns the current number of bytes this Sketch would require if serialized.
+
+
getSerializedSizeBytes() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getSerializedSizeBytes(ArrayOfItemsSerDe) - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Returns the size of a byte array representation of this sketch.
+
+
getSerializedSizeBytes(ArrayOfItemsSerDe, Class) - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Returns the length of a byte array representation of this sketch.
+
+
getSerVer() - Method in enum class org.apache.datasketches.kll.KllSketch.SketchStructure
+
+
gets the Serialization Version for this Structure.
+
+
getShort() - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the short value at the current position.
+
+
getShort(long) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the short value at the given offset.
+
+
getShortArray(short[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets the short array at the current position.
+
+
getShortBE(byte[], int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Get a short from the given byte array starting at the given offset +in big endian order.
+
+
getShortLE(byte[], int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Get a short from the given byte array starting at the given offset +in little endian order.
+
+
getSize() - Method in class org.apache.datasketches.tuple.DeserializeResult
+
+
Returns size in bytes occupied by the object in the serialized form
+
+
getSketchSamples() - Method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Gets a result iterator object.
+
+
getSketchStructure(int, int) - Static method in enum class org.apache.datasketches.kll.KllSketch.SketchStructure
+
+
gets the SketchStructure given preInts and serVer.
+
+
getSketchType(MemorySegment) - Static method in class org.apache.datasketches.tuple.SerializerDeserializer
+
+
Gets the sketch type byte from the given MemorySegment image
+
+
getSortedView() - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
 
+
getSortedView() - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
 
+
getSortedView() - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
getSortedView() - Method in class org.apache.datasketches.kll.KllLongsSketch
+
 
+
getSortedView() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
getSortedView() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
getSortedView() - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Gets the sorted view of this sketch
+
+
getSortedView() - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Gets the sorted view of this sketch
+
+
getSortedView() - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Gets the sorted view of this sketch
+
+
getSortedView() - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Gets the sorted view of this sketch
+
+
getSortedView() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
getStart() - Method in interface org.apache.datasketches.common.positional.Positional
+
+
Gets start position
+
+
getStartingCapacity(int, int) - Static method in class org.apache.datasketches.tuple.Util
+
+
Gets the starting capacity of a new sketch given the Nominal Entries and the log Resize Factor.
+
+
getStorageBytes() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns the number of bytes required to store this sketch as an array of bytes.
+
+
getStreamLength() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns the sum of the frequencies in the stream seen so far by the sketch
+
+
getStreamLength() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns the sum of the frequencies (weights or counts) in the stream seen so far by the sketch
+
+
getSummary() - Method in class org.apache.datasketches.tuple.TupleSketchIterator
+
+
Gets a Summary object from the current entry in the sketch.
+
+
getSummaryFactory() - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Gets the Summary Factory class of type S
+
+
getTgtHllType() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
getTgtHllType() - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
getTheta() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Gets the value of theta as a double with a value between zero and one
+
+
getTheta() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Gets the value of theta as a double between zero and one
+
+
getTheta() - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Gets the value of theta as a double between zero and one
+
+
getThetaLong() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Gets the value of theta as a long
+
+
getThetaLong() - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Returns Theta as a long
+
+
getTotalSketchWeight() - Method in class org.apache.datasketches.sampling.SampleSubsetSummary
+
+
Returns the total sketch weight
+
+
getTotalUsageBytes() - Method in class org.apache.datasketches.hllmap.UniqueCountMap
+
+
Returns total bytes used by all internal maps
+
+
getTotalWeight() - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Returns total weight
+
+
getTotalWeight_() - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the total weight of all items inserted into the sketch.
+
+
getUnionAction() - Method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Gets the union action
+
+
getUpdatableSerializationBytes() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
getUpdatableSerializationBytes() - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
getUpdatableStorageBytes(int, long) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Returns the number of bytes a sketch would require to store in updatable form.
+
+
getUpdateSketchMaxBytes(int) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns the maximum number of storage bytes required for an UpdatableThetaSketch with the given +log_base2 of the nominal entries.
+
+
getUpperBound() - Method in class org.apache.datasketches.fdt.Group
+
+
Returns the upper bound
+
+
getUpperBound() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch.Row
+
+
Returns the upper bound
+
+
getUpperBound() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch.Row
+
+
Returns the upper bound
+
+
getUpperBound() - Method in class org.apache.datasketches.sampling.SampleSubsetSummary
+
+
Returns the upper bound
+
+
getUpperBound(byte[]) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the upper bound of the estimated frequency for the given item.
+
+
getUpperBound(byte[]) - Method in class org.apache.datasketches.hllmap.UniqueCountMap
+
+
Returns the upper bound cardinality with respect to UniqueCountMap.getEstimate(byte[]) associated +with the given key.
+
+
getUpperBound(int) - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Returns the best estimate of the upper bound of the confidence interval given kappa, +the number of standard deviations from the mean.
+
+
getUpperBound(int) - Method in class org.apache.datasketches.cpc.CpcWrapper
+
+
Returns the best estimate of the upper bound of the confidence interval given kappa, +the number of standard deviations from the mean.
+
+
getUpperBound(int) - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
getUpperBound(int) - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
getUpperBound(int) - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Gets the approximate upper error bound given the specified number of Standard Deviations.
+
+
getUpperBound(int) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Gets the approximate upper error bound given the specified number of Standard Deviations.
+
+
getUpperBound(int) - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Gets the approximate upper error bound given the specified number of Standard Deviations.
+
+
getUpperBound(int, int) - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Gets the estimate of the upper bound of the true distinct population represented by the count +of entries in a subset of the total retained entries of the sketch.
+
+
getUpperBound(int, MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Gets the approximate upper error bound from a valid MemorySegment image of a ThetaSketch +given the specified number of Standard Deviations.
+
+
getUpperBound(long) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the upper bound of the estimated frequency for the given item.
+
+
getUpperBound(long) - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Gets the guaranteed upper bound frequency of the given item.
+
+
getUpperBound(long, double, int, boolean) - Static method in class org.apache.datasketches.thetacommon.BinomialBoundsN
+
+
Returns the approximate upper bound value
+
+
getUpperBound(String) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the upper bound of the estimated frequency for the given item.
+
+
getUpperBound(T) - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Gets the guaranteed upper bound frequency of the given item.
+
+
getUpperBoundForBoverA(long, long, double) - Static method in class org.apache.datasketches.common.BoundsOnRatiosInSampledSets
+
+
Return the approximate upper bound based on a 95% confidence interval
+
+
getUpperBoundForBoverA(ThetaSketch, ThetaSketch) - Static method in class org.apache.datasketches.thetacommon.BoundsOnRatiosInThetaSketchedSets
+
+
Gets the approximate upper bound for B over A based on a 95% confidence interval
+
+
getUpperBoundForBoverA(TupleSketch, ThetaSketch) - Static method in class org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets
+
+
Gets the approximate upper bound for B over A based on a 95% confidence interval
+
+
getUpperBoundForBoverA(TupleSketch, TupleSketch) - Static method in class org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets
+
+
Gets the approximate upper bound for B over A based on a 95% confidence interval
+
+
getValue() - Method in enum class org.apache.datasketches.common.ResizeFactor
+
+
Returns the Resize Factor
+
+
getValue() - Method in class org.apache.datasketches.tuple.adouble.DoubleSummary
+
+
Returns current value of the DoubleSummary
+
+
getValue() - Method in class org.apache.datasketches.tuple.aninteger.IntegerSummary
+
+
Returns the current value of the IntegerSummary
+
+
getValue() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsSummary
+
+
Returns the nodes array for this summary.
+
+
getValues() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Returns array of arrays of double values in the sketch
+
+
getValues() - Method in interface org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator
+
+
Gets an array of values from the current entry in the sketch.
+
+
getWeight() - Method in class org.apache.datasketches.kll.KllSketchIterator
+
 
+
getWeight() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketchIterator
+
 
+
getWeight() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketchIterator
+
 
+
getWeight() - Method in interface org.apache.datasketches.quantilescommon.QuantilesSketchIteratorAPI
+
+
Gets the natural weight at the current index.
+
+
getWeight() - Method in class org.apache.datasketches.quantilescommon.SortedViewIterator
+
+
Gets the weight contribution of the item at the current index.
+
+
getWeight() - Method in class org.apache.datasketches.req.ReqSketchIterator
+
 
+
getWeight() - Method in class org.apache.datasketches.sampling.VarOptItemsSamples.WeightedSample
+
+
Accesses the iterator's current weight value
+
+
gpb - Variable in class org.apache.datasketches.partitions.Partitioner.StackElement
+
+
A reference to the relevant GenericPartitionBoundaries class
+
+
Group - Class in org.apache.datasketches.fdt
+
+
Defines a Group from a Frequent Distinct Tuple query.
+
+
Group() - Constructor for class org.apache.datasketches.fdt.Group
+
+
Construct an empty Group
+
+
GT - Enum constant in enum class org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality
+
+
Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the lowest adjacent pair of +values {A,B} such that A ≤ V < B.
+Let low = index of the lowest value in the range.
+Let high = index of the highest value in the range.
+
+
GT - Enum constant in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the lowest adjacent pair of +values {A,B} such that A ≤ V < B.
+Let low = index of the lowest value in the range.
+Let high = index of the highest value in the range.
+
+
+

H

+
+
hash(byte[], int, int, long) - Static method in class org.apache.datasketches.hash.MurmurHash3
+
+
Hash a portion of the given byte[] array.
+
+
hash(byte[], long) - Static method in class org.apache.datasketches.hash.MurmurHash3
+
+
Hash the given byte[] array.
+
+
hash(byte[], long) - Static method in class org.apache.datasketches.hash.MurmurHash3FFM
+
+
Returns a 128-bit hash of the input.
+
+
hash(char[], int, int, long) - Static method in class org.apache.datasketches.hash.MurmurHash3
+
+
Hash a portion of the given char[] array.
+
+
hash(char[], long) - Static method in class org.apache.datasketches.hash.MurmurHash3
+
+
Hash the given char[] array.
+
+
hash(char[], long) - Static method in class org.apache.datasketches.hash.MurmurHash3FFM
+
+
Returns a 128-bit hash of the input.
+
+
hash(double, long, long[]) - Static method in class org.apache.datasketches.hash.MurmurHash3FFM
+
+
Returns a 128-bit hash of the input.
+
+
hash(int[], int, int, long) - Static method in class org.apache.datasketches.hash.MurmurHash3
+
+
Hash a portion of the given int[] array.
+
+
hash(int[], long) - Static method in class org.apache.datasketches.hash.MurmurHash3
+
+
Hash the given int[] array.
+
+
hash(int[], long) - Static method in class org.apache.datasketches.hash.MurmurHash3FFM
+
+
Returns a 128-bit hash of the input.
+
+
hash(long[], int, int, long) - Static method in class org.apache.datasketches.hash.MurmurHash3
+
+
Hash a portion of the given long[] array.
+
+
hash(long[], long) - Static method in class org.apache.datasketches.hash.MurmurHash3
+
+
Hash the given long[] array.
+
+
hash(long[], long) - Static method in class org.apache.datasketches.hash.MurmurHash3FFM
+
+
Returns a 128-bit hash of the input.
+
+
hash(long, long) - Static method in class org.apache.datasketches.hash.MurmurHash3
+
+
Hash the given long.
+
+
hash(long, long) - Static method in class org.apache.datasketches.hash.XxHash64
+
+
Returns a 64-bit hash from a single long.
+
+
hash(long, long, long[]) - Static method in class org.apache.datasketches.hash.MurmurHash3FFM
+
+
Returns a 128-bit hash of the input.
+
+
hash(MemorySegment, long) - Static method in class org.apache.datasketches.hash.MurmurHash3
+
+
Hash the given MemorySegment.
+
+
hash(MemorySegment, long, long, long) - Static method in class org.apache.datasketches.hash.XxHash64
+
+
Returns the 64-bit hash of the sequence of bytes in the given MemorySegment
+
+
hash(MemorySegment, long, long, long, long[]) - Static method in class org.apache.datasketches.hash.MurmurHash3FFM
+
+
Returns a 128-bit hash of the input as a long array of size 2.
+
+
hash(String, long, long[]) - Static method in class org.apache.datasketches.hash.MurmurHash3FFM
+
+
Returns a 128-bit hash of the input.
+
+
hash(ByteBuffer, long) - Static method in class org.apache.datasketches.hash.MurmurHash3
+
+
Hash the remaining bytes of the given ByteBuffer starting at position() ending at limit (exclusive).
+
+
hashArrayInsert(long[], long[], int, long) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
Inserts the given long array into the given OADH hashTable of the target size, +ignores duplicates and counts the values inserted.
+
+
hashByteArr(byte[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashBytes(byte[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash64
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashCharArr(char[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashChars(char[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash64
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashCode() - Method in class org.apache.datasketches.fdt.Group
+
 
+
hashCode() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch.Row
+
+
This hashCode is computed only from the Row.getEstimate() value.
+
+
hashCode() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch.Row
+
+
This hashCode is computed only from the Row.getEstimate() value.
+
+
hashCode() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsSummary
+
 
+
hashDoubleArr(double[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashDoubles(double[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash64
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashFloatArr(float[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashFloats(float[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash64
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashInsertOnly(long[], int, long) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
This is a classical Knuth-style Open Addressing, Double Hash (OADH) insert scheme for on-heap.
+
+
hashInsertOnlyMemorySegment(MemorySegment, int, long, int) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
This is a classical Knuth-style Open Addressing, Double Hash (OADH) insert scheme for MemorySegment.
+
+
hashIntArr(int[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashInts(int[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash64
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
HashIterator - Interface in org.apache.datasketches.theta
+
+
This is used to iterate over the retained hash values of the Theta sketch.
+
+
hashLong(long, long) - Static method in class org.apache.datasketches.hash.XxHash
+
+
Returns a 64-bit hash from a single long.
+
+
hashLongArr(long[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashLongs(long[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash64
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
HashOperations - Class in org.apache.datasketches.thetacommon
+
+
Helper class for the common hash table methods.
+
+
hashSearch(long[], int, long) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
This is a classical Knuth-style Open Addressing, Double Hash (OADH) search scheme for on-heap.
+
+
hashSearchMemorySegment(MemorySegment, int, long, int) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
This is a classical Knuth-style Open Addressing, Double Hash (OADH) search scheme for MemorySegment.
+
+
hashSearchOrInsert(long[], int, long) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
This is a classical Knuth-style Open Addressing, Double Hash (OADH) insert scheme for on-heap.
+
+
hashSearchOrInsertMemorySegment(MemorySegment, int, long, int) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
This is a classical Knuth-style Open Addressing, Double Hash insert scheme, but inserts +values directly into a writable MemorySegment.
+
+
hashShortArr(short[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashShorts(short[], int, int, long) - Static method in class org.apache.datasketches.hash.XxHash64
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashString(String, int, int, long) - Static method in class org.apache.datasketches.hash.XxHash
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hashString(String, int, int, long) - Static method in class org.apache.datasketches.hash.XxHash64
+
+
Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
+
+
hasMemorySegment() - Method in interface org.apache.datasketches.common.MemorySegmentStatus
+
+
Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
+
+
hasMemorySegment() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
 
+
hasMemorySegment() - Method in class org.apache.datasketches.filters.bloomfilter.DirectBitArrayR
+
 
+
hasMemorySegment() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
hasMemorySegment() - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
hasMemorySegment() - Method in class org.apache.datasketches.kll.KllSketch
+
 
+
hasMemorySegment() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
hasMemorySegment() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
 
+
hasMemorySegment() - Method in class org.apache.datasketches.theta.CompactThetaSketch
+
 
+
hasMemorySegment() - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
 
+
hasMemorySegment() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Returns true if this sketch's data structure is backed by MemorySegment.
+
+
hasNext() - Method in class org.apache.datasketches.sampling.VarOptItemsSamples.VarOptItemsIterator
+
 
+
hasRemaining() - Method in interface org.apache.datasketches.common.positional.Positional
+
+
Returns true if there are elements remaining between the current position and the end position
+
+
hasResult() - Method in class org.apache.datasketches.theta.ThetaIntersection
+
+
Returns true if there is a valid intersection result available
+
+
hasResult() - Method in class org.apache.datasketches.tuple.TupleIntersection
+
+
Returns true if there is a valid intersection result available
+
+
heapify(byte[]) - Static method in class org.apache.datasketches.cpc.CpcSketch
+
+
Return the given byte array as a CpcSketch on the Java heap using the DEFAULT_UPDATE_SEED.
+
+
heapify(byte[]) - Static method in class org.apache.datasketches.hll.HllSketch
+
+
Heapify the given byte array, which must be a valid HllSketch image and may have data.
+
+
heapify(byte[]) - Static method in class org.apache.datasketches.hll.HllUnion
+
+
Construct a HllUnion operator populated with the given byte array image of an HllSketch.
+
+
heapify(byte[], long) - Static method in class org.apache.datasketches.cpc.CpcSketch
+
+
Return the given byte array as a CpcSketch on the Java heap.
+
+
heapify(Class, MemorySegment, Comparator, ArrayOfItemsSerDe) - Static method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Heapifies the given srcSeg, which must be a MemorySegment image of a QuantilesItemsSketch.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.cpc.CpcSketch
+
+
Return the given MemorySegment as a CpcSketch on the Java heap using the DEFAULT_UPDATE_SEED.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Reads a serialized image of a BloomFilter from the provided MemorySegment
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.hll.HllSketch
+
+
Heapify the given MemorySegment, which must be a valid HllSketch image and may have data.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.hll.HllUnion
+
+
Construct a HllUnion operator populated with the given MemorySegment image of an HllSketch.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Heapify takes the sketch image in MemorySegment and instantiates an on-heap Sketch.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Returns a Heap Union object that has been initialized with the data from the given MemorySegment that contains an +image of a sketch.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.quantiles.UpdatableQuantilesDoublesSketch
+
+
Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.req.ReqSketch
+
+
Returns an ReqSketch on the heap from a MemorySegment image of the sketch.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Returns a sketch instance of this class from the given srcSeg, which must be a MemorySegment +representation of this sketch class.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.sampling.ReservoirLongsUnion
+
+
Instantiates a Union from MemorySegment
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Deserialize TDigest from a given MemorySegment.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.theta.CompactThetaSketch
+
+
Heapify takes a CompactThetaSketch image in a MemorySegment and instantiates an on-heap CompactThetaSketch.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaSetOperation
+
+
Heapify takes the ThetaSetOperation image in MemorySegment and instantiates an on-heap +ThetaSetOperation using the +Default Update Seed.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Heapify takes the sketch image in MemorySegment and instantiates an on-heap ThetaSketch.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Instantiates an on-heap UpdatableThetaSketch from a MemorySegment.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Heapify the given MemorySegment as an ArrayOfDoublesSketch
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion
+
+
Heapify the given MemorySegment as an ArrayOfDoublesUnion.
+
+
heapify(MemorySegment) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Heapify the given MemorySegment as an ArrayOfDoublesUpdatableSketch
+
+
heapify(MemorySegment, boolean) - Static method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Deserialize TDigest from a given MemorySegment.
+
+
heapify(MemorySegment, long) - Static method in class org.apache.datasketches.cpc.CpcSketch
+
+
Return the given MemorySegment as a CpcSketch on the Java heap.
+
+
heapify(MemorySegment, long) - Static method in class org.apache.datasketches.theta.CompactThetaSketch
+
+
Heapify takes a CompactThetaSketch image in a MemorySegment and instantiates an on-heap CompactThetaSketch.
+
+
heapify(MemorySegment, long) - Static method in class org.apache.datasketches.theta.ThetaSetOperation
+
+
Heapify takes the ThetaSetOperation image in MemorySegment and instantiates an on-heap +ThetaSetOperation using the given expectedSeed.
+
+
heapify(MemorySegment, long) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Heapify takes the sketch image in MemorySegment and instantiates an on-heap ThetaSketch.
+
+
heapify(MemorySegment, long) - Static method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Instantiates an on-heap UpdatableThetaSketch from a MemorySegment.
+
+
heapify(MemorySegment, long) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Heapify the given MemorySegment and seed as a ArrayOfDoublesSketch
+
+
heapify(MemorySegment, long) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion
+
+
Heapify the given MemorySegment and seed as an ArrayOfDoublesUnion.
+
+
heapify(MemorySegment, long) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Heapify the given MemorySegment and seed as a ArrayOfDoublesUpdatableSketch
+
+
heapify(MemorySegment, Comparator, ArrayOfItemsSerDe) - Static method in class org.apache.datasketches.kll.KllItemsSketch
+
+
Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch.
+
+
heapify(MemorySegment, ArrayOfItemsSerDe) - Static method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
+
+
heapify(MemorySegment, ArrayOfItemsSerDe) - Static method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
+
+
heapify(MemorySegment, ArrayOfItemsSerDe) - Static method in class org.apache.datasketches.sampling.ReservoirItemsUnion
+
+
Instantiates a Union from MemorySegment
+
+
heapify(MemorySegment, ArrayOfItemsSerDe) - Static method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
+
+
heapify(MemorySegment, ArrayOfItemsSerDe) - Static method in class org.apache.datasketches.sampling.VarOptItemsUnion
+
+
Instantiates a Union from MemorySegment
+
+
heapify(QuantilesDoublesSketch) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Returns a Heap Union object that has been initialized with the data from the given sketch.
+
+
heapifySketch(MemorySegment) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Heapify the given MemorySegment as an ArrayOfDoublesSketch
+
+
heapifySketch(MemorySegment, long) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Heapify the given MemorySegment and seed as a ArrayOfDoublesSketch
+
+
heapifySketch(MemorySegment, SummaryDeserializer) - Static method in class org.apache.datasketches.tuple.TupleSketch
+
+
Instantiate a TupleSketch from a given MemorySegment.
+
+
heapifySummary(MemorySegment) - Method in class org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer
+
 
+
heapifySummary(MemorySegment) - Method in class org.apache.datasketches.tuple.aninteger.IntegerSummaryDeserializer
+
 
+
heapifySummary(MemorySegment) - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryDeserializer
+
 
+
heapifySummary(MemorySegment) - Method in interface org.apache.datasketches.tuple.SummaryDeserializer
+
+
This is to create an instance of a Summary given a serialized representation.
+
+
heapifyUnion(MemorySegment) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Heapify the given MemorySegment as an ArrayOfDoublesUnion
+
+
heapifyUnion(MemorySegment, long) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Heapify the given MemorySegment and seed as an ArrayOfDoublesUnion
+
+
heapifyUpdatableSketch(MemorySegment) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Heapify the given MemorySegment as an ArrayOfDoublesUpdatableSketch
+
+
heapifyUpdatableSketch(MemorySegment, long) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Heapify the given MemorySegment and seed as a ArrayOfDoublesUpdatableSketch
+
+
heapifyUpdatableSketch(MemorySegment, SummaryDeserializer, SummaryFactory) - Static method in class org.apache.datasketches.tuple.TupleSketch
+
+
Instantiate an UpdatableTupleSketch from a given MemorySegment on the heap,
+
+
HIP / Martingale Estimator - Section in package org.apache.datasketches.hll
+
 
+
HLL - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The HLL family of sketches.
+
+
HLL_4 - Enum constant in enum class org.apache.datasketches.hll.TgtHllType
+
+
An HLL sketch with a bin size of 4 bits
+
+
HLL_6 - Enum constant in enum class org.apache.datasketches.hll.TgtHllType
+
+
An HLL sketch with a bin size of 6 bits
+
+
HLL_8 - Enum constant in enum class org.apache.datasketches.hll.TgtHllType
+
+
An HLL Sketch with a bin size of 8 bits
+
+
HLL 4 - Section in package org.apache.datasketches.hll
+
 
+
HLL 6 - Section in package org.apache.datasketches.hll
+
 
+
HLL 8 - Section in package org.apache.datasketches.hll
+
 
+
HllSketch - Class in org.apache.datasketches.hll
+
+
The HllSketch is actually a collection of compact implementations of Phillipe Flajolet’s HyperLogLog (HLL) +sketch but with significantly improved error behavior and excellent speed performance.
+
+
HllSketch() - Constructor for class org.apache.datasketches.hll.HllSketch
+
+
Constructs a new on-heap sketch with the default lgConfigK and tgtHllType.
+
+
HllSketch(int) - Constructor for class org.apache.datasketches.hll.HllSketch
+
+
Constructs a new on-heap sketch with the default tgtHllType.
+
+
HllSketch(int, TgtHllType) - Constructor for class org.apache.datasketches.hll.HllSketch
+
+
Constructs a new on-heap sketch with the type of HLL sketch to configure.
+
+
HllSketch(int, TgtHllType, MemorySegment) - Constructor for class org.apache.datasketches.hll.HllSketch
+
+
Constructs a new sketch with the type of HLL sketch to configure and the given +MemorySegment as the destination for the sketch.
+
+
HllUnion - Class in org.apache.datasketches.hll
+
+
This performs union operations for all HllSketches.
+
+
HllUnion() - Constructor for class org.apache.datasketches.hll.HllUnion
+
+
Construct this HllUnion operator with the default maximum log-base-2 of K.
+
+
HllUnion(int) - Constructor for class org.apache.datasketches.hll.HllUnion
+
+
Construct this HllUnion operator with a given maximum log-base-2 of K.
+
+
HllUnion(int, MemorySegment) - Constructor for class org.apache.datasketches.hll.HllUnion
+
+
Construct this HllUnion operator with a given maximum log-base-2 of K and the given +MemorySegment as the destination for this HllUnion.
+
+
+

I

+
+
idToFamily(int) - Static method in enum class org.apache.datasketches.common.Family
+
+
Returns the Family given the ID
+
+
INCLUDE_BOTH - Enum constant in enum class org.apache.datasketches.partitions.BoundsRule
+
+
Include both the upper and lower bounds
+
+
INCLUDE_LOWER - Enum constant in enum class org.apache.datasketches.partitions.BoundsRule
+
+
Include only the lower bound but not the upper bound
+
+
INCLUDE_NEITHER - Enum constant in enum class org.apache.datasketches.partitions.BoundsRule
+
+
Include none
+
+
INCLUDE_UPPER - Enum constant in enum class org.apache.datasketches.partitions.BoundsRule
+
+
Include only the upper bound but not the lower bound
+
+
includeDoublesMinMax(double[], long[], double, double) - Static method in class org.apache.datasketches.quantilescommon.IncludeMinMax
+
+
The logic to include the min and max of type double.
+
+
includeFloatsMinMax(float[], long[], float, float) - Static method in class org.apache.datasketches.quantilescommon.IncludeMinMax
+
+
The logic to include the min and max of type float.
+
+
includeItemsMinMax(T[], long[], T, T, Comparator) - Static method in class org.apache.datasketches.quantilescommon.IncludeMinMax
+
+
The logic to include the min and max of type T.
+
+
includeLongsMinMax(long[], long[], long, long) - Static method in class org.apache.datasketches.quantilescommon.IncludeMinMax
+
+
The logic to include the min and max of type double.
+
+
IncludeMinMax - Class in org.apache.datasketches.quantilescommon
+
+
This class reinserts the min and max values into the sorted view arrays as required.
+
+
IncludeMinMax() - Constructor for class org.apache.datasketches.quantilescommon.IncludeMinMax
+
+
No argument constructor.
+
+
IncludeMinMax.DoublesPair - Class in org.apache.datasketches.quantilescommon
+
+
A simple structure to hold a pair of arrays
+
+
IncludeMinMax.FloatsPair - Class in org.apache.datasketches.quantilescommon
+
+
A simple structure to hold a pair of arrays
+
+
IncludeMinMax.ItemsPair<T> - Class in org.apache.datasketches.quantilescommon
+
+
A simple structure to hold a pair of arrays
+
+
IncludeMinMax.LongsPair - Class in org.apache.datasketches.quantilescommon
+
+
A simple structure to hold a pair of arrays
+
+
INCLUSIVE - Enum constant in enum class org.apache.datasketches.quantilescommon.QuantileSearchCriteria
+
+
Definition of INCLUSIVE getQuantile(r) search:
+Given rank r, return the quantile of the smallest rank that is +strictly greater than or equal to r.
+
+
incrementPosition(long) - Method in interface org.apache.datasketches.common.positional.Positional
+
+
Increments the current position by the given increment.
+
+
InequalitySearch - Enum Class in org.apache.datasketches.quantilescommon
+
+
This provides efficient, unique and unambiguous binary searching for inequality comparison criteria +for ordered arrays of values that may include duplicate values.
+
+
init(String, int, double, double, double, double, double) - Method in class org.apache.datasketches.fdt.Group
+
+
Specifies the parameters to be listed as columns
+
+
initialize(QuantilesItemsSketch) - Static method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Initialize a new QuantilesItemsUnion with an instance of QuantilesItemsSketch
+
+
initializeByAccuracy(long, double, long, MemorySegment) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using the provided base seed for the hash function and writing into the provided MemorySegment.
+
+
initializeByAccuracy(long, double, MemorySegment) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using a random base seed for the hash function and writing into the provided MemorySegment.
+
+
initializeBySize(long, int, long, MemorySegment) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Initializes a BloomFilter with given number of bits and number of hash functions, +using the provided base seed for the hash function and writing into the provided MemorySegment.
+
+
initializeBySize(long, int, MemorySegment) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Initializes a BloomFilter with given number of bits and number of hash functions, +using a random base seed for the hash function and writing into the provided MemorySegment.
+
+
initializeWithMemorySegment(Class, MemorySegment, Comparator, ArrayOfItemsSerDe) - Static method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Initialize a new QuantilesItemsUnion with a heapified instance of an QuantilesItemsSketch from a MemorySegment.
+
+
InsertedCountIncremented - Enum constant in enum class org.apache.datasketches.theta.UpdateReturnState
+
+
The hash was accepted into the sketch and the retained count was incremented.
+
+
InsertedCountIncrementedRebuilt - Enum constant in enum class org.apache.datasketches.theta.UpdateReturnState
+
+
The hash was accepted into the sketch, the retained count was incremented.
+
+
InsertedCountIncrementedResized - Enum constant in enum class org.apache.datasketches.theta.UpdateReturnState
+
+
The hash was accepted into the sketch, the retained count was incremented.
+
+
InsertedCountNotIncremented - Enum constant in enum class org.apache.datasketches.theta.UpdateReturnState
+
+
The hash was accepted into the sketch and the retained count was not incremented.
+
+
IntegerSummary - Class in org.apache.datasketches.tuple.aninteger
+
+
Summary for generic tuple sketches of type Integer.
+
+
IntegerSummary(IntegerSummary.Mode) - Constructor for class org.apache.datasketches.tuple.aninteger.IntegerSummary
+
+
Creates an instance of IntegerSummary with a given mode.
+
+
IntegerSummary.Mode - Enum Class in org.apache.datasketches.tuple.aninteger
+
+
The aggregation modes for this Summary
+
+
IntegerSummaryDeserializer - Class in org.apache.datasketches.tuple.aninteger
+
+
Implements SummaryDeserializer<IntegerSummary>
+
+
IntegerSummaryDeserializer() - Constructor for class org.apache.datasketches.tuple.aninteger.IntegerSummaryDeserializer
+
+
No argument constructor.
+
+
IntegerSummaryFactory - Class in org.apache.datasketches.tuple.aninteger
+
+
Factory for IntegerSummary.
+
+
IntegerSummaryFactory(IntegerSummary.Mode) - Constructor for class org.apache.datasketches.tuple.aninteger.IntegerSummaryFactory
+
+
Creates an instance of IntegerSummaryFactory with a given mode
+
+
IntegerSummarySetOperations - Class in org.apache.datasketches.tuple.aninteger
+
+
Methods for defining how unions and intersections of two objects of type IntegerSummary +are performed.
+
+
IntegerSummarySetOperations(IntegerSummary.Mode, IntegerSummary.Mode) - Constructor for class org.apache.datasketches.tuple.aninteger.IntegerSummarySetOperations
+
+
Creates a new instance with two modes
+
+
IntegerTupleSketch - Class in org.apache.datasketches.tuple.aninteger
+
+
Extends UpdatableTupleSketch<Integer, IntegerSummary>
+
+
IntegerTupleSketch(int, int, float, IntegerSummary.Mode) - Constructor for class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
+
Creates this sketch with the following parameters:
+
+
IntegerTupleSketch(int, IntegerSummary.Mode) - Constructor for class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
+
Constructs this sketch with given lgK.
+
+
IntegerTupleSketch(MemorySegment, IntegerSummary.Mode) - Constructor for class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
+
Deprecated. +
As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Heapifying a CompactTupleSketch is not deprecated.
+
+
+
intersect(BloomFilter) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Intersects two BloomFilters by applying a logical AND.
+
+
intersect(ThetaSketch) - Method in class org.apache.datasketches.theta.ThetaIntersection
+
+
Intersect the given sketch with the internal state.
+
+
intersect(ThetaSketch, ThetaSketch) - Method in class org.apache.datasketches.theta.ThetaIntersection
+
+
Perform intersect set operation on the two given sketch arguments and return the result as an +ordered CompactThetaSketch on the heap.
+
+
intersect(ThetaSketch, ThetaSketch, boolean, MemorySegment) - Method in class org.apache.datasketches.theta.ThetaIntersection
+
+
Perform intersect set operation on the two given sketches and return the result as a +CompactThetaSketch.
+
+
intersect(ThetaSketch, S) - Method in class org.apache.datasketches.tuple.TupleIntersection
+
+
Performs a stateful intersection of the internal set with the given ThetaSketch by combining entries +using the hashes from the ThetaSketch and summary values from the given summary and rules +from the summarySetOps defined by the TupleIntersection constructor.
+
+
intersect(ArrayOfDoublesSketch, ArrayOfDoublesCombiner) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesIntersection
+
+
Performs a stateful intersection of the internal set with the given TupleSketch.
+
+
intersect(TupleSketch) - Method in class org.apache.datasketches.tuple.TupleIntersection
+
+
Performs a stateful intersection of the internal set with the given TupleSketch.
+
+
intersect(TupleSketch, ThetaSketch, S) - Method in class org.apache.datasketches.tuple.TupleIntersection
+
+
Perform a stateless intersect set operation on a TupleSketch and a ThetaSketch and returns the +result as an unordered CompactTupleSketch on the heap.
+
+
intersect(TupleSketch, TupleSketch) - Method in class org.apache.datasketches.tuple.TupleIntersection
+
+
Perform a stateless intersect set operation on the two given TupleSketches and returns the +result as an unordered CompactTupleSketch on the heap.
+
+
intersection(DoubleSummary, DoubleSummary) - Method in class org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations
+
 
+
intersection(IntegerSummary, IntegerSummary) - Method in class org.apache.datasketches.tuple.aninteger.IntegerSummarySetOperations
+
 
+
intersection(ArrayOfStringsSummary, ArrayOfStringsSummary) - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsSummarySetOperations
+
 
+
intersection(S, S) - Method in interface org.apache.datasketches.tuple.SummarySetOperations
+
+
This is called by the intersection operator when both sketches have the same hash value.
+
+
INTERSECTION - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The Intersection family is an operation for the Theta Sketch Framework of sketches.
+
+
intToBytes(int, byte[]) - Static method in class org.apache.datasketches.common.Util
+
+
Returns a Little-Endian byte array extracted from the given int.
+
+
INVERSE_GOLDEN - Static variable in class org.apache.datasketches.common.Util
+
+
The inverse golden ratio as a fraction.
+
+
INVERSE_GOLDEN_U64 - Static variable in class org.apache.datasketches.common.Util
+
+
The inverse golden ratio as an unsigned long.
+
+
invert() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Inverts all the bits of the BloomFilter.
+
+
invPow2(int) - Static method in class org.apache.datasketches.common.Util
+
+
Computes the inverse integer power of 2: 1/(2^e) = 2^(-e).
+
+
isCompact() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
isCompact() - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
isCompact() - Method in class org.apache.datasketches.theta.CompactThetaSketch
+
 
+
isCompact() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns true if this sketch is in compact form.
+
+
isCompact() - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
 
+
isCompactMemorySegmentFormat() - Method in class org.apache.datasketches.kll.KllSketch
+
+
Returns true if this sketch is in a Compact MemorySegment Format.
+
+
isCompatible(BloomFilter) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Helps identify if two BloomFilters may be unioned or intersected.
+
+
isEmpty() - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Checks if the CountMinSketch has processed any items.
+
+
isEmpty() - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Return true if this sketch is empty
+
+
isEmpty() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Checks if the BloomFilter has processed any items
+
+
isEmpty() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns true if this sketch is empty
+
+
isEmpty() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns true if this sketch is empty
+
+
isEmpty() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
isEmpty() - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
isEmpty() - Method in class org.apache.datasketches.kll.KllSketch
+
 
+
isEmpty() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
isEmpty() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Returns true if this union is empty
+
+
isEmpty() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
isEmpty() - Method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Returns true if this union is empty
+
+
isEmpty() - Method in class org.apache.datasketches.quantilescommon.DoublesSketchSortedView
+
 
+
isEmpty() - Method in class org.apache.datasketches.quantilescommon.FloatsSketchSortedView
+
 
+
isEmpty() - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
isEmpty() - Method in class org.apache.datasketches.quantilescommon.LongsSketchSortedView
+
 
+
isEmpty() - Method in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Returns true if this sketch is empty.
+
+
isEmpty() - Method in interface org.apache.datasketches.quantilescommon.SortedView
+
+
Returns true if this sorted view is empty.
+
+
isEmpty() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
isEmpty() - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Returns true if the sketch is empty.
+
+
isEmpty() - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Returns true if TDigest has not seen any data
+
+
isEmpty() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+ +
+
isEmpty() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+ +
+
isEmpty() - Method in class org.apache.datasketches.tuple.TupleSketch
+
+ +
+
isEstimationMode() - Method in class org.apache.datasketches.hll.HllSketch
+
+
This HLL family of sketches and operators is always estimating, even for very small values.
+
+
isEstimationMode() - Method in class org.apache.datasketches.hll.HllUnion
+
+
This HLL family of sketches and operators is always estimating, even for very small values.
+
+
isEstimationMode() - Method in class org.apache.datasketches.kll.KllSketch
+
 
+
isEstimationMode() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
isEstimationMode() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
isEstimationMode() - Method in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Returns true if this sketch is in estimation mode.
+
+
isEstimationMode() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
isEstimationMode() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns true if the sketch is Estimation Mode (as opposed to Exact Mode).
+
+
isEstimationMode() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Returns true if the sketch is Estimation Mode (as opposed to Exact Mode).
+
+
isEstimationMode() - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Returns true if the sketch is Estimation Mode (as opposed to Exact Mode).
+
+
isEven(long) - Static method in class org.apache.datasketches.common.Util
+
+
Returns true if given n is even.
+
+
isLessThanUnsigned(long, long) - Static method in class org.apache.datasketches.common.Util
+
+
Unsigned compare with longs.
+
+
isMemorySegmentUpdatableFormat() - Method in class org.apache.datasketches.kll.KllSketch
+
+
Returns true if the backing MemorySegment is in updatable format.
+
+
isMultipleOf8AndGT0(long) - Static method in class org.apache.datasketches.common.Util
+
+
Returns true if v is a multiple of 8 and greater than zero
+
+
isOdd(long) - Static method in class org.apache.datasketches.common.Util
+
+
Returns true if given n is odd.
+
+
isOffHeap() - Method in interface org.apache.datasketches.common.MemorySegmentStatus
+
+
Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
+
+
isOffHeap() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
 
+
isOffHeap() - Method in class org.apache.datasketches.filters.bloomfilter.DirectBitArrayR
+
 
+
isOffHeap() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
isOffHeap() - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
isOffHeap() - Method in class org.apache.datasketches.kll.KllSketch
+
 
+
isOffHeap() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
isOffHeap() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
 
+
isOffHeap() - Method in class org.apache.datasketches.theta.CompactThetaSketch
+
 
+
isOffHeap() - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
 
+
isOrdered() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns true if internal cache is ordered
+
+
isOrdered() - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
 
+
isPowerOf2(long) - Static method in class org.apache.datasketches.common.Util
+
+
Returns true if given long argument is exactly a positive power of 2.
+
+
isReadOnly() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Returns whether the filter is in read-only mode.
+
+
isReadOnly() - Method in class org.apache.datasketches.filters.bloomfilter.DirectBitArrayR
+
 
+
isReadOnly() - Method in class org.apache.datasketches.kll.KllSketch
+
 
+
isReadOnly() - Method in class org.apache.datasketches.quantiles.CompactQuantilesDoublesSketch
+
 
+
isReadOnly() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
isReadOnly() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
isReadOnly() - Method in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Returns true if this sketch is read only.
+
+
isReadOnly() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
isSameResource(MemorySegment) - Method in interface org.apache.datasketches.common.MemorySegmentStatus
+
+
Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap.
+
+
isSameResource(MemorySegment) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
 
+
isSameResource(MemorySegment) - Method in class org.apache.datasketches.filters.bloomfilter.DirectBitArrayR
+
 
+
isSameResource(MemorySegment) - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
isSameResource(MemorySegment) - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
isSameResource(MemorySegment) - Method in class org.apache.datasketches.kll.KllSketch
+
 
+
isSameResource(MemorySegment) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
isSameResource(MemorySegment) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
 
+
isSameResource(MemorySegment) - Method in class org.apache.datasketches.theta.CompactThetaSketch
+
 
+
isSameResource(MemorySegment) - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
 
+
isSameResource(MemorySegment, MemorySegment) - Static method in interface org.apache.datasketches.common.MemorySegmentStatus
+
+
Returns true if the two given MemorySegments have to the same backing resource, or equivalently, +if the two memory regions overlap.
+
+
items() - Method in class org.apache.datasketches.sampling.VarOptItemsSamples
+
+
Returns a shallow copy of the array of sample items contained in the sketch.
+
+
items(int) - Method in class org.apache.datasketches.sampling.VarOptItemsSamples
+
+
Returns a single item from the samples contained in the sketch.
+
+
ItemsPair(T[], long[]) - Constructor for class org.apache.datasketches.quantilescommon.IncludeMinMax.ItemsPair
+
+
Constructor.
+
+
ItemsSketchSortedView<T> - Class in org.apache.datasketches.quantilescommon
+
+
The SortedView for the KllItemsSketch and the classic QuantilesItemsSketch.
+
+
ItemsSketchSortedView(T[], long[], QuantilesGenericAPI) - Constructor for class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
+
Constructor.
+
+
iterator() - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
 
+
iterator() - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
 
+
iterator() - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
iterator() - Method in class org.apache.datasketches.kll.KllLongsSketch
+
 
+
iterator() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
iterator() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
iterator() - Method in class org.apache.datasketches.quantilescommon.DoublesSketchSortedView
+
 
+
iterator() - Method in interface org.apache.datasketches.quantilescommon.DoublesSortedView
+
 
+
iterator() - Method in class org.apache.datasketches.quantilescommon.FloatsSketchSortedView
+
 
+
iterator() - Method in interface org.apache.datasketches.quantilescommon.FloatsSortedView
+
 
+
iterator() - Method in interface org.apache.datasketches.quantilescommon.GenericSortedView
+
 
+
iterator() - Method in class org.apache.datasketches.quantilescommon.ItemsSketchSortedView
+
 
+
iterator() - Method in class org.apache.datasketches.quantilescommon.LongsSketchSortedView
+
 
+
iterator() - Method in interface org.apache.datasketches.quantilescommon.LongsSortedView
+
 
+
iterator() - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Gets the iterator for this sketch, which is not sorted.
+
+
iterator() - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Gets the iterator for this sketch, which is not sorted.
+
+
iterator() - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Gets the iterator for this sketch, which is not sorted.
+
+
iterator() - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Gets the iterator for this sketch, which is not sorted.
+
+
iterator() - Method in interface org.apache.datasketches.quantilescommon.SortedView
+
+
Returns an iterator for this Sorted View.
+
+
iterator() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
iterator() - Method in class org.apache.datasketches.sampling.VarOptItemsSamples
+
 
+
iterator() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns a HashIterator that can be used to iterate over the retained hash values of the +Theta sketch.
+
+
iterator() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Returns an iterator over the sketch
+
+
iterator() - Method in class org.apache.datasketches.tuple.CompactTupleSketch
+
 
+
iterator() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
 
+
iterator() - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
 
+
iterator() - Method in class org.apache.datasketches.fdt.FdtSketch
+
 
+
iterator() - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
 
+
iterator() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
 
+
iterator() - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Returns a SketchIterator
+
+
+

J

+
+
jaccard(ThetaSketch, ThetaSketch) - Static method in class org.apache.datasketches.theta.JaccardSimilarity
+
+
Computes the Jaccard similarity index with upper and lower bounds.
+
+
jaccard(TupleSketch, ThetaSketch, S, SummarySetOperations) - Static method in class org.apache.datasketches.tuple.JaccardSimilarity
+
+
Computes the Jaccard similarity index with upper and lower bounds.
+
+
jaccard(TupleSketch, TupleSketch, SummarySetOperations) - Static method in class org.apache.datasketches.tuple.JaccardSimilarity
+
+
Computes the Jaccard similarity index with upper and lower bounds.
+
+
JaccardSimilarity - Class in org.apache.datasketches.theta
+
+
Jaccard similarity of two ThetaSketches.
+
+
JaccardSimilarity - Class in org.apache.datasketches.tuple
+
+
Jaccard similarity of two TupleSketches, or alternatively, of a TupleSketch and a ThetaSketch.
+
+
JaccardSimilarity() - Constructor for class org.apache.datasketches.tuple.JaccardSimilarity
+
+
No argument constructor.
+
+
JAVA_CHAR_UNALIGNED_BIG_ENDIAN - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for ByteOrder.BIG_ENDIAN char.
+
+
JAVA_CHAR_UNALIGNED_NON_NATIVE - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for NON ByteOrder.nativeOrder() char.
+
+
JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for ByteOrder.BIG_ENDIAN double.
+
+
JAVA_DOUBLE_UNALIGNED_NON_NATIVE - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for NON ByteOrder.nativeOrder() double.
+
+
JAVA_FLOAT_UNALIGNED_BIG_ENDIAN - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for ByteOrder.BIG_ENDIAN float.
+
+
JAVA_FLOAT_UNALIGNED_NON_NATIVE - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for NON ByteOrder.nativeOrder() float.
+
+
JAVA_INT_UNALIGNED_BIG_ENDIAN - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for ByteOrder.BIG_ENDIAN int.
+
+
JAVA_INT_UNALIGNED_NON_NATIVE - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for NON ByteOrder.nativeOrder() int.
+
+
JAVA_LONG_UNALIGNED_BIG_ENDIAN - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for ByteOrder.BIG_ENDIAN long.
+
+
JAVA_LONG_UNALIGNED_NON_NATIVE - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for NON ByteOrder.nativeOrder() long.
+
+
JAVA_SHORT_UNALIGNED_BIG_ENDIAN - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for ByteOrder.BIG_ENDIAN short.
+
+
JAVA_SHORT_UNALIGNED_NON_NATIVE - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for NON ByteOrder.nativeOrder() short.
+
+
justification() - Element in annotation interface org.apache.datasketches.common.SuppressFBWarnings
+
+
Optional explanation for the suppression.
+
+
+

K

+
+
Key Features of the DataSketches™ HllSketch and its companion HllUnion - Section in package org.apache.datasketches.hll
+
 
+
KLL - Enum constant in enum class org.apache.datasketches.common.Family
+
+
KLL quantiles sketch
+
+
KLL_DOUBLES_SKETCH - Enum constant in enum class org.apache.datasketches.kll.KllSketch.SketchType
+
+
KllDoublesSketch
+
+
KLL_FLOATS_SKETCH - Enum constant in enum class org.apache.datasketches.kll.KllSketch.SketchType
+
+
KllFloatsSketch
+
+
KLL_ITEMS_SKETCH - Enum constant in enum class org.apache.datasketches.kll.KllSketch.SketchType
+
+
KllItemsSketch
+
+
KLL_LONGS_SKETCH - Enum constant in enum class org.apache.datasketches.kll.KllSketch.SketchType
+
+
KllDoublesSketch
+
+
KllDoublesSketch - Class in org.apache.datasketches.kll
+
+
This variation of the KllSketch implements primitive doubles.
+
+
KllDoublesSketchIterator - Class in org.apache.datasketches.kll
+
+
Iterator over KllDoublesSketch.
+
+
KllFloatsSketch - Class in org.apache.datasketches.kll
+
+
This variation of the KllSketch implements primitive floats.
+
+
KllFloatsSketchIterator - Class in org.apache.datasketches.kll
+
+
Iterator over KllFloatsSketch.
+
+
KllItemsSketch<T> - Class in org.apache.datasketches.kll
+
+
This variation of the KllSketch implements generic data types.
+
+
KllItemsSketchIterator<T> - Class in org.apache.datasketches.kll
+
+
Iterator over KllItemsSketch.
+
+
KllLongsSketch - Class in org.apache.datasketches.kll
+
+
This variation of the KllSketch implements primitive longs.
+
+
KllLongsSketchIterator - Class in org.apache.datasketches.kll
+
+
Iterator over KllLongsSketch.
+
+
KllSketch - Class in org.apache.datasketches.kll
+
+
This class is the root of the KLL sketch class hierarchy.
+
+
KllSketch.SketchStructure - Enum Class in org.apache.datasketches.kll
+
+
Used primarily to define the structure of the serialized sketch.
+
+
KllSketch.SketchType - Enum Class in org.apache.datasketches.kll
+
+
Used to define the variable type of the current instance of this class.
+
+
KllSketchIterator - Class in org.apache.datasketches.kll
+
+
The base implementation for the KLL sketch iterator hierarchy used for viewing the +non-ordered quantiles retained by a sketch.
+
+
KolmogorovSmirnov - Class in org.apache.datasketches.quantilescommon
+
+
Kolmogorov-Smirnov Test +See Kolmogorov–Smirnov Test
+
+
KolmogorovSmirnov() - Constructor for class org.apache.datasketches.quantilescommon.KolmogorovSmirnov
+
+
No argument constructor.
+
+
kolmogorovSmirnovTest(QuantilesAPI, QuantilesAPI, double) - Static method in class org.apache.datasketches.quantilescommon.KolmogorovSmirnov
+
+
Performs the Kolmogorov-Smirnov Test between two QuantilesAPI sketches.
+
+
+

L

+
+
le(Object, Object, Comparator) - Static method in class org.apache.datasketches.common.Util
+
+
Is item1 Less-Than-Or-Equal-To item2?
+
+
LE - Enum constant in enum class org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality
+
+
Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the highest adjacent pair of +values {A,B} such that A ≤ V < B.
+Let low = index of the lowest value in the range.
+Let high = index of the highest value in the range.
+
+
LE - Enum constant in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the highest adjacent pair of +values {A,B} such that A ≤ V < B.
+Let low = index of the lowest value in the range.
+Let high = index of the highest value in the range.
+
+
levelPartId - Variable in class org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow
+
+
A brief string description of the partition and its hierarchy
+
+
levelPartId - Variable in class org.apache.datasketches.partitions.Partitioner.StackElement
+
+
A brief string description of the partition and its hierarchy
+
+
lg() - Method in enum class org.apache.datasketches.common.ResizeFactor
+
+
Returns the Log-base 2 of the Resize Factor
+
+
log2(double) - Static method in class org.apache.datasketches.common.Util
+
+
The log2(value)
+
+
LOG2 - Static variable in class org.apache.datasketches.common.Util
+
+
The natural logarithm of 2.0.
+
+
logBaseOfX(double, double) - Static method in class org.apache.datasketches.common.Util
+
+
Returns the logbase(x).
+
+
LONG_MAX_VALUE_AS_DOUBLE - Static variable in class org.apache.datasketches.common.Util
+
+
Long.MAX_VALUE as a double.
+
+
LongsPair(long[], long[]) - Constructor for class org.apache.datasketches.quantilescommon.IncludeMinMax.LongsPair
+
+
Constructor.
+
+
LongsSketchSortedView - Class in org.apache.datasketches.quantilescommon
+
+
The SortedView of the KllLongsSketch.
+
+
LongsSketchSortedView(long[], long[], QuantilesLongsAPI) - Constructor for class org.apache.datasketches.quantilescommon.LongsSketchSortedView
+
+
Construct from elements, also used in testing.
+
+
LongsSortedView - Interface in org.apache.datasketches.quantilescommon
+
+
The Sorted View for quantile sketches of primitive type long.
+
+
LongsSortedViewIterator - Class in org.apache.datasketches.quantilescommon
+
+
Iterator over quantile sketches of primitive type long.
+
+
LongsSortedViewIterator(long[], long[]) - Constructor for class org.apache.datasketches.quantilescommon.LongsSortedViewIterator
+
+
Constructor.
+
+
longToBytes(long, byte[]) - Static method in class org.apache.datasketches.common.Util
+
+
Returns a Little-Endian byte array extracted from the given long.
+
+
longToFixedLengthString(long, int) - Static method in class org.apache.datasketches.common.Util
+
+
Converts the given number to a string prepended with spaces, if necessary, to +match the given length.
+
+
longToHexBytes(long) - Static method in class org.apache.datasketches.common.Util
+
+
Returns a string of spaced hex bytes in Big-Endian order.
+
+
lowerBound - Variable in class org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow
+
+
The lower bound value
+
+
LS - Static variable in class org.apache.datasketches.common.Util
+
+
The java line separator character as a String.
+
+
lt(Object, Object, Comparator) - Static method in class org.apache.datasketches.common.Util
+
+
Is item1 Less-Than item2?
+
+
LT - Enum constant in enum class org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality
+
+
Given a sorted array of increasing values arr[] and a key value v, +this criterion instructs the binary search algorithm to find the highest adjacent pair of +values {A,B} such that A < v ≤ B.
+Let low = index of the lowest value in the range.
+Let high = index of the highest value in the range.
+
+
LT - Enum constant in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Given a sorted array of increasing values arr[] and a key value v, +this criterion instructs the binary search algorithm to find the highest adjacent pair of +values {A,B} such that A < v ≤ B.
+Let low = index of the lowest value in the range.
+Let high = index of the highest value in the range.
+
+
+

M

+
+
Max - Enum constant in enum class org.apache.datasketches.tuple.adouble.DoubleSummary.Mode
+
+
The aggregation mode is the maximum function.
+
+
Max - Enum constant in enum class org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode
+
+
The aggregation mode is the maximum function.
+
+
MAX_K - Static variable in class org.apache.datasketches.kll.KllSketch
+
+
The maximum K
+
+
MAX_LG_NOM_LONGS - Static variable in class org.apache.datasketches.thetacommon.ThetaUtil
+
+
The largest Log2 nom entries allowed: 26.
+
+
MAX_SIZE_BITS - Static variable in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
The maximum size of a bloom filter in bits.
+
+
maxT(Object, Object, Comparator) - Static method in class org.apache.datasketches.common.Util
+
+
Finds the maximum of two generic items
+
+
MEM_REQ_SVR_NULL_MSG - Static variable in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
MemoryRequestServer must not be null.
+
+
MemorySegmentRequest - Interface in org.apache.datasketches.common
+
+
This is a callback interface to provide a means to request a new MemorySegment of a specified size.
+
+
MemorySegmentRequest.Default - Class in org.apache.datasketches.common
+
+
A convenience class that implements a default implementation.
+
+
MemorySegmentRequestExample - Class in org.apache.datasketches.common
+
+
This is an example of a possible implementation of the MemorySegmentRequest interface +where all requested segments are allocated off-heap.
+
+
MemorySegmentRequestExample() - Constructor for class org.apache.datasketches.common.MemorySegmentRequestExample
+
+
No argument constructor.
+
+
MemorySegmentStatus - Interface in org.apache.datasketches.common
+
+
Methods for inquiring the status of a backing MemorySegment.
+
+
merge(CountMinSketch) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Merges another CountMinSketch into this one.
+
+
merge(FrequentItemsSketch) - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
This function merges the other sketch into this one.
+
+
merge(FrequentLongsSketch) - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
This function merges the other sketch into this one.
+
+
merge(KllSketch) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
 
+
merge(KllSketch) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
 
+
merge(KllSketch) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
merge(KllSketch) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
 
+
merge(KllSketch) - Method in class org.apache.datasketches.kll.KllSketch
+
+
Merges another sketch into this one.
+
+
merge(ReqSketch) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
merge(EbppsItemsSketch) - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Merges the provided sketch into the current one.
+
+
merge(TDigestDouble) - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Merge the given TDigest into this one
+
+
Merging sketches with different configured lgConfigK - Section in package org.apache.datasketches.hll
+
 
+
MergingValidation - Class in org.apache.datasketches.cpc
+
+
This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing.
+
+
MergingValidation(int, int, int, int, int, PrintStream, PrintWriter) - Constructor for class org.apache.datasketches.cpc.MergingValidation
+
+
Constructor
+
+
milliSecToString(long) - Static method in class org.apache.datasketches.common.Util
+
+
Returns the given time in milliseconds formatted as Hours:Min:Sec.mSec
+
+
Min - Enum constant in enum class org.apache.datasketches.tuple.adouble.DoubleSummary.Mode
+
+
The aggregation mode is the minimum function.
+
+
Min - Enum constant in enum class org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode
+
+
The aggregation mode is the minimum function.
+
+
MIN_LG_ARR_LONGS - Static variable in class org.apache.datasketches.thetacommon.ThetaUtil
+
+
The smallest Log2 cache size allowed: 5.
+
+
MIN_LG_NOM_LONGS - Static variable in class org.apache.datasketches.thetacommon.ThetaUtil
+
+
The smallest Log2 nom entries allowed: 4.
+
+
minLgHashTableSize(int, double) - Static method in class org.apache.datasketches.thetacommon.HashOperations
+
+
Returns the smallest log hash table size given the count of items and the rebuild threshold.
+
+
minT(Object, Object, Comparator) - Static method in class org.apache.datasketches.common.Util
+
+
Finds the minimum of two generic items
+
+
Multi-language, multi-platform. - Section in package org.apache.datasketches.hll
+
 
+
MurmurHash3 - Class in org.apache.datasketches.hash
+
+
The MurmurHash3 is a fast, non-cryptographic, 128-bit hash function that has +excellent avalanche and 2-way bit independence properties.
+
+
MurmurHash3FFM - Class in org.apache.datasketches.hash
+
+
The MurmurHash3 is a fast, non-cryptographic, 128-bit hash function that has +excellent avalanche and 2-way bit independence properties.
+
+
+

N

+
+
nanoSecToString(long) - Static method in class org.apache.datasketches.common.Util
+
+
Returns the given time in nanoseconds formatted as Sec.mSec_uSec_nSec
+
+
newDirectInstance(int, MemorySegment, MemorySegmentRequest) - Static method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Create a new direct updatable instance of this sketch with a given k.
+
+
newDirectInstance(int, MemorySegment, MemorySegmentRequest) - Static method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Create a new direct updatable instance of this sketch with a given k.
+
+
newDirectInstance(int, MemorySegment, MemorySegmentRequest) - Static method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Create a new direct updatable instance of this sketch with a given k.
+
+
newDirectInstance(MemorySegment) - Static method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Create a new direct updatable instance of this sketch with the default k.
+
+
newDirectInstance(MemorySegment) - Static method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Create a new direct updatable instance of this sketch with the default k.
+
+
newDirectInstance(MemorySegment) - Static method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Create a new direct updatable instance of this sketch with the default k.
+
+
newHeapInstance() - Static method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Create a new heap instance of this sketch with the default k = 200.
+
+
newHeapInstance() - Static method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Create a new heap instance of this sketch with the default k = 200.
+
+
newHeapInstance() - Static method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Create a new heap instance of this sketch with the default k = 200.
+
+
newHeapInstance(int) - Static method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Create a new heap instance of this sketch with a given parameter k.
+
+
newHeapInstance(int) - Static method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Create a new heap instance of this sketch with a given parameter k.
+
+
newHeapInstance(int) - Static method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Create a new heap instance of this sketch with a given parameter k.
+
+
newHeapInstance(int, Comparator, ArrayOfItemsSerDe) - Static method in class org.apache.datasketches.kll.KllItemsSketch
+
+
Create a new heap instance of this sketch with a given parameter k.
+
+
newHeapInstance(Comparator, ArrayOfItemsSerDe) - Static method in class org.apache.datasketches.kll.KllItemsSketch
+
+
Create a new heap instance of this sketch with the default k = 200.
+
+
newInstance(int) - Static method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Construct a mergeable sampling sketch with up to k samples using the default resize +factor (8).
+
+
newInstance(int) - Static method in class org.apache.datasketches.sampling.ReservoirItemsUnion
+
+
Creates an empty Union with a maximum reservoir capacity of size k.
+
+
newInstance(int) - Static method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Construct a mergeable reservoir sampling sketch with up to k samples using the default resize +factor (8).
+
+
newInstance(int) - Static method in class org.apache.datasketches.sampling.ReservoirLongsUnion
+
+
Creates an empty Union with a maximum reservoir capacity of size k.
+
+
newInstance(int) - Static method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Construct a varopt sampling sketch with up to k samples using the default resize factor (8).
+
+
newInstance(int) - Static method in class org.apache.datasketches.sampling.VarOptItemsUnion
+
+
Creates an empty Union with a maximum capacity of size k.
+
+
newInstance(int, ResizeFactor) - Static method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Construct a mergeable sampling sketch with up to k samples using a specified resize factor.
+
+
newInstance(int, ResizeFactor) - Static method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Construct a mergeable reservoir sampling sketch with up to k samples using the default resize +factor (8).
+
+
newInstance(int, ResizeFactor) - Static method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Construct a varopt sampling sketch with up to k samples using the specified resize factor.
+
+
newSummary() - Method in class org.apache.datasketches.tuple.adouble.DoubleSummaryFactory
+
 
+
newSummary() - Method in class org.apache.datasketches.tuple.aninteger.IntegerSummaryFactory
+
 
+
newSummary() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryFactory
+
 
+
newSummary() - Method in interface org.apache.datasketches.tuple.SummaryFactory
+
+
Returns new instance of Summary
+
+
newSummaryArray(S[], int) - Static method in class org.apache.datasketches.tuple.Util
+
+
Creates a new Summary Array with the specified length
+
+
next() - Method in class org.apache.datasketches.kll.KllSketchIterator
+
 
+
next() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketchIterator
+
 
+
next() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketchIterator
+
 
+
next() - Method in interface org.apache.datasketches.quantilescommon.QuantilesSketchIteratorAPI
+
+
Advances the index and checks if it is valid.
+
+
next() - Method in class org.apache.datasketches.quantilescommon.SortedViewIterator
+
+
Advances the index and checks if it is valid.
+
+
next() - Method in class org.apache.datasketches.req.ReqSketchIterator
+
 
+
next() - Method in class org.apache.datasketches.sampling.VarOptItemsSamples.VarOptItemsIterator
+
 
+
next() - Method in interface org.apache.datasketches.theta.HashIterator
+
+
Returns true at the next hash value in sequence.
+
+
next() - Method in interface org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator
+
+
Advancing the iterator and checking existence of the next entry +is combined here for efficiency.
+
+
next() - Method in class org.apache.datasketches.tuple.TupleSketchIterator
+
+
Advancing the iterator and checking existence of the next entry +is combined here for efficiency.
+
+
NO_FALSE_NEGATIVES - Enum constant in enum class org.apache.datasketches.frequencies.ErrorType
+
+
No Type II error samples will be excluded from the sample set, +which means all Truly Positive samples will be included in the sample set.
+
+
NO_FALSE_POSITIVES - Enum constant in enum class org.apache.datasketches.frequencies.ErrorType
+
+
No Type I error samples will be included in the sample set, +which means all Truly Negative samples will be excluded from the sample set.
+
+
NON_NATIVE_BYTE_ORDER - Static variable in class org.apache.datasketches.common.SpecialValueLayouts
+
+
The static final for NON ByteOrder.nativeOrder().
+
+
normalCDF(double) - Static method in class org.apache.datasketches.common.BoundsOnBinomialProportions
+
+
Computes an approximation to normalCDF(x).
+
+
NOT_SINGLE_ITEM_MSG - Static variable in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Sketch does not have just one item.
+
+
notB(ThetaSketch) - Method in class org.apache.datasketches.theta.ThetaAnotB
+
+
This is part of a multistep, stateful ThetaAnotB operation and sets the given ThetaSketch as the +second (or n+1th) argument B of A-AND-NOT-B.
+
+
notB(ThetaSketch) - Method in class org.apache.datasketches.tuple.TupleAnotB
+
+
This is part of a multistep, stateful TupleAnotB operation and sets the given ThetaSketch as the +second (or n+1th) argument B of A-AND-NOT-B.
+
+
notB(TupleSketch) - Method in class org.apache.datasketches.tuple.TupleAnotB
+
+
This is part of a multistep, stateful TupleAnotB operation and sets the given TupleSketch as the +second (or n+1th) argument B of A-AND-NOT-B.
+
+
numberOfLeadingOnes(long) - Static method in class org.apache.datasketches.common.Util
+
+
Returns the number of one bits preceding the highest-order ("leftmost") zero-bit in the +two's complement binary representation of the specified long value, or 64 if the value is equal +to minus one.
+
+
numberOfTrailingOnes(long) - Static method in class org.apache.datasketches.common.Util
+
+
Returns the number of one bits following the lowest-order ("rightmost") zero-bit in the +two's complement binary representation of the specified long value, or 64 if the value is equal +to minus one.
+
+
numDigits(long) - Static method in class org.apache.datasketches.common.Util
+
+
Computes the number of decimal digits of the number n
+
+
+

O

+
+
Off-Heap Operation - Section in package org.apache.datasketches.hll
+
 
+
org.apache.datasketches - package org.apache.datasketches
+
+
This package is the parent package for all sketch families and common code areas.
+
+
org.apache.datasketches.common - package org.apache.datasketches.common
+
+
This package is for common classes that may be used across all the sketch families.
+
+
org.apache.datasketches.common.positional - package org.apache.datasketches.common.positional
+
+
This package provides the classes that define and implement a relative positional API.
+
+
org.apache.datasketches.count - package org.apache.datasketches.count
+
+
This package in intended for implementations of the the Count Sketch and the Count-min Sketch both of which can be used to estimate +frequency-moments of a stream of distinct elements.
+
+
org.apache.datasketches.cpc - package org.apache.datasketches.cpc
+
+
Compressed Probabilistic Counting sketch family
+
+
org.apache.datasketches.fdt - package org.apache.datasketches.fdt
+
+
Frequent Distinct Tuples Sketch
+
+
org.apache.datasketches.filters - package org.apache.datasketches.filters
+
+
The filters package contains data structures used to determine +approximate set-membership.
+
+
org.apache.datasketches.filters.bloomfilter - package org.apache.datasketches.filters.bloomfilter
+
+
BloomFilter package
+
+
org.apache.datasketches.frequencies - package org.apache.datasketches.frequencies
+
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+
org.apache.datasketches.hash - package org.apache.datasketches.hash
+
+
The hash package contains a high-performing and extended Java implementations +of Austin Appleby's 128-bit MurmurHash3 hash function originally coded in C.
+
+
org.apache.datasketches.hll - package org.apache.datasketches.hll
+
+
The DataSketches™ HllSketch family package
+
+
org.apache.datasketches.hllmap - package org.apache.datasketches.hllmap
+
+
The hllmap package contains a space efficient HLL mapping sketch of keys to approximate unique +count of identifiers.
+
+
org.apache.datasketches.kll - package org.apache.datasketches.kll
+
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+
org.apache.datasketches.partitions - package org.apache.datasketches.partitions
+
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+
org.apache.datasketches.quantiles - package org.apache.datasketches.quantiles
+
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
org.apache.datasketches.quantilescommon - package org.apache.datasketches.quantilescommon
+
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
org.apache.datasketches.req - package org.apache.datasketches.req
+
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
org.apache.datasketches.sampling - package org.apache.datasketches.sampling
+
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
org.apache.datasketches.tdigest - package org.apache.datasketches.tdigest
+
+
t-Digest for estimating quantiles and ranks.
+
+
org.apache.datasketches.theta - package org.apache.datasketches.theta
+
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
org.apache.datasketches.thetacommon - package org.apache.datasketches.thetacommon
+
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+
org.apache.datasketches.tuple - package org.apache.datasketches.tuple
+
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+
org.apache.datasketches.tuple.adouble - package org.apache.datasketches.tuple.adouble
+
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+
org.apache.datasketches.tuple.aninteger - package org.apache.datasketches.tuple.aninteger
+
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+
org.apache.datasketches.tuple.arrayofdoubles - package org.apache.datasketches.tuple.arrayofdoubles
+
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
org.apache.datasketches.tuple.strings - package org.apache.datasketches.tuple.strings
+
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
Overview - Section in Overview
+
 
+
+

P

+
+
part - Variable in class org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow
+
+
The partition index
+
+
part - Variable in class org.apache.datasketches.partitions.Partitioner.StackElement
+
+
The partition index
+
+
partition(S) - Method in class org.apache.datasketches.partitions.Partitioner
+
+
This initiates the partitioning process
+
+
PartitionBoundsRow(Partitioner.StackElement) - Constructor for class org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow
+
+
The constructor for the StackElement class.
+
+
Partitioner<T,S> - Class in org.apache.datasketches.partitions
+
+
A partitioning process that can partition very large data sets into thousands +of partitions of approximately the same size.
+
+
Partitioner(long, int, SketchFillRequest) - Constructor for class org.apache.datasketches.partitions.Partitioner
+
+
This constructor assumes a QuantileSearchCriteria of INCLUSIVE.
+
+
Partitioner(long, int, SketchFillRequest, QuantileSearchCriteria) - Constructor for class org.apache.datasketches.partitions.Partitioner
+
+
This constructor includes the QuantileSearchCriteria criteria as a parameter.
+
+
Partitioner.PartitionBoundsRow<T> - Class in org.apache.datasketches.partitions
+
+
Defines a row for List of PartitionBounds.
+
+
Partitioner.StackElement<T> - Class in org.apache.datasketches.partitions
+
+
Holds data for a Stack element
+
+
PartitioningFeature<T> - Interface in org.apache.datasketches.quantilescommon
+
+
This enables the special functions for performing efficient partitioning of massive data.
+
+
Positional - Interface in org.apache.datasketches.common.positional
+
+
Defines the relative positional API.
+
+
PositionalSegment - Interface in org.apache.datasketches.common.positional
+
+
Defines the API for relative positional access to a MemorySegment.
+
+
PositionInvariantsException - Exception Class in org.apache.datasketches.common.positional
+
+
Position operation violation.
+
+
PositionInvariantsException(String) - Constructor for exception class org.apache.datasketches.common.positional.PositionInvariantsException
+
+
The associated position operation violated one of the positional invariants.
+
+
PostProcessor - Class in org.apache.datasketches.fdt
+
+
This processes the contents of a FDT sketch to extract the +primary keys with the most frequent unique combinations of the non-primary dimensions.
+
+
PostProcessor(FdtSketch, Group, char) - Constructor for class org.apache.datasketches.fdt.PostProcessor
+
+
Construct with a populated FdtSketch
+
+
powerSeriesNextDouble(int, double, boolean, double) - Static method in class org.apache.datasketches.common.Util
+
+
Computes the next larger double in the power series +point = logBase( i / ppb ) given the current point in the series.
+
+
putDoubleBE(byte[], int, double) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Put the source double into the destination byte array starting at the given offset +in big endian order.
+
+
putDoubleLE(byte[], int, double) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Put the source double into the destination byte array starting at the given offset +in little endian order.
+
+
putFloatBE(byte[], int, float) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Put the source float into the destination byte array starting at the given offset +in big endian order.
+
+
putFloatLE(byte[], int, float) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Put the source float into the destination byte array starting at the given offset +in little endian order.
+
+
putIntBE(byte[], int, int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Put the source int into the destination byte array starting at the given offset +in big endian order.
+
+
putIntLE(byte[], int, int) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Put the source int into the destination byte array starting at the given offset +in little endian order.
+
+
putIntoMemorySegment(MemorySegment) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Puts the current sketch into the given MemorySegment in compact form if there is sufficient space, +otherwise, it throws an error.
+
+
putIntoMemorySegment(MemorySegment, boolean) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Puts the current sketch into the given MemorySegment if there is sufficient space, otherwise, +throws an error.
+
+
putIntoMemorySegment(MemorySegment, ArrayOfItemsSerDe) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Puts the current sketch into the given MemorySegment if there is sufficient space.
+
+
putLongBE(byte[], int, long) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Put the source long into the destination byte array starting at the given offset +in big endian order.
+
+
putLongLE(byte[], int, long) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Put the source long into the destination byte array starting at the given offset +in little endian order.
+
+
putShortBE(byte[], int, short) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Put the source short into the destination byte array starting at the given offset +in big endian order.
+
+
putShortLE(byte[], int, short) - Static method in class org.apache.datasketches.common.ByteArrayUtil
+
+
Put the source short into the destination byte array starting at the given offset +in little endian order.
+
+
pwr2SeriesNext(int, long) - Static method in class org.apache.datasketches.common.Util
+
+
Computes the next larger integer point in the power series +point = 2( i / ppo ) given the current point in the series.
+
+
pwr2SeriesPrev(int, int) - Static method in class org.apache.datasketches.common.Util
+
+
Computes the previous, smaller integer point in the power series +point = 2( i / ppo ) given the current point in the series.
+
+
+

Q

+
+
quantiles - Variable in class org.apache.datasketches.quantilescommon.IncludeMinMax.DoublesPair
+
+
the array of quantiles
+
+
quantiles - Variable in class org.apache.datasketches.quantilescommon.IncludeMinMax.FloatsPair
+
+
The array of quantiles
+
+
quantiles - Variable in class org.apache.datasketches.quantilescommon.IncludeMinMax.ItemsPair
+
+
The array of quantiles
+
+
quantiles - Variable in class org.apache.datasketches.quantilescommon.IncludeMinMax.LongsPair
+
+
the array of quantiles
+
+
QUANTILES - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The Quantiles family of sketches.
+
+
QuantilesAPI - Interface in org.apache.datasketches.quantilescommon
+
+
This is a stochastic streaming sketch that enables near-real time analysis of the +approximate distribution of items from a very large stream in a single pass, requiring only +that the items are comparable.
+
+
QuantilesDoublesAPI - Interface in org.apache.datasketches.quantilescommon
+
+
The Quantiles API for item type double.
+
+
QuantilesDoublesSketch - Class in org.apache.datasketches.quantiles
+
+
This is an implementation of the Low Discrepancy Mergeable Quantiles Sketch, using doubles, + described in section 3.2 of the journal version of the paper "Mergeable Summaries" + by Agarwal, Cormode, Huang, Phillips, Wei, and Yi:
+
+
QuantilesDoublesSketchBuilder - Class in org.apache.datasketches.quantiles
+
+
For building a new quantiles QuantilesDoublesSketch.
+
+
QuantilesDoublesSketchBuilder() - Constructor for class org.apache.datasketches.quantiles.QuantilesDoublesSketchBuilder
+
+
Constructor for a new QuantilesDoublesSketchBuilder.
+
+
QuantilesDoublesSketchIterator - Class in org.apache.datasketches.quantiles
+
+
Iterator over QuantilesDoublesSketch.
+
+
QuantilesDoublesSketchIteratorAPI - Interface in org.apache.datasketches.quantilescommon
+
+
The quantiles sketch iterator for primitive type double.
+
+
QuantilesDoublesUnion - Class in org.apache.datasketches.quantiles
+
+
The API for Union operations for QuantilesDoublesSketches
+
+
QuantilesDoublesUnion() - Constructor for class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
No argument constructor.
+
+
QuantilesDoublesUnionBuilder - Class in org.apache.datasketches.quantiles
+
+
For building a new QuantilesDoublesSketch Union operation.
+
+
QuantilesDoublesUnionBuilder() - Constructor for class org.apache.datasketches.quantiles.QuantilesDoublesUnionBuilder
+
+
Constructor for a new QuantilesDoublesUnionBuilder.
+
+
QuantileSearchCriteria - Enum Class in org.apache.datasketches.quantilescommon
+
+
These search criteria are used by the KLL, REQ and Classic Quantiles sketches in the DataSketches library.
+
+
QuantilesFloatsAPI - Interface in org.apache.datasketches.quantilescommon
+
+
The Quantiles API for item type float.
+
+
QuantilesFloatsSketchIterator - Interface in org.apache.datasketches.quantilescommon
+
+
The quantiles sketch iterator for primitive type float.
+
+
QuantilesGenericAPI<T> - Interface in org.apache.datasketches.quantilescommon
+
+
The Quantiles API for item type generic.
+
+
QuantilesGenericSketchIteratorAPI<T> - Interface in org.apache.datasketches.quantilescommon
+
+
The quantiles sketch iterator for generic types.
+
+
QuantilesItemsSketch<T> - Class in org.apache.datasketches.quantiles
+
+
This is an implementation of the Low Discrepancy Mergeable Quantiles Sketch, using generic items, +described in section 3.2 of the journal version of the paper "Mergeable Summaries" +by Agarwal, Cormode, Huang, Phillips, Wei, and Yi:
+
+
QuantilesItemsSketchIterator<T> - Class in org.apache.datasketches.quantiles
+
+
Iterator over QuantilesItemsSketch.
+
+
QuantilesItemsUnion<T> - Class in org.apache.datasketches.quantiles
+
+
The API for Union operations for generic QuantilesItemsSketches
+
+
QuantilesLongsAPI - Interface in org.apache.datasketches.quantilescommon
+
+
The Quantiles API for item type long.
+
+
QuantilesLongsSketchIterator - Interface in org.apache.datasketches.quantilescommon
+
+
The quantiles sketch iterator for primitive type long.
+
+
QuantilesSketchIteratorAPI - Interface in org.apache.datasketches.quantilescommon
+
+
This is the base API for the iterator hierarchy used for viewing the +non-ordered quantiles retained by the classic Quantiles* sketches and KLL sketches, for example.
+
+
QuantilesUtil - Class in org.apache.datasketches.quantilescommon
+
+
Utilities for the quantiles sketches.
+
+
query(byte[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Queries the filter with the provided byte[] and returns whether the +array might have been seen previously.
+
+
query(char[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Queries the filter with the provided char[] and returns whether the +array might have been seen previously.
+
+
query(double) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Queries the filter with the provided double and returns whether the +value might have been seen previously.
+
+
query(int[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Queries the filter with the provided int[] and returns whether the +array might have been seen previously.
+
+
query(long) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Queries the filter with the provided long and returns whether the +value might have been seen previously.
+
+
query(long[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Queries the filter with the provided long[] and returns whether the +array might have been seen previously.
+
+
query(short[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Queries the filter with the provided short[] and returns whether the +array might have been seen previously.
+
+
query(MemorySegment) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Queries the filter with the provided MemorySegment and returns whether the +data might have been seen previously.
+
+
query(String) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Queries the filter with the provided double and returns whether the +value might have been seen previously.
+
+
queryAndUpdate(byte[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided byte[] and +returns the result from querying that array prior to the update.
+
+
queryAndUpdate(char[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided char[] and +returns the result from querying that array prior to the update.
+
+
queryAndUpdate(double) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided double and +returns the result from querying that value prior to the update.
+
+
queryAndUpdate(int[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided int[] and +returns the result from querying that array prior to the update.
+
+
queryAndUpdate(long) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided long and +returns the result from querying that value prior to the update.
+
+
queryAndUpdate(long[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided long[] and +returns the result from querying that array prior to the update.
+
+
queryAndUpdate(short[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided short[] and +returns the result from querying that array prior to the update.
+
+
queryAndUpdate(MemorySegment) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided MemorySegment and +returns the result from querying that MemorySegment prior to the update.
+
+
queryAndUpdate(String) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided String and +returns the result from querying that value prior to the update.
+
+
QuickMergingValidation - Class in org.apache.datasketches.cpc
+
+
This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing.
+
+
QuickMergingValidation(int, int, int, PrintStream, PrintWriter) - Constructor for class org.apache.datasketches.cpc.QuickMergingValidation
+
+
Constructor
+
+
QuickSelect - Class in org.apache.datasketches.common
+
+
QuickSelect algorithm improved from Sedgewick.
+
+
QUICKSELECT - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The QuickSelect Sketch family is a member of the Theta Sketch Framework of sketches and +is the workhorse of the Theta Sketch Families and can be constructed for either on-heap or +off-heap operation.
+
+
QuickSelectSketch - Enum constant in enum class org.apache.datasketches.tuple.SerializerDeserializer.SketchType
+
+
QuickSelectSketch
+
+
+

R

+
+
rand - Static variable in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Setting the seed makes the results of the sketch deterministic if the input items are +received in exactly the same order.
+
+
rebuild() - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Rebuilds the hash table to remove dirty values or to reduce the size +to nominal entries.
+
+
REBUILD_THRESHOLD - Static variable in class org.apache.datasketches.thetacommon.ThetaUtil
+
+
The hash table rebuild threshold = 15.0/16.0.
+
+
RejectedDuplicate - Enum constant in enum class org.apache.datasketches.theta.UpdateReturnState
+
+
The hash was rejected as a duplicate.
+
+
RejectedNullOrEmpty - Enum constant in enum class org.apache.datasketches.theta.UpdateReturnState
+
+
The hash was rejected because it was null or empty.
+
+
RejectedOverTheta - Enum constant in enum class org.apache.datasketches.theta.UpdateReturnState
+
+
The hash was rejected because the value was negative, zero or +greater than theta.
+
+
REQ - Enum constant in enum class org.apache.datasketches.common.Family
+
+
Relative Error Quantiles Sketch
+
+
ReqDebug - Interface in org.apache.datasketches.req
+
+
The signaling interface that allows comprehensive analysis of the ReqSketch and ReqCompactor +while eliminating code clutter in the main classes.
+
+
ReqSketch - Class in org.apache.datasketches.req
+
+
This Relative Error Quantiles Sketch is the Java implementation based on the paper +"Relative Error Streaming Quantiles" by Graham Cormode, Zohar Karnin, Edo Liberty, +Justin Thaler, Pavel Veselý, and loosely derived from a Python prototype written by Pavel Veselý.
+
+
ReqSketchBuilder - Class in org.apache.datasketches.req
+
+
For building a new ReqSketch
+
+
ReqSketchBuilder() - Constructor for class org.apache.datasketches.req.ReqSketchBuilder
+
+
Constructor for the ReqSketchBuilder.
+
+
ReqSketchIterator - Class in org.apache.datasketches.req
+
+
Iterator over all retained items of the ReqSketch.
+
+
request(long) - Method in interface org.apache.datasketches.common.MemorySegmentRequest
+
+
Request a new heap MemorySegment with the given newByteSize.
+
+
request(long) - Method in class org.apache.datasketches.common.MemorySegmentRequestExample
+
+
Request a new off-heap MemorySegment with the given newByteSeze.
+
+
requestClose(MemorySegment) - Method in interface org.apache.datasketches.common.MemorySegmentRequest
+
+
Request to close the given MemorySegment.
+
+
requestClose(MemorySegment) - Method in class org.apache.datasketches.common.MemorySegmentRequestExample
+
 
+
RESERVOIR - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The Reservoir family of sketches.
+
+
RESERVOIR_UNION - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The reservoir sampling family of Union operations.
+
+
ReservoirItemsSketch<T> - Class in org.apache.datasketches.sampling
+
+
This sketch provides a reservoir sample over an input stream of items.
+
+
ReservoirItemsUnion<T> - Class in org.apache.datasketches.sampling
+
+
Class to union reservoir samples of generic items.
+
+
ReservoirLongsSketch - Class in org.apache.datasketches.sampling
+
+
This sketch provides a reservoir sample over an input stream of longs.
+
+
ReservoirLongsUnion - Class in org.apache.datasketches.sampling
+
+
Class to union reservoir samples of longs.
+
+
reset() - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Resets this sketch to empty but retains the original LgK and Seed.
+
+
reset() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Resets the BloomFilter to an empty state
+
+
reset() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Resets this sketch to a virgin state.
+
+
reset() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Resets this sketch to a virgin state.
+
+
reset() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
reset() - Method in class org.apache.datasketches.hll.HllUnion
+
+
Resets to empty and retains the current lgK, but does not change the configured value of +lgMaxK.
+
+
reset() - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Resets this sketch to the empty state.
+
+
reset() - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Resets this sketch to the empty state.
+
+
reset() - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
reset() - Method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Resets this sketch to the empty state.
+
+
reset() - Method in class org.apache.datasketches.quantiles.CompactQuantilesDoublesSketch
+
 
+
reset() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
reset() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Resets this Union to a virgin state.
+
+
reset() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
reset() - Method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Resets this Union to a virgin state.
+
+
reset() - Method in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Resets this sketch to the empty state.
+
+
reset() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
reset() - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Resets the sketch to its default, empty state.
+
+
reset() - Method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Resets this sketch to the empty state, but retains the original value of k.
+
+
reset() - Method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Resets this sketch to the empty state, but retains the original value of k.
+
+
reset() - Method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Resets this sketch to the empty state, but retains the original value of k.
+
+
reset() - Method in class org.apache.datasketches.sampling.VarOptItemsUnion
+
+
Resets this sketch to the empty state, but retains the original value of max k.
+
+
reset() - Method in class org.apache.datasketches.theta.ThetaIntersection
+
+
Resets this ThetaIntersection for stateful operations only.
+
+
reset() - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Resets this ThetaUnion.
+
+
reset() - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Resets this sketch back to a virgin empty state.
+
+
reset() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesIntersection
+
+
Resets the internal set to the initial state, which represents the Universal Set
+
+
reset() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion
+
+
Resets the union to an empty state
+
+
reset() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Resets this sketch an empty state.
+
+
reset() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Resets this sketch an empty state.
+
+
reset() - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
+
Resets this sketch an empty state.
+
+
reset() - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Resets this sketch an empty state.
+
+
reset() - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
+
Resets this sketch an empty state.
+
+
reset() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Resets this sketch an empty state.
+
+
reset() - Method in class org.apache.datasketches.tuple.TupleAnotB
+
+
Resets this operation back to the empty state.
+
+
reset() - Method in class org.apache.datasketches.tuple.TupleIntersection
+
+
Resets the internal set to the initial state, which represents the Universal Set
+
+
reset() - Method in class org.apache.datasketches.tuple.TupleUnion
+
+
Resets the internal set to the initial state, which represents an empty set.
+
+
reset() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketchBuilder
+
+
Resets the Nominal Entries, Resize Factor and Sampling Probability to their default values.
+
+
resetPosition() - Method in interface org.apache.datasketches.common.positional.Positional
+
+
Resets the current position to the start position, +This does not modify any data.
+
+
RESIZE_THRESHOLD - Static variable in class org.apache.datasketches.thetacommon.ThetaUtil
+
+
The resize threshold = 0.5; tuned for speed.
+
+
ResizeFactor - Enum Class in org.apache.datasketches.common
+
+
For the Families that accept this configuration parameter, it controls the size multiple that +affects how fast the internal cache grows, when more space is required.
+
+
reverse(double[], int) - Static method in class org.apache.datasketches.tdigest.Sort
+
+
Reverse the first n elements of the given array.
+
+
reverse(long[], int) - Static method in class org.apache.datasketches.tdigest.Sort
+
+
Reverse the first n elements of the given array.
+
+
rule - Variable in class org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow
+
+
The BoundsRule for this partition description row.
+
+
+

S

+
+
SampleSubsetSummary - Class in org.apache.datasketches.sampling
+
+
A simple object o capture the results of a subset sum query on a sampling sketch.
+
+
select(double[], int, int, int) - Static method in class org.apache.datasketches.common.QuickSelect
+
+
Gets the 0-based kth order statistic from the array.
+
+
select(long[], int, int, int) - Static method in class org.apache.datasketches.common.QuickSelect
+
+
Gets the 0-based kth order statistic from the array.
+
+
selectExcludingZeros(double[], int, int) - Static method in class org.apache.datasketches.common.QuickSelect
+
+
Gets the 1-based kth order statistic from the array excluding any zero values in the +array.
+
+
selectExcludingZeros(long[], int, int) - Static method in class org.apache.datasketches.common.QuickSelect
+
+
Gets the 1-based kth order statistic from the array excluding any zero values in the +array.
+
+
selectIncludingZeros(double[], int) - Static method in class org.apache.datasketches.common.QuickSelect
+
+
Gets the 1-based kth order statistic from the array including any zero values in the +array.
+
+
selectIncludingZeros(long[], int) - Static method in class org.apache.datasketches.common.QuickSelect
+
+
Gets the 1-based kth order statistic from the array including any zero values in the +array.
+
+
SELF_MERGE_MSG - Static variable in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
A sketch cannot merge with itself.
+
+
SerializerDeserializer - Class in org.apache.datasketches.tuple
+
+
Multipurpose serializer-deserializer for a collection of sketches defined by the enum.
+
+
SerializerDeserializer() - Constructor for class org.apache.datasketches.tuple.SerializerDeserializer
+
+
No argument constructor.
+
+
SerializerDeserializer.SketchType - Enum Class in org.apache.datasketches.tuple
+
+
Defines the sketch classes that this SerializerDeserializer can handle.
+
+
serializeToByteArray(Boolean) - Method in class org.apache.datasketches.common.ArrayOfBooleansSerDe
+
 
+
serializeToByteArray(Boolean[]) - Method in class org.apache.datasketches.common.ArrayOfBooleansSerDe
+
 
+
serializeToByteArray(Double) - Method in class org.apache.datasketches.common.ArrayOfDoublesSerDe
+
 
+
serializeToByteArray(Double[]) - Method in class org.apache.datasketches.common.ArrayOfDoublesSerDe
+
 
+
serializeToByteArray(Long) - Method in class org.apache.datasketches.common.ArrayOfLongsSerDe
+
 
+
serializeToByteArray(Long[]) - Method in class org.apache.datasketches.common.ArrayOfLongsSerDe
+
 
+
serializeToByteArray(Number) - Method in class org.apache.datasketches.common.ArrayOfNumbersSerDe
+
 
+
serializeToByteArray(Number[]) - Method in class org.apache.datasketches.common.ArrayOfNumbersSerDe
+
 
+
serializeToByteArray(String) - Method in class org.apache.datasketches.common.ArrayOfStringsSerDe
+
 
+
serializeToByteArray(String) - Method in class org.apache.datasketches.common.ArrayOfUtf16StringsSerDe
+
 
+
serializeToByteArray(String[]) - Method in class org.apache.datasketches.common.ArrayOfStringsSerDe
+
 
+
serializeToByteArray(String[]) - Method in class org.apache.datasketches.common.ArrayOfUtf16StringsSerDe
+
 
+
serializeToByteArray(T) - Method in class org.apache.datasketches.common.ArrayOfItemsSerDe
+
+
Serialize a single unserialized item to a byte array.
+
+
serializeToByteArray(T[]) - Method in class org.apache.datasketches.common.ArrayOfItemsSerDe
+
+
Serialize an array of unserialized items to a byte array of contiguous serialized items.
+
+
serializeToString() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns a String representation of this sketch
+
+
setA(ThetaSketch) - Method in class org.apache.datasketches.theta.ThetaAnotB
+
+
This is part of a multistep, stateful ThetaAnotB operation and sets the given ThetaSketch as the +first argument A of A-AND-NOT-B.
+
+
setA(TupleSketch) - Method in class org.apache.datasketches.tuple.TupleAnotB
+
+
This is part of a multistep, stateful TupleAnotB operation and sets the given TupleSketch as the +first argument A of A-AND-NOT-B.
+
+
setBits(MemorySegment, long, byte) - Static method in class org.apache.datasketches.common.Util
+
+
Sets the bits defined by the bitMask
+
+
setBoolean(boolean) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the boolean value at the current position.
+
+
setBoolean(long, boolean) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the boolean value at the given offset.
+
+
setByte(byte) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the byte value at the current position.
+
+
setByte(long, byte) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the byte value at the given offset.
+
+
setByteArray(byte[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the byte array at the current position.
+
+
setChar(char) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the char value at the current position.
+
+
setChar(long, char) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the char value at the given offset.
+
+
setCharArray(char[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the char array at the current position.
+
+
setClass(Class) - Method in class org.apache.datasketches.sampling.VarOptItemsSamples
+
+
Specifies the class to use when copying the item array from the sketch.
+
+
setConCurLogNominalEntries(int) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Alternative method of setting the local (default) Nominal Entries for a local concurrent sketch from the log_base2 value.
+
+
setConCurNominalEntries(int) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Sets the local (default) Concurrent Nominal Entries for the concurrent local sketch.
+
+
setDouble(double) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the double value at the current position.
+
+
setDouble(long, double) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the double value at the given offset.
+
+
setDoubleArray(double[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the double array at the current position.
+
+
setFamily(Family) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Set the local Family.
+
+
setFloat(float) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the float value at the current position.
+
+
setFloat(long, float) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the float value at the given offset.
+
+
setFloatArray(float[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the float array at the current position.
+
+
setHighRankAccuracy(boolean) - Method in class org.apache.datasketches.req.ReqSketchBuilder
+
+
This sets the parameter highRankAccuracy.
+
+
setInt(int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the int value at the current position.
+
+
setInt(long, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the int value at the given offset.
+
+
setIntArray(int[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the int array at the current position.
+
+
setK(int) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketchBuilder
+
+
Sets the parameter k that determines the accuracy and size of the sketch.
+
+
setK(int) - Method in class org.apache.datasketches.req.ReqSketchBuilder
+
+
This sets the parameter k.
+
+
setLgK(int) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Alternative method of setting the Nominal Entries for this builder from the log_base2 value, commonly called LgK.
+
+
setLogNominalEntries(int) - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Alternative method of setting the Nominal Entries for this set operation from the log_base2 value.
+
+
setLogNominalEntries(int) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Alternative method of setting the local Nominal Entries for this builder from the log_base2 value.
+
+
setLong(long) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the long value at the current position.
+
+
setLong(long, long) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the long value at the given offset.
+
+
setLongArray(long[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the long array at the current position.
+
+
setMaxConcurrencyError(double) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Sets the local Maximum Concurrency Error.
+
+
setMaxK(int) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnionBuilder
+
+
Sets the parameter masK that determines the maximum size of the sketch that +results from a union and its accuracy.
+
+
setMaxNumLocalThreads(int) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Sets the local Maximum Number of Local Threads.
+
+
setMemorySegmentRequest(MemorySegmentRequest) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Sets the local MemorySegmentRequest
+
+
setNominalEntries(int) - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Sets the Maximum Nominal Entries (max K) for this set operation.
+
+
setNominalEntries(int) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Sets the local Nominal Entries for this builder.
+
+
setNominalEntries(int) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder
+
+
This is to set the nominal number of entries.
+
+
setNominalEntries(int) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder
+
+
This is to set the nominal number of entries.
+
+
setNominalEntries(int) - Method in class org.apache.datasketches.tuple.UpdatableTupleSketchBuilder
+
+
This is to set the nominal number of entries.
+
+
setNumberOfValues(int) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder
+
+
This is to set the number of double values associated with each key
+
+
setNumberOfValues(int) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder
+
+
This is to set the number of double values associated with each key
+
+
setNumPoolThreads(int) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Sets the local number of pool threads used for background propagation in the concurrent sketches.
+
+
SetOperationCornerCases - Class in org.apache.datasketches.thetacommon
+
+
Simplifies and speeds up set operations by resolving specific corner cases.
+
+
SetOperationCornerCases() - Constructor for class org.apache.datasketches.thetacommon.SetOperationCornerCases
+
+
No argument constructor.
+
+
SetOperationCornerCases.AnotbAction - Enum Class in org.apache.datasketches.thetacommon
+
+
A not B actions
+
+
SetOperationCornerCases.CornerCase - Enum Class in org.apache.datasketches.thetacommon
+
+
List of corner cases
+
+
SetOperationCornerCases.IntersectAction - Enum Class in org.apache.datasketches.thetacommon
+
+
Intersection actions
+
+
SetOperationCornerCases.UnionAction - Enum Class in org.apache.datasketches.thetacommon
+
+
List of union actions
+
+
setP(float) - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Sets the upfront uniform sampling probability, p.
+
+
setP(float) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Sets the local upfront uniform pre-sampling probability, p
+
+
setPosition(long) - Method in interface org.apache.datasketches.common.positional.Positional
+
+
Sets the current position.
+
+
setPropagateOrderedCompact(boolean) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Sets the local Propagate Ordered Compact flag to the given value.
+
+
setReqDebug(ReqDebug) - Method in class org.apache.datasketches.req.ReqSketchBuilder
+
+
This sets the parameter reqDebug.
+
+
setResizeFactor(ResizeFactor) - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Sets the cache Resize Factor
+
+
setResizeFactor(ResizeFactor) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Sets the local cache Resize Factor.
+
+
setResizeFactor(ResizeFactor) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder
+
+
This is to set the resize factor.
+
+
setResizeFactor(ResizeFactor) - Method in class org.apache.datasketches.tuple.UpdatableTupleSketchBuilder
+
+
This is to set the resize factor.
+
+
setSamplingProbability(float) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder
+
+
This is to set sampling probability.
+
+
setSamplingProbability(float) - Method in class org.apache.datasketches.tuple.UpdatableTupleSketchBuilder
+
+
This is to set sampling probability.
+
+
setSeed(long) - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Sets the long seed value that is require by the hashing function.
+
+
setSeed(long) - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Sets the local long seed value that is required by the hashing function.
+
+
setSeed(long) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder
+
+
Sets the long seed value that is required by the hashing function.
+
+
setSeed(long) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder
+
+
Sets the long seed value that is required by the hashing function.
+
+
setShort(long, short) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the short value at the given offset.
+
+
setShort(short) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the short value at the current position.
+
+
setShortArray(short[], int, int) - Method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Sets the short array at the current position.
+
+
setStartPositionEnd(long, long, long) - Method in interface org.apache.datasketches.common.positional.Positional
+
+
Sets start position, current position, and end position.
+
+
similarityTest(ThetaSketch, ThetaSketch, double) - Static method in class org.apache.datasketches.theta.JaccardSimilarity
+
+
Tests similarity of a measured ThetaSketch against an expected ThetaSketch.
+
+
similarityTest(TupleSketch, ThetaSketch, S, SummarySetOperations, double) - Static method in class org.apache.datasketches.tuple.JaccardSimilarity
+
+
Tests similarity of a measured TupleSketch against an expected ThetaSketch.
+
+
similarityTest(TupleSketch, TupleSketch, SummarySetOperations, double) - Static method in class org.apache.datasketches.tuple.JaccardSimilarity
+
+
Tests similarity of a measured TupleSketch against an expected TupleSketch.
+
+
sizeOf(Boolean) - Method in class org.apache.datasketches.common.ArrayOfBooleansSerDe
+
 
+
sizeOf(Boolean[]) - Method in class org.apache.datasketches.common.ArrayOfBooleansSerDe
+
 
+
sizeOf(Double) - Method in class org.apache.datasketches.common.ArrayOfDoublesSerDe
+
 
+
sizeOf(Double[]) - Method in class org.apache.datasketches.common.ArrayOfDoublesSerDe
+
 
+
sizeOf(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfBooleansSerDe
+
 
+
sizeOf(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfDoublesSerDe
+
 
+
sizeOf(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfItemsSerDe
+
+
Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment.
+
+
sizeOf(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfLongsSerDe
+
 
+
sizeOf(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfNumbersSerDe
+
 
+
sizeOf(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfStringsSerDe
+
 
+
sizeOf(MemorySegment, long, int) - Method in class org.apache.datasketches.common.ArrayOfUtf16StringsSerDe
+
 
+
sizeOf(Long) - Method in class org.apache.datasketches.common.ArrayOfLongsSerDe
+
 
+
sizeOf(Long[]) - Method in class org.apache.datasketches.common.ArrayOfLongsSerDe
+
 
+
sizeOf(Number) - Method in class org.apache.datasketches.common.ArrayOfNumbersSerDe
+
 
+
sizeOf(Number[]) - Method in class org.apache.datasketches.common.ArrayOfNumbersSerDe
+
 
+
sizeOf(String) - Method in class org.apache.datasketches.common.ArrayOfStringsSerDe
+
 
+
sizeOf(String) - Method in class org.apache.datasketches.common.ArrayOfUtf16StringsSerDe
+
 
+
sizeOf(T) - Method in class org.apache.datasketches.common.ArrayOfItemsSerDe
+
+
Returns the serialized size in bytes of a single unserialized item.
+
+
sizeOf(T[]) - Method in class org.apache.datasketches.common.ArrayOfItemsSerDe
+
+
Returns the serialized size in bytes of the array of items.
+
+
SKETCH_A - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction
+
+
Sketch A Exact
+
+
SKETCH_A - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Sketch A Exactly
+
+
SKETCH_B - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Sketch B Exactly
+
+
SketchesArgumentException - Exception Class in org.apache.datasketches.common
+
+
Illegal Arguments Exception class for the library
+
+
SketchesArgumentException(String) - Constructor for exception class org.apache.datasketches.common.SketchesArgumentException
+
+
Constructs a new runtime exception with the specified detail message.
+
+
SketchesException - Exception Class in org.apache.datasketches.common
+
+
Exception class for the library
+
+
SketchesException(String) - Constructor for exception class org.apache.datasketches.common.SketchesException
+
+
Constructs a new runtime exception with the specified detail message.
+
+
SketchesException(String, Throwable) - Constructor for exception class org.apache.datasketches.common.SketchesException
+
+
Constructs a new runtime exception with the specified detail message and cause.
+
+
SketchesNotSupportedException - Exception Class in org.apache.datasketches.common
+
+
This operation or mode is not supported.
+
+
SketchesNotSupportedException(String) - Constructor for exception class org.apache.datasketches.common.SketchesNotSupportedException
+
+
Constructs a new runtime exception with the specified detail message.
+
+
SketchesReadOnlyException - Exception Class in org.apache.datasketches.common
+
+
Write operation attempted on a read-only class.
+
+
SketchesReadOnlyException() - Constructor for exception class org.apache.datasketches.common.SketchesReadOnlyException
+
+
Constructs a new runtime exception with the message: +"Write operation attempted on a read-only class."
+
+
SketchesReadOnlyException(String) - Constructor for exception class org.apache.datasketches.common.SketchesReadOnlyException
+
+
Constructs a new runtime exception with the specified detail message.
+
+
SketchesStateException - Exception Class in org.apache.datasketches.common
+
+
Illegal State Exception class for the library
+
+
SketchesStateException(String) - Constructor for exception class org.apache.datasketches.common.SketchesStateException
+
+
Constructs a new runtime exception with the specified detail message.
+
+
SketchFillRequest<T,S> - Interface in org.apache.datasketches.partitions
+
+
This is a callback request to the data source to fill a quantiles sketch, +which is returned to the caller.
+
+
Sketching Core Library - Section in Overview
+
 
+
SketchPartitionLimits - Interface in org.apache.datasketches.quantilescommon
+
+
This defines the methods required to compute the partition limits.
+
+
sketchStateId(boolean, int, long) - Static method in class org.apache.datasketches.thetacommon.SetOperationCornerCases
+
+
Returns the sketch state ID
+
+
Sort - Class in org.apache.datasketches.tdigest
+
+
Specialized sorting algorithm that can sort one array and permute another array the same way.
+
+
Sort() - Constructor for class org.apache.datasketches.tdigest.Sort
+
+
No argument constructor.
+
+
SortedView - Interface in org.apache.datasketches.quantilescommon
+
+
This is the base interface for the Sorted View interface hierarchy and defines the methods that are type independent.
+
+
SortedViewIterator - Class in org.apache.datasketches.quantilescommon
+
+
This is the base interface for the SortedViewIterator hierarchy used with a SortedView obtained +from a quantile-type sketch.
+
+
SpecialValueLayouts - Class in org.apache.datasketches.common
+
+
Value Layouts for Non-native Endianness
+
+
stableSort(double[], long[], int) - Static method in class org.apache.datasketches.tdigest.Sort
+
+
Stable sort two arrays.
+
+
StackElement(GenericPartitionBoundaries, int, String) - Constructor for class org.apache.datasketches.partitions.Partitioner.StackElement
+
+
Constructs this StackElement
+
+
start() - Method in class org.apache.datasketches.cpc.CompressionCharacterization
+
+
Only used in test
+
+
start() - Method in class org.apache.datasketches.cpc.MergingValidation
+
+
Start the merging validation process
+
+
start() - Method in class org.apache.datasketches.cpc.QuickMergingValidation
+
+
Start the Quick Merging Validation process
+
+
start() - Method in class org.apache.datasketches.cpc.StreamingValidation
+
+
Start the streaming validation process
+
+
startingSubMultiple(int, int, int) - Static method in class org.apache.datasketches.thetacommon.ThetaUtil
+
+
Gets the smallest allowed exponent of 2 that it is a sub-multiple of the target by zero, +one or more resize factors.
+
+
StreamingValidation - Class in org.apache.datasketches.cpc
+
+
This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing.
+
+
StreamingValidation(int, int, int, int, PrintStream, PrintWriter) - Constructor for class org.apache.datasketches.cpc.StreamingValidation
+
+
Constructor
+
+
STRIDE_MASK - Static variable in class org.apache.datasketches.thetacommon.HashOperations
+
+
The stride mask for the Open Address, Double Hashing (OADH) hash table algorithm.
+
+
stringArrHash(String[]) - Static method in class org.apache.datasketches.tuple.Util
+
+
Returns the hash of the concatenated strings
+
+
stringConcat(String[]) - Static method in class org.apache.datasketches.tuple.Util
+
+
Concatenate array of Strings to a single String.
+
+
stringHash(String) - Static method in class org.apache.datasketches.tuple.Util
+
+
Returns the hash of the given string
+
+
stringToByteArray(String) - Static method in class org.apache.datasketches.tuple.Util
+
+
Converts a String to a UTF_8 byte array.
+
+
stringToFamily(String) - Static method in enum class org.apache.datasketches.common.Family
+
+
Returns the Family given the family name
+
+
suggestNumBuckets(double) - Static method in class org.apache.datasketches.count.CountMinSketch
+
+
Suggests an appropriate number of buckets per hash function for a given relative error.
+
+
suggestNumFilterBits(long, double) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Returns the optimal number of bits to use in a Bloom Filter given a target number of distinct +items and a target false positive probability.
+
+
suggestNumHashes(double) - Static method in class org.apache.datasketches.count.CountMinSketch
+
+
Suggests an appropriate number of hash functions to use for a given confidence level.
+
+
suggestNumHashes(double) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Returns the optimal number of hash functions to achieve a target false positive probability.
+
+
suggestNumHashes(long, long) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
Returns the optimal number of hash functions to given target numbers of distinct items +and the BloomFilter size in bits.
+
+
Sum - Enum constant in enum class org.apache.datasketches.tuple.adouble.DoubleSummary.Mode
+
+
The aggregation mode is the summation function.
+
+
Sum - Enum constant in enum class org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode
+
+
The aggregation mode is the summation function.
+
+
Summary - Interface in org.apache.datasketches.tuple
+
+
Interface for user-defined Summary, which is associated with every hash in a tuple sketch
+
+
SummaryDeserializer<S> - Interface in org.apache.datasketches.tuple
+
+
Interface for deserializing user-defined Summary
+
+
SummaryFactory<S> - Interface in org.apache.datasketches.tuple
+
+
Interface for user-defined SummaryFactory
+
+
SummarySetOperations<S> - Interface in org.apache.datasketches.tuple
+
+
This is to provide methods of producing unions and intersections of two Summary objects.
+
+
SuppressFBWarnings - Annotation Interface in org.apache.datasketches.common
+
+
Used to suppress SpotBug warnings.
+
+
+

T

+
+
TAB - Static variable in class org.apache.datasketches.common.Util
+
+
The tab character
+
+
tailRoundingFactor - Static variable in class org.apache.datasketches.quantilescommon.QuantilesUtil
+
+
used in search to improve rounding over a wide dynamic range
+
+
TDIGEST - Enum constant in enum class org.apache.datasketches.common.Family
+
+
t-Digest for estimating quantiles and ranks
+
+
TDigestDouble - Class in org.apache.datasketches.tdigest
+
+
t-Digest for estimating quantiles and ranks.
+
+
TDigestDouble() - Constructor for class org.apache.datasketches.tdigest.TDigestDouble
+
+
Constructor with the default K
+
+
TDigestDouble(short) - Constructor for class org.apache.datasketches.tdigest.TDigestDouble
+
+
Constructor
+
+
TestUtil - Class in org.apache.datasketches.cpc
+
+
Utility methods for Test
+
+
TestUtil() - Constructor for class org.apache.datasketches.cpc.TestUtil
+
+
No argument constructor.
+
+
TGT_IS_READ_ONLY_MSG - Static variable in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Target sketch is Read Only, cannot write.
+
+
TgtHllType - Enum Class in org.apache.datasketches.hll
+
+
Specifies the target type of HLL sketch to be created.
+
+
The DataSketches™ HllSketch family package - Section in package org.apache.datasketches.hll
+
 
+
ThetaAnotB - Class in org.apache.datasketches.theta
+
+
Computes a set difference, A-AND-NOT-B, of two ThetaSketches.
+
+
ThetaIntersection - Class in org.apache.datasketches.theta
+
+
The API for intersection operations
+
+
ThetaIntersection() - Constructor for class org.apache.datasketches.theta.ThetaIntersection
+
+
No argument constructor.
+
+
ThetaSetOperation - Class in org.apache.datasketches.theta
+
+
The parent API for all Set Operations
+
+
ThetaSetOperationBuilder - Class in org.apache.datasketches.theta
+
+
For building a new ThetaSetOperation.
+
+
ThetaSetOperationBuilder() - Constructor for class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
Constructor for building a new ThetaSetOperation.
+
+
ThetaSketch - Class in org.apache.datasketches.theta
+
+
The top-level class for all theta sketches.
+
+
ThetaUnion - Class in org.apache.datasketches.theta
+
+
Compute the union of two or more theta sketches.
+
+
ThetaUnion() - Constructor for class org.apache.datasketches.theta.ThetaUnion
+
+
No argument constructor.
+
+
ThetaUtil - Class in org.apache.datasketches.thetacommon
+
+
Utility methods for the Theta Family of sketches
+
+
Three HllSketch Types - Section in package org.apache.datasketches.hll
+
 
+
toByteArray() - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Returns the sketch as a byte array.
+
+
toByteArray() - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Return this sketch as a compressed byte array.
+
+
toByteArray() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Serializes the current BloomFilter to an array of bytes.
+
+
toByteArray() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns a byte array representation of this sketch
+
+
toByteArray() - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
 
+
toByteArray() - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
 
+
toByteArray() - Method in class org.apache.datasketches.kll.KllItemsSketch
+
+
Export the current sketch as a compact byte array.
+
+
toByteArray() - Method in class org.apache.datasketches.kll.KllLongsSketch
+
 
+
toByteArray() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
 
+
toByteArray() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Serialize this union to a byte array.
+
+
toByteArray() - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Returns a byte array representation of this sketch.
+
+
toByteArray() - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Returns a byte array representation of this sketch.
+
+
toByteArray() - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Returns a byte array representation of this sketch.
+
+
toByteArray() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
toByteArray() - Method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Returns a byte array representation of this sketch
+
+
toByteArray() - Method in class org.apache.datasketches.sampling.ReservoirLongsUnion
+
+
Returns a byte array representation of this union
+
+
toByteArray() - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Serialize this TDigest to a byte array form.
+
+
toByteArray() - Method in class org.apache.datasketches.theta.ThetaIntersection
+
+
Serialize this intersection to a byte array form.
+
+
toByteArray() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Serialize this sketch to a byte array form.
+
+
toByteArray() - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Returns a byte array image of this ThetaUnion object
+
+
toByteArray() - Method in class org.apache.datasketches.tuple.adouble.DoubleSummary
+
 
+
toByteArray() - Method in class org.apache.datasketches.tuple.aninteger.IntegerSummary
+
 
+
toByteArray() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Returns serialized representation of the sketch
+
+
toByteArray() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion
+
+
Returns a byte array representation of this object
+
+
toByteArray() - Method in class org.apache.datasketches.tuple.CompactTupleSketch
+
 
+
toByteArray() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Deprecated. +
As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Serializing a CompactTupleSketch is not deprecated.
+
+
+
toByteArray() - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
+
Deprecated. +
As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Serializing a CompactTupleSketch is not deprecated.
+
+
+
toByteArray() - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Deprecated. +
As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Serializing a CompactTupleSketch is not deprecated.
+
+
+
toByteArray() - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
+
Deprecated. +
As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Serializing a CompactTupleSketch is not deprecated.
+
+
+
toByteArray() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Deprecated. +
As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Serializing a CompactTupleSketch is not deprecated.
+
+
+
toByteArray() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsSummary
+
 
+
toByteArray() - Method in interface org.apache.datasketches.tuple.Summary
+
+
This is to serialize a Summary instance to a byte array.
+
+
toByteArray() - Method in class org.apache.datasketches.tuple.TupleSketch
+
+
Serialize this sketch to a byte array.
+
+
toByteArray(boolean) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Serialize this sketch in a byte array form.
+
+
toByteArray(boolean, ArrayOfItemsSerDe) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Serialize this sketch to a byte array form.
+
+
toByteArray(ArrayOfItemsSerDe) - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Returns a byte array representation of this sketch.
+
+
toByteArray(ArrayOfItemsSerDe) - Method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Returns a byte array representation of this sketch.
+
+
toByteArray(ArrayOfItemsSerDe) - Method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Returns a byte array representation of this sketch.
+
+
toByteArray(ArrayOfItemsSerDe, Class) - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Returns a byte array representation of this sketch.
+
+
toByteArray(ArrayOfItemsSerDe, Class) - Method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Returns a byte array representation of this sketch.
+
+
toByteArray(ArrayOfItemsSerDe, Class) - Method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Returns a byte array representation of this sketch.
+
+
toByteArray(ArrayOfItemsSerDe) - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns a byte array representation of this sketch
+
+
toByteArray(ArrayOfItemsSerDe) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Serialize this sketch to a byte array form.
+
+
toByteArray(ArrayOfItemsSerDe) - Method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Serialize this union to a byte array.
+
+
toByteArray(ArrayOfItemsSerDe) - Method in class org.apache.datasketches.sampling.ReservoirItemsUnion
+
+
Returns a byte array representation of this union
+
+
toByteArray(ArrayOfItemsSerDe) - Method in class org.apache.datasketches.sampling.VarOptItemsUnion
+
+
Returns a byte array representation of this union
+
+
toByteArray(ArrayOfItemsSerDe, Class) - Method in class org.apache.datasketches.sampling.ReservoirItemsUnion
+
+
Returns a byte array representation of this union.
+
+
toByteArray(ArrayOfItemsSerDe, Class) - Method in class org.apache.datasketches.sampling.VarOptItemsUnion
+
+
Returns a byte array representation of this union.
+
+
toByteArrayCompressed() - Method in class org.apache.datasketches.theta.CompactThetaSketch
+
+
gets the sketch as a compressed byte array
+
+
toCompactByteArray() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
toCompactByteArray() - Method in class org.apache.datasketches.hll.HllUnion
+
+
Gets the serialization of this HllUnion operator as a byte array in compact form, which is +designed to be heapified only.
+
+
toLongArray() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Serializes the current BloomFilter to an array of longs.
+
+
toString() - Method in enum class org.apache.datasketches.common.Family
+
 
+
toString() - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Return a human-readable string summary of this sketch
+
+
toString() - Method in class org.apache.datasketches.fdt.Group
+
 
+
toString() - Method in class org.apache.datasketches.filters.bloomfilter.DirectBitArrayR
+
 
+
toString() - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
 
+
toString() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch.Row
+
 
+
toString() - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns a human readable summary of this sketch.
+
+
toString() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch.Row
+
 
+
toString() - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns a human readable summary of this sketch.
+
+
toString() - Method in class org.apache.datasketches.hll.HllSketch
+
+
Human readable summary as a string.
+
+
toString() - Method in class org.apache.datasketches.hll.HllUnion
+
+
Human readable summary as a string.
+
+
toString() - Method in class org.apache.datasketches.hllmap.UniqueCountMap
+
+
Returns a string with a human-readable summary of the UniqueCountMap and all the internal maps
+
+
toString() - Method in class org.apache.datasketches.kll.KllSketch
+
 
+
toString() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Returns human readable summary information about this sketch.
+
+
toString() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketchBuilder
+
+
Creates a human readable string that describes the current configuration of this builder.
+
+
toString() - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Returns summary information about the backing sketch.
+
+
toString() - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Returns human readable summary information about this sketch.
+
+
toString() - Method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Returns summary information about the backing sketch.
+
+
toString() - Method in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Returns a summary of the key parameters of the sketch.
+
+
toString() - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
toString() - Method in class org.apache.datasketches.req.ReqSketchBuilder
+
 
+
toString() - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Provides a human-readable summary of the sketch
+
+
toString() - Method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Returns a human-readable summary of the sketch, without items.
+
+
toString() - Method in class org.apache.datasketches.sampling.ReservoirItemsUnion
+
+
Returns a human-readable summary of the sketch, without items.
+
+
toString() - Method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Returns a human-readable summary of the sketch, without items.
+
+
toString() - Method in class org.apache.datasketches.sampling.ReservoirLongsUnion
+
+
Returns a human-readable summary of the sketch, without items.
+
+
toString() - Method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Returns a human-readable summary of the sketch.
+
+
toString() - Method in class org.apache.datasketches.sampling.VarOptItemsUnion
+
+
Returns a human-readable summary of the sketch, without items.
+
+
toString() - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Human-readable summary of this TDigest as a string
+
+
toString() - Method in class org.apache.datasketches.theta.ThetaSetOperationBuilder
+
 
+
toString() - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns a human readable summary of the sketch.
+
+
toString() - Method in class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
 
+
toString() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
 
+
toString() - Method in class org.apache.datasketches.tuple.TupleSketch
+
 
+
toString(boolean) - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Return a human-readable string summary of this sketch
+
+
toString(boolean) - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Human-readable summary of this TDigest as a string
+
+
toString(boolean, boolean) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
 
+
toString(boolean, boolean) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
 
+
toString(boolean, boolean) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
toString(boolean, boolean) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
 
+
toString(boolean, boolean) - Method in class org.apache.datasketches.kll.KllSketch
+
+
Returns human readable summary information about this sketch.
+
+
toString(boolean, boolean) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Returns human readable summary information about this sketch.
+
+
toString(boolean, boolean) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Returns summary information about the backing sketch.
+
+
toString(boolean, boolean) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Returns human readable summary information about this sketch.
+
+
toString(boolean, boolean) - Method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Returns summary information about the backing sketch.
+
+
toString(boolean, boolean, boolean) - Method in class org.apache.datasketches.hll.HllSketch
+
+
Human readable summary with optional detail.
+
+
toString(boolean, boolean, boolean) - Method in class org.apache.datasketches.hll.HllUnion
+
+
Human readable summary with optional detail.
+
+
toString(boolean, boolean, boolean, boolean) - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
toString(boolean, boolean, boolean, boolean) - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
toString(boolean, boolean, int, boolean) - Method in class org.apache.datasketches.theta.ThetaSketch
+
+
Gets a human readable listing of contents and summary of the given sketch.
+
+
toString(byte[]) - Static method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns a human readable string of the preamble of a byte array image of a FrequentItemsSketch.
+
+
toString(byte[]) - Static method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns a human readable string of the preamble of a byte array image of a FrequentLongsSketch.
+
+
toString(byte[]) - Static method in class org.apache.datasketches.hll.HllSketch
+
+
Returns a human readable string of the preamble of a byte array image of an HllSketch.
+
+
toString(byte[]) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Returns a human readable string of the preamble of a byte array image of a QuantilesDoublesSketch.
+
+
toString(byte[]) - Static method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Returns a human readable string of the preamble of a byte array image of an QuantilesItemsSketch.
+
+
toString(byte[]) - Static method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Returns a human readable string of the preamble of a byte array image of a ReservoirItemsSketch.
+
+
toString(byte[]) - Static method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Returns a human readable string of the preamble of a byte array image of a ReservoirLongsSketch.
+
+
toString(byte[]) - Static method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Returns a human readable string of the preamble of a byte array image of a VarOptItemsSketch.
+
+
toString(byte[]) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns a human readable string of the preamble of a byte array image of a ThetaSketch.
+
+
toString(byte[], boolean) - Static method in class org.apache.datasketches.cpc.CpcSketch
+
+
Returns a human readable string of the preamble of a byte array image of a CpcSketch.
+
+
toString(Boolean) - Method in class org.apache.datasketches.common.ArrayOfBooleansSerDe
+
 
+
toString(Double) - Method in class org.apache.datasketches.common.ArrayOfDoublesSerDe
+
 
+
toString(MemorySegment) - Static method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Returns a human readable string of the preamble of a MemorySegment image of a FrequentItemsSketch.
+
+
toString(MemorySegment) - Static method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Returns a human readable string of the preamble of a MemorySegment image of a FrequentLongsSketch.
+
+
toString(MemorySegment) - Static method in class org.apache.datasketches.hll.HllSketch
+
+
Returns a human readable string of the preamble of a MemorySegment image of an HllSketch.
+
+
toString(MemorySegment) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Returns a human readable string of the preamble of a MemorySegment image of a QuantilesDoublesSketch.
+
+
toString(MemorySegment) - Static method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
+
Returns a human readable string of the preamble of a MemorySegment image of an QuantilesItemsSketch.
+
+
toString(MemorySegment) - Static method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Returns a human readable string of the preamble of a MemorySegment image of a ReservoirItemsSketch.
+
+
toString(MemorySegment) - Static method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Returns a human readable string of the preamble of a MemorySegment image of a ReservoirLongsSketch.
+
+
toString(MemorySegment) - Static method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Returns a human readable string of the preamble of a MemorySegment image of a VarOptItemsSketch.
+
+
toString(MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Returns a human readable string of the preamble of a MemorySegment image of a ThetaSketch.
+
+
toString(MemorySegment, boolean) - Static method in class org.apache.datasketches.cpc.CpcSketch
+
+
Returns a human readable string of the preamble of a MemorySegment image of a CpcSketch.
+
+
toString(Long) - Method in class org.apache.datasketches.common.ArrayOfLongsSerDe
+
 
+
toString(Number) - Method in class org.apache.datasketches.common.ArrayOfNumbersSerDe
+
 
+
toString(String) - Method in class org.apache.datasketches.common.ArrayOfStringsSerDe
+
 
+
toString(String) - Method in class org.apache.datasketches.common.ArrayOfUtf16StringsSerDe
+
 
+
toString(T) - Method in class org.apache.datasketches.common.ArrayOfItemsSerDe
+
+
Returns a human readable string of an item.
+
+
toUpdatableByteArray() - Method in class org.apache.datasketches.hll.HllSketch
+
 
+
toUpdatableByteArray() - Method in class org.apache.datasketches.hll.HllUnion
+
 
+
trim() - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Rebuilds reducing the actual number of entries to the nominal number of entries if needed
+
+
trim() - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Rebuilds reducing the actual number of entries to the nominal number of entries if needed
+
+
trim() - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
+
Rebuilds reducing the actual number of entries to the nominal number of entries if needed
+
+
trim() - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Rebuilds reducing the actual number of entries to the nominal number of entries if needed
+
+
trim() - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
+
Rebuilds reducing the actual number of entries to the nominal number of entries if needed
+
+
trim() - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Rebuilds reducing the actual number of entries to the nominal number of entries if needed
+
+
TRIM_A - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction
+
+
Trim Sketch A by MinTheta
+
+
TRIM_A - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Trim Sketch A by MinTheta
+
+
TRIM_B - Enum constant in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Trim Sketch B by MinTheta
+
+
TUPLE - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The Tuple family of sketches is a large family of sketches that are extensions of the +Theta Sketch Framework.
+
+
TupleAnotB<S> - Class in org.apache.datasketches.tuple
+
+
Computes a set difference, A-AND-NOT-B, of two generic TupleSketches.
+
+
TupleAnotB() - Constructor for class org.apache.datasketches.tuple.TupleAnotB
+
+
No argument constructor.
+
+
TupleIntersection<S> - Class in org.apache.datasketches.tuple
+
+
Computes an intersection of two or more generic TupleSketches or generic TupleSketches +combined with ThetaSketches.
+
+
TupleIntersection(SummarySetOperations) - Constructor for class org.apache.datasketches.tuple.TupleIntersection
+
+
Creates new TupleIntersection instance with instructions on how to process two summaries that intersect.
+
+
TupleSketch<S> - Class in org.apache.datasketches.tuple
+
+
The top-level class for all Tuple sketches.
+
+
TupleSketchIterator<S> - Class in org.apache.datasketches.tuple
+
+
Iterator over a generic tuple sketch
+
+
TupleUnion<S> - Class in org.apache.datasketches.tuple
+
+
Compute the union of two or more generic tuple sketches or generic TupleSketches combined with +ThetaSketches.
+
+
TupleUnion(int, SummarySetOperations) - Constructor for class org.apache.datasketches.tuple.TupleUnion
+
+
Creates new TupleUnion instance.
+
+
TupleUnion(SummarySetOperations) - Constructor for class org.apache.datasketches.tuple.TupleUnion
+
+
Creates new TupleUnion instance with instructions on how to process two summaries that +overlap.
+
+
+

U

+
+
union(MemorySegment) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Iterative union operation, which means this method can be repeatedly called.
+
+
union(MemorySegment) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Perform a union operation with this ThetaUnion and the given MemorySegment image of any sketch of the +Theta Family.
+
+
union(MemorySegment, ArrayOfItemsSerDe) - Method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Iterative union operation, which means this method can be repeatedly called.
+
+
union(BloomFilter) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Unions two BloomFilters by applying a logical OR.
+
+
union(QuantilesDoublesSketch) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Iterative union operation, which means this method can be repeatedly called.
+
+
union(QuantilesItemsSketch) - Method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Iterative union operation, which means this method can be repeatedly called.
+
+
union(ThetaSketch) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Perform a union operation with this ThetaUnion and the given on-heap sketch of the Theta Family.
+
+
union(ThetaSketch, ThetaSketch) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
This implements a stateless, pair-wise union operation.
+
+
union(ThetaSketch, ThetaSketch, boolean, MemorySegment) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
This implements a stateless, pair-wise union operation.
+
+
union(ThetaSketch, S) - Method in class org.apache.datasketches.tuple.TupleUnion
+
+
Performs a stateful union of the internal set with the given ThetaSketch by combining entries +using the hashes from the ThetaSketch and summary values from the given summary.
+
+
union(DoubleSummary, DoubleSummary) - Method in class org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations
+
 
+
union(IntegerSummary, IntegerSummary) - Method in class org.apache.datasketches.tuple.aninteger.IntegerSummarySetOperations
+
 
+
union(ArrayOfDoublesSketch) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion
+
+
Updates the union by adding a set of entries from a given sketch, which can be on-heap or off-heap.
+
+
union(ArrayOfStringsSummary, ArrayOfStringsSummary) - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsSummarySetOperations
+
 
+
union(TupleSketch) - Method in class org.apache.datasketches.tuple.TupleUnion
+
+
Performs a stateful union of the internal set with the given TupleSketch.
+
+
union(TupleSketch, ThetaSketch, S) - Method in class org.apache.datasketches.tuple.TupleUnion
+
+
Perform a stateless, pair-wise union operation between a tupleSketch and a ThetaSketch.
+
+
union(TupleSketch, TupleSketch) - Method in class org.apache.datasketches.tuple.TupleUnion
+
+
Perform a stateless, pair-wise union operation between two tuple sketches.
+
+
union(S, S) - Method in interface org.apache.datasketches.tuple.SummarySetOperations
+
+
This is called by the union operator when both sketches have the same hash value.
+
+
UNION - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The Union family is an operation for the Theta Sketch Framework of sketches.
+
+
UniqueCountMap - Class in org.apache.datasketches.hllmap
+
+
This is a real-time, key-value HLL mapping sketch that tracks approximate unique counts of +identifiers (the values) associated with each key.
+
+
UniqueCountMap(int) - Constructor for class org.apache.datasketches.hllmap.UniqueCountMap
+
+
Constructs a UniqueCountMap with an initial capacity of one million entries.
+
+
UniqueCountMap(int, int) - Constructor for class org.apache.datasketches.hllmap.UniqueCountMap
+
+
Constructs a UniqueCountMap with a given initial number of entries.
+
+
UNSUPPORTED_MSG - Static variable in interface org.apache.datasketches.quantilescommon.QuantilesAPI
+
+
Unsupported operation for this Sketch Type.
+
+
UPDATABLE - Enum constant in enum class org.apache.datasketches.kll.KllSketch.SketchStructure
+
+
Updatable Preamble Structure
+
+
UpdatableQuantilesDoublesSketch - Class in org.apache.datasketches.quantiles
+
+
Extends QuantilesDoubleSketch
+
+
UpdatableSummary<U> - Interface in org.apache.datasketches.tuple
+
+
Interface for updating user-defined Summary
+
+
UpdatableThetaSketch - Class in org.apache.datasketches.theta
+
+
The parent class for the UpdatableThetaSketch families, such as QuickSelectThetaSketch and AlphaSketch.
+
+
UpdatableThetaSketchBuilder - Class in org.apache.datasketches.theta
+
+
For building a new UpdatableThetaSketch.
+
+
UpdatableThetaSketchBuilder() - Constructor for class org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
Constructor for building a new UpdatableThetaSketch.
+
+
UpdatableTupleSketch<U,S> - Class in org.apache.datasketches.tuple
+
+
An extension of QuickSelectSketch<S>, which can be updated with many types of keys.
+
+
UpdatableTupleSketch(int, int, float, SummaryFactory) - Constructor for class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
This is to create a new instance of an UpdatableQuickSelectSketch.
+
+
UpdatableTupleSketch(MemorySegment, SummaryDeserializer, SummaryFactory) - Constructor for class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Deprecated. +
As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Heapifying a CompactTupleSketch is not deprecated.
+
+
+
UpdatableTupleSketch(UpdatableTupleSketch) - Constructor for class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Copy Constructor
+
+
UpdatableTupleSketchBuilder<U,S> - Class in org.apache.datasketches.tuple
+
+
For building a new generic tuple UpdatableTupleSketch
+
+
UpdatableTupleSketchBuilder(SummaryFactory) - Constructor for class org.apache.datasketches.tuple.UpdatableTupleSketchBuilder
+
+
Creates an instance of UpdatableTupleSketchBuilder with default parameters
+
+
update(byte[]) - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Present the given byte array as a potential unique item.
+
+
update(byte[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided byte[].
+
+
update(byte[]) - Method in class org.apache.datasketches.hll.HllSketch
+
+
Present the given byte array as a potential unique item.
+
+
update(byte[]) - Method in class org.apache.datasketches.hll.HllUnion
+
+
Present the given byte array as a potential unique item.
+
+
update(byte[]) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Update this union with the given byte array item.
+
+
update(byte[]) - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Present this sketch with the given byte array.
+
+
update(byte[], byte[]) - Method in class org.apache.datasketches.hllmap.UniqueCountMap
+
+
Updates the map with a given key and identifier and returns the estimate of the number of +unique identifiers encountered so far for the given key.
+
+
update(byte[], double[]) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Updates this sketch with a byte[] key and double values.
+
+
update(byte[], long) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Updates the sketch with the provided item and weight.
+
+
update(byte[], U) - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Updates this sketch with a byte[] key and U value.
+
+
update(char[]) - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Present the given char array as a potential unique item.
+
+
update(char[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided char[].
+
+
update(char[]) - Method in class org.apache.datasketches.hll.HllSketch
+
+
Present the given char array as a potential unique item.
+
+
update(char[]) - Method in class org.apache.datasketches.hll.HllUnion
+
+
Present the given char array as a potential unique item.
+
+
update(char[]) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Update this union with the given char array item.
+
+
update(char[]) - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Present this sketch with the given char array.
+
+
update(double) - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Present the given double (or float) datum as a potential unique item.
+
+
update(double) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided double value.
+
+
update(double) - Method in class org.apache.datasketches.hll.HllSketch
+
+
Present the given double (or float) datum as a potential unique item.
+
+
update(double) - Method in class org.apache.datasketches.hll.HllUnion
+
+
Present the given double (or float) datum as a potential unique item.
+
+
update(double) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
 
+
update(double) - Method in class org.apache.datasketches.quantiles.CompactQuantilesDoublesSketch
+
 
+
update(double) - Method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Update this union with the given double (or float) data Item.
+
+
update(double) - Method in class org.apache.datasketches.quantiles.UpdatableQuantilesDoublesSketch
+
 
+
update(double) - Method in interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI
+
+
Updates this sketch with the given item.
+
+
update(double) - Method in class org.apache.datasketches.tdigest.TDigestDouble
+
+
Update this TDigest with the given value
+
+
update(double) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Update this union with the given double (or float) data item.
+
+
update(double) - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Present this sketch with the given double (or float) datum.
+
+
update(double[], int, int) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Vector update.
+
+
update(double, double[]) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Updates this sketch with a double key and double values.
+
+
update(double, long) - Method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Weighted update.
+
+
update(double, U) - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Updates this sketch with a double key and U value.
+
+
update(float) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
 
+
update(float) - Method in interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI
+
+
Updates this sketch with the given item.
+
+
update(float) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
update(float[], int, int) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Vector update.
+
+
update(float, long) - Method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Weighted update.
+
+
update(int[]) - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Present the given integer array as a potential unique item.
+
+
update(int[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided int[].
+
+
update(int[]) - Method in class org.apache.datasketches.hll.HllSketch
+
+
Present the given integer array as a potential unique item.
+
+
update(int[]) - Method in class org.apache.datasketches.hll.HllUnion
+
+
Present the given integer array as a potential unique item.
+
+
update(int[]) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Update this union with the given integer array item.
+
+
update(int[]) - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Present this sketch with the given integer array.
+
+
update(int[], double[]) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Updates this sketch with a int[] key and double values.
+
+
update(int[], U) - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Updates this sketch with a int[] key and U value.
+
+
update(long) - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Present the given long as a potential unique item.
+
+
update(long) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided long value.
+
+
update(long) - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Update this sketch with an item and a frequency count of one.
+
+
update(long) - Method in class org.apache.datasketches.hll.HllSketch
+
+
Present the given long as a potential unique item.
+
+
update(long) - Method in class org.apache.datasketches.hll.HllUnion
+
+
Present the given long as a potential unique item.
+
+
update(long) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
 
+
update(long) - Method in interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI
+
+
Updates this sketch with the given item.
+
+
update(long) - Method in class org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
Randomly decide whether or not to include an item in the sample set.
+
+
update(long) - Method in class org.apache.datasketches.sampling.ReservoirLongsUnion
+
+
Present this union with a long.
+
+
update(long) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Update this union with the given long data item.
+
+
update(long) - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Present this sketch with a long.
+
+
update(long[]) - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Present the given long array as a potential unique item.
+
+
update(long[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided long[].
+
+
update(long[]) - Method in class org.apache.datasketches.hll.HllSketch
+
+
Present the given long array as a potential unique item.
+
+
update(long[]) - Method in class org.apache.datasketches.hll.HllUnion
+
+
Present the given long array as a potential unique item.
+
+
update(long[]) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Update this union with the given long array item.
+
+
update(long[]) - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Present this sketch with the given long array.
+
+
update(long[], double[]) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Updates this sketch with a long[] key and double values.
+
+
update(long[], int, int) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Vector update.
+
+
update(long[], U) - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Updates this sketch with a long[] key and U value.
+
+
update(long, double[]) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Updates this sketch with a long key and double values.
+
+
update(long, int, ArrayList) - Method in class org.apache.datasketches.sampling.ReservoirItemsUnion
+
+
Present this union with raw elements of a sketch.
+
+
update(long, long) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Updates the sketch with the provided item and weight.
+
+
update(long, long) - Method in class org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
Update this sketch with a item and a positive frequency count (or weight).
+
+
update(long, long) - Method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Weighted update.
+
+
update(long, Double) - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
 
+
update(long, Integer) - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
 
+
update(long, U) - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Updates this sketch with a long key and U value.
+
+
update(short[]) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided short[].
+
+
update(Double) - Method in class org.apache.datasketches.tuple.adouble.DoubleSummary
+
 
+
update(MemorySegment) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the data in the provided MemorySegment.
+
+
update(MemorySegment) - Method in class org.apache.datasketches.sampling.ReservoirLongsUnion
+
+
Union the given MemorySegment image of the sketch.
+
+
update(MemorySegment, ArrayOfItemsSerDe) - Method in class org.apache.datasketches.sampling.ReservoirItemsUnion
+
+
Union the given MemorySegment image of the sketch.
+
+
update(MemorySegment, ArrayOfItemsSerDe) - Method in class org.apache.datasketches.sampling.VarOptItemsUnion
+
+
Union the given MemorySegment image of the sketch.
+
+
update(Integer) - Method in class org.apache.datasketches.tuple.aninteger.IntegerSummary
+
 
+
update(String) - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Present the given String as a potential unique item.
+
+
update(String) - Method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Updates the filter with the provided String.
+
+
update(String) - Method in class org.apache.datasketches.hll.HllSketch
+
+
Present the given String as a potential unique item.
+
+
update(String) - Method in class org.apache.datasketches.hll.HllUnion
+
+
Present the given String as a potential unique item.
+
+
update(String) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Update this union with the with the given String data item.
+
+
update(String) - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Present this sketch with the given String.
+
+
update(String[]) - Method in class org.apache.datasketches.fdt.FdtSketch
+
+
Update the sketch with the given string array tuple.
+
+
update(String[]) - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsSummary
+
 
+
update(String[], String[]) - Method in class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch
+
+
Updates the sketch with String arrays for both key and value.
+
+
update(String, double[]) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Updates this sketch with a String key and double values.
+
+
update(String, long) - Method in class org.apache.datasketches.count.CountMinSketch
+
+
Updates the sketch with the provided item and weight.
+
+
update(String, Double) - Method in class org.apache.datasketches.tuple.adouble.DoubleTupleSketch
+
 
+
update(String, Integer) - Method in class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch
+
 
+
update(String, U) - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Updates this sketch with a String key and U value.
+
+
update(ByteBuffer) - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Present the given ByteBuffer as a potential unique item +If the ByteBuffer is null or empty no update attempt is made and the method returns
+
+
update(ByteBuffer) - Method in class org.apache.datasketches.hll.HllSketch
+
+
Present the given byte buffer as a potential unique item.
+
+
update(ByteBuffer) - Method in class org.apache.datasketches.hll.HllUnion
+
+
Present the given byte buffer as a potential unique item.
+
+
update(ByteBuffer) - Method in class org.apache.datasketches.theta.ThetaUnion
+
+
Update this union with the given ByteBuffer item.
+
+
update(ByteBuffer) - Method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Present this sketch with the given ByteBuffer +If the ByteBuffer is null or empty, no update attempt is made and the method returns.
+
+
update(ByteBuffer, double[]) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Updates this sketch with a ByteBuffer key and double values.
+
+
update(ByteBuffer, U) - Method in class org.apache.datasketches.tuple.UpdatableTupleSketch
+
+
Updates this sketch with a ByteBuffer and U value +The value is passed to the update() method of the Summary object associated with the key
+
+
update(CpcSketch) - Method in class org.apache.datasketches.cpc.CpcUnion
+
+
Update this union with a CpcSketch.
+
+
update(HllSketch) - Method in class org.apache.datasketches.hll.HllUnion
+
+
Update this HllUnion operator with the given sketch.
+
+
update(ReservoirItemsSketch) - Method in class org.apache.datasketches.sampling.ReservoirItemsUnion
+
+
Union the given sketch.
+
+
update(ReservoirItemsSketch) - Method in class org.apache.datasketches.sampling.VarOptItemsUnion
+
+
Union a reservoir sketch.
+
+
update(ReservoirLongsSketch) - Method in class org.apache.datasketches.sampling.ReservoirLongsUnion
+
+
Union the given sketch.
+
+
update(VarOptItemsSketch) - Method in class org.apache.datasketches.sampling.VarOptItemsUnion
+
+
Union the given sketch.
+
+
update(ArrayOfDoublesSketch, ArrayOfDoublesSketch) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotB
+
+
Perform A-and-not-B set operation on the two given sketches.
+
+
update(ArrayOfDoublesSketch, ArrayOfDoublesSketch) - Method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotBImpl
+
 
+
update(T) - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Update this sketch with an item and a frequency count of one.
+
+
update(T) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
 
+
update(T) - Method in class org.apache.datasketches.quantiles.QuantilesItemsSketch
+
 
+
update(T) - Method in class org.apache.datasketches.quantiles.QuantilesItemsUnion
+
+
Update this union with the given dataItem.
+
+
update(T) - Method in interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI
+
+
Updates this sketch with the given item.
+
+
update(T) - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Updates this sketch with the given data item with weight 1.0.
+
+
update(T) - Method in class org.apache.datasketches.sampling.ReservoirItemsSketch
+
+
Randomly decide whether or not to include an item in the sample set.
+
+
update(T) - Method in class org.apache.datasketches.sampling.ReservoirItemsUnion
+
+
Present this union with a single item to be added to the union.
+
+
update(T, double) - Method in class org.apache.datasketches.sampling.EbppsItemsSketch
+
+
Updates this sketch with the given data item with the given weight.
+
+
update(T, double) - Method in class org.apache.datasketches.sampling.VarOptItemsSketch
+
+
Randomly decide whether or not to include an item in the sample set.
+
+
update(T, long) - Method in class org.apache.datasketches.frequencies.FrequentItemsSketch
+
+
Update this sketch with an item and a positive frequency count.
+
+
update(T, long) - Method in class org.apache.datasketches.kll.KllItemsSketch
+
+
Weighted update.
+
+
update(U) - Method in interface org.apache.datasketches.tuple.UpdatableSummary
+
+
This is to provide a method of updating summaries.
+
+
UpdateReturnState - Enum Class in org.apache.datasketches.theta
+
+ +
+
upperBound - Variable in class org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow
+
+
The upper bound value
+
+
Util - Class in org.apache.datasketches.common
+
+
Common utility functions.
+
+
Util - Class in org.apache.datasketches.tuple
+
+
Common utility functions for Tuples
+
+
Util() - Constructor for class org.apache.datasketches.tuple.Util
+
+
No argument constructor.
+
+
+

V

+
+
validate() - Method in class org.apache.datasketches.cpc.CpcSketch
+
+
Convience function that this Sketch is valid.
+
+
validateFamily(byte, byte) - Static method in class org.apache.datasketches.tuple.SerializerDeserializer
+
+
Validates the preamble-Longs value given the family ID
+
+
validateItems(T[], Comparator) - Static method in interface org.apache.datasketches.quantilescommon.GenericSortedView
+
+
Checks the sequential validity of the given array of generic items.
+
+
validateType(byte, SerializerDeserializer.SketchType) - Static method in class org.apache.datasketches.tuple.SerializerDeserializer
+
+
Validates the sketch type byte versus the expected value
+
+
value() - Element in annotation interface org.apache.datasketches.common.SuppressFBWarnings
+
+
A list of comma-separated, quoted SpotBugs warnings that are to be suppressed in the associated +annotated element.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.common.Family
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.common.ResizeFactor
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.frequencies.ErrorType
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.hll.TgtHllType
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.kll.KllSketch.SketchStructure
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.kll.KllSketch.SketchType
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.partitions.BoundsRule
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.quantilescommon.QuantileSearchCriteria
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.theta.UpdateReturnState
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.IntersectAction
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.tuple.adouble.DoubleSummary.Mode
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode
+
+
Returns the enum constant of this class with the specified name.
+
+
valueOf(String) - Static method in enum class org.apache.datasketches.tuple.SerializerDeserializer.SketchType
+
+
Returns the enum constant of this class with the specified name.
+
+
values() - Static method in enum class org.apache.datasketches.common.Family
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.common.ResizeFactor
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.frequencies.ErrorType
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.hll.TgtHllType
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.kll.KllSketch.SketchStructure
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.kll.KllSketch.SketchType
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.partitions.BoundsRule
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.quantilescommon.InequalitySearch
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.quantilescommon.QuantileSearchCriteria
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.theta.UpdateReturnState
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.IntersectAction
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.tuple.adouble.DoubleSummary.Mode
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
values() - Static method in enum class org.apache.datasketches.tuple.SerializerDeserializer.SketchType
+
+
Returns an array containing the constants of this enum class, in +the order they are declared.
+
+
VAROPT - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The VarOpt family of sketches.
+
+
VAROPT_UNION - Enum constant in enum class org.apache.datasketches.common.Family
+
+
The VarOpt family of sketches.
+
+
VarOptItemsSamples<T> - Class in org.apache.datasketches.sampling
+
+
This class provides access to the samples contained in a VarOptItemsSketch.
+
+
VarOptItemsSamples.VarOptItemsIterator - Class in org.apache.datasketches.sampling
+
+
The standard iterator
+
+
VarOptItemsSamples.WeightedSample - Class in org.apache.datasketches.sampling
+
+
A convenience class to allow easy iterator access to a VarOpt sample.
+
+
VarOptItemsSketch<T> - Class in org.apache.datasketches.sampling
+
+
This sketch provides a variance optimal sample over an input stream of weighted items.
+
+
VarOptItemsUnion<T> - Class in org.apache.datasketches.sampling
+
+
Provides a unioning operation over varopt sketches.
+
+
viewCompactorDetail(String, boolean) - Method in class org.apache.datasketches.req.ReqSketch
+
 
+
+

W

+
+
weights() - Method in class org.apache.datasketches.sampling.VarOptItemsSamples
+
+
Returns a copy of the array of weights contained in the sketch.
+
+
weights(int) - Method in class org.apache.datasketches.sampling.VarOptItemsSamples
+
+
Returns a single weight from the samples contained in the sketch.
+
+
wrap(byte[]) - Static method in class org.apache.datasketches.theta.CompactThetaSketch
+
+
Wrap takes the sketch image in the given byte array and refers to it directly.
+
+
wrap(byte[], long) - Static method in class org.apache.datasketches.theta.CompactThetaSketch
+
+
Wrap takes the sketch image in the given byte array and refers to it directly.
+
+
wrap(MemorySegment) - Static method in interface org.apache.datasketches.common.positional.PositionalSegment
+
+
Gets an instance of this PositionalSegment.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Wraps the given MemorySegment into this filter class.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.hll.HllSketch
+
+
Wraps the given read-only MemorySegment that must be a image of a valid sketch, +which may be in compact or updatable form, and should have data.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Wrap this sketch around the given MemorySegment image of a compact, read-only QuantilesDoublesSketch.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Returns an updatable Union object that wraps the given MemorySegment that contains an image of a QuantilesDoublesSketch.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.quantiles.UpdatableQuantilesDoublesSketch
+
+
Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.theta.CompactThetaSketch
+
+
Wrap takes the CompactThetaSketch image in given MemorySegment and refers to it directly.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaIntersection
+
+
Factory: Wrap a ThetaIntersection target around the given source MemorySegment containing intersection data.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaSetOperation
+
+
Wrap takes the ThetaSetOperation image in MemorySegment and refers to it directly.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Wrap takes the sketch image in the given MemorySegment and refers to it directly.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.theta.ThetaUnion
+
+
Wrap a ThetaUnion object around a ThetaUnion MemorySegment object containing data.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Wrap takes the writable sketch image in MemorySegment and refers to it directly.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Wrap the given MemorySegment as an ArrayOfDoublesSketch.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion
+
+
Wrap the given MemorySegment as an ArrayOfDoublesUnion.
+
+
wrap(MemorySegment) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Wrap the given MemorySegment as an ArrayOfDoublesUpdatableSketch.
+
+
wrap(MemorySegment, long) - Static method in class org.apache.datasketches.theta.CompactThetaSketch
+
+
Wrap takes the sketch image in the given MemorySegment and refers to it directly.
+
+
wrap(MemorySegment, long) - Static method in class org.apache.datasketches.theta.ThetaIntersection
+
+
Factory: Wrap a ThetaIntersection target around the given source MemorySegment containing intersection data.
+
+
wrap(MemorySegment, long) - Static method in class org.apache.datasketches.theta.ThetaSetOperation
+
+
Wrap takes the ThetaSetOperation image in MemorySegment and refers to it directly.
+
+
wrap(MemorySegment, long) - Static method in class org.apache.datasketches.theta.ThetaSketch
+
+
Wrap takes the sketch image in the given MemorySegment and refers to it directly.
+
+
wrap(MemorySegment, long) - Static method in class org.apache.datasketches.theta.ThetaUnion
+
+
Wrap a ThetaUnion object around a ThetaUnion MemorySegment object containing data.
+
+
wrap(MemorySegment, long) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Wrap the given MemorySegment and seed as a ArrayOfDoublesSketch.
+
+
wrap(MemorySegment, long) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion
+
+
Wrap the given MemorySegment and seed as an ArrayOfDoublesUnion.
+
+
wrap(MemorySegment, long) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
Wrap the given MemorySegment and seed as a ArrayOfDoublesUpdatableSketch.
+
+
wrap(MemorySegment, Comparator, ArrayOfItemsSerDe) - Static method in class org.apache.datasketches.kll.KllItemsSketch
+
+
Constructs a thin wrapper on the heap around a MemorySegment (or MemorySegment) already initialized with a +validated sketch image of a type T consistent with the given comparator and serDe.
+
+
wrap(MemorySegment, MemorySegmentRequest) - Static method in class org.apache.datasketches.kll.KllDoublesSketch
+
+
Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch and including an +optional, user defined MemorySegmentRequest.
+
+
wrap(MemorySegment, MemorySegmentRequest) - Static method in class org.apache.datasketches.kll.KllFloatsSketch
+
+
Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch and including an +optional, user defined MemorySegmentRequest.
+
+
wrap(MemorySegment, MemorySegmentRequest) - Static method in class org.apache.datasketches.kll.KllLongsSketch
+
+
Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch and including an +optional, user defined MemorySegmentRequest.
+
+
wrap(MemorySegment, MemorySegmentRequest) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
Returns an updatable Union object that wraps the given MemorySegment that contains an image of a QuantilesDoublesSketch.
+
+
wrap(MemorySegment, MemorySegmentRequest) - Static method in class org.apache.datasketches.quantiles.UpdatableQuantilesDoublesSketch
+
+
Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch and including an +optional, user defined MemorySegmentRequest.
+
+
wrap(MemorySegment, MemorySegmentRequest, long) - Static method in class org.apache.datasketches.theta.UpdatableThetaSketch
+
+
Wrap takes the sketch image in MemorySegment and refers to it directly.
+
+
wrapSketch(MemorySegment) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Wrap the given MemorySegment as an ArrayOfDoublesSketch.
+
+
wrapSketch(MemorySegment, long) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Wrap the given MemorySegment and seed as a ArrayOfDoublesSketch.
+
+
wrapUnion(MemorySegment) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Wrap the given MemorySegment as an ArrayOfDoublesUnion +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
+
+
wrapUnion(MemorySegment, long) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Wrap the given MemorySegment and seed as an ArrayOfDoublesUnion +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
+
+
wrapUpdatableSketch(MemorySegment) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Wrap the given MemorySegment as an ArrayOfDoublesUpdatableSketch.
+
+
wrapUpdatableSketch(MemorySegment, long) - Static method in class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
Wrap the given MemorySegment and seed as a ArrayOfDoublesUpdatableSketch.
+
+
writableWrap(MemorySegment) - Static method in class org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
Wraps the given MemorySegment into this filter class.
+
+
writableWrap(MemorySegment) - Static method in class org.apache.datasketches.hll.HllSketch
+
+
Wraps the given MemorySegment, which must be a image of a valid updatable sketch, +and may have data.
+
+
writableWrap(MemorySegment) - Static method in class org.apache.datasketches.hll.HllUnion
+
+
Wraps the given MemorySegment, which must be a image of a valid updatable HLL_8 sketch, +and may have data.
+
+
writableWrap(MemorySegment) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Wrap this sketch around the given MemorySegment image of an updatable QuantilesDoublesSketch.
+
+
writableWrap(MemorySegment, MemorySegmentRequest) - Static method in class org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
Wrap this sketch around the given MemorySegment image of an updatable QuantilesDoublesSketch.
+
+
+

X

+
+
X1 - Enum constant in enum class org.apache.datasketches.common.ResizeFactor
+
+
Do not resize.
+
+
X2 - Enum constant in enum class org.apache.datasketches.common.ResizeFactor
+
+
Resize factor is 2.
+
+
X4 - Enum constant in enum class org.apache.datasketches.common.ResizeFactor
+
+
Resize factor is 4.
+
+
X8 - Enum constant in enum class org.apache.datasketches.common.ResizeFactor
+
+
Resize factor is 8.
+
+
XxHash - Class in org.apache.datasketches.hash
+
+
The XxHash is a fast, non-cryptographic, 64-bit hash function that has +excellent avalanche and 2-way bit independence properties.
+
+
XxHash64 - Class in org.apache.datasketches.hash
+
+
The XxHash is a fast, non-cryptographic, 64-bit hash function that has +excellent avalanche and 2-way bit independence properties.
+
+
+

Z

+
+
Zero error at low cardinalities - Section in package org.apache.datasketches.hll
+
 
+
zeroPad(String, int) - Static method in class org.apache.datasketches.common.Util
+
+
Prepend the given string with zeros.
+
+
+A B C D E F G H I J K L M N O P Q R S T U V W X Z 
All Classes and Interfaces|All Packages|Constant Field Values|Serialized Form +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/index.html b/target/site/apidocs/index.html new file mode 100644 index 000000000..a192a2496 --- /dev/null +++ b/target/site/apidocs/index.html @@ -0,0 +1,199 @@ + + + + +Overview (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

datasketches-java 9.0.1-SNAPSHOT API

+
+

Sketching Core Library

+

Overview

+ +

The Sketching Core Library provides a range of stochastic streaming algorithms and closely + related java technologies that are particularly useful when integrating this technology into + systems that must deal with massive data. +

+ +

This library is divided into packages that constitute distinct groups of functionality:

+ +Note: In general, if the requirements or promises of any method's contract are not fulfilled +(that is, if there is a bug in either the method or its caller), +then an unchecked exception will be thrown. +The precise type of such an unchecked exception does not form part of any method's contract.
+
+
Packages
+
+
Package
+
Description
+ +
+
This package is the parent package for all sketch families and common code areas.
+
+ +
+
This package is for common classes that may be used across all the sketch families.
+
+ +
+
This package provides the classes that define and implement a relative positional API.
+
+ +
+
This package in intended for implementations of the the Count Sketch and the Count-min Sketch both of which can be used to estimate +frequency-moments of a stream of distinct elements.
+
+ +
+
Compressed Probabilistic Counting sketch family
+
+ +
+
Frequent Distinct Tuples Sketch
+
+ +
+
The filters package contains data structures used to determine +approximate set-membership.
+
+ +
+
BloomFilter package
+
+ +
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+ +
+
The hash package contains a high-performing and extended Java implementations +of Austin Appleby's 128-bit MurmurHash3 hash function originally coded in C.
+
+ +
+
The DataSketches™ HllSketch family package
+
+ +
+
The hllmap package contains a space efficient HLL mapping sketch of keys to approximate unique +count of identifiers.
+
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+ +
+
t-Digest for estimating quantiles and ranks.
+
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+ +
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/legal/ADDITIONAL_LICENSE_INFO b/target/site/apidocs/legal/ADDITIONAL_LICENSE_INFO new file mode 100644 index 000000000..ff700cd09 --- /dev/null +++ b/target/site/apidocs/legal/ADDITIONAL_LICENSE_INFO @@ -0,0 +1,37 @@ + ADDITIONAL INFORMATION ABOUT LICENSING + +Certain files distributed by Oracle America, Inc. and/or its affiliates are +subject to the following clarification and special exception to the GPLv2, +based on the GNU Project exception for its Classpath libraries, known as the +GNU Classpath Exception. + +Note that Oracle includes multiple, independent programs in this software +package. Some of those programs are provided under licenses deemed +incompatible with the GPLv2 by the Free Software Foundation and others. +For example, the package includes programs licensed under the Apache +License, Version 2.0 and may include FreeType. Such programs are licensed +to you under their original licenses. + +Oracle facilitates your further distribution of this package by adding the +Classpath Exception to the necessary parts of its GPLv2 code, which permits +you to use that code in combination with other independent modules not +licensed under the GPLv2. However, note that this would not permit you to +commingle code under an incompatible license with Oracle's GPLv2 licensed +code by, for example, cutting and pasting such code into a file also +containing Oracle's GPLv2 licensed code and then distributing the result. + +Additionally, if you were to remove the Classpath Exception from any of the +files to which it applies and distribute the result, you would likely be +required to license some or all of the other code in that distribution under +the GPLv2 as well, and since the GPLv2 is incompatible with the license terms +of some items included in the distribution by Oracle, removing the Classpath +Exception could therefore effectively compromise your ability to further +distribute the package. + +Failing to distribute notices associated with some files may also create +unexpected legal consequences. + +Proceed with caution and we recommend that you obtain the advice of a lawyer +skilled in open source matters before removing the Classpath Exception or +making modifications to this package which may subsequently be redistributed +and/or involve the use of third party software. diff --git a/target/site/apidocs/legal/ASSEMBLY_EXCEPTION b/target/site/apidocs/legal/ASSEMBLY_EXCEPTION new file mode 100644 index 000000000..429666664 --- /dev/null +++ b/target/site/apidocs/legal/ASSEMBLY_EXCEPTION @@ -0,0 +1,27 @@ + +OPENJDK ASSEMBLY EXCEPTION + +The OpenJDK source code made available by Oracle America, Inc. (Oracle) at +openjdk.org ("OpenJDK Code") is distributed under the terms of the GNU +General Public License version 2 +only ("GPL2"), with the following clarification and special exception. + + Linking this OpenJDK Code statically or dynamically with other code + is making a combined work based on this library. Thus, the terms + and conditions of GPL2 cover the whole combination. + + As a special exception, Oracle gives you permission to link this + OpenJDK Code with certain code licensed by Oracle as indicated at + https://openjdk.org/legal/exception-modules-2007-05-08.html + ("Designated Exception Modules") to produce an executable, + regardless of the license terms of the Designated Exception Modules, + and to copy and distribute the resulting executable under GPL2, + provided that the Designated Exception Modules continue to be + governed by the licenses under which they were offered by Oracle. + +As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code +to build an executable that includes those portions of necessary code that +Oracle could not provide under GPL2 (or that Oracle has provided under GPL2 +with the Classpath exception). If you modify or add to the OpenJDK code, +that new GPL2 code may still be combined with Designated Exception Modules +if the new code is made subject to this exception by its copyright holder. diff --git a/target/site/apidocs/legal/LICENSE b/target/site/apidocs/legal/LICENSE new file mode 100644 index 000000000..8b400c7ab --- /dev/null +++ b/target/site/apidocs/legal/LICENSE @@ -0,0 +1,347 @@ +The GNU General Public License (GPL) + +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to share +and change it. By contrast, the GNU General Public License is intended to +guarantee your freedom to share and change free software--to make sure the +software is free for all its users. This General Public License applies to +most of the Free Software Foundation's software and to any other program whose +authors commit to using it. (Some other Free Software Foundation software is +covered by the GNU Library General Public License instead.) You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom to +distribute copies of free software (and charge for this service if you wish), +that you receive source code or can get it if you want it, that you can change +the software or use pieces of it in new free programs; and that you know you +can do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny +you these rights or to ask you to surrender the rights. These restrictions +translate to certain responsibilities for you if you distribute copies of the +software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for +a fee, you must give the recipients all the rights that you have. You must +make sure that they, too, receive or can get the source code. And you must +show them these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) +offer you this license which gives you legal permission to copy, distribute +and/or modify the software. + +Also, for each author's protection and ours, we want to make certain that +everyone understands that there is no warranty for this free software. If the +software is modified by someone else and passed on, we want its recipients to +know that what they have is not the original, so that any problems introduced +by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We +wish to avoid the danger that redistributors of a free program will +individually obtain patent licenses, in effect making the program proprietary. +To prevent this, we have made it clear that any patent must be licensed for +everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License applies to any program or other work which contains a notice +placed by the copyright holder saying it may be distributed under the terms of +this General Public License. The "Program", below, refers to any such program +or work, and a "work based on the Program" means either the Program or any +derivative work under copyright law: that is to say, a work containing the +Program or a portion of it, either verbatim or with modifications and/or +translated into another language. (Hereinafter, translation is included +without limitation in the term "modification".) Each licensee is addressed as +"you". + +Activities other than copying, distribution and modification are not covered by +this License; they are outside its scope. The act of running the Program is +not restricted, and the output from the Program is covered only if its contents +constitute a work based on the Program (independent of having been made by +running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute verbatim copies of the Program's source code as +you receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice and +disclaimer of warranty; keep intact all the notices that refer to this License +and to the absence of any warranty; and give any other recipients of the +Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may +at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus +forming a work based on the Program, and copy and distribute such modifications +or work under the terms of Section 1 above, provided that you also meet all of +these conditions: + + a) You must cause the modified files to carry prominent notices stating + that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in whole or + in part contains or is derived from the Program or any part thereof, to be + licensed as a whole at no charge to all third parties under the terms of + this License. + + c) If the modified program normally reads commands interactively when run, + you must cause it, when started running for such interactive use in the + most ordinary way, to print or display an announcement including an + appropriate copyright notice and a notice that there is no warranty (or + else, saying that you provide a warranty) and that users may redistribute + the program under these conditions, and telling the user how to view a copy + of this License. (Exception: if the Program itself is interactive but does + not normally print such an announcement, your work based on the Program is + not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable +sections of that work are not derived from the Program, and can be reasonably +considered independent and separate works in themselves, then this License, and +its terms, do not apply to those sections when you distribute them as separate +works. But when you distribute the same sections as part of a whole which is a +work based on the Program, the distribution of the whole must be on the terms +of this License, whose permissions for other licensees extend to the entire +whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your +rights to work written entirely by you; rather, the intent is to exercise the +right to control the distribution of derivative or collective works based on +the Program. + +In addition, mere aggregation of another work not based on the Program with the +Program (or with a work based on the Program) on a volume of a storage or +distribution medium does not bring the other work under the scope of this +License. + +3. You may copy and distribute the Program (or a work based on it, under +Section 2) in object code or executable form under the terms of Sections 1 and +2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable source + code, which must be distributed under the terms of Sections 1 and 2 above + on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three years, to + give any third party, for a charge no more than your cost of physically + performing source distribution, a complete machine-readable copy of the + corresponding source code, to be distributed under the terms of Sections 1 + and 2 above on a medium customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer to + distribute corresponding source code. (This alternative is allowed only + for noncommercial distribution and only if you received the program in + object code or executable form with such an offer, in accord with + Subsection b above.) + +The source code for a work means the preferred form of the work for making +modifications to it. For an executable work, complete source code means all +the source code for all modules it contains, plus any associated interface +definition files, plus the scripts used to control compilation and installation +of the executable. However, as a special exception, the source code +distributed need not include anything that is normally distributed (in either +source or binary form) with the major components (compiler, kernel, and so on) +of the operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the source +code from the same place counts as distribution of the source code, even though +third parties are not compelled to copy the source along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program except as +expressly provided under this License. Any attempt otherwise to copy, modify, +sublicense or distribute the Program is void, and will automatically terminate +your rights under this License. However, parties who have received copies, or +rights, from you under this License will not have their licenses terminated so +long as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. +However, nothing else grants you permission to modify or distribute the Program +or its derivative works. These actions are prohibited by law if you do not +accept this License. Therefore, by modifying or distributing the Program (or +any work based on the Program), you indicate your acceptance of this License to +do so, and all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), +the recipient automatically receives a license from the original licensor to +copy, distribute or modify the Program subject to these terms and conditions. +You may not impose any further restrictions on the recipients' exercise of the +rights granted herein. You are not responsible for enforcing compliance by +third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), conditions +are imposed on you (whether by court order, agreement or otherwise) that +contradict the conditions of this License, they do not excuse you from the +conditions of this License. If you cannot distribute so as to satisfy +simultaneously your obligations under this License and any other pertinent +obligations, then as a consequence you may not distribute the Program at all. +For example, if a patent license would not permit royalty-free redistribution +of the Program by all those who receive copies directly or indirectly through +you, then the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply and +the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or +other property right claims or to contest validity of any such claims; this +section has the sole purpose of protecting the integrity of the free software +distribution system, which is implemented by public license practices. Many +people have made generous contributions to the wide range of software +distributed through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing to +distribute software through any other system and a licensee cannot impose that +choice. + +This section is intended to make thoroughly clear what is believed to be a +consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain +countries either by patents or by copyrighted interfaces, the original +copyright holder who places the Program under this License may add an explicit +geographical distribution limitation excluding those countries, so that +distribution is permitted only in or among countries not thus excluded. In +such case, this License incorporates the limitation as if written in the body +of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the +General Public License from time to time. Such new versions will be similar in +spirit to the present version, but may differ in detail to address new problems +or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any later +version", you have the option of following the terms and conditions either of +that version or of any later version published by the Free Software Foundation. +If the Program does not specify a version number of this License, you may +choose any version ever published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs +whose distribution conditions are different, write to the author to ask for +permission. For software which is copyrighted by the Free Software Foundation, +write to the Free Software Foundation; we sometimes make exceptions for this. +Our decision will be guided by the two goals of preserving the free status of +all derivatives of our free software and of promoting the sharing and reuse of +software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR +THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE +STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE +PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, +YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL +ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE +PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR +INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA +BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER +OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively convey the exclusion +of warranty; and each file should have at least the "copyright" line and a +pointer to where the full notice is found. + + One line to give the program's name and a brief idea of what it does. + + Copyright (C) + + This program is free software; you can redistribute it and/or modify it + under the terms of the GNU General Public License as published by the Free + Software Foundation; either version 2 of the License, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this when it +starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author Gnomovision comes + with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is free + software, and you are welcome to redistribute it under certain conditions; + type 'show c' for details. + +The hypothetical commands 'show w' and 'show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may be +called something other than 'show w' and 'show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your school, +if any, to sign a "copyright disclaimer" for the program, if necessary. Here +is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + 'Gnomovision' (which makes passes at compilers) written by James Hacker. + + signature of Ty Coon, 1 April 1989 + + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General Public +License instead of this License. + + +"CLASSPATH" EXCEPTION TO THE GPL + +Certain source files distributed by Oracle America and/or its affiliates are +subject to the following clarification and special exception to the GPL, but +only where Oracle has expressly included in the particular source file's header +the words "Oracle designates this particular file as subject to the "Classpath" +exception as provided by Oracle in the LICENSE file that accompanied this code." + + Linking this library statically or dynamically with other modules is making + a combined work based on this library. Thus, the terms and conditions of + the GNU General Public License cover the whole combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent modules, + and to copy and distribute the resulting executable under terms of your + choice, provided that you also meet, for each linked independent module, + the terms and conditions of the license of that module. An independent + module is a module which is not derived from or based on this library. If + you modify this library, you may extend this exception to your version of + the library, but you are not obligated to do so. If you do not wish to do + so, delete this exception statement from your version. diff --git a/target/site/apidocs/legal/dejavufonts.md b/target/site/apidocs/legal/dejavufonts.md new file mode 100644 index 000000000..8c9e3cf3e --- /dev/null +++ b/target/site/apidocs/legal/dejavufonts.md @@ -0,0 +1,191 @@ +## DejaVu fonts v2.37 + +### DejaVu License +
+Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
+Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
+
+
+Bitstream Vera Fonts Copyright
+------------------------------
+
+Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
+a trademark of Bitstream, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of the fonts accompanying this license ("Fonts") and associated
+documentation files (the "Font Software"), to reproduce and distribute the
+Font Software, including without limitation the rights to use, copy, merge,
+publish, distribute, and/or sell copies of the Font Software, and to permit
+persons to whom the Font Software is furnished to do so, subject to the
+following conditions:
+
+The above copyright and trademark notices and this permission notice shall
+be included in all copies of one or more of the Font Software typefaces.
+
+The Font Software may be modified, altered, or added to, and in particular
+the designs of glyphs or characters in the Fonts may be modified and
+additional glyphs or characters may be added to the Fonts, only if the fonts
+are renamed to names not containing either the words "Bitstream" or the word
+"Vera".
+
+This License becomes null and void to the extent applicable to Fonts or Font
+Software that has been modified and is distributed under the "Bitstream
+Vera" names.
+
+The Font Software may be sold as part of a larger software package but no
+copy of one or more of the Font Software typefaces may be sold by itself.
+
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
+TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
+FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
+ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
+THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
+FONT SOFTWARE.
+
+Except as contained in this notice, the names of Gnome, the Gnome
+Foundation, and Bitstream Inc., shall not be used in advertising or
+otherwise to promote the sale, use or other dealings in this Font Software
+without prior written authorization from the Gnome Foundation or Bitstream
+Inc., respectively. For further information, contact: fonts at gnome dot
+org.
+
+Arev Fonts Copyright
+------------------------------
+
+Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the fonts accompanying this license ("Fonts") and
+associated documentation files (the "Font Software"), to reproduce
+and distribute the modifications to the Bitstream Vera Font Software,
+including without limitation the rights to use, copy, merge, publish,
+distribute, and/or sell copies of the Font Software, and to permit
+persons to whom the Font Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright and trademark notices and this permission notice
+shall be included in all copies of one or more of the Font Software
+typefaces.
+
+The Font Software may be modified, altered, or added to, and in
+particular the designs of glyphs or characters in the Fonts may be
+modified and additional glyphs or characters may be added to the
+Fonts, only if the fonts are renamed to names not containing either
+the words "Tavmjong Bah" or the word "Arev".
+
+This License becomes null and void to the extent applicable to Fonts
+or Font Software that has been modified and is distributed under the
+"Tavmjong Bah Arev" names.
+
+The Font Software may be sold as part of a larger software package but
+no copy of one or more of the Font Software typefaces may be sold by
+itself.
+
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
+TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
+
+Except as contained in this notice, the name of Tavmjong Bah shall not
+be used in advertising or otherwise to promote the sale, use or other
+dealings in this Font Software without prior written authorization
+from Tavmjong Bah. For further information, contact: tavmjong @ free
+. fr.
+
+TeX Gyre DJV Math
+-----------------
+Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
+
+Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
+(on behalf of TeX users groups) are in public domain.
+
+Letters imported from Euler Fraktur from AMSfonts are (c) American
+Mathematical Society (see below).
+Bitstream Vera Fonts Copyright
+Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
+is a trademark of Bitstream, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of the fonts accompanying this license ("Fonts") and associated
+documentation
+files (the "Font Software"), to reproduce and distribute the Font Software,
+including without limitation the rights to use, copy, merge, publish,
+distribute,
+and/or sell copies of the Font Software, and to permit persons  to whom
+the Font Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright and trademark notices and this permission notice
+shall be
+included in all copies of one or more of the Font Software typefaces.
+
+The Font Software may be modified, altered, or added to, and in particular
+the designs of glyphs or characters in the Fonts may be modified and
+additional
+glyphs or characters may be added to the Fonts, only if the fonts are
+renamed
+to names not containing either the words "Bitstream" or the word "Vera".
+
+This License becomes null and void to the extent applicable to Fonts or
+Font Software
+that has been modified and is distributed under the "Bitstream Vera"
+names.
+
+The Font Software may be sold as part of a larger software package but
+no copy
+of one or more of the Font Software typefaces may be sold by itself.
+
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
+TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
+FOUNDATION
+BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL,
+SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN
+ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR
+INABILITY TO USE
+THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
+Except as contained in this notice, the names of GNOME, the GNOME
+Foundation,
+and Bitstream Inc., shall not be used in advertising or otherwise to promote
+the sale, use or other dealings in this Font Software without prior written
+authorization from the GNOME Foundation or Bitstream Inc., respectively.
+For further information, contact: fonts at gnome dot org.
+
+AMSFonts (v. 2.2) copyright
+
+The PostScript Type 1 implementation of the AMSFonts produced by and
+previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
+available for general use. This has been accomplished through the
+cooperation
+of a consortium of scientific publishers with Blue Sky Research and Y&Y.
+Members of this consortium include:
+
+Elsevier Science IBM Corporation Society for Industrial and Applied
+Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
+
+In order to assure the authenticity of these fonts, copyright will be
+held by
+the American Mathematical Society. This is not meant to restrict in any way
+the legitimate use of the fonts, such as (but not limited to) electronic
+distribution of documents containing these fonts, inclusion of these fonts
+into other public domain or commercial font collections or computer
+applications, use of the outline data to create derivative fonts and/or
+faces, etc. However, the AMS does require that the AMS copyright notice be
+removed from any derivative versions of the fonts which have been altered in
+any way. In addition, to ensure the fidelity of TeX documents using Computer
+Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
+has requested that any alterations which yield different font metrics be
+given a different name.
+
+
diff --git a/target/site/apidocs/legal/jquery.md b/target/site/apidocs/legal/jquery.md new file mode 100644 index 000000000..a763ec6f1 --- /dev/null +++ b/target/site/apidocs/legal/jquery.md @@ -0,0 +1,26 @@ +## jQuery v3.7.1 + +### jQuery License +``` +jQuery v 3.7.1 +Copyright OpenJS Foundation and other contributors, https://openjsf.org/ + +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. +``` diff --git a/target/site/apidocs/legal/jqueryUI.md b/target/site/apidocs/legal/jqueryUI.md new file mode 100644 index 000000000..46bfbaa5c --- /dev/null +++ b/target/site/apidocs/legal/jqueryUI.md @@ -0,0 +1,49 @@ +## jQuery UI v1.14.1 + +### jQuery UI License +``` +Copyright OpenJS Foundation and other contributors, https://openjsf.org/ + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/jquery/jquery-ui + +The following license applies to all parts of this software except as +documented below: + +==== + +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. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code contained within the demos directory. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +All files located in the node_modules and external directories are +externally maintained libraries used by this software which have their +own licenses; we recommend you read them, as their terms may differ from +the terms above. + +``` diff --git a/target/site/apidocs/member-search-index.js b/target/site/apidocs/member-search-index.js new file mode 100644 index 000000000..def339da5 --- /dev/null +++ b/target/site/apidocs/member-search-index.js @@ -0,0 +1 @@ +memberSearchIndex = [{"p":"org.apache.datasketches.common","c":"Family","l":"A_NOT_B","k":"0"},{"p":"org.apache.datasketches.common","c":"Util","l":"alignedHeapSegment(int, boolean)","u":"alignedHeapSegment(int,boolean)","k":"6"},{"p":"org.apache.datasketches.common","c":"Family","l":"ALPHA","k":"0"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummary.Mode","l":"AlwaysOne","k":"0"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummary.Mode","l":"AlwaysOne","k":"0"},{"p":"org.apache.datasketches.theta","c":"ThetaAnotB","l":"aNotB(ThetaSketch, ThetaSketch)","u":"aNotB(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch)"},{"p":"org.apache.datasketches.theta","c":"ThetaAnotB","l":"aNotB(ThetaSketch, ThetaSketch, boolean, MemorySegment)","u":"aNotB(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch,boolean,java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple","c":"TupleAnotB","l":"aNotB(TupleSketch, ThetaSketch)","u":"aNotB(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.theta.ThetaSketch)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"TupleAnotB","l":"aNotB(TupleSketch, TupleSketch)","u":"aNotB(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.TupleSketch)","k":"6"},{"p":"org.apache.datasketches.common","c":"BoundsOnBinomialProportions","l":"approximateLowerBoundOnP(long, long, double)","u":"approximateLowerBoundOnP(long,long,double)","k":"6"},{"p":"org.apache.datasketches.common","c":"BoundsOnBinomialProportions","l":"approximateUpperBoundOnP(long, long, double)","u":"approximateUpperBoundOnP(long,long,double)","k":"6"},{"p":"org.apache.datasketches.partitions","c":"Partitioner.PartitionBoundsRow","l":"approxNumDeltaItems","k":"1"},{"p":"org.apache.datasketches.common","c":"ArrayOfBooleansSerDe","l":"ArrayOfBooleansSerDe()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple","c":"SerializerDeserializer.SketchType","l":"ArrayOfDoublesCompactSketch","k":"0"},{"p":"org.apache.datasketches.tuple","c":"SerializerDeserializer.SketchType","l":"ArrayOfDoublesQuickSelectSketch","k":"0"},{"p":"org.apache.datasketches.common","c":"ArrayOfDoublesSerDe","l":"ArrayOfDoublesSerDe()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSetOperationBuilder","l":"ArrayOfDoublesSetOperationBuilder()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple","c":"SerializerDeserializer.SketchType","l":"ArrayOfDoublesUnion","k":"0"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketchBuilder","l":"ArrayOfDoublesUpdatableSketchBuilder()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.common","c":"ArrayOfItemsSerDe","l":"ArrayOfItemsSerDe()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.common","c":"ArrayOfLongsSerDe","l":"ArrayOfLongsSerDe()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.common","c":"ArrayOfNumbersSerDe","l":"ArrayOfNumbersSerDe()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.common","c":"ArrayOfStringsSerDe","l":"ArrayOfStringsSerDe()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummaryDeserializer","l":"ArrayOfStringsSummaryDeserializer()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummaryFactory","l":"ArrayOfStringsSummaryFactory()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummarySetOperations","l":"ArrayOfStringsSummarySetOperations()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"ArrayOfStringsTupleSketch()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"ArrayOfStringsTupleSketch(ArrayOfStringsTupleSketch)","u":"%3Cinit%3E(org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch)","k":"3"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"ArrayOfStringsTupleSketch(int)","u":"%3Cinit%3E(int)","k":"3"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"ArrayOfStringsTupleSketch(int, ResizeFactor, float)","u":"%3Cinit%3E(int,org.apache.datasketches.common.ResizeFactor,float)","k":"3"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"ArrayOfStringsTupleSketch(MemorySegment)","u":"%3Cinit%3E(java.lang.foreign.MemorySegment)","k":"3"},{"p":"org.apache.datasketches.common","c":"ArrayOfUtf16StringsSerDe","l":"ArrayOfUtf16StringsSerDe()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"asSlice()"},{"p":"org.apache.datasketches.quantilescommon","c":"BinarySearch","l":"BinarySearch()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tdigest","c":"BinarySearch","l":"BinarySearch()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.common","c":"Util","l":"bitAt(long, int)","u":"bitAt(long,int)","k":"6"},{"p":"org.apache.datasketches.common","c":"Family","l":"BLOOMFILTER","k":"0"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"BloomFilterBuilder()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketchBuilder","l":"build()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnionBuilder","l":"build()"},{"p":"org.apache.datasketches.req","c":"ReqSketchBuilder","l":"build()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"build()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketchBuilder","l":"build()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketchBuilder","l":"build()"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"build(Family)","u":"build(org.apache.datasketches.common.Family)"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"build(Family, MemorySegment)","u":"build(org.apache.datasketches.common.Family,java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketchBuilder","l":"build(MemorySegment)","u":"build(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"build(MemorySegment)","u":"build(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketchBuilder","l":"build(MemorySegment)","u":"build(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketchBuilder","l":"build(MemorySegment, MemorySegmentRequest)","u":"build(java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnionBuilder","l":"build(MemorySegment, MemorySegmentRequest)","u":"build(java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSetOperationBuilder","l":"buildAnotB()"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"buildANotB()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"builder()","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"builder()","k":"6"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"builder()","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperation","l":"builder()","k":"6"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"builder()","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"buildIntersection()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSetOperationBuilder","l":"buildIntersection()"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"buildIntersection(MemorySegment)","u":"buildIntersection(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSetOperationBuilder","l":"buildIntersection(MemorySegment)","u":"buildIntersection(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"buildLocal(UpdatableThetaSketch)","u":"buildLocal(org.apache.datasketches.theta.UpdatableThetaSketch)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"buildShared()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"buildShared(MemorySegment)","u":"buildShared(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"buildSharedFromSketch(UpdatableThetaSketch, MemorySegment)","u":"buildSharedFromSketch(org.apache.datasketches.theta.UpdatableThetaSketch,java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"buildUnion()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSetOperationBuilder","l":"buildUnion()"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"buildUnion(MemorySegment)","u":"buildUnion(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSetOperationBuilder","l":"buildUnion(MemorySegment)","u":"buildUnion(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"ByteArrayUtil()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.common","c":"Util","l":"bytesToInt(byte[])","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"bytesToLong(byte[])","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"bytesToString(byte[], boolean, boolean, String)","u":"bytesToString(byte[],boolean,boolean,java.lang.String)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"caseIdToCornerCase(int)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"ceilingMultiple2expK(long, int)","u":"ceilingMultiple2expK(long,int)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"ceilingPowerBaseOfDouble(double, double)","u":"ceilingPowerBaseOfDouble(double,double)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"ceilingPowerOf2(int)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"ceilingPowerOf2(long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"characterPad(String, int, char, boolean)","u":"characterPad(java.lang.String,int,char,boolean)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"checkBounds(long, long, long)","u":"checkBounds(long,long,long)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesUtil","l":"checkDoublesSplitPointsOrder(double[])","k":"6"},{"p":"org.apache.datasketches.common","c":"Family","l":"checkFamilyID(int)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesUtil","l":"checkFloatsSplitPointsOrder(float[])","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"checkHashCorruption(long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"checkIfMultipleOf8AndGT0(long, String)","u":"checkIfMultipleOf8AndGT0(long,java.lang.String)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"checkIfPowerOf2(long, String)","u":"checkIfPowerOf2(long,java.lang.String)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesUtil","l":"checkLongsSplitPointsOrder(long[])","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"ThetaUtil","l":"checkNomLongs(int)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesUtil","l":"checkNormalizedRankBounds(double)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"checkProbability(double, String)","u":"checkProbability(double,java.lang.String)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"checkSeedHashes(short, short)","u":"checkSeedHashes(short,short)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"checkThetaCorruption(long)","k":"6"},{"p":"org.apache.datasketches.common","c":"MemorySegmentRequestExample","l":"cleanup()"},{"p":"org.apache.datasketches.common","c":"Util","l":"clear(MemorySegment)","u":"clear(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"clear(MemorySegment, long, long)","u":"clear(java.lang.foreign.MemorySegment,long,long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"clearBits(MemorySegment, long, byte)","u":"clearBits(java.lang.foreign.MemorySegment,long,byte)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesCombiner","l":"combine(double[], double[])","u":"combine(double[],double[])"},{"p":"org.apache.datasketches.common","c":"Family","l":"COMPACT","k":"0"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchStructure","l":"COMPACT_EMPTY","k":"0"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchStructure","l":"COMPACT_FULL","k":"0"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchStructure","l":"COMPACT_SINGLE","k":"0"},{"p":"org.apache.datasketches.quantiles","c":"UpdatableQuantilesDoublesSketch","l":"compact()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"compact()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"compact()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"compact()"},{"p":"org.apache.datasketches.tuple","c":"CompactTupleSketch","l":"compact()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"compact()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"compact()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"compact()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"compact()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"compact()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"compact()"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"compact(boolean, MemorySegment)","u":"compact(boolean,java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"compact(boolean, MemorySegment)","u":"compact(boolean,java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"compact(boolean, MemorySegment)","u":"compact(boolean,java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.quantiles","c":"UpdatableQuantilesDoublesSketch","l":"compact(MemorySegment)","u":"compact(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"compact(MemorySegment)","u":"compact(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"compact(MemorySegment)","u":"compact(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"CompactThetaSketch()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple","c":"SerializerDeserializer.SketchType","l":"CompactTupleSketch","k":"0"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch.Row","l":"compareTo(FrequentItemsSketch.Row)","u":"compareTo(org.apache.datasketches.frequencies.FrequentItemsSketch.Row)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch.Row","l":"compareTo(FrequentLongsSketch.Row)","u":"compareTo(org.apache.datasketches.frequencies.FrequentLongsSketch.Row)"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"compareTo(Group)","u":"compareTo(org.apache.datasketches.fdt.Group)"},{"p":"org.apache.datasketches.cpc","c":"CompressionCharacterization","l":"CompressionCharacterization(int, int, int, int, int, int, int, PrintStream, PrintWriter)","u":"%3Cinit%3E(int,int,int,int,int,int,int,java.io.PrintStream,java.io.PrintWriter)","k":"3"},{"p":"org.apache.datasketches.common","c":"ArrayOfBooleansSerDe","l":"computeBytesNeeded(int)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"KolmogorovSmirnov","l":"computeKSDelta(QuantilesDoublesAPI, QuantilesDoublesAPI)","u":"computeKSDelta(org.apache.datasketches.quantilescommon.QuantilesDoublesAPI,org.apache.datasketches.quantilescommon.QuantilesDoublesAPI)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"KolmogorovSmirnov","l":"computeKSDelta(QuantilesFloatsAPI, QuantilesFloatsAPI)","u":"computeKSDelta(org.apache.datasketches.quantilescommon.QuantilesFloatsAPI,org.apache.datasketches.quantilescommon.QuantilesFloatsAPI)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"KolmogorovSmirnov","l":"computeKSThreshold(QuantilesAPI, QuantilesAPI, double)","u":"computeKSThreshold(org.apache.datasketches.quantilescommon.QuantilesAPI,org.apache.datasketches.quantilescommon.QuantilesAPI,double)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"computeSeedHash(long)","k":"6"},{"p":"org.apache.datasketches.theta","c":"UpdateReturnState","l":"ConcurrentBufferInserted","k":"0"},{"p":"org.apache.datasketches.theta","c":"UpdateReturnState","l":"ConcurrentPropagated","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"continueCondition(long, long)","u":"continueCondition(long,long)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"convertToHashTable(long[], int, long, double)","u":"convertToHashTable(long[],int,long,double)","k":"6"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"copy()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"copy()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummary","l":"copy()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummary","l":"copy()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummary","l":"copy()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"copy()"},{"p":"org.apache.datasketches.tuple","c":"Summary","l":"copy()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"copy()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"copyAs(TgtHllType)","u":"copyAs(org.apache.datasketches.hll.TgtHllType)"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"copyBytes(byte[], int, byte[], int, int)","u":"copyBytes(byte[],int,byte[],int,int)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"Util","l":"copySummaryArray(S[])","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"count(long[], long)","u":"count(long[],long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Family","l":"COUNTMIN","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"countPart(long[], int, long)","u":"countPart(long[],int,long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Family","l":"CPC","k":"0"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"CpcSketch()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"CpcSketch(int)","u":"%3Cinit%3E(int)","k":"3"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"CpcSketch(int, long)","u":"%3Cinit%3E(int,long)","k":"3"},{"p":"org.apache.datasketches.cpc","c":"CpcUnion","l":"CpcUnion()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.cpc","c":"CpcUnion","l":"CpcUnion(int)","u":"%3Cinit%3E(int)","k":"3"},{"p":"org.apache.datasketches.cpc","c":"CpcUnion","l":"CpcUnion(int, long)","u":"%3Cinit%3E(int,long)","k":"3"},{"p":"org.apache.datasketches.cpc","c":"CpcWrapper","l":"CpcWrapper(byte[])","u":"%3Cinit%3E(byte[])","k":"3"},{"p":"org.apache.datasketches.cpc","c":"CpcWrapper","l":"CpcWrapper(MemorySegment)","u":"%3Cinit%3E(java.lang.foreign.MemorySegment)","k":"3"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"createByAccuracy(long, double)","u":"createByAccuracy(long,double)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"createByAccuracy(long, double, long)","u":"createByAccuracy(long,double,long)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"createBySize(long, int)","u":"createBySize(long,int)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"createBySize(long, int, long)","u":"createBySize(long,int,long)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases","l":"createCornerCaseId(long, int, boolean, long, int, boolean)","u":"createCornerCaseId(long,int,boolean,long,int,boolean)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"createEmptySketch()","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax.DoublesPair","l":"cumWeights","k":"1"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax.FloatsPair","l":"cumWeights","k":"1"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax.ItemsPair","l":"cumWeights","k":"1"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax.LongsPair","l":"cumWeights","k":"1"},{"p":"org.apache.datasketches.common","c":"MemorySegmentRequest","l":"DEFAULT","k":"2"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"DEFAULT_HLL_TYPE","k":"2"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"DEFAULT_K","k":"2"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"DEFAULT_K","k":"2"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"DEFAULT_LG_K","k":"2"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"DEFAULT_LG_K","k":"2"},{"p":"org.apache.datasketches.thetacommon","c":"ThetaUtil","l":"DEFAULT_NOMINAL_ENTRIES","k":"2"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSetOperationBuilder","l":"DEFAULT_NOMINAL_ENTRIES","k":"2"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSetOperationBuilder","l":"DEFAULT_NUMBER_OF_VALUES","k":"2"},{"p":"org.apache.datasketches.common","c":"Util","l":"DEFAULT_UPDATE_SEED","k":"2"},{"p":"org.apache.datasketches.common","c":"MemorySegmentRequest.Default","l":"Default()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Degen_Degen","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Degen_Empty","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Degen_Estimation","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Degen_Exact","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.AnotbAction","l":"DEGEN_MIN_0_F","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.IntersectAction","l":"DEGEN_MIN_0_F","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"DEGEN_MIN_0_F","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.AnotbAction","l":"DEGEN_THA_0_F","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"DEGEN_THA_0_F","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"DEGEN_THB_0_F","k":"0"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"desc(double[], int, int, double, int)","u":"desc(double[],int,int,double,int)"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"desc(float[], int, int, float, int)","u":"desc(float[],int,int,float,int)"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"desc(long[], int, int, double, int)","u":"desc(long[],int,int,double,int)"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"desc(long[], int, int, long, int)","u":"desc(long[],int,int,long,int)"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"deserialize(byte[], long)","u":"deserialize(byte[],long)","k":"6"},{"p":"org.apache.datasketches.common","c":"ArrayOfBooleansSerDe","l":"deserializeFromMemorySegment(MemorySegment, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfDoublesSerDe","l":"deserializeFromMemorySegment(MemorySegment, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfItemsSerDe","l":"deserializeFromMemorySegment(MemorySegment, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfLongsSerDe","l":"deserializeFromMemorySegment(MemorySegment, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfNumbersSerDe","l":"deserializeFromMemorySegment(MemorySegment, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfStringsSerDe","l":"deserializeFromMemorySegment(MemorySegment, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfUtf16StringsSerDe","l":"deserializeFromMemorySegment(MemorySegment, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfBooleansSerDe","l":"deserializeFromMemorySegment(MemorySegment, long, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfDoublesSerDe","l":"deserializeFromMemorySegment(MemorySegment, long, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfItemsSerDe","l":"deserializeFromMemorySegment(MemorySegment, long, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfLongsSerDe","l":"deserializeFromMemorySegment(MemorySegment, long, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfNumbersSerDe","l":"deserializeFromMemorySegment(MemorySegment, long, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfStringsSerDe","l":"deserializeFromMemorySegment(MemorySegment, long, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfUtf16StringsSerDe","l":"deserializeFromMemorySegment(MemorySegment, long, int)","u":"deserializeFromMemorySegment(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.tuple","c":"DeserializeResult","l":"DeserializeResult(T, int)","u":"%3Cinit%3E(T,int)","k":"3"},{"p":"org.apache.datasketches.theta","c":"JaccardSimilarity","l":"dissimilarityTest(ThetaSketch, ThetaSketch, double)","u":"dissimilarityTest(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch,double)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"JaccardSimilarity","l":"dissimilarityTest(TupleSketch, ThetaSketch, S, SummarySetOperations, double)","u":"dissimilarityTest(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.theta.ThetaSketch,S,org.apache.datasketches.tuple.SummarySetOperations,double)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"JaccardSimilarity","l":"dissimilarityTest(TupleSketch, TupleSketch, SummarySetOperations, double)","u":"dissimilarityTest(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.SummarySetOperations,double)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax.DoublesPair","l":"DoublesPair(double[], long[])","u":"%3Cinit%3E(double[],long[])","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSketchSortedView","l":"DoublesSketchSortedView(double[], long[], QuantilesDoublesAPI)","u":"%3Cinit%3E(double[],long[],org.apache.datasketches.quantilescommon.QuantilesDoublesAPI)","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSortedViewIterator","l":"DoublesSortedViewIterator(double[], long[])","u":"%3Cinit%3E(double[],long[])","k":"3"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummary","l":"DoubleSummary(DoubleSummary.Mode)","u":"%3Cinit%3E(org.apache.datasketches.tuple.adouble.DoubleSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummaryDeserializer","l":"DoubleSummaryDeserializer()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummaryFactory","l":"DoubleSummaryFactory(DoubleSummary.Mode)","u":"%3Cinit%3E(org.apache.datasketches.tuple.adouble.DoubleSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummarySetOperations","l":"DoubleSummarySetOperations()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummarySetOperations","l":"DoubleSummarySetOperations(DoubleSummary.Mode)","u":"%3Cinit%3E(org.apache.datasketches.tuple.adouble.DoubleSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummarySetOperations","l":"DoubleSummarySetOperations(DoubleSummary.Mode, DoubleSummary.Mode)","u":"%3Cinit%3E(org.apache.datasketches.tuple.adouble.DoubleSummary.Mode,org.apache.datasketches.tuple.adouble.DoubleSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.tuple","c":"Util","l":"doubleToLongArray(double)","k":"6"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"DoubleTupleSketch(int, DoubleSummary.Mode)","u":"%3Cinit%3E(int,org.apache.datasketches.tuple.adouble.DoubleSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"DoubleTupleSketch(int, int, float, DoubleSummary.Mode)","u":"%3Cinit%3E(int,int,float,org.apache.datasketches.tuple.adouble.DoubleSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"DoubleTupleSketch(MemorySegment, DoubleSummary.Mode)","u":"%3Cinit%3E(java.lang.foreign.MemorySegment,org.apache.datasketches.tuple.adouble.DoubleSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"downSample(int)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"downSample(QuantilesDoublesSketch, int, MemorySegment, MemorySegmentRequest)","u":"downSample(org.apache.datasketches.quantiles.QuantilesDoublesSketch,int,java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)"},{"p":"org.apache.datasketches.common","c":"Family","l":"EBPPS","k":"0"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"EbppsItemsSketch(int)","u":"%3Cinit%3E(int)","k":"3"},{"p":"org.apache.datasketches.req","c":"ReqDebug","l":"emitAdjSecSizeNumSec(byte)"},{"p":"org.apache.datasketches.req","c":"ReqDebug","l":"emitAllHorizList()"},{"p":"org.apache.datasketches.req","c":"ReqDebug","l":"emitCompactingStart(byte)"},{"p":"org.apache.datasketches.req","c":"ReqDebug","l":"emitCompactionDetail(int, int, int, int, boolean)","u":"emitCompactionDetail(int,int,int,int,boolean)"},{"p":"org.apache.datasketches.req","c":"ReqDebug","l":"emitCompactionDone(byte)"},{"p":"org.apache.datasketches.req","c":"ReqDebug","l":"emitCompressDone()"},{"p":"org.apache.datasketches.req","c":"ReqDebug","l":"emitMustAddCompactor()"},{"p":"org.apache.datasketches.req","c":"ReqDebug","l":"emitNewCompactor(byte)"},{"p":"org.apache.datasketches.req","c":"ReqDebug","l":"emitStart(ReqSketch)","u":"emitStart(org.apache.datasketches.req.ReqSketch)"},{"p":"org.apache.datasketches.req","c":"ReqDebug","l":"emitStartCompress()"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.AnotbAction","l":"EMPTY_1_0_T","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.IntersectAction","l":"EMPTY_1_0_T","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"EMPTY_1_0_T","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Empty_Degen","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Empty_Empty","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Empty_Estimation","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Empty_Exact","k":"0"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"EMPTY_MSG","k":"2"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericInequalitySearch.Inequality","l":"EQ","k":"0"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"EQ","k":"0"},{"p":"org.apache.datasketches.common","c":"Util","l":"equalContents(MemorySegment, long, MemorySegment, long, long)","u":"equalContents(java.lang.foreign.MemorySegment,long,java.lang.foreign.MemorySegment,long,long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"equalContents(MemorySegment, MemorySegment)","u":"equalContents(java.lang.foreign.MemorySegment,java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesUtil","l":"equallySpacedDoubles(int)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesUtil","l":"equallySpacedLongs(long, long, int)","u":"equallySpacedLongs(long,long,int)","k":"6"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"equals(Object)","u":"equals(java.lang.Object)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch.Row","l":"equals(Object)","u":"equals(java.lang.Object)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch.Row","l":"equals(Object)","u":"equals(java.lang.Object)"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummary","l":"equals(Object)","u":"equals(java.lang.Object)"},{"p":"org.apache.datasketches.common","c":"BoundsOnBinomialProportions","l":"erf(double)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"estimateSubsetSum(Predicate)","u":"estimateSubsetSum(java.util.function.Predicate)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"estimateSubsetSum(Predicate)","u":"estimateSubsetSum(java.util.function.Predicate)"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"estimateSubsetSum(Predicate)","u":"estimateSubsetSum(java.util.function.Predicate)"},{"p":"org.apache.datasketches.common","c":"BoundsOnBinomialProportions","l":"estimateUnknownP(long, long)","u":"estimateUnknownP(long,long)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Estimation_Degen","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Estimation_Empty","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Estimation_Estimation","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Estimation_Exact","k":"0"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesUtil","l":"evenlyLogSpaced(double, double, int)","u":"evenlyLogSpaced(double,double,int)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesUtil","l":"evenlySpacedDoubles(double, double, int)","u":"evenlySpacedDoubles(double,double,int)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesUtil","l":"evenlySpacedFloats(float, float, int)","u":"evenlySpacedFloats(float,float,int)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Exact_Degen","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Exact_Empty","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Exact_Estimation","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"Exact_Exact","k":"0"},{"p":"org.apache.datasketches.common","c":"Util","l":"exactLog2OfInt(int)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"exactLog2OfInt(int, String)","u":"exactLog2OfInt(int,java.lang.String)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"exactLog2OfLong(long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"exactLog2OfLong(long, String)","u":"exactLog2OfLong(long,java.lang.String)","k":"6"},{"p":"org.apache.datasketches.theta","c":"JaccardSimilarity","l":"exactlyEqual(ThetaSketch, ThetaSketch)","u":"exactlyEqual(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"JaccardSimilarity","l":"exactlyEqual(TupleSketch, ThetaSketch, S, SummarySetOperations)","u":"exactlyEqual(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.theta.ThetaSketch,S,org.apache.datasketches.tuple.SummarySetOperations)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"JaccardSimilarity","l":"exactlyEqual(TupleSketch, TupleSketch, SummarySetOperations)","u":"exactlyEqual(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.SummarySetOperations)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantileSearchCriteria","l":"EXCLUSIVE","k":"0"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"fastWrap(MemorySegment)","u":"fastWrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"fastWrap(MemorySegment, long)","u":"fastWrap(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"FdtSketch(double, double)","u":"%3Cinit%3E(double,double)","k":"3"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"FdtSketch(FdtSketch)","u":"%3Cinit%3E(org.apache.datasketches.fdt.FdtSketch)","k":"3"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"FdtSketch(int)","u":"%3Cinit%3E(int)","k":"3"},{"p":"org.apache.datasketches.common","c":"Util","l":"fill(MemorySegment, long, long, byte)","u":"fill(java.lang.foreign.MemorySegment,long,long,byte)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"Filter","l":"Filter(Predicate)","u":"%3Cinit%3E(java.util.function.Predicate)","k":"3"},{"p":"org.apache.datasketches.tuple","c":"Filter","l":"filter(TupleSketch)","u":"filter(org.apache.datasketches.tuple.TupleSketch)"},{"p":"org.apache.datasketches.quantilescommon","c":"BinarySearch","l":"find(double[], int, int, double)","u":"find(double[],int,int,double)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"find(double[], int, int, double, InequalitySearch)","u":"find(double[],int,int,double,org.apache.datasketches.quantilescommon.InequalitySearch)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"BinarySearch","l":"find(float[], int, int, float)","u":"find(float[],int,int,float)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"find(float[], int, int, float, InequalitySearch)","u":"find(float[],int,int,float,org.apache.datasketches.quantilescommon.InequalitySearch)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"find(long[], int, int, double, InequalitySearch)","u":"find(long[],int,int,double,org.apache.datasketches.quantilescommon.InequalitySearch)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"BinarySearch","l":"find(long[], int, int, long)","u":"find(long[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"find(long[], int, int, long, InequalitySearch)","u":"find(long[],int,int,long,org.apache.datasketches.quantilescommon.InequalitySearch)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericInequalitySearch","l":"find(T[], int, int, T, GenericInequalitySearch.Inequality, Comparator)","u":"find(T[],int,int,T,org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality,java.util.Comparator)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax.FloatsPair","l":"FloatsPair(float[], long[])","u":"%3Cinit%3E(float[],long[])","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSketchSortedView","l":"FloatsSketchSortedView(float[], long[], QuantilesFloatsAPI)","u":"%3Cinit%3E(float[],long[],org.apache.datasketches.quantilescommon.QuantilesFloatsAPI)","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSortedViewIterator","l":"FloatsSortedViewIterator(float[], long[])","u":"%3Cinit%3E(float[],long[])","k":"3"},{"p":"org.apache.datasketches.common","c":"Util","l":"floorPowerBaseOfDouble(double, double)","u":"floorPowerBaseOfDouble(double,double)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"floorPowerOf2(int)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"floorPowerOf2(long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Family","l":"FREQUENCY","k":"0"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"FrequentItemsSketch(int)","u":"%3Cinit%3E(int)","k":"3"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"FrequentLongsSketch(int)","u":"%3Cinit%3E(int)","k":"3"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummary","l":"fromMemorySegment(MemorySegment)","u":"fromMemorySegment(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummary","l":"fromMemorySegment(MemorySegment)","u":"fromMemorySegment(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.hll","c":"TgtHllType","l":"fromOrdinal(int)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.AnotbAction","l":"FULL_ANOTB","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.IntersectAction","l":"FULL_INTERSECT","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"FULL_UNION","k":"0"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericInequalitySearch.Inequality","l":"GE","k":"0"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"GE","k":"0"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericInequalitySearch","l":"GenericInequalitySearch()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericPartitionBoundaries","l":"GenericPartitionBoundaries(long, T[], long[], double[], T, T, QuantileSearchCriteria)","u":"%3Cinit%3E(long,T[],long[],double[],T,T,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedViewIterator","l":"GenericSortedViewIterator(T[], long[])","u":"%3Cinit%3E(T[],long[])","k":"3"},{"p":"org.apache.datasketches.theta","c":"HashIterator","l":"get()"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.AnotbAction","l":"getActionDescription()"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.IntersectAction","l":"getActionDescription()"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"getActionDescription()"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.AnotbAction","l":"getActionId()"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.IntersectAction","l":"getActionId()"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"getActionId()"},{"p":"org.apache.datasketches.hllmap","c":"UniqueCountMap","l":"getActiveEntries()"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"getAnotbAction()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getAprioriError(int, long)","u":"getAprioriError(int,long)","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getAprioriError(int, long)","u":"getAprioriError(int,long)","k":"6"},{"p":"org.apache.datasketches.hllmap","c":"UniqueCountMap","l":"getAverageSketchBytesPerKey()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"getBitsUsed()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getBoolean()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getBoolean(long)"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericPartitionBoundaries","l":"getBoundaries()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getByte()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getByte(long)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getByteArray(byte[], int, int)","u":"getByteArray(byte[],int,int)"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchType","l":"getBytes()"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"getC()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"getCapacity()"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"getCaseDescription()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getCDF(double[])"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"getCDF(double[])"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"getCDF(double[], QuantileSearchCriteria)","u":"getCDF(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getCDF(double[], QuantileSearchCriteria)","u":"getCDF(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSortedView","l":"getCDF(double[], QuantileSearchCriteria)","u":"getCDF(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getCDF(double[], QuantileSearchCriteria)","u":"getCDF(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getCDF(float[])"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"getCDF(float[], QuantileSearchCriteria)","u":"getCDF(float[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSortedView","l":"getCDF(float[], QuantileSearchCriteria)","u":"getCDF(float[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getCDF(float[], QuantileSearchCriteria)","u":"getCDF(float[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getCDF(float[], QuantileSearchCriteria)","u":"getCDF(float[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getCDF(long[])"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"getCDF(long[], QuantileSearchCriteria)","u":"getCDF(long[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSortedView","l":"getCDF(long[], QuantileSearchCriteria)","u":"getCDF(long[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getCDF(long[], QuantileSearchCriteria)","u":"getCDF(long[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getCDF(T[])"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getCDF(T[], QuantileSearchCriteria)","u":"getCDF(T[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getCDF(T[], QuantileSearchCriteria)","u":"getCDF(T[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedView","l":"getCDF(T[], QuantileSearchCriteria)","u":"getCDF(T[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getCDF(T[], QuantileSearchCriteria)","u":"getCDF(T[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getChar()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getChar(long)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getCharArray(char[], int, int)","u":"getCharArray(char[],int,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfBooleansSerDe","l":"getClassOfT()"},{"p":"org.apache.datasketches.common","c":"ArrayOfDoublesSerDe","l":"getClassOfT()"},{"p":"org.apache.datasketches.common","c":"ArrayOfItemsSerDe","l":"getClassOfT()"},{"p":"org.apache.datasketches.common","c":"ArrayOfLongsSerDe","l":"getClassOfT()"},{"p":"org.apache.datasketches.common","c":"ArrayOfNumbersSerDe","l":"getClassOfT()"},{"p":"org.apache.datasketches.common","c":"ArrayOfStringsSerDe","l":"getClassOfT()"},{"p":"org.apache.datasketches.common","c":"ArrayOfUtf16StringsSerDe","l":"getClassOfT()"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getClassOfT()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getClassOfT()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getClassOfT()"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"getCompactBytes()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getCompactBytes()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"getCompactBytes()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getCompactSerialiedSizeBytes(int, long)","u":"getCompactSerialiedSizeBytes(int,long)","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"getCompactSerializationBytes()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getCompactSerializationBytes()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getCompactSketchMaxBytes(int)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getComparator()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getComparator()"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedView","l":"getComparator()"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getComparator()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getComparator()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"getCompositeEstimate()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getCompositeEstimate()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"getConCurLgNominalEntries()"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"getCount()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getCountLessThanThetaLong(long)"},{"p":"org.apache.datasketches.tuple","c":"CompactTupleSketch","l":"getCountLessThanThetaLong(long)"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"getCountLessThanThetaLong(long)"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"getCountLessThanThetaLong(long)"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"getCountLessThanThetaLong(long)"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"getCountLessThanThetaLong(long)"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"getCountLessThanThetaLong(long)"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"getCountLessThanThetaLong(long)"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"getCumulativeWeight()"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSketchSortedView","l":"getCumulativeWeights()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSketchSortedView","l":"getCumulativeWeights()"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getCumulativeWeights()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSketchSortedView","l":"getCumulativeWeights()"},{"p":"org.apache.datasketches.quantilescommon","c":"SortedView","l":"getCumulativeWeights()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getCurrentBytes()"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"getCurrentBytes()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesCompactSketch","l":"getCurrentBytes()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"getCurrentBytes()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"getCurrentCapacity()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"getCurrentCapacity()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"getCurrentCapacity()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"getCurrentCapacity()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"getCurrentCapacity()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getCurrentCompactSerializedSizeBytes()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getCurrentMapCapacity()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getCurrentMapCapacity()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getCurrentUpdatableSerializedSizeBytes()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getDouble()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getDouble(long)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getDoubleArray(double[], int, int)","u":"getDoubleArray(double[],int,int)"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"getDoubleBE(byte[], int)","u":"getDoubleBE(byte[],int)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"getDoubleLE(byte[], int)","u":"getDoubleLE(byte[],int)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"getEffectiveK()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"getEffectiveK()"},{"p":"org.apache.datasketches.common.positional","c":"Positional","l":"getEnd()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getEpsilon(int)","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getEpsilon(int)","k":"6"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"getEstimate()"},{"p":"org.apache.datasketches.cpc","c":"CpcWrapper","l":"getEstimate()"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"getEstimate()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch.Row","l":"getEstimate()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch.Row","l":"getEstimate()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"getEstimate()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getEstimate()"},{"p":"org.apache.datasketches.sampling","c":"SampleSubsetSummary","l":"getEstimate()"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"getEstimate()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getEstimate()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"getEstimate()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"getEstimate()"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getEstimate(byte[])"},{"p":"org.apache.datasketches.hllmap","c":"UniqueCountMap","l":"getEstimate(byte[])"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"getEstimate(int)"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getEstimate(long)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getEstimate(long)"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getEstimate(MemorySegment)","u":"getEstimate(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getEstimate(String)","u":"getEstimate(java.lang.String)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getEstimate(T)"},{"p":"org.apache.datasketches.common","c":"BoundsOnRatiosInSampledSets","l":"getEstimateOfA(long, double)","u":"getEstimateOfA(long,double)","k":"6"},{"p":"org.apache.datasketches.common","c":"BoundsOnRatiosInSampledSets","l":"getEstimateOfB(long, double)","u":"getEstimateOfB(long,double)","k":"6"},{"p":"org.apache.datasketches.common","c":"BoundsOnRatiosInSampledSets","l":"getEstimateOfBoverA(long, long)","u":"getEstimateOfBoverA(long,long)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"BoundsOnRatiosInThetaSketchedSets","l":"getEstimateOfBoverA(ThetaSketch, ThetaSketch)","u":"getEstimateOfBoverA(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"BoundsOnRatiosInTupleSketchedSets","l":"getEstimateOfBoverA(TupleSketch, ThetaSketch)","u":"getEstimateOfBoverA(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.theta.ThetaSketch)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"BoundsOnRatiosInTupleSketchedSets","l":"getEstimateOfBoverA(TupleSketch, TupleSketch)","u":"getEstimateOfBoverA(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.TupleSketch)","k":"6"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"getFamily()","k":"6"},{"p":"org.apache.datasketches.cpc","c":"CpcUnion","l":"getFamily()","k":"6"},{"p":"org.apache.datasketches.cpc","c":"CpcWrapper","l":"getFamily()","k":"6"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"getFamily()"},{"p":"org.apache.datasketches.theta","c":"ThetaAnotB","l":"getFamily()"},{"p":"org.apache.datasketches.theta","c":"ThetaIntersection","l":"getFamily()"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperation","l":"getFamily()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getFamily()"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"getFamily()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"getFamily()"},{"p":"org.apache.datasketches.common","c":"Family","l":"getFamilyName()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"getFillPercentage()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getFloat()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getFloat(long)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getFloatArray(float[], int, int)","u":"getFloatArray(float[],int,int)"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"getFloatBE(byte[], int)","u":"getFloatBE(byte[],int)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"getFloatLE(byte[], int)","u":"getFloatLE(byte[],int)","k":"6"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"getFraction()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getFrequentItems(ErrorType)","u":"getFrequentItems(org.apache.datasketches.frequencies.ErrorType)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getFrequentItems(ErrorType)","u":"getFrequentItems(org.apache.datasketches.frequencies.ErrorType)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getFrequentItems(long, ErrorType)","u":"getFrequentItems(long,org.apache.datasketches.frequencies.ErrorType)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getFrequentItems(long, ErrorType)","u":"getFrequentItems(long,org.apache.datasketches.frequencies.ErrorType)"},{"p":"org.apache.datasketches.fdt","c":"PostProcessor","l":"getGroupCount()"},{"p":"org.apache.datasketches.fdt","c":"PostProcessor","l":"getGroupList(int[], int, int)","u":"getGroupList(int[],int,int)"},{"p":"org.apache.datasketches.tuple","c":"TupleSketchIterator","l":"getHash()"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"getHeader()"},{"p":"org.apache.datasketches.req","c":"ReqSketchBuilder","l":"getHighRankAccuracy()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getHighRankAccuracyMode()"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"getId()"},{"p":"org.apache.datasketches.common","c":"Family","l":"getID()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getInstance(Class, Comparator)","u":"getInstance(java.lang.Class,java.util.Comparator)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"getInstance(Class, Comparator)","u":"getInstance(java.lang.Class,java.util.Comparator)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getInstance(Class, int, Comparator)","u":"getInstance(java.lang.Class,int,java.util.Comparator)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"getInstance(Class, int, Comparator)","u":"getInstance(java.lang.Class,int,java.util.Comparator)","k":"6"},{"p":"org.apache.datasketches.common.positional","c":"Positional","l":"getInstance(long)","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getInstance(MemorySegment)","u":"getInstance(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getInstance(MemorySegment, ArrayOfItemsSerDe)","u":"getInstance(java.lang.foreign.MemorySegment,org.apache.datasketches.common.ArrayOfItemsSerDe)","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getInstance(String)","u":"getInstance(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getInt()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getInt(long)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getIntArray(int[], int, int)","u":"getIntArray(int[],int,int)"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"getIntBE(byte[], int)","u":"getIntBE(byte[],int)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"getIntersectAction()"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"getIntLE(byte[], int)","u":"getIntLE(byte[],int)","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch.Row","l":"getItem()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch.Row","l":"getItem()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSamples.WeightedSample","l":"getItem()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getK()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketchBuilder","l":"getK()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getK()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"getK()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getK()"},{"p":"org.apache.datasketches.req","c":"ReqSketchBuilder","l":"getK()"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"getK()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"getK()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"getK()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"getK()"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"getK()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketchIterator","l":"getKey()"},{"p":"org.apache.datasketches.hllmap","c":"UniqueCountMap","l":"getKeyUsageBytes()"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"getKFromEpsilon(double, boolean)","u":"getKFromEpsilon(double,boolean)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"ClassicUtil","l":"getKFromEpsilon(double, boolean)","u":"getKFromEpsilon(double,boolean)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getKFromEpsilon(double, boolean)","u":"getKFromEpsilon(double,boolean)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getKFromEpsilon(double, boolean)","u":"getKFromEpsilon(double,boolean)","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"getLgConfigK()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getLgConfigK()"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"getLgK()"},{"p":"org.apache.datasketches.cpc","c":"CpcUnion","l":"getLgK()"},{"p":"org.apache.datasketches.cpc","c":"CpcWrapper","l":"getLgK()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"getLgK()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"getLgK()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"getLgK()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"getLgK()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"getLgK()"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"getLgNominalEntries()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"getLgNominalEntries()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"getLgNomLongs()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getLong()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getLong(long)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getLongArray(long[], int, int)","u":"getLongArray(long[],int,int)"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"getLongBE(byte[], int)","u":"getLongBE(byte[],int)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"getLongLE(byte[], int)","u":"getLongLE(byte[],int)","k":"6"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"getLowerBound()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch.Row","l":"getLowerBound()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch.Row","l":"getLowerBound()"},{"p":"org.apache.datasketches.sampling","c":"SampleSubsetSummary","l":"getLowerBound()"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getLowerBound(byte[])"},{"p":"org.apache.datasketches.hllmap","c":"UniqueCountMap","l":"getLowerBound(byte[])"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"getLowerBound(int)"},{"p":"org.apache.datasketches.cpc","c":"CpcWrapper","l":"getLowerBound(int)"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"getLowerBound(int)"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getLowerBound(int)"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getLowerBound(int)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"getLowerBound(int)"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"getLowerBound(int)"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"getLowerBound(int, int)","u":"getLowerBound(int,int)"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getLowerBound(int, MemorySegment)","u":"getLowerBound(int,java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getLowerBound(long)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getLowerBound(long)"},{"p":"org.apache.datasketches.thetacommon","c":"BinomialBoundsN","l":"getLowerBound(long, double, int, boolean)","u":"getLowerBound(long,double,int,boolean)","k":"6"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getLowerBound(String)","u":"getLowerBound(java.lang.String)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getLowerBound(T)"},{"p":"org.apache.datasketches.common","c":"BoundsOnRatiosInSampledSets","l":"getLowerBoundForBoverA(long, long, double)","u":"getLowerBoundForBoverA(long,long,double)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"BoundsOnRatiosInThetaSketchedSets","l":"getLowerBoundForBoverA(ThetaSketch, ThetaSketch)","u":"getLowerBoundForBoverA(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"BoundsOnRatiosInTupleSketchedSets","l":"getLowerBoundForBoverA(TupleSketch, ThetaSketch)","u":"getLowerBoundForBoverA(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.theta.ThetaSketch)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"BoundsOnRatiosInTupleSketchedSets","l":"getLowerBoundForBoverA(TupleSketch, TupleSketch)","u":"getLowerBoundForBoverA(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.TupleSketch)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperation","l":"getMaxAnotBResultBytes(int)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesCompactSketch","l":"getMaxBytes()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"getMaxBytes()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUnion","l":"getMaxBytes(int, int)","u":"getMaxBytes(int,int)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getMaxCompactSketchBytes(int)","k":"6"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"getMaxConcurrencyError()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getMaximumError()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getMaximumError()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getMaximumMapCapacity()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getMaximumMapCapacity()"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperation","l":"getMaxIntersectionBytes(int)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSketchSortedView","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSortedView","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSketchSortedView","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSortedView","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericPartitionBoundaries","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedView","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSketchSortedView","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSortedView","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getMaxItem()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getMaxItem()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"getMaxK()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnionBuilder","l":"getMaxK()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"getMaxK()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsUnion","l":"getMaxK()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsUnion","l":"getMaxK()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"getMaxNumLocalThreads()"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getMaxPartitions()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getMaxPartitions()"},{"p":"org.apache.datasketches.quantilescommon","c":"SketchPartitionLimits","l":"getMaxPartitions()"},{"p":"org.apache.datasketches.common","c":"Family","l":"getMaxPreLongs()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getMaxSerializationBytes(int)","k":"6"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"getMaxSerializedBytes(int)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"getMaxSerializedSizeBytes(int, long, KllSketch.SketchType, boolean)","u":"getMaxSerializedSizeBytes(int,long,org.apache.datasketches.kll.KllSketch.SketchType,boolean)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"getMaxUnionBytes()"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperation","l":"getMaxUnionBytes(int)","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"getMaxUpdatableSerializationBytes(int, TgtHllType)","u":"getMaxUpdatableSerializationBytes(int,org.apache.datasketches.hll.TgtHllType)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getMaxUpdateSketchBytes(int)","k":"6"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"getMaxValue()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getMemorySegment()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"getMemorySegmentRequest()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getMinItem()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSketchSortedView","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSortedView","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSketchSortedView","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSortedView","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericPartitionBoundaries","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedView","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSketchSortedView","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSortedView","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getMinItem()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getMinItem()"},{"p":"org.apache.datasketches.quantilescommon","c":"SketchPartitionLimits","l":"getMinPartitionSizeItems()"},{"p":"org.apache.datasketches.common","c":"Family","l":"getMinPreLongs()"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"getMinValue()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getN()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getN()"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSketchSortedView","l":"getN()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSketchSortedView","l":"getN()"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericPartitionBoundaries","l":"getN()"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getN()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSketchSortedView","l":"getN()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"getN()"},{"p":"org.apache.datasketches.quantilescommon","c":"SketchPartitionLimits","l":"getN()"},{"p":"org.apache.datasketches.quantilescommon","c":"SortedView","l":"getN()"},{"p":"org.apache.datasketches.quantilescommon","c":"SortedViewIterator","l":"getN()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getN()"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"getN()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"getN()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"getN()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"getN()"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchType","l":"getName()"},{"p":"org.apache.datasketches.quantilescommon","c":"SortedViewIterator","l":"getNaturalRank()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesUtil","l":"getNaturalRank(double, long, QuantileSearchCriteria)","u":"getNaturalRank(double,long,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"SortedViewIterator","l":"getNaturalRank(QuantileSearchCriteria)","u":"getNaturalRank(org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericPartitionBoundaries","l":"getNaturalRanks()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"getNominalEntries()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"getNominalEntries()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"getNominalEntries()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"getNominalEntries()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"getNominalEntries()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"getNominalEntries()"},{"p":"org.apache.datasketches.quantilescommon","c":"SortedViewIterator","l":"getNormalizedRank()"},{"p":"org.apache.datasketches.quantilescommon","c":"SortedViewIterator","l":"getNormalizedRank(QuantileSearchCriteria)","u":"getNormalizedRank(org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"getNormalizedRankError(boolean)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getNormalizedRankError(boolean)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getNormalizedRankError(boolean)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"getNormalizedRankError(boolean)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getNormalizedRankError(boolean)"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"getNormalizedRankError(int, boolean)","u":"getNormalizedRankError(int,boolean)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"ClassicUtil","l":"getNormalizedRankError(int, boolean)","u":"getNormalizedRankError(int,boolean)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getNormalizedRankError(int, boolean)","u":"getNormalizedRankError(int,boolean)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getNormalizedRankError(int, boolean)","u":"getNormalizedRankError(int,boolean)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericPartitionBoundaries","l":"getNormalizedRanks()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getNumActiveItems()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getNumActiveItems()"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getNumBuckets_()"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericPartitionBoundaries","l":"getNumDeltaItems()"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getNumHashes_()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"getNumHashes()"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericPartitionBoundaries","l":"getNumPartitions()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"getNumPoolThreads()"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"getNumRetained()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getNumRetained()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getNumRetained()"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSketchSortedView","l":"getNumRetained()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSketchSortedView","l":"getNumRetained()"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getNumRetained()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSketchSortedView","l":"getNumRetained()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"getNumRetained()"},{"p":"org.apache.datasketches.quantilescommon","c":"SortedView","l":"getNumRetained()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getNumRetained()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"getNumSamples()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"getNumSamples()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSamples","l":"getNumSamples()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"getNumSamples()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"getNumValues()"},{"p":"org.apache.datasketches.tuple","c":"DeserializeResult","l":"getObject()"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"getP()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"getP()"},{"p":"org.apache.datasketches.quantilescommon","c":"PartitioningFeature","l":"getPartitionBoundariesFromNumParts(int)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getPartitionBoundariesFromNumParts(int, QuantileSearchCriteria)","u":"getPartitionBoundariesFromNumParts(int,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getPartitionBoundariesFromNumParts(int, QuantileSearchCriteria)","u":"getPartitionBoundariesFromNumParts(int,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getPartitionBoundariesFromNumParts(int, QuantileSearchCriteria)","u":"getPartitionBoundariesFromNumParts(int,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"PartitioningFeature","l":"getPartitionBoundariesFromNumParts(int, QuantileSearchCriteria)","u":"getPartitionBoundariesFromNumParts(int,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"PartitioningFeature","l":"getPartitionBoundariesFromPartSize(long)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getPartitionBoundariesFromPartSize(long, QuantileSearchCriteria)","u":"getPartitionBoundariesFromPartSize(long,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getPartitionBoundariesFromPartSize(long, QuantileSearchCriteria)","u":"getPartitionBoundariesFromPartSize(long,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getPartitionBoundariesFromPartSize(long, QuantileSearchCriteria)","u":"getPartitionBoundariesFromPartSize(long,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"PartitioningFeature","l":"getPartitionBoundariesFromPartSize(long, QuantileSearchCriteria)","u":"getPartitionBoundariesFromPartSize(long,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getPMF(double[])"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"getPMF(double[])"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"getPMF(double[], QuantileSearchCriteria)","u":"getPMF(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getPMF(double[], QuantileSearchCriteria)","u":"getPMF(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSortedView","l":"getPMF(double[], QuantileSearchCriteria)","u":"getPMF(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getPMF(double[], QuantileSearchCriteria)","u":"getPMF(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getPMF(float[])"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"getPMF(float[], QuantileSearchCriteria)","u":"getPMF(float[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSortedView","l":"getPMF(float[], QuantileSearchCriteria)","u":"getPMF(float[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getPMF(float[], QuantileSearchCriteria)","u":"getPMF(float[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getPMF(float[], QuantileSearchCriteria)","u":"getPMF(float[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getPMF(long[])"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"getPMF(long[], QuantileSearchCriteria)","u":"getPMF(long[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSortedView","l":"getPMF(long[], QuantileSearchCriteria)","u":"getPMF(long[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getPMF(long[], QuantileSearchCriteria)","u":"getPMF(long[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getPMF(T[])"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getPMF(T[], QuantileSearchCriteria)","u":"getPMF(T[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getPMF(T[], QuantileSearchCriteria)","u":"getPMF(T[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedView","l":"getPMF(T[], QuantileSearchCriteria)","u":"getPMF(T[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getPMF(T[], QuantileSearchCriteria)","u":"getPMF(T[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.common.positional","c":"Positional","l":"getPosition()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"getPostProcessor()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"getPostProcessor(Group, char)","u":"getPostProcessor(org.apache.datasketches.fdt.Group,char)"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchStructure","l":"getPreInts()"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"getPrimaryKey()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"getPropagateOrderedCompact()"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketchIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketchIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketchIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketchIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketchIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketchIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSortedViewIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSortedViewIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedViewIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSortedViewIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesSketchIteratorAPI","l":"getQuantile()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsSketchIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericSketchIteratorAPI","l":"getQuantile()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsSketchIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.req","c":"ReqSketchIterator","l":"getQuantile()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getQuantile(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getQuantile(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getQuantile(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getQuantile(double)"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"getQuantile(double)"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSketchSortedView","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSortedView","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSketchSortedView","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSortedView","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedView","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSketchSortedView","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSortedView","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getQuantile(double, QuantileSearchCriteria)","u":"getQuantile(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedViewIterator","l":"getQuantile(QuantileSearchCriteria)","u":"getQuantile(org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"getQuantileLowerBound(double)"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"getQuantileLowerBound(double)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getQuantileLowerBound(double)"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"getQuantileLowerBound(double)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getQuantileLowerBound(double)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getQuantileLowerBound(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getQuantileLowerBound(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getQuantileLowerBound(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getQuantileLowerBound(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getQuantileLowerBound(double)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getQuantileLowerBound(double)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getQuantileLowerBound(double, int)","u":"getQuantileLowerBound(double,int)"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSketchSortedView","l":"getQuantiles()"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSortedView","l":"getQuantiles()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSketchSortedView","l":"getQuantiles()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSortedView","l":"getQuantiles()"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedView","l":"getQuantiles()"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getQuantiles()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSketchSortedView","l":"getQuantiles()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSortedView","l":"getQuantiles()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getQuantiles(double[])"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getQuantiles(double[])"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getQuantiles(double[])"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getQuantiles(double[])"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"getQuantiles(double[], QuantileSearchCriteria)","u":"getQuantiles(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"getQuantiles(double[], QuantileSearchCriteria)","u":"getQuantiles(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getQuantiles(double[], QuantileSearchCriteria)","u":"getQuantiles(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"getQuantiles(double[], QuantileSearchCriteria)","u":"getQuantiles(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getQuantiles(double[], QuantileSearchCriteria)","u":"getQuantiles(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getQuantiles(double[], QuantileSearchCriteria)","u":"getQuantiles(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getQuantiles(double[], QuantileSearchCriteria)","u":"getQuantiles(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getQuantiles(double[], QuantileSearchCriteria)","u":"getQuantiles(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getQuantiles(double[], QuantileSearchCriteria)","u":"getQuantiles(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getQuantiles(double[], QuantileSearchCriteria)","u":"getQuantiles(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getQuantiles(double[], QuantileSearchCriteria)","u":"getQuantiles(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getQuantiles(double[], QuantileSearchCriteria)","u":"getQuantiles(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"getQuantileUpperBound(double)"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"getQuantileUpperBound(double)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getQuantileUpperBound(double)"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"getQuantileUpperBound(double)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getQuantileUpperBound(double)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getQuantileUpperBound(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getQuantileUpperBound(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getQuantileUpperBound(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getQuantileUpperBound(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getQuantileUpperBound(double)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getQuantileUpperBound(double)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getQuantileUpperBound(double, int)","u":"getQuantileUpperBound(double,int)"},{"p":"org.apache.datasketches.partitions","c":"SketchFillRequest","l":"getRange(T, T, BoundsRule)","u":"getRange(T,T,org.apache.datasketches.partitions.BoundsRule)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getRank(double)"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"getRank(double)"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"getRank(double, QuantileSearchCriteria)","u":"getRank(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getRank(double, QuantileSearchCriteria)","u":"getRank(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSketchSortedView","l":"getRank(double, QuantileSearchCriteria)","u":"getRank(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSortedView","l":"getRank(double, QuantileSearchCriteria)","u":"getRank(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getRank(double, QuantileSearchCriteria)","u":"getRank(double,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getRank(float)"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"getRank(float, QuantileSearchCriteria)","u":"getRank(float,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSketchSortedView","l":"getRank(float, QuantileSearchCriteria)","u":"getRank(float,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSortedView","l":"getRank(float, QuantileSearchCriteria)","u":"getRank(float,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getRank(float, QuantileSearchCriteria)","u":"getRank(float,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getRank(float, QuantileSearchCriteria)","u":"getRank(float,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getRank(long)"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"getRank(long, QuantileSearchCriteria)","u":"getRank(long,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSketchSortedView","l":"getRank(long, QuantileSearchCriteria)","u":"getRank(long,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSortedView","l":"getRank(long, QuantileSearchCriteria)","u":"getRank(long,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getRank(long, QuantileSearchCriteria)","u":"getRank(long,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getRank(T)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getRank(T, QuantileSearchCriteria)","u":"getRank(T,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getRank(T, QuantileSearchCriteria)","u":"getRank(T,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedView","l":"getRank(T, QuantileSearchCriteria)","u":"getRank(T,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"getRank(T, QuantileSearchCriteria)","u":"getRank(T,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getRank(T, QuantileSearchCriteria)","u":"getRank(T,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"getRankLowerBound(double)"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"getRankLowerBound(double)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getRankLowerBound(double)"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"getRankLowerBound(double)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getRankLowerBound(double)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getRankLowerBound(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"getRankLowerBound(double)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getRankLowerBound(double)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getRankLowerBound(double, int)","u":"getRankLowerBound(double,int)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getRanks(double[])"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"getRanks(double[], QuantileSearchCriteria)","u":"getRanks(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getRanks(double[], QuantileSearchCriteria)","u":"getRanks(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getRanks(double[], QuantileSearchCriteria)","u":"getRanks(double[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getRanks(float[])"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"getRanks(float[], QuantileSearchCriteria)","u":"getRanks(float[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getRanks(float[], QuantileSearchCriteria)","u":"getRanks(float[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getRanks(float[], QuantileSearchCriteria)","u":"getRanks(float[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getRanks(long[])"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"getRanks(long[], QuantileSearchCriteria)","u":"getRanks(long[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getRanks(long[], QuantileSearchCriteria)","u":"getRanks(long[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getRanks(T[])"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getRanks(T[], QuantileSearchCriteria)","u":"getRanks(T[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getRanks(T[], QuantileSearchCriteria)","u":"getRanks(T[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getRanks(T[], QuantileSearchCriteria)","u":"getRanks(T[],org.apache.datasketches.quantilescommon.QuantileSearchCriteria)"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"getRankUpperBound(double)"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"getRankUpperBound(double)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getRankUpperBound(double)"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"getRankUpperBound(double)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getRankUpperBound(double)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getRankUpperBound(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"getRankUpperBound(double)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getRankUpperBound(double)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getRankUpperBound(double, int)","u":"getRankUpperBound(double,int)"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getRelativeError()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"getRelErr(boolean, boolean, int, int)","u":"getRelErr(boolean,boolean,int,int)","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getRelErr(boolean, boolean, int, int)","u":"getRelErr(boolean,boolean,int,int)","k":"6"},{"p":"org.apache.datasketches.common.positional","c":"Positional","l":"getRemaining()"},{"p":"org.apache.datasketches.req","c":"ReqSketchBuilder","l":"getReqDebug()"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"getResizeFactor()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"getResizeFactor()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"getResizeFactor()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"getResizeFactor()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"getResizeFactor()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"getResizeFactor()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"getResizeFactor()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"getResizeFactor()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"getResizeFactor()"},{"p":"org.apache.datasketches.cpc","c":"CpcUnion","l":"getResult()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getResult()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"getResult()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"getResult()"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"getResult()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsUnion","l":"getResult()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsUnion","l":"getResult()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsUnion","l":"getResult()"},{"p":"org.apache.datasketches.theta","c":"ThetaIntersection","l":"getResult()"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"getResult()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesAnotB","l":"getResult()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesAnotBImpl","l":"getResult()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesIntersection","l":"getResult()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUnion","l":"getResult()"},{"p":"org.apache.datasketches.tuple","c":"TupleIntersection","l":"getResult()"},{"p":"org.apache.datasketches.tuple","c":"TupleUnion","l":"getResult()"},{"p":"org.apache.datasketches.theta","c":"ThetaAnotB","l":"getResult(boolean)"},{"p":"org.apache.datasketches.tuple","c":"TupleAnotB","l":"getResult(boolean)"},{"p":"org.apache.datasketches.tuple","c":"TupleUnion","l":"getResult(boolean)"},{"p":"org.apache.datasketches.theta","c":"ThetaIntersection","l":"getResult(boolean, MemorySegment)","u":"getResult(boolean,java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"getResult(boolean, MemorySegment)","u":"getResult(boolean,java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.theta","c":"ThetaAnotB","l":"getResult(boolean, MemorySegment, boolean)","u":"getResult(boolean,java.lang.foreign.MemorySegment,boolean)"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"getResult(int[], int, int, char)","u":"getResult(int[],int,int,char)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesAnotB","l":"getResult(MemorySegment)","u":"getResult(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesAnotBImpl","l":"getResult(MemorySegment)","u":"getResult(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesIntersection","l":"getResult(MemorySegment)","u":"getResult(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUnion","l":"getResult(MemorySegment)","u":"getResult(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"getResult(MemorySegment, MemorySegmentRequest)","u":"getResult(java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getResult(TgtHllType)","u":"getResult(org.apache.datasketches.hll.TgtHllType)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"getResultAndReset()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"getResultAndReset()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getRetainedEntries()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"getRetainedEntries()"},{"p":"org.apache.datasketches.tuple","c":"CompactTupleSketch","l":"getRetainedEntries()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"getRetainedEntries()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"getRetainedEntries()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"getRetainedEntries()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"getRetainedEntries()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"getRetainedEntries()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"getRetainedEntries()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getRetainedEntries(boolean)"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getRetainedEntries(MemorySegment)","u":"getRetainedEntries(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.common","c":"ResizeFactor","l":"getRF(int)","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch.Row","l":"getRowHeader()","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch.Row","l":"getRowHeader()","k":"6"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"getRse()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getRSE(int, double, boolean, long)","u":"getRSE(int,double,boolean,long)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"getSamples()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"getSamples()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"getSamples(Class)","u":"getSamples(java.lang.Class)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"getSamplingProbability()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"getSamplingProbability()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"getSamplingProbability()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"getSamplingProbability()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"getSamplingProbability()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"getSamplingProbability()"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericPartitionBoundaries","l":"getSearchCriteria()"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getSeed_()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"getSeed()"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"getSeed()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"getSeed()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"getSeed()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"getSerializationVersion()","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getSerializationVersion()","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"getSerializationVersion(MemorySegment)","u":"getSerializationVersion(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getSerializationVersion(MemorySegment)","u":"getSerializationVersion(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getSerializationVersion(MemorySegment)","u":"getSerializationVersion(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"getSerializedFilterSize(long)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"getSerializedFilterSizeByAccuracy(long, double)","u":"getSerializedFilterSizeByAccuracy(long,double)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"getSerializedSize(long)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"getSerializedSizeBytes()"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"getSerializedSizeBytes()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getSerializedSizeBytes()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getSerializedSizeBytes()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getSerializedSizeBytes()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getSerializedSizeBytes()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getSerializedSizeBytes()"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"getSerializedSizeBytes(ArrayOfItemsSerDe)","u":"getSerializedSizeBytes(org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"getSerializedSizeBytes(ArrayOfItemsSerDe, Class)","u":"getSerializedSizeBytes(org.apache.datasketches.common.ArrayOfItemsSerDe,java.lang.Class)"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchStructure","l":"getSerVer()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getShort()"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getShort(long)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"getShortArray(short[], int, int)","u":"getShortArray(short[],int,int)"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"getShortBE(byte[], int)","u":"getShortBE(byte[],int)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"getShortLE(byte[], int)","u":"getShortLE(byte[],int)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"DeserializeResult","l":"getSize()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"getSketchSamples()"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchStructure","l":"getSketchStructure(int, int)","u":"getSketchStructure(int,int)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"SerializerDeserializer","l":"getSketchType(MemorySegment)","u":"getSketchType(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"getSortedView()"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"getSortedView()"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"getSortedView()"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"getSortedView()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getSortedView()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"getSortedView()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"getSortedView()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"getSortedView()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"getSortedView()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"getSortedView()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"getSortedView()"},{"p":"org.apache.datasketches.common.positional","c":"Positional","l":"getStart()"},{"p":"org.apache.datasketches.tuple","c":"Util","l":"getStartingCapacity(int, int)","u":"getStartingCapacity(int,int)","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getStorageBytes()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getStreamLength()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getStreamLength()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketchIterator","l":"getSummary()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"getSummaryFactory()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"getTgtHllType()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getTgtHllType()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getTheta()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"getTheta()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"getTheta()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getThetaLong()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"getThetaLong()"},{"p":"org.apache.datasketches.sampling","c":"SampleSubsetSummary","l":"getTotalSketchWeight()"},{"p":"org.apache.datasketches.hllmap","c":"UniqueCountMap","l":"getTotalUsageBytes()"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getTotalWeight_()"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"getTotalWeight()"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"getUnionAction()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"getUpdatableSerializationBytes()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getUpdatableSerializationBytes()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"getUpdatableStorageBytes(int, long)","u":"getUpdatableStorageBytes(int,long)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getUpdateSketchMaxBytes(int)","k":"6"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"getUpperBound()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch.Row","l":"getUpperBound()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch.Row","l":"getUpperBound()"},{"p":"org.apache.datasketches.sampling","c":"SampleSubsetSummary","l":"getUpperBound()"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getUpperBound(byte[])"},{"p":"org.apache.datasketches.hllmap","c":"UniqueCountMap","l":"getUpperBound(byte[])"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"getUpperBound(int)"},{"p":"org.apache.datasketches.cpc","c":"CpcWrapper","l":"getUpperBound(int)"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"getUpperBound(int)"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"getUpperBound(int)"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getUpperBound(int)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"getUpperBound(int)"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"getUpperBound(int)"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"getUpperBound(int, int)","u":"getUpperBound(int,int)"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"getUpperBound(int, MemorySegment)","u":"getUpperBound(int,java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getUpperBound(long)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"getUpperBound(long)"},{"p":"org.apache.datasketches.thetacommon","c":"BinomialBoundsN","l":"getUpperBound(long, double, int, boolean)","u":"getUpperBound(long,double,int,boolean)","k":"6"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"getUpperBound(String)","u":"getUpperBound(java.lang.String)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"getUpperBound(T)"},{"p":"org.apache.datasketches.common","c":"BoundsOnRatiosInSampledSets","l":"getUpperBoundForBoverA(long, long, double)","u":"getUpperBoundForBoverA(long,long,double)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"BoundsOnRatiosInThetaSketchedSets","l":"getUpperBoundForBoverA(ThetaSketch, ThetaSketch)","u":"getUpperBoundForBoverA(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"BoundsOnRatiosInTupleSketchedSets","l":"getUpperBoundForBoverA(TupleSketch, ThetaSketch)","u":"getUpperBoundForBoverA(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.theta.ThetaSketch)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"BoundsOnRatiosInTupleSketchedSets","l":"getUpperBoundForBoverA(TupleSketch, TupleSketch)","u":"getUpperBoundForBoverA(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.TupleSketch)","k":"6"},{"p":"org.apache.datasketches.common","c":"ResizeFactor","l":"getValue()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummary","l":"getValue()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummary","l":"getValue()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummary","l":"getValue()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"getValues()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketchIterator","l":"getValues()"},{"p":"org.apache.datasketches.kll","c":"KllSketchIterator","l":"getWeight()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketchIterator","l":"getWeight()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketchIterator","l":"getWeight()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesSketchIteratorAPI","l":"getWeight()"},{"p":"org.apache.datasketches.quantilescommon","c":"SortedViewIterator","l":"getWeight()"},{"p":"org.apache.datasketches.req","c":"ReqSketchIterator","l":"getWeight()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSamples.WeightedSample","l":"getWeight()"},{"p":"org.apache.datasketches.partitions","c":"Partitioner.StackElement","l":"gpb","k":"1"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"Group()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericInequalitySearch.Inequality","l":"GT","k":"0"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"GT","k":"0"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3","l":"hash(byte[], int, int, long)","u":"hash(byte[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3","l":"hash(byte[], long)","u":"hash(byte[],long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3FFM","l":"hash(byte[], long)","u":"hash(byte[],long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3","l":"hash(ByteBuffer, long)","u":"hash(java.nio.ByteBuffer,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3","l":"hash(char[], int, int, long)","u":"hash(char[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3","l":"hash(char[], long)","u":"hash(char[],long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3FFM","l":"hash(char[], long)","u":"hash(char[],long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3FFM","l":"hash(double, long, long[])","u":"hash(double,long,long[])","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3","l":"hash(int[], int, int, long)","u":"hash(int[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3","l":"hash(int[], long)","u":"hash(int[],long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3FFM","l":"hash(int[], long)","u":"hash(int[],long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3","l":"hash(long, long)","u":"hash(long,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash64","l":"hash(long, long)","u":"hash(long,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3FFM","l":"hash(long, long, long[])","u":"hash(long,long,long[])","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3","l":"hash(long[], int, int, long)","u":"hash(long[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3","l":"hash(long[], long)","u":"hash(long[],long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3FFM","l":"hash(long[], long)","u":"hash(long[],long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3","l":"hash(MemorySegment, long)","u":"hash(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash64","l":"hash(MemorySegment, long, long, long)","u":"hash(java.lang.foreign.MemorySegment,long,long,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3FFM","l":"hash(MemorySegment, long, long, long, long[])","u":"hash(java.lang.foreign.MemorySegment,long,long,long,long[])","k":"6"},{"p":"org.apache.datasketches.hash","c":"MurmurHash3FFM","l":"hash(String, long, long[])","u":"hash(java.lang.String,long,long[])","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"hashArrayInsert(long[], long[], int, long)","u":"hashArrayInsert(long[],long[],int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash","l":"hashByteArr(byte[], int, int, long)","u":"hashByteArr(byte[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash64","l":"hashBytes(byte[], int, int, long)","u":"hashBytes(byte[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash","l":"hashCharArr(char[], int, int, long)","u":"hashCharArr(char[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash64","l":"hashChars(char[], int, int, long)","u":"hashChars(char[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"hashCode()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch.Row","l":"hashCode()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch.Row","l":"hashCode()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummary","l":"hashCode()"},{"p":"org.apache.datasketches.hash","c":"XxHash","l":"hashDoubleArr(double[], int, int, long)","u":"hashDoubleArr(double[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash64","l":"hashDoubles(double[], int, int, long)","u":"hashDoubles(double[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash","l":"hashFloatArr(float[], int, int, long)","u":"hashFloatArr(float[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash64","l":"hashFloats(float[], int, int, long)","u":"hashFloats(float[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"hashInsertOnly(long[], int, long)","u":"hashInsertOnly(long[],int,long)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"hashInsertOnlyMemorySegment(MemorySegment, int, long, int)","u":"hashInsertOnlyMemorySegment(java.lang.foreign.MemorySegment,int,long,int)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash","l":"hashIntArr(int[], int, int, long)","u":"hashIntArr(int[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash64","l":"hashInts(int[], int, int, long)","u":"hashInts(int[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash","l":"hashLong(long, long)","u":"hashLong(long,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash","l":"hashLongArr(long[], int, int, long)","u":"hashLongArr(long[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash64","l":"hashLongs(long[], int, int, long)","u":"hashLongs(long[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"hashSearch(long[], int, long)","u":"hashSearch(long[],int,long)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"hashSearchMemorySegment(MemorySegment, int, long, int)","u":"hashSearchMemorySegment(java.lang.foreign.MemorySegment,int,long,int)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"hashSearchOrInsert(long[], int, long)","u":"hashSearchOrInsert(long[],int,long)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"hashSearchOrInsertMemorySegment(MemorySegment, int, long, int)","u":"hashSearchOrInsertMemorySegment(java.lang.foreign.MemorySegment,int,long,int)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash","l":"hashShortArr(short[], int, int, long)","u":"hashShortArr(short[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash64","l":"hashShorts(short[], int, int, long)","u":"hashShorts(short[],int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash","l":"hashString(String, int, int, long)","u":"hashString(java.lang.String,int,int,long)","k":"6"},{"p":"org.apache.datasketches.hash","c":"XxHash64","l":"hashString(String, int, int, long)","u":"hashString(java.lang.String,int,int,long)","k":"6"},{"p":"org.apache.datasketches.common","c":"MemorySegmentStatus","l":"hasMemorySegment()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"hasMemorySegment()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"DirectBitArrayR","l":"hasMemorySegment()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"hasMemorySegment()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"hasMemorySegment()"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"hasMemorySegment()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"hasMemorySegment()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"hasMemorySegment()"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"hasMemorySegment()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"hasMemorySegment()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"hasMemorySegment()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSamples.VarOptItemsIterator","l":"hasNext()"},{"p":"org.apache.datasketches.common.positional","c":"Positional","l":"hasRemaining()"},{"p":"org.apache.datasketches.theta","c":"ThetaIntersection","l":"hasResult()"},{"p":"org.apache.datasketches.tuple","c":"TupleIntersection","l":"hasResult()"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"heapify(byte[])","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"heapify(byte[])","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"heapify(byte[])","k":"6"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"heapify(byte[], long)","u":"heapify(byte[],long)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"heapify(Class, MemorySegment, Comparator, ArrayOfItemsSerDe)","u":"heapify(java.lang.Class,java.lang.foreign.MemorySegment,java.util.Comparator,org.apache.datasketches.common.ArrayOfItemsSerDe)","k":"6"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"UpdatableQuantilesDoublesSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsUnion","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperation","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUnion","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"heapify(MemorySegment)","u":"heapify(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"heapify(MemorySegment, ArrayOfItemsSerDe)","u":"heapify(java.lang.foreign.MemorySegment,org.apache.datasketches.common.ArrayOfItemsSerDe)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"heapify(MemorySegment, ArrayOfItemsSerDe)","u":"heapify(java.lang.foreign.MemorySegment,org.apache.datasketches.common.ArrayOfItemsSerDe)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsUnion","l":"heapify(MemorySegment, ArrayOfItemsSerDe)","u":"heapify(java.lang.foreign.MemorySegment,org.apache.datasketches.common.ArrayOfItemsSerDe)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"heapify(MemorySegment, ArrayOfItemsSerDe)","u":"heapify(java.lang.foreign.MemorySegment,org.apache.datasketches.common.ArrayOfItemsSerDe)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsUnion","l":"heapify(MemorySegment, ArrayOfItemsSerDe)","u":"heapify(java.lang.foreign.MemorySegment,org.apache.datasketches.common.ArrayOfItemsSerDe)","k":"6"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"heapify(MemorySegment, boolean)","u":"heapify(java.lang.foreign.MemorySegment,boolean)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"heapify(MemorySegment, Comparator, ArrayOfItemsSerDe)","u":"heapify(java.lang.foreign.MemorySegment,java.util.Comparator,org.apache.datasketches.common.ArrayOfItemsSerDe)","k":"6"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"heapify(MemorySegment, long)","u":"heapify(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"heapify(MemorySegment, long)","u":"heapify(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperation","l":"heapify(MemorySegment, long)","u":"heapify(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"heapify(MemorySegment, long)","u":"heapify(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"heapify(MemorySegment, long)","u":"heapify(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"heapify(MemorySegment, long)","u":"heapify(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUnion","l":"heapify(MemorySegment, long)","u":"heapify(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"heapify(MemorySegment, long)","u":"heapify(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"heapify(QuantilesDoublesSketch)","u":"heapify(org.apache.datasketches.quantiles.QuantilesDoublesSketch)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"heapifySketch(MemorySegment)","u":"heapifySketch(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"heapifySketch(MemorySegment, long)","u":"heapifySketch(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"heapifySketch(MemorySegment, SummaryDeserializer)","u":"heapifySketch(java.lang.foreign.MemorySegment,org.apache.datasketches.tuple.SummaryDeserializer)","k":"6"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummaryDeserializer","l":"heapifySummary(MemorySegment)","u":"heapifySummary(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummaryDeserializer","l":"heapifySummary(MemorySegment)","u":"heapifySummary(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummaryDeserializer","l":"heapifySummary(MemorySegment)","u":"heapifySummary(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple","c":"SummaryDeserializer","l":"heapifySummary(MemorySegment)","u":"heapifySummary(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"heapifyUnion(MemorySegment)","u":"heapifyUnion(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"heapifyUnion(MemorySegment, long)","u":"heapifyUnion(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"heapifyUpdatableSketch(MemorySegment)","u":"heapifyUpdatableSketch(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"heapifyUpdatableSketch(MemorySegment, long)","u":"heapifyUpdatableSketch(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"heapifyUpdatableSketch(MemorySegment, SummaryDeserializer, SummaryFactory)","u":"heapifyUpdatableSketch(java.lang.foreign.MemorySegment,org.apache.datasketches.tuple.SummaryDeserializer,org.apache.datasketches.tuple.SummaryFactory)","k":"6"},{"p":"org.apache.datasketches.common","c":"Family","l":"HLL","k":"0"},{"p":"org.apache.datasketches.hll","c":"TgtHllType","l":"HLL_4","k":"0"},{"p":"org.apache.datasketches.hll","c":"TgtHllType","l":"HLL_6","k":"0"},{"p":"org.apache.datasketches.hll","c":"TgtHllType","l":"HLL_8","k":"0"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"HllSketch()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"HllSketch(int)","u":"%3Cinit%3E(int)","k":"3"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"HllSketch(int, TgtHllType)","u":"%3Cinit%3E(int,org.apache.datasketches.hll.TgtHllType)","k":"3"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"HllSketch(int, TgtHllType, MemorySegment)","u":"%3Cinit%3E(int,org.apache.datasketches.hll.TgtHllType,java.lang.foreign.MemorySegment)","k":"3"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"HllUnion()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"HllUnion(int)","u":"%3Cinit%3E(int)","k":"3"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"HllUnion(int, MemorySegment)","u":"%3Cinit%3E(int,java.lang.foreign.MemorySegment)","k":"3"},{"p":"org.apache.datasketches.common","c":"Family","l":"idToFamily(int)","k":"6"},{"p":"org.apache.datasketches.partitions","c":"BoundsRule","l":"INCLUDE_BOTH","k":"0"},{"p":"org.apache.datasketches.partitions","c":"BoundsRule","l":"INCLUDE_LOWER","k":"0"},{"p":"org.apache.datasketches.partitions","c":"BoundsRule","l":"INCLUDE_NEITHER","k":"0"},{"p":"org.apache.datasketches.partitions","c":"BoundsRule","l":"INCLUDE_UPPER","k":"0"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax","l":"includeDoublesMinMax(double[], long[], double, double)","u":"includeDoublesMinMax(double[],long[],double,double)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax","l":"includeFloatsMinMax(float[], long[], float, float)","u":"includeFloatsMinMax(float[],long[],float,float)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax","l":"includeItemsMinMax(T[], long[], T, T, Comparator)","u":"includeItemsMinMax(T[],long[],T,T,java.util.Comparator)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax","l":"includeLongsMinMax(long[], long[], long, long)","u":"includeLongsMinMax(long[],long[],long,long)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax","l":"IncludeMinMax()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantileSearchCriteria","l":"INCLUSIVE","k":"0"},{"p":"org.apache.datasketches.common.positional","c":"Positional","l":"incrementPosition(long)"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"init(String, int, double, double, double, double, double)","u":"init(java.lang.String,int,double,double,double,double,double)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"initialize(QuantilesItemsSketch)","u":"initialize(org.apache.datasketches.quantiles.QuantilesItemsSketch)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"initializeByAccuracy(long, double, long, MemorySegment)","u":"initializeByAccuracy(long,double,long,java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"initializeByAccuracy(long, double, MemorySegment)","u":"initializeByAccuracy(long,double,java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"initializeBySize(long, int, long, MemorySegment)","u":"initializeBySize(long,int,long,java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"initializeBySize(long, int, MemorySegment)","u":"initializeBySize(long,int,java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"initializeWithMemorySegment(Class, MemorySegment, Comparator, ArrayOfItemsSerDe)","u":"initializeWithMemorySegment(java.lang.Class,java.lang.foreign.MemorySegment,java.util.Comparator,org.apache.datasketches.common.ArrayOfItemsSerDe)","k":"6"},{"p":"org.apache.datasketches.theta","c":"UpdateReturnState","l":"InsertedCountIncremented","k":"0"},{"p":"org.apache.datasketches.theta","c":"UpdateReturnState","l":"InsertedCountIncrementedRebuilt","k":"0"},{"p":"org.apache.datasketches.theta","c":"UpdateReturnState","l":"InsertedCountIncrementedResized","k":"0"},{"p":"org.apache.datasketches.theta","c":"UpdateReturnState","l":"InsertedCountNotIncremented","k":"0"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummary","l":"IntegerSummary(IntegerSummary.Mode)","u":"%3Cinit%3E(org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummaryDeserializer","l":"IntegerSummaryDeserializer()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummaryFactory","l":"IntegerSummaryFactory(IntegerSummary.Mode)","u":"%3Cinit%3E(org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummarySetOperations","l":"IntegerSummarySetOperations(IntegerSummary.Mode, IntegerSummary.Mode)","u":"%3Cinit%3E(org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode,org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"IntegerTupleSketch(int, int, float, IntegerSummary.Mode)","u":"%3Cinit%3E(int,int,float,org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"IntegerTupleSketch(int, IntegerSummary.Mode)","u":"%3Cinit%3E(int,org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"IntegerTupleSketch(MemorySegment, IntegerSummary.Mode)","u":"%3Cinit%3E(java.lang.foreign.MemorySegment,org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode)","k":"3"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesIntersection","l":"intersect(ArrayOfDoublesSketch, ArrayOfDoublesCombiner)","u":"intersect(org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch,org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCombiner)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"intersect(BloomFilter)","u":"intersect(org.apache.datasketches.filters.bloomfilter.BloomFilter)"},{"p":"org.apache.datasketches.theta","c":"ThetaIntersection","l":"intersect(ThetaSketch)","u":"intersect(org.apache.datasketches.theta.ThetaSketch)"},{"p":"org.apache.datasketches.tuple","c":"TupleIntersection","l":"intersect(ThetaSketch, S)","u":"intersect(org.apache.datasketches.theta.ThetaSketch,S)"},{"p":"org.apache.datasketches.theta","c":"ThetaIntersection","l":"intersect(ThetaSketch, ThetaSketch)","u":"intersect(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch)"},{"p":"org.apache.datasketches.theta","c":"ThetaIntersection","l":"intersect(ThetaSketch, ThetaSketch, boolean, MemorySegment)","u":"intersect(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch,boolean,java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple","c":"TupleIntersection","l":"intersect(TupleSketch)","u":"intersect(org.apache.datasketches.tuple.TupleSketch)"},{"p":"org.apache.datasketches.tuple","c":"TupleIntersection","l":"intersect(TupleSketch, ThetaSketch, S)","u":"intersect(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.theta.ThetaSketch,S)"},{"p":"org.apache.datasketches.tuple","c":"TupleIntersection","l":"intersect(TupleSketch, TupleSketch)","u":"intersect(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.TupleSketch)"},{"p":"org.apache.datasketches.common","c":"Family","l":"INTERSECTION","k":"0"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummarySetOperations","l":"intersection(ArrayOfStringsSummary, ArrayOfStringsSummary)","u":"intersection(org.apache.datasketches.tuple.strings.ArrayOfStringsSummary,org.apache.datasketches.tuple.strings.ArrayOfStringsSummary)"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummarySetOperations","l":"intersection(DoubleSummary, DoubleSummary)","u":"intersection(org.apache.datasketches.tuple.adouble.DoubleSummary,org.apache.datasketches.tuple.adouble.DoubleSummary)"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummarySetOperations","l":"intersection(IntegerSummary, IntegerSummary)","u":"intersection(org.apache.datasketches.tuple.aninteger.IntegerSummary,org.apache.datasketches.tuple.aninteger.IntegerSummary)"},{"p":"org.apache.datasketches.tuple","c":"SummarySetOperations","l":"intersection(S, S)","u":"intersection(S,S)"},{"p":"org.apache.datasketches.common","c":"Util","l":"intToBytes(int, byte[])","u":"intToBytes(int,byte[])","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"INVERSE_GOLDEN","k":"2"},{"p":"org.apache.datasketches.common","c":"Util","l":"INVERSE_GOLDEN_U64","k":"2"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"invert()"},{"p":"org.apache.datasketches.common","c":"Util","l":"invPow2(int)","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"isCompact()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"isCompact()"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"isCompact()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"isCompact()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"isCompact()"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"isCompactMemorySegmentFormat()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"isCompatible(BloomFilter)","u":"isCompatible(org.apache.datasketches.filters.bloomfilter.BloomFilter)"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"isEmpty()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"isEmpty()"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"isEmpty()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"isEmpty()"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSketchSortedView","l":"isEmpty()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSketchSortedView","l":"isEmpty()"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"isEmpty()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSketchSortedView","l":"isEmpty()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"isEmpty()"},{"p":"org.apache.datasketches.quantilescommon","c":"SortedView","l":"isEmpty()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"isEmpty()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"isEmpty()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"isEstimationMode()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"isEstimationMode()"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"isEstimationMode()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"isEstimationMode()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"isEstimationMode()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"isEstimationMode()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"isEstimationMode()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"isEstimationMode()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"isEstimationMode()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"isEstimationMode()"},{"p":"org.apache.datasketches.common","c":"Util","l":"isEven(long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"isLessThanUnsigned(long, long)","u":"isLessThanUnsigned(long,long)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"isMemorySegmentUpdatableFormat()"},{"p":"org.apache.datasketches.common","c":"Util","l":"isMultipleOf8AndGT0(long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"isOdd(long)","k":"6"},{"p":"org.apache.datasketches.common","c":"MemorySegmentStatus","l":"isOffHeap()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"isOffHeap()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"DirectBitArrayR","l":"isOffHeap()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"isOffHeap()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"isOffHeap()"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"isOffHeap()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"isOffHeap()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"isOffHeap()"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"isOffHeap()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"isOffHeap()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"isOrdered()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"isOrdered()"},{"p":"org.apache.datasketches.common","c":"Util","l":"isPowerOf2(long)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"isReadOnly()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"DirectBitArrayR","l":"isReadOnly()"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"isReadOnly()"},{"p":"org.apache.datasketches.quantiles","c":"CompactQuantilesDoublesSketch","l":"isReadOnly()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"isReadOnly()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"isReadOnly()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"isReadOnly()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"isReadOnly()"},{"p":"org.apache.datasketches.common","c":"MemorySegmentStatus","l":"isSameResource(MemorySegment)","u":"isSameResource(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"isSameResource(MemorySegment)","u":"isSameResource(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"DirectBitArrayR","l":"isSameResource(MemorySegment)","u":"isSameResource(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"isSameResource(MemorySegment)","u":"isSameResource(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"isSameResource(MemorySegment)","u":"isSameResource(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"isSameResource(MemorySegment)","u":"isSameResource(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"isSameResource(MemorySegment)","u":"isSameResource(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"isSameResource(MemorySegment)","u":"isSameResource(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"isSameResource(MemorySegment)","u":"isSameResource(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"isSameResource(MemorySegment)","u":"isSameResource(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.common","c":"MemorySegmentStatus","l":"isSameResource(MemorySegment, MemorySegment)","u":"isSameResource(java.lang.foreign.MemorySegment,java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSamples","l":"items()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSamples","l":"items(int)"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax.ItemsPair","l":"ItemsPair(T[], long[])","u":"%3Cinit%3E(T[],long[])","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"ItemsSketchSortedView(T[], long[], QuantilesGenericAPI)","u":"%3Cinit%3E(T[],long[],org.apache.datasketches.quantilescommon.QuantilesGenericAPI)","k":"3"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"iterator()"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"iterator()"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"iterator()"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"iterator()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"iterator()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSketchSortedView","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"DoublesSortedView","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSketchSortedView","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"FloatsSortedView","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedView","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"ItemsSketchSortedView","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSketchSortedView","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSortedView","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"iterator()"},{"p":"org.apache.datasketches.quantilescommon","c":"SortedView","l":"iterator()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"iterator()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSamples","l":"iterator()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"iterator()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"iterator()"},{"p":"org.apache.datasketches.tuple","c":"CompactTupleSketch","l":"iterator()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"iterator()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"iterator()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"iterator()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"iterator()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"iterator()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"iterator()"},{"p":"org.apache.datasketches.theta","c":"JaccardSimilarity","l":"jaccard(ThetaSketch, ThetaSketch)","u":"jaccard(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"JaccardSimilarity","l":"jaccard(TupleSketch, ThetaSketch, S, SummarySetOperations)","u":"jaccard(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.theta.ThetaSketch,S,org.apache.datasketches.tuple.SummarySetOperations)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"JaccardSimilarity","l":"jaccard(TupleSketch, TupleSketch, SummarySetOperations)","u":"jaccard(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.SummarySetOperations)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"JaccardSimilarity","l":"JaccardSimilarity()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"JAVA_CHAR_UNALIGNED_BIG_ENDIAN","k":"2"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"JAVA_CHAR_UNALIGNED_NON_NATIVE","k":"2"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN","k":"2"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"JAVA_DOUBLE_UNALIGNED_NON_NATIVE","k":"2"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"JAVA_FLOAT_UNALIGNED_BIG_ENDIAN","k":"2"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"JAVA_FLOAT_UNALIGNED_NON_NATIVE","k":"2"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"JAVA_INT_UNALIGNED_BIG_ENDIAN","k":"2"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"JAVA_INT_UNALIGNED_NON_NATIVE","k":"2"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"JAVA_LONG_UNALIGNED_BIG_ENDIAN","k":"2"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"JAVA_LONG_UNALIGNED_NON_NATIVE","k":"2"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"JAVA_SHORT_UNALIGNED_BIG_ENDIAN","k":"2"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"JAVA_SHORT_UNALIGNED_NON_NATIVE","k":"2"},{"p":"org.apache.datasketches.common","c":"SuppressFBWarnings","l":"justification()","k":"4"},{"p":"org.apache.datasketches.common","c":"Family","l":"KLL","k":"0"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchType","l":"KLL_DOUBLES_SKETCH","k":"0"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchType","l":"KLL_FLOATS_SKETCH","k":"0"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchType","l":"KLL_ITEMS_SKETCH","k":"0"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchType","l":"KLL_LONGS_SKETCH","k":"0"},{"p":"org.apache.datasketches.quantilescommon","c":"KolmogorovSmirnov","l":"KolmogorovSmirnov()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"KolmogorovSmirnov","l":"kolmogorovSmirnovTest(QuantilesAPI, QuantilesAPI, double)","u":"kolmogorovSmirnovTest(org.apache.datasketches.quantilescommon.QuantilesAPI,org.apache.datasketches.quantilescommon.QuantilesAPI,double)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericInequalitySearch.Inequality","l":"LE","k":"0"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"LE","k":"0"},{"p":"org.apache.datasketches.common","c":"Util","l":"le(Object, Object, Comparator)","u":"le(java.lang.Object,java.lang.Object,java.util.Comparator)","k":"6"},{"p":"org.apache.datasketches.partitions","c":"Partitioner.PartitionBoundsRow","l":"levelPartId","k":"1"},{"p":"org.apache.datasketches.partitions","c":"Partitioner.StackElement","l":"levelPartId","k":"1"},{"p":"org.apache.datasketches.common","c":"ResizeFactor","l":"lg()"},{"p":"org.apache.datasketches.common","c":"Util","l":"LOG2","k":"2"},{"p":"org.apache.datasketches.common","c":"Util","l":"log2(double)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"logBaseOfX(double, double)","u":"logBaseOfX(double,double)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"LONG_MAX_VALUE_AS_DOUBLE","k":"2"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax.LongsPair","l":"LongsPair(long[], long[])","u":"%3Cinit%3E(long[],long[])","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSketchSortedView","l":"LongsSketchSortedView(long[], long[], QuantilesLongsAPI)","u":"%3Cinit%3E(long[],long[],org.apache.datasketches.quantilescommon.QuantilesLongsAPI)","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"LongsSortedViewIterator","l":"LongsSortedViewIterator(long[], long[])","u":"%3Cinit%3E(long[],long[])","k":"3"},{"p":"org.apache.datasketches.common","c":"Util","l":"longToBytes(long, byte[])","u":"longToBytes(long,byte[])","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"longToFixedLengthString(long, int)","u":"longToFixedLengthString(long,int)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"longToHexBytes(long)","k":"6"},{"p":"org.apache.datasketches.partitions","c":"Partitioner.PartitionBoundsRow","l":"lowerBound","k":"1"},{"p":"org.apache.datasketches.common","c":"Util","l":"LS","k":"2"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericInequalitySearch.Inequality","l":"LT","k":"0"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"LT","k":"0"},{"p":"org.apache.datasketches.common","c":"Util","l":"lt(Object, Object, Comparator)","u":"lt(java.lang.Object,java.lang.Object,java.util.Comparator)","k":"6"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummary.Mode","l":"Max","k":"0"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummary.Mode","l":"Max","k":"0"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"MAX_K","k":"2"},{"p":"org.apache.datasketches.thetacommon","c":"ThetaUtil","l":"MAX_LG_NOM_LONGS","k":"2"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"MAX_SIZE_BITS","k":"2"},{"p":"org.apache.datasketches.common","c":"Util","l":"maxT(Object, Object, Comparator)","u":"maxT(java.lang.Object,java.lang.Object,java.util.Comparator)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"MEM_REQ_SVR_NULL_MSG","k":"2"},{"p":"org.apache.datasketches.common","c":"MemorySegmentRequestExample","l":"MemorySegmentRequestExample()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"merge(CountMinSketch)","u":"merge(org.apache.datasketches.count.CountMinSketch)"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"merge(EbppsItemsSketch)","u":"merge(org.apache.datasketches.sampling.EbppsItemsSketch)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"merge(FrequentItemsSketch)","u":"merge(org.apache.datasketches.frequencies.FrequentItemsSketch)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"merge(FrequentLongsSketch)","u":"merge(org.apache.datasketches.frequencies.FrequentLongsSketch)"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"merge(KllSketch)","u":"merge(org.apache.datasketches.kll.KllSketch)"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"merge(KllSketch)","u":"merge(org.apache.datasketches.kll.KllSketch)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"merge(KllSketch)","u":"merge(org.apache.datasketches.kll.KllSketch)"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"merge(KllSketch)","u":"merge(org.apache.datasketches.kll.KllSketch)"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"merge(KllSketch)","u":"merge(org.apache.datasketches.kll.KllSketch)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"merge(ReqSketch)","u":"merge(org.apache.datasketches.req.ReqSketch)"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"merge(TDigestDouble)","u":"merge(org.apache.datasketches.tdigest.TDigestDouble)"},{"p":"org.apache.datasketches.cpc","c":"MergingValidation","l":"MergingValidation(int, int, int, int, int, PrintStream, PrintWriter)","u":"%3Cinit%3E(int,int,int,int,int,java.io.PrintStream,java.io.PrintWriter)","k":"3"},{"p":"org.apache.datasketches.common","c":"Util","l":"milliSecToString(long)","k":"6"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummary.Mode","l":"Min","k":"0"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummary.Mode","l":"Min","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"ThetaUtil","l":"MIN_LG_ARR_LONGS","k":"2"},{"p":"org.apache.datasketches.thetacommon","c":"ThetaUtil","l":"MIN_LG_NOM_LONGS","k":"2"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"minLgHashTableSize(int, double)","u":"minLgHashTableSize(int,double)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"minT(Object, Object, Comparator)","u":"minT(java.lang.Object,java.lang.Object,java.util.Comparator)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"nanoSecToString(long)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"newDirectInstance(int, MemorySegment, MemorySegmentRequest)","u":"newDirectInstance(int,java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"newDirectInstance(int, MemorySegment, MemorySegmentRequest)","u":"newDirectInstance(int,java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"newDirectInstance(int, MemorySegment, MemorySegmentRequest)","u":"newDirectInstance(int,java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"newDirectInstance(MemorySegment)","u":"newDirectInstance(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"newDirectInstance(MemorySegment)","u":"newDirectInstance(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"newDirectInstance(MemorySegment)","u":"newDirectInstance(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"newHeapInstance()","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"newHeapInstance()","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"newHeapInstance()","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"newHeapInstance(Comparator, ArrayOfItemsSerDe)","u":"newHeapInstance(java.util.Comparator,org.apache.datasketches.common.ArrayOfItemsSerDe)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"newHeapInstance(int)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"newHeapInstance(int)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"newHeapInstance(int)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"newHeapInstance(int, Comparator, ArrayOfItemsSerDe)","u":"newHeapInstance(int,java.util.Comparator,org.apache.datasketches.common.ArrayOfItemsSerDe)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"newInstance(int)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsUnion","l":"newInstance(int)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"newInstance(int)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsUnion","l":"newInstance(int)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"newInstance(int)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsUnion","l":"newInstance(int)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"newInstance(int, ResizeFactor)","u":"newInstance(int,org.apache.datasketches.common.ResizeFactor)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"newInstance(int, ResizeFactor)","u":"newInstance(int,org.apache.datasketches.common.ResizeFactor)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"newInstance(int, ResizeFactor)","u":"newInstance(int,org.apache.datasketches.common.ResizeFactor)","k":"6"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummaryFactory","l":"newSummary()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummaryFactory","l":"newSummary()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummaryFactory","l":"newSummary()"},{"p":"org.apache.datasketches.tuple","c":"SummaryFactory","l":"newSummary()"},{"p":"org.apache.datasketches.tuple","c":"Util","l":"newSummaryArray(S[], int)","u":"newSummaryArray(S[],int)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllSketchIterator","l":"next()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketchIterator","l":"next()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketchIterator","l":"next()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesSketchIteratorAPI","l":"next()"},{"p":"org.apache.datasketches.quantilescommon","c":"SortedViewIterator","l":"next()"},{"p":"org.apache.datasketches.req","c":"ReqSketchIterator","l":"next()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSamples.VarOptItemsIterator","l":"next()"},{"p":"org.apache.datasketches.theta","c":"HashIterator","l":"next()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketchIterator","l":"next()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketchIterator","l":"next()"},{"p":"org.apache.datasketches.frequencies","c":"ErrorType","l":"NO_FALSE_NEGATIVES","k":"0"},{"p":"org.apache.datasketches.frequencies","c":"ErrorType","l":"NO_FALSE_POSITIVES","k":"0"},{"p":"org.apache.datasketches.common","c":"SpecialValueLayouts","l":"NON_NATIVE_BYTE_ORDER","k":"2"},{"p":"org.apache.datasketches.common","c":"BoundsOnBinomialProportions","l":"normalCDF(double)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"NOT_SINGLE_ITEM_MSG","k":"2"},{"p":"org.apache.datasketches.theta","c":"ThetaAnotB","l":"notB(ThetaSketch)","u":"notB(org.apache.datasketches.theta.ThetaSketch)"},{"p":"org.apache.datasketches.tuple","c":"TupleAnotB","l":"notB(ThetaSketch)","u":"notB(org.apache.datasketches.theta.ThetaSketch)"},{"p":"org.apache.datasketches.tuple","c":"TupleAnotB","l":"notB(TupleSketch)","u":"notB(org.apache.datasketches.tuple.TupleSketch)"},{"p":"org.apache.datasketches.common","c":"Util","l":"numberOfLeadingOnes(long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"numberOfTrailingOnes(long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"numDigits(long)","k":"6"},{"p":"org.apache.datasketches.partitions","c":"Partitioner.PartitionBoundsRow","l":"part","k":"1"},{"p":"org.apache.datasketches.partitions","c":"Partitioner.StackElement","l":"part","k":"1"},{"p":"org.apache.datasketches.partitions","c":"Partitioner","l":"partition(S)"},{"p":"org.apache.datasketches.partitions","c":"Partitioner.PartitionBoundsRow","l":"PartitionBoundsRow(Partitioner.StackElement)","u":"%3Cinit%3E(org.apache.datasketches.partitions.Partitioner.StackElement)","k":"3"},{"p":"org.apache.datasketches.partitions","c":"Partitioner","l":"Partitioner(long, int, SketchFillRequest)","u":"%3Cinit%3E(long,int,org.apache.datasketches.partitions.SketchFillRequest)","k":"3"},{"p":"org.apache.datasketches.partitions","c":"Partitioner","l":"Partitioner(long, int, SketchFillRequest, QuantileSearchCriteria)","u":"%3Cinit%3E(long,int,org.apache.datasketches.partitions.SketchFillRequest,org.apache.datasketches.quantilescommon.QuantileSearchCriteria)","k":"3"},{"p":"org.apache.datasketches.common.positional","c":"PositionInvariantsException","l":"PositionInvariantsException(String)","u":"%3Cinit%3E(java.lang.String)","k":"3"},{"p":"org.apache.datasketches.fdt","c":"PostProcessor","l":"PostProcessor(FdtSketch, Group, char)","u":"%3Cinit%3E(org.apache.datasketches.fdt.FdtSketch,org.apache.datasketches.fdt.Group,char)","k":"3"},{"p":"org.apache.datasketches.common","c":"Util","l":"powerSeriesNextDouble(int, double, boolean, double)","u":"powerSeriesNextDouble(int,double,boolean,double)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"putDoubleBE(byte[], int, double)","u":"putDoubleBE(byte[],int,double)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"putDoubleLE(byte[], int, double)","u":"putDoubleLE(byte[],int,double)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"putFloatBE(byte[], int, float)","u":"putFloatBE(byte[],int,float)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"putFloatLE(byte[], int, float)","u":"putFloatLE(byte[],int,float)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"putIntBE(byte[], int, int)","u":"putIntBE(byte[],int,int)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"putIntLE(byte[], int, int)","u":"putIntLE(byte[],int,int)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"putIntoMemorySegment(MemorySegment)","u":"putIntoMemorySegment(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"putIntoMemorySegment(MemorySegment, ArrayOfItemsSerDe)","u":"putIntoMemorySegment(java.lang.foreign.MemorySegment,org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"putIntoMemorySegment(MemorySegment, boolean)","u":"putIntoMemorySegment(java.lang.foreign.MemorySegment,boolean)"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"putLongBE(byte[], int, long)","u":"putLongBE(byte[],int,long)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"putLongLE(byte[], int, long)","u":"putLongLE(byte[],int,long)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"putShortBE(byte[], int, short)","u":"putShortBE(byte[],int,short)","k":"6"},{"p":"org.apache.datasketches.common","c":"ByteArrayUtil","l":"putShortLE(byte[], int, short)","u":"putShortLE(byte[],int,short)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"pwr2SeriesNext(int, long)","u":"pwr2SeriesNext(int,long)","k":"6"},{"p":"org.apache.datasketches.common","c":"Util","l":"pwr2SeriesPrev(int, int)","u":"pwr2SeriesPrev(int,int)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax.DoublesPair","l":"quantiles","k":"1"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax.FloatsPair","l":"quantiles","k":"1"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax.ItemsPair","l":"quantiles","k":"1"},{"p":"org.apache.datasketches.quantilescommon","c":"IncludeMinMax.LongsPair","l":"quantiles","k":"1"},{"p":"org.apache.datasketches.common","c":"Family","l":"QUANTILES","k":"0"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketchBuilder","l":"QuantilesDoublesSketchBuilder()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"QuantilesDoublesUnion()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnionBuilder","l":"QuantilesDoublesUnionBuilder()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"query(byte[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"query(char[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"query(double)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"query(int[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"query(long)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"query(long[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"query(MemorySegment)","u":"query(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"query(short[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"query(String)","u":"query(java.lang.String)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"queryAndUpdate(byte[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"queryAndUpdate(char[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"queryAndUpdate(double)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"queryAndUpdate(int[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"queryAndUpdate(long)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"queryAndUpdate(long[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"queryAndUpdate(MemorySegment)","u":"queryAndUpdate(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"queryAndUpdate(short[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"queryAndUpdate(String)","u":"queryAndUpdate(java.lang.String)"},{"p":"org.apache.datasketches.cpc","c":"QuickMergingValidation","l":"QuickMergingValidation(int, int, int, PrintStream, PrintWriter)","u":"%3Cinit%3E(int,int,int,java.io.PrintStream,java.io.PrintWriter)","k":"3"},{"p":"org.apache.datasketches.common","c":"Family","l":"QUICKSELECT","k":"0"},{"p":"org.apache.datasketches.tuple","c":"SerializerDeserializer.SketchType","l":"QuickSelectSketch","k":"0"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"rand","k":"2"},{"p":"org.apache.datasketches.thetacommon","c":"ThetaUtil","l":"REBUILD_THRESHOLD","k":"2"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"rebuild()"},{"p":"org.apache.datasketches.theta","c":"UpdateReturnState","l":"RejectedDuplicate","k":"0"},{"p":"org.apache.datasketches.theta","c":"UpdateReturnState","l":"RejectedNullOrEmpty","k":"0"},{"p":"org.apache.datasketches.theta","c":"UpdateReturnState","l":"RejectedOverTheta","k":"0"},{"p":"org.apache.datasketches.common","c":"Family","l":"REQ","k":"0"},{"p":"org.apache.datasketches.req","c":"ReqSketchBuilder","l":"ReqSketchBuilder()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.common","c":"MemorySegmentRequest","l":"request(long)"},{"p":"org.apache.datasketches.common","c":"MemorySegmentRequestExample","l":"request(long)"},{"p":"org.apache.datasketches.common","c":"MemorySegmentRequest","l":"requestClose(MemorySegment)","u":"requestClose(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.common","c":"MemorySegmentRequestExample","l":"requestClose(MemorySegment)","u":"requestClose(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.common","c":"Family","l":"RESERVOIR","k":"0"},{"p":"org.apache.datasketches.common","c":"Family","l":"RESERVOIR_UNION","k":"0"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"reset()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"reset()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"reset()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"reset()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"reset()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"reset()"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"reset()"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"reset()"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"reset()"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"reset()"},{"p":"org.apache.datasketches.quantiles","c":"CompactQuantilesDoublesSketch","l":"reset()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"reset()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"reset()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"reset()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"reset()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"reset()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"reset()"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"reset()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"reset()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"reset()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"reset()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsUnion","l":"reset()"},{"p":"org.apache.datasketches.theta","c":"ThetaIntersection","l":"reset()"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"reset()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"reset()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesIntersection","l":"reset()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUnion","l":"reset()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"reset()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"reset()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"reset()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"reset()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"reset()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"reset()"},{"p":"org.apache.datasketches.tuple","c":"TupleAnotB","l":"reset()"},{"p":"org.apache.datasketches.tuple","c":"TupleIntersection","l":"reset()"},{"p":"org.apache.datasketches.tuple","c":"TupleUnion","l":"reset()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketchBuilder","l":"reset()"},{"p":"org.apache.datasketches.common.positional","c":"Positional","l":"resetPosition()"},{"p":"org.apache.datasketches.thetacommon","c":"ThetaUtil","l":"RESIZE_THRESHOLD","k":"2"},{"p":"org.apache.datasketches.tdigest","c":"Sort","l":"reverse(double[], int)","u":"reverse(double[],int)","k":"6"},{"p":"org.apache.datasketches.tdigest","c":"Sort","l":"reverse(long[], int)","u":"reverse(long[],int)","k":"6"},{"p":"org.apache.datasketches.partitions","c":"Partitioner.PartitionBoundsRow","l":"rule","k":"1"},{"p":"org.apache.datasketches.common","c":"QuickSelect","l":"select(double[], int, int, int)","u":"select(double[],int,int,int)","k":"6"},{"p":"org.apache.datasketches.common","c":"QuickSelect","l":"select(long[], int, int, int)","u":"select(long[],int,int,int)","k":"6"},{"p":"org.apache.datasketches.common","c":"QuickSelect","l":"selectExcludingZeros(double[], int, int)","u":"selectExcludingZeros(double[],int,int)","k":"6"},{"p":"org.apache.datasketches.common","c":"QuickSelect","l":"selectExcludingZeros(long[], int, int)","u":"selectExcludingZeros(long[],int,int)","k":"6"},{"p":"org.apache.datasketches.common","c":"QuickSelect","l":"selectIncludingZeros(double[], int)","u":"selectIncludingZeros(double[],int)","k":"6"},{"p":"org.apache.datasketches.common","c":"QuickSelect","l":"selectIncludingZeros(long[], int)","u":"selectIncludingZeros(long[],int)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"SELF_MERGE_MSG","k":"2"},{"p":"org.apache.datasketches.tuple","c":"SerializerDeserializer","l":"SerializerDeserializer()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.common","c":"ArrayOfBooleansSerDe","l":"serializeToByteArray(Boolean)","u":"serializeToByteArray(java.lang.Boolean)"},{"p":"org.apache.datasketches.common","c":"ArrayOfBooleansSerDe","l":"serializeToByteArray(Boolean[])","u":"serializeToByteArray(java.lang.Boolean[])"},{"p":"org.apache.datasketches.common","c":"ArrayOfDoublesSerDe","l":"serializeToByteArray(Double)","u":"serializeToByteArray(java.lang.Double)"},{"p":"org.apache.datasketches.common","c":"ArrayOfDoublesSerDe","l":"serializeToByteArray(Double[])","u":"serializeToByteArray(java.lang.Double[])"},{"p":"org.apache.datasketches.common","c":"ArrayOfLongsSerDe","l":"serializeToByteArray(Long)","u":"serializeToByteArray(java.lang.Long)"},{"p":"org.apache.datasketches.common","c":"ArrayOfLongsSerDe","l":"serializeToByteArray(Long[])","u":"serializeToByteArray(java.lang.Long[])"},{"p":"org.apache.datasketches.common","c":"ArrayOfNumbersSerDe","l":"serializeToByteArray(Number)","u":"serializeToByteArray(java.lang.Number)"},{"p":"org.apache.datasketches.common","c":"ArrayOfNumbersSerDe","l":"serializeToByteArray(Number[])","u":"serializeToByteArray(java.lang.Number[])"},{"p":"org.apache.datasketches.common","c":"ArrayOfStringsSerDe","l":"serializeToByteArray(String)","u":"serializeToByteArray(java.lang.String)"},{"p":"org.apache.datasketches.common","c":"ArrayOfUtf16StringsSerDe","l":"serializeToByteArray(String)","u":"serializeToByteArray(java.lang.String)"},{"p":"org.apache.datasketches.common","c":"ArrayOfStringsSerDe","l":"serializeToByteArray(String[])","u":"serializeToByteArray(java.lang.String[])"},{"p":"org.apache.datasketches.common","c":"ArrayOfUtf16StringsSerDe","l":"serializeToByteArray(String[])","u":"serializeToByteArray(java.lang.String[])"},{"p":"org.apache.datasketches.common","c":"ArrayOfItemsSerDe","l":"serializeToByteArray(T)"},{"p":"org.apache.datasketches.common","c":"ArrayOfItemsSerDe","l":"serializeToByteArray(T[])"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"serializeToString()"},{"p":"org.apache.datasketches.theta","c":"ThetaAnotB","l":"setA(ThetaSketch)","u":"setA(org.apache.datasketches.theta.ThetaSketch)"},{"p":"org.apache.datasketches.tuple","c":"TupleAnotB","l":"setA(TupleSketch)","u":"setA(org.apache.datasketches.tuple.TupleSketch)"},{"p":"org.apache.datasketches.common","c":"Util","l":"setBits(MemorySegment, long, byte)","u":"setBits(java.lang.foreign.MemorySegment,long,byte)","k":"6"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setBoolean(boolean)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setBoolean(long, boolean)","u":"setBoolean(long,boolean)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setByte(byte)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setByte(long, byte)","u":"setByte(long,byte)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setByteArray(byte[], int, int)","u":"setByteArray(byte[],int,int)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setChar(char)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setChar(long, char)","u":"setChar(long,char)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setCharArray(char[], int, int)","u":"setCharArray(char[],int,int)"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSamples","l":"setClass(Class)","u":"setClass(java.lang.Class)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setConCurLogNominalEntries(int)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setConCurNominalEntries(int)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setDouble(double)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setDouble(long, double)","u":"setDouble(long,double)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setDoubleArray(double[], int, int)","u":"setDoubleArray(double[],int,int)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setFamily(Family)","u":"setFamily(org.apache.datasketches.common.Family)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setFloat(float)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setFloat(long, float)","u":"setFloat(long,float)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setFloatArray(float[], int, int)","u":"setFloatArray(float[],int,int)"},{"p":"org.apache.datasketches.req","c":"ReqSketchBuilder","l":"setHighRankAccuracy(boolean)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setInt(int)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setInt(long, int)","u":"setInt(long,int)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setIntArray(int[], int, int)","u":"setIntArray(int[],int,int)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketchBuilder","l":"setK(int)"},{"p":"org.apache.datasketches.req","c":"ReqSketchBuilder","l":"setK(int)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setLgK(int)"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"setLogNominalEntries(int)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setLogNominalEntries(int)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setLong(long)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setLong(long, long)","u":"setLong(long,long)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setLongArray(long[], int, int)","u":"setLongArray(long[],int,int)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setMaxConcurrencyError(double)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnionBuilder","l":"setMaxK(int)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setMaxNumLocalThreads(int)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setMemorySegmentRequest(MemorySegmentRequest)","u":"setMemorySegmentRequest(org.apache.datasketches.common.MemorySegmentRequest)"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"setNominalEntries(int)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setNominalEntries(int)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSetOperationBuilder","l":"setNominalEntries(int)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketchBuilder","l":"setNominalEntries(int)"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketchBuilder","l":"setNominalEntries(int)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSetOperationBuilder","l":"setNumberOfValues(int)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketchBuilder","l":"setNumberOfValues(int)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setNumPoolThreads(int)"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases","l":"SetOperationCornerCases()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"setP(float)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setP(float)"},{"p":"org.apache.datasketches.common.positional","c":"Positional","l":"setPosition(long)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setPropagateOrderedCompact(boolean)"},{"p":"org.apache.datasketches.req","c":"ReqSketchBuilder","l":"setReqDebug(ReqDebug)","u":"setReqDebug(org.apache.datasketches.req.ReqDebug)"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"setResizeFactor(ResizeFactor)","u":"setResizeFactor(org.apache.datasketches.common.ResizeFactor)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setResizeFactor(ResizeFactor)","u":"setResizeFactor(org.apache.datasketches.common.ResizeFactor)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketchBuilder","l":"setResizeFactor(ResizeFactor)","u":"setResizeFactor(org.apache.datasketches.common.ResizeFactor)"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketchBuilder","l":"setResizeFactor(ResizeFactor)","u":"setResizeFactor(org.apache.datasketches.common.ResizeFactor)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketchBuilder","l":"setSamplingProbability(float)"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketchBuilder","l":"setSamplingProbability(float)"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"setSeed(long)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"setSeed(long)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSetOperationBuilder","l":"setSeed(long)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketchBuilder","l":"setSeed(long)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setShort(long, short)","u":"setShort(long,short)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setShort(short)"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"setShortArray(short[], int, int)","u":"setShortArray(short[],int,int)"},{"p":"org.apache.datasketches.common.positional","c":"Positional","l":"setStartPositionEnd(long, long, long)","u":"setStartPositionEnd(long,long,long)"},{"p":"org.apache.datasketches.theta","c":"JaccardSimilarity","l":"similarityTest(ThetaSketch, ThetaSketch, double)","u":"similarityTest(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch,double)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"JaccardSimilarity","l":"similarityTest(TupleSketch, ThetaSketch, S, SummarySetOperations, double)","u":"similarityTest(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.theta.ThetaSketch,S,org.apache.datasketches.tuple.SummarySetOperations,double)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"JaccardSimilarity","l":"similarityTest(TupleSketch, TupleSketch, SummarySetOperations, double)","u":"similarityTest(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.SummarySetOperations,double)","k":"6"},{"p":"org.apache.datasketches.common","c":"ArrayOfBooleansSerDe","l":"sizeOf(Boolean)","u":"sizeOf(java.lang.Boolean)"},{"p":"org.apache.datasketches.common","c":"ArrayOfBooleansSerDe","l":"sizeOf(Boolean[])","u":"sizeOf(java.lang.Boolean[])"},{"p":"org.apache.datasketches.common","c":"ArrayOfDoublesSerDe","l":"sizeOf(Double)","u":"sizeOf(java.lang.Double)"},{"p":"org.apache.datasketches.common","c":"ArrayOfDoublesSerDe","l":"sizeOf(Double[])","u":"sizeOf(java.lang.Double[])"},{"p":"org.apache.datasketches.common","c":"ArrayOfLongsSerDe","l":"sizeOf(Long)","u":"sizeOf(java.lang.Long)"},{"p":"org.apache.datasketches.common","c":"ArrayOfLongsSerDe","l":"sizeOf(Long[])","u":"sizeOf(java.lang.Long[])"},{"p":"org.apache.datasketches.common","c":"ArrayOfBooleansSerDe","l":"sizeOf(MemorySegment, long, int)","u":"sizeOf(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfDoublesSerDe","l":"sizeOf(MemorySegment, long, int)","u":"sizeOf(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfItemsSerDe","l":"sizeOf(MemorySegment, long, int)","u":"sizeOf(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfLongsSerDe","l":"sizeOf(MemorySegment, long, int)","u":"sizeOf(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfNumbersSerDe","l":"sizeOf(MemorySegment, long, int)","u":"sizeOf(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfStringsSerDe","l":"sizeOf(MemorySegment, long, int)","u":"sizeOf(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfUtf16StringsSerDe","l":"sizeOf(MemorySegment, long, int)","u":"sizeOf(java.lang.foreign.MemorySegment,long,int)"},{"p":"org.apache.datasketches.common","c":"ArrayOfNumbersSerDe","l":"sizeOf(Number)","u":"sizeOf(java.lang.Number)"},{"p":"org.apache.datasketches.common","c":"ArrayOfNumbersSerDe","l":"sizeOf(Number[])","u":"sizeOf(java.lang.Number[])"},{"p":"org.apache.datasketches.common","c":"ArrayOfStringsSerDe","l":"sizeOf(String)","u":"sizeOf(java.lang.String)"},{"p":"org.apache.datasketches.common","c":"ArrayOfUtf16StringsSerDe","l":"sizeOf(String)","u":"sizeOf(java.lang.String)"},{"p":"org.apache.datasketches.common","c":"ArrayOfItemsSerDe","l":"sizeOf(T)"},{"p":"org.apache.datasketches.common","c":"ArrayOfItemsSerDe","l":"sizeOf(T[])"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.AnotbAction","l":"SKETCH_A","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"SKETCH_A","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"SKETCH_B","k":"0"},{"p":"org.apache.datasketches.common","c":"SketchesArgumentException","l":"SketchesArgumentException(String)","u":"%3Cinit%3E(java.lang.String)","k":"3"},{"p":"org.apache.datasketches.common","c":"SketchesException","l":"SketchesException(String)","u":"%3Cinit%3E(java.lang.String)","k":"3"},{"p":"org.apache.datasketches.common","c":"SketchesException","l":"SketchesException(String, Throwable)","u":"%3Cinit%3E(java.lang.String,java.lang.Throwable)","k":"3"},{"p":"org.apache.datasketches.common","c":"SketchesNotSupportedException","l":"SketchesNotSupportedException(String)","u":"%3Cinit%3E(java.lang.String)","k":"3"},{"p":"org.apache.datasketches.common","c":"SketchesReadOnlyException","l":"SketchesReadOnlyException()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.common","c":"SketchesReadOnlyException","l":"SketchesReadOnlyException(String)","u":"%3Cinit%3E(java.lang.String)","k":"3"},{"p":"org.apache.datasketches.common","c":"SketchesStateException","l":"SketchesStateException(String)","u":"%3Cinit%3E(java.lang.String)","k":"3"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases","l":"sketchStateId(boolean, int, long)","u":"sketchStateId(boolean,int,long)","k":"6"},{"p":"org.apache.datasketches.tdigest","c":"Sort","l":"Sort()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tdigest","c":"Sort","l":"stableSort(double[], long[], int)","u":"stableSort(double[],long[],int)","k":"6"},{"p":"org.apache.datasketches.partitions","c":"Partitioner.StackElement","l":"StackElement(GenericPartitionBoundaries, int, String)","u":"%3Cinit%3E(org.apache.datasketches.quantilescommon.GenericPartitionBoundaries,int,java.lang.String)","k":"3"},{"p":"org.apache.datasketches.cpc","c":"CompressionCharacterization","l":"start()"},{"p":"org.apache.datasketches.cpc","c":"MergingValidation","l":"start()"},{"p":"org.apache.datasketches.cpc","c":"QuickMergingValidation","l":"start()"},{"p":"org.apache.datasketches.cpc","c":"StreamingValidation","l":"start()"},{"p":"org.apache.datasketches.thetacommon","c":"ThetaUtil","l":"startingSubMultiple(int, int, int)","u":"startingSubMultiple(int,int,int)","k":"6"},{"p":"org.apache.datasketches.cpc","c":"StreamingValidation","l":"StreamingValidation(int, int, int, int, PrintStream, PrintWriter)","u":"%3Cinit%3E(int,int,int,int,java.io.PrintStream,java.io.PrintWriter)","k":"3"},{"p":"org.apache.datasketches.thetacommon","c":"HashOperations","l":"STRIDE_MASK","k":"2"},{"p":"org.apache.datasketches.tuple","c":"Util","l":"stringArrHash(String[])","u":"stringArrHash(java.lang.String[])","k":"6"},{"p":"org.apache.datasketches.tuple","c":"Util","l":"stringConcat(String[])","u":"stringConcat(java.lang.String[])","k":"6"},{"p":"org.apache.datasketches.tuple","c":"Util","l":"stringHash(String)","u":"stringHash(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"Util","l":"stringToByteArray(String)","u":"stringToByteArray(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.common","c":"Family","l":"stringToFamily(String)","u":"stringToFamily(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"suggestNumBuckets(double)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"suggestNumFilterBits(long, double)","u":"suggestNumFilterBits(long,double)","k":"6"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"suggestNumHashes(double)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"suggestNumHashes(double)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilterBuilder","l":"suggestNumHashes(long, long)","u":"suggestNumHashes(long,long)","k":"6"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummary.Mode","l":"Sum","k":"0"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummary.Mode","l":"Sum","k":"0"},{"p":"org.apache.datasketches.common","c":"Util","l":"TAB","k":"2"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesUtil","l":"tailRoundingFactor","k":"2"},{"p":"org.apache.datasketches.common","c":"Family","l":"TDIGEST","k":"0"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"TDigestDouble()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"TDigestDouble(short)","u":"%3Cinit%3E(short)","k":"3"},{"p":"org.apache.datasketches.cpc","c":"TestUtil","l":"TestUtil()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"TGT_IS_READ_ONLY_MSG","k":"2"},{"p":"org.apache.datasketches.theta","c":"ThetaIntersection","l":"ThetaIntersection()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"ThetaSetOperationBuilder()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"ThetaUnion()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"toByteArray()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"toByteArray()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"toByteArray()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"toByteArray()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"toByteArray()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsUnion","l":"toByteArray()"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"toByteArray()"},{"p":"org.apache.datasketches.theta","c":"ThetaIntersection","l":"toByteArray()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"toByteArray()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummary","l":"toByteArray()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummary","l":"toByteArray()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUnion","l":"toByteArray()"},{"p":"org.apache.datasketches.tuple","c":"CompactTupleSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummary","l":"toByteArray()"},{"p":"org.apache.datasketches.tuple","c":"Summary","l":"toByteArray()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"toByteArray()"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"toByteArray(ArrayOfItemsSerDe)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"toByteArray(ArrayOfItemsSerDe)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"toByteArray(ArrayOfItemsSerDe)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"toByteArray(ArrayOfItemsSerDe)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"toByteArray(ArrayOfItemsSerDe)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"toByteArray(ArrayOfItemsSerDe)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsUnion","l":"toByteArray(ArrayOfItemsSerDe)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsUnion","l":"toByteArray(ArrayOfItemsSerDe)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"toByteArray(ArrayOfItemsSerDe, Class)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe,java.lang.Class)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"toByteArray(ArrayOfItemsSerDe, Class)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe,java.lang.Class)"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"toByteArray(ArrayOfItemsSerDe, Class)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe,java.lang.Class)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsUnion","l":"toByteArray(ArrayOfItemsSerDe, Class)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe,java.lang.Class)"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsUnion","l":"toByteArray(ArrayOfItemsSerDe, Class)","u":"toByteArray(org.apache.datasketches.common.ArrayOfItemsSerDe,java.lang.Class)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"toByteArray(boolean)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"toByteArray(boolean, ArrayOfItemsSerDe)","u":"toByteArray(boolean,org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"toByteArrayCompressed()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"toCompactByteArray()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"toCompactByteArray()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"toLongArray()"},{"p":"org.apache.datasketches.common","c":"Family","l":"toString()"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"toString()"},{"p":"org.apache.datasketches.fdt","c":"Group","l":"toString()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"DirectBitArrayR","l":"toString()"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"toString()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch.Row","l":"toString()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"toString()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch.Row","l":"toString()"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"toString()"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"toString()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"toString()"},{"p":"org.apache.datasketches.hllmap","c":"UniqueCountMap","l":"toString()"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"toString()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"toString()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketchBuilder","l":"toString()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"toString()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"toString()"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"toString()"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"toString()"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"toString()"},{"p":"org.apache.datasketches.req","c":"ReqSketchBuilder","l":"toString()"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"toString()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"toString()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsUnion","l":"toString()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"toString()"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsUnion","l":"toString()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"toString()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsUnion","l":"toString()"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"toString()"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperationBuilder","l":"toString()"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"toString()"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"toString()"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"toString()"},{"p":"org.apache.datasketches.tuple","c":"TupleSketch","l":"toString()"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"toString(boolean)"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"toString(boolean)"},{"p":"org.apache.datasketches.common","c":"ArrayOfBooleansSerDe","l":"toString(Boolean)","u":"toString(java.lang.Boolean)"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"toString(boolean, boolean)","u":"toString(boolean,boolean)"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"toString(boolean, boolean)","u":"toString(boolean,boolean)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"toString(boolean, boolean)","u":"toString(boolean,boolean)"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"toString(boolean, boolean)","u":"toString(boolean,boolean)"},{"p":"org.apache.datasketches.kll","c":"KllSketch","l":"toString(boolean, boolean)","u":"toString(boolean,boolean)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"toString(boolean, boolean)","u":"toString(boolean,boolean)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"toString(boolean, boolean)","u":"toString(boolean,boolean)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"toString(boolean, boolean)","u":"toString(boolean,boolean)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"toString(boolean, boolean)","u":"toString(boolean,boolean)"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"toString(boolean, boolean, boolean)","u":"toString(boolean,boolean,boolean)"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"toString(boolean, boolean, boolean)","u":"toString(boolean,boolean,boolean)"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"toString(boolean, boolean, boolean, boolean)","u":"toString(boolean,boolean,boolean,boolean)"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"toString(boolean, boolean, boolean, boolean)","u":"toString(boolean,boolean,boolean,boolean)"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"toString(boolean, boolean, int, boolean)","u":"toString(boolean,boolean,int,boolean)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"toString(byte[])","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"toString(byte[])","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"toString(byte[])","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"toString(byte[])","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"toString(byte[])","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"toString(byte[])","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"toString(byte[])","k":"6"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"toString(byte[])","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"toString(byte[])","k":"6"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"toString(byte[], boolean)","u":"toString(byte[],boolean)","k":"6"},{"p":"org.apache.datasketches.common","c":"ArrayOfDoublesSerDe","l":"toString(Double)","u":"toString(java.lang.Double)"},{"p":"org.apache.datasketches.common","c":"ArrayOfLongsSerDe","l":"toString(Long)","u":"toString(java.lang.Long)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"toString(MemorySegment)","u":"toString(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"toString(MemorySegment)","u":"toString(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"toString(MemorySegment)","u":"toString(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"toString(MemorySegment)","u":"toString(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"toString(MemorySegment)","u":"toString(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"toString(MemorySegment)","u":"toString(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"toString(MemorySegment)","u":"toString(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"toString(MemorySegment)","u":"toString(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"toString(MemorySegment)","u":"toString(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"toString(MemorySegment, boolean)","u":"toString(java.lang.foreign.MemorySegment,boolean)","k":"6"},{"p":"org.apache.datasketches.common","c":"ArrayOfNumbersSerDe","l":"toString(Number)","u":"toString(java.lang.Number)"},{"p":"org.apache.datasketches.common","c":"ArrayOfStringsSerDe","l":"toString(String)","u":"toString(java.lang.String)"},{"p":"org.apache.datasketches.common","c":"ArrayOfUtf16StringsSerDe","l":"toString(String)","u":"toString(java.lang.String)"},{"p":"org.apache.datasketches.common","c":"ArrayOfItemsSerDe","l":"toString(T)"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"toUpdatableByteArray()"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"toUpdatableByteArray()"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.AnotbAction","l":"TRIM_A","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"TRIM_A","k":"0"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"TRIM_B","k":"0"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"trim()"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"trim()"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"trim()"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"trim()"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"trim()"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"trim()"},{"p":"org.apache.datasketches.common","c":"Family","l":"TUPLE","k":"0"},{"p":"org.apache.datasketches.tuple","c":"TupleAnotB","l":"TupleAnotB()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple","c":"TupleIntersection","l":"TupleIntersection(SummarySetOperations)","u":"%3Cinit%3E(org.apache.datasketches.tuple.SummarySetOperations)","k":"3"},{"p":"org.apache.datasketches.tuple","c":"TupleUnion","l":"TupleUnion(int, SummarySetOperations)","u":"%3Cinit%3E(int,org.apache.datasketches.tuple.SummarySetOperations)","k":"3"},{"p":"org.apache.datasketches.tuple","c":"TupleUnion","l":"TupleUnion(SummarySetOperations)","u":"%3Cinit%3E(org.apache.datasketches.tuple.SummarySetOperations)","k":"3"},{"p":"org.apache.datasketches.common","c":"Family","l":"UNION","k":"0"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUnion","l":"union(ArrayOfDoublesSketch)","u":"union(org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch)"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummarySetOperations","l":"union(ArrayOfStringsSummary, ArrayOfStringsSummary)","u":"union(org.apache.datasketches.tuple.strings.ArrayOfStringsSummary,org.apache.datasketches.tuple.strings.ArrayOfStringsSummary)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"union(BloomFilter)","u":"union(org.apache.datasketches.filters.bloomfilter.BloomFilter)"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummarySetOperations","l":"union(DoubleSummary, DoubleSummary)","u":"union(org.apache.datasketches.tuple.adouble.DoubleSummary,org.apache.datasketches.tuple.adouble.DoubleSummary)"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummarySetOperations","l":"union(IntegerSummary, IntegerSummary)","u":"union(org.apache.datasketches.tuple.aninteger.IntegerSummary,org.apache.datasketches.tuple.aninteger.IntegerSummary)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"union(MemorySegment)","u":"union(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"union(MemorySegment)","u":"union(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"union(MemorySegment, ArrayOfItemsSerDe)","u":"union(java.lang.foreign.MemorySegment,org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"union(QuantilesDoublesSketch)","u":"union(org.apache.datasketches.quantiles.QuantilesDoublesSketch)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"union(QuantilesItemsSketch)","u":"union(org.apache.datasketches.quantiles.QuantilesItemsSketch)"},{"p":"org.apache.datasketches.tuple","c":"SummarySetOperations","l":"union(S, S)","u":"union(S,S)"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"union(ThetaSketch)","u":"union(org.apache.datasketches.theta.ThetaSketch)"},{"p":"org.apache.datasketches.tuple","c":"TupleUnion","l":"union(ThetaSketch, S)","u":"union(org.apache.datasketches.theta.ThetaSketch,S)"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"union(ThetaSketch, ThetaSketch)","u":"union(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch)"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"union(ThetaSketch, ThetaSketch, boolean, MemorySegment)","u":"union(org.apache.datasketches.theta.ThetaSketch,org.apache.datasketches.theta.ThetaSketch,boolean,java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.tuple","c":"TupleUnion","l":"union(TupleSketch)","u":"union(org.apache.datasketches.tuple.TupleSketch)"},{"p":"org.apache.datasketches.tuple","c":"TupleUnion","l":"union(TupleSketch, ThetaSketch, S)","u":"union(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.theta.ThetaSketch,S)"},{"p":"org.apache.datasketches.tuple","c":"TupleUnion","l":"union(TupleSketch, TupleSketch)","u":"union(org.apache.datasketches.tuple.TupleSketch,org.apache.datasketches.tuple.TupleSketch)"},{"p":"org.apache.datasketches.hllmap","c":"UniqueCountMap","l":"UniqueCountMap(int)","u":"%3Cinit%3E(int)","k":"3"},{"p":"org.apache.datasketches.hllmap","c":"UniqueCountMap","l":"UniqueCountMap(int, int)","u":"%3Cinit%3E(int,int)","k":"3"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesAPI","l":"UNSUPPORTED_MSG","k":"2"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchStructure","l":"UPDATABLE","k":"0"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketchBuilder","l":"UpdatableThetaSketchBuilder()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"UpdatableTupleSketch(int, int, float, SummaryFactory)","u":"%3Cinit%3E(int,int,float,org.apache.datasketches.tuple.SummaryFactory)","k":"3"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"UpdatableTupleSketch(MemorySegment, SummaryDeserializer, SummaryFactory)","u":"%3Cinit%3E(java.lang.foreign.MemorySegment,org.apache.datasketches.tuple.SummaryDeserializer,org.apache.datasketches.tuple.SummaryFactory)","k":"3"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"UpdatableTupleSketch(UpdatableTupleSketch)","u":"%3Cinit%3E(org.apache.datasketches.tuple.UpdatableTupleSketch)","k":"3"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketchBuilder","l":"UpdatableTupleSketchBuilder(SummaryFactory)","u":"%3Cinit%3E(org.apache.datasketches.tuple.SummaryFactory)","k":"3"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesAnotB","l":"update(ArrayOfDoublesSketch, ArrayOfDoublesSketch)","u":"update(org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch,org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesAnotBImpl","l":"update(ArrayOfDoublesSketch, ArrayOfDoublesSketch)","u":"update(org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch,org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch)"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"update(byte[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"update(byte[])"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"update(byte[])"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"update(byte[])"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"update(byte[])"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"update(byte[])"},{"p":"org.apache.datasketches.hllmap","c":"UniqueCountMap","l":"update(byte[], byte[])","u":"update(byte[],byte[])"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"update(byte[], double[])","u":"update(byte[],double[])"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"update(byte[], long)","u":"update(byte[],long)"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"update(byte[], U)","u":"update(byte[],U)"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"update(ByteBuffer)","u":"update(java.nio.ByteBuffer)"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"update(ByteBuffer)","u":"update(java.nio.ByteBuffer)"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"update(ByteBuffer)","u":"update(java.nio.ByteBuffer)"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"update(ByteBuffer)","u":"update(java.nio.ByteBuffer)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"update(ByteBuffer)","u":"update(java.nio.ByteBuffer)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"update(ByteBuffer, double[])","u":"update(java.nio.ByteBuffer,double[])"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"update(ByteBuffer, U)","u":"update(java.nio.ByteBuffer,U)"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"update(char[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"update(char[])"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"update(char[])"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"update(char[])"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"update(char[])"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"update(char[])"},{"p":"org.apache.datasketches.cpc","c":"CpcUnion","l":"update(CpcSketch)","u":"update(org.apache.datasketches.cpc.CpcSketch)"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"update(double)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"update(double)"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"update(double)"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"update(double)"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"update(double)"},{"p":"org.apache.datasketches.quantiles","c":"CompactQuantilesDoublesSketch","l":"update(double)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"update(double)"},{"p":"org.apache.datasketches.quantiles","c":"UpdatableQuantilesDoublesSketch","l":"update(double)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesDoublesAPI","l":"update(double)"},{"p":"org.apache.datasketches.tdigest","c":"TDigestDouble","l":"update(double)"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"update(double)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"update(double)"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummary","l":"update(Double)","u":"update(java.lang.Double)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"update(double, double[])","u":"update(double,double[])"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"update(double, long)","u":"update(double,long)"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"update(double, U)","u":"update(double,U)"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"update(double[], int, int)","u":"update(double[],int,int)"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"update(float)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesFloatsAPI","l":"update(float)"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"update(float)"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"update(float, long)","u":"update(float,long)"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"update(float[], int, int)","u":"update(float[],int,int)"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"update(HllSketch)","u":"update(org.apache.datasketches.hll.HllSketch)"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"update(int[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"update(int[])"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"update(int[])"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"update(int[])"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"update(int[])"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"update(int[])"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"update(int[], double[])","u":"update(int[],double[])"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"update(int[], U)","u":"update(int[],U)"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummary","l":"update(Integer)","u":"update(java.lang.Integer)"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"update(long)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"update(long)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"update(long)"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"update(long)"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"update(long)"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"update(long)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesLongsAPI","l":"update(long)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsSketch","l":"update(long)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsUnion","l":"update(long)"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"update(long)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"update(long)"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"update(long, Double)","u":"update(long,java.lang.Double)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"update(long, double[])","u":"update(long,double[])"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsUnion","l":"update(long, int, ArrayList)","u":"update(long,int,java.util.ArrayList)"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"update(long, Integer)","u":"update(long,java.lang.Integer)"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"update(long, long)","u":"update(long,long)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentLongsSketch","l":"update(long, long)","u":"update(long,long)"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"update(long, long)","u":"update(long,long)"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"update(long, U)","u":"update(long,U)"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"update(long[])"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"update(long[])"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"update(long[])"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"update(long[])"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"update(long[])"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"update(long[])"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"update(long[], double[])","u":"update(long[],double[])"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"update(long[], int, int)","u":"update(long[],int,int)"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"update(long[], U)","u":"update(long[],U)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"update(MemorySegment)","u":"update(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsUnion","l":"update(MemorySegment)","u":"update(java.lang.foreign.MemorySegment)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsUnion","l":"update(MemorySegment, ArrayOfItemsSerDe)","u":"update(java.lang.foreign.MemorySegment,org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsUnion","l":"update(MemorySegment, ArrayOfItemsSerDe)","u":"update(java.lang.foreign.MemorySegment,org.apache.datasketches.common.ArrayOfItemsSerDe)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsUnion","l":"update(ReservoirItemsSketch)","u":"update(org.apache.datasketches.sampling.ReservoirItemsSketch)"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsUnion","l":"update(ReservoirItemsSketch)","u":"update(org.apache.datasketches.sampling.ReservoirItemsSketch)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirLongsUnion","l":"update(ReservoirLongsSketch)","u":"update(org.apache.datasketches.sampling.ReservoirLongsSketch)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"update(short[])"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"update(String)","u":"update(java.lang.String)"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"update(String)","u":"update(java.lang.String)"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"update(String)","u":"update(java.lang.String)"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"update(String)","u":"update(java.lang.String)"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"update(String)","u":"update(java.lang.String)"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"update(String)","u":"update(java.lang.String)"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleTupleSketch","l":"update(String, Double)","u":"update(java.lang.String,java.lang.Double)"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"update(String, double[])","u":"update(java.lang.String,double[])"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerTupleSketch","l":"update(String, Integer)","u":"update(java.lang.String,java.lang.Integer)"},{"p":"org.apache.datasketches.count","c":"CountMinSketch","l":"update(String, long)","u":"update(java.lang.String,long)"},{"p":"org.apache.datasketches.tuple","c":"UpdatableTupleSketch","l":"update(String, U)","u":"update(java.lang.String,U)"},{"p":"org.apache.datasketches.fdt","c":"FdtSketch","l":"update(String[])","u":"update(java.lang.String[])"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsSummary","l":"update(String[])","u":"update(java.lang.String[])"},{"p":"org.apache.datasketches.tuple.strings","c":"ArrayOfStringsTupleSketch","l":"update(String[], String[])","u":"update(java.lang.String[],java.lang.String[])"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"update(T)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"update(T)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsSketch","l":"update(T)"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesItemsUnion","l":"update(T)"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantilesGenericAPI","l":"update(T)"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"update(T)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsSketch","l":"update(T)"},{"p":"org.apache.datasketches.sampling","c":"ReservoirItemsUnion","l":"update(T)"},{"p":"org.apache.datasketches.sampling","c":"EbppsItemsSketch","l":"update(T, double)","u":"update(T,double)"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSketch","l":"update(T, double)","u":"update(T,double)"},{"p":"org.apache.datasketches.frequencies","c":"FrequentItemsSketch","l":"update(T, long)","u":"update(T,long)"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"update(T, long)","u":"update(T,long)"},{"p":"org.apache.datasketches.tuple","c":"UpdatableSummary","l":"update(U)"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsUnion","l":"update(VarOptItemsSketch)","u":"update(org.apache.datasketches.sampling.VarOptItemsSketch)"},{"p":"org.apache.datasketches.partitions","c":"Partitioner.PartitionBoundsRow","l":"upperBound","k":"1"},{"p":"org.apache.datasketches.tuple","c":"Util","l":"Util()","u":"%3Cinit%3E()","k":"3"},{"p":"org.apache.datasketches.cpc","c":"CpcSketch","l":"validate()"},{"p":"org.apache.datasketches.tuple","c":"SerializerDeserializer","l":"validateFamily(byte, byte)","u":"validateFamily(byte,byte)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericSortedView","l":"validateItems(T[], Comparator)","u":"validateItems(T[],java.util.Comparator)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"SerializerDeserializer","l":"validateType(byte, SerializerDeserializer.SketchType)","u":"validateType(byte,org.apache.datasketches.tuple.SerializerDeserializer.SketchType)","k":"6"},{"p":"org.apache.datasketches.common","c":"SuppressFBWarnings","l":"value()","k":"4"},{"p":"org.apache.datasketches.common","c":"Family","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.common","c":"ResizeFactor","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"ErrorType","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.hll","c":"TgtHllType","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchStructure","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchType","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.partitions","c":"BoundsRule","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericInequalitySearch.Inequality","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantileSearchCriteria","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.theta","c":"UpdateReturnState","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.AnotbAction","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.IntersectAction","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummary.Mode","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummary.Mode","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.tuple","c":"SerializerDeserializer.SketchType","l":"valueOf(String)","u":"valueOf(java.lang.String)","k":"6"},{"p":"org.apache.datasketches.common","c":"Family","l":"values()","k":"6"},{"p":"org.apache.datasketches.common","c":"ResizeFactor","l":"values()","k":"6"},{"p":"org.apache.datasketches.frequencies","c":"ErrorType","l":"values()","k":"6"},{"p":"org.apache.datasketches.hll","c":"TgtHllType","l":"values()","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchStructure","l":"values()","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllSketch.SketchType","l":"values()","k":"6"},{"p":"org.apache.datasketches.partitions","c":"BoundsRule","l":"values()","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"GenericInequalitySearch.Inequality","l":"values()","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"InequalitySearch","l":"values()","k":"6"},{"p":"org.apache.datasketches.quantilescommon","c":"QuantileSearchCriteria","l":"values()","k":"6"},{"p":"org.apache.datasketches.theta","c":"UpdateReturnState","l":"values()","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.AnotbAction","l":"values()","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.CornerCase","l":"values()","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.IntersectAction","l":"values()","k":"6"},{"p":"org.apache.datasketches.thetacommon","c":"SetOperationCornerCases.UnionAction","l":"values()","k":"6"},{"p":"org.apache.datasketches.tuple.adouble","c":"DoubleSummary.Mode","l":"values()","k":"6"},{"p":"org.apache.datasketches.tuple.aninteger","c":"IntegerSummary.Mode","l":"values()","k":"6"},{"p":"org.apache.datasketches.tuple","c":"SerializerDeserializer.SketchType","l":"values()","k":"6"},{"p":"org.apache.datasketches.common","c":"Family","l":"VAROPT","k":"0"},{"p":"org.apache.datasketches.common","c":"Family","l":"VAROPT_UNION","k":"0"},{"p":"org.apache.datasketches.req","c":"ReqSketch","l":"viewCompactorDetail(String, boolean)","u":"viewCompactorDetail(java.lang.String,boolean)"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSamples","l":"weights()"},{"p":"org.apache.datasketches.sampling","c":"VarOptItemsSamples","l":"weights(int)"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"wrap(byte[])","k":"6"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"wrap(byte[], long)","u":"wrap(byte[],long)","k":"6"},{"p":"org.apache.datasketches.common.positional","c":"PositionalSegment","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"UpdatableQuantilesDoublesSketch","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaIntersection","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperation","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUnion","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"wrap(MemorySegment)","u":"wrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllItemsSketch","l":"wrap(MemorySegment, Comparator, ArrayOfItemsSerDe)","u":"wrap(java.lang.foreign.MemorySegment,java.util.Comparator,org.apache.datasketches.common.ArrayOfItemsSerDe)","k":"6"},{"p":"org.apache.datasketches.theta","c":"CompactThetaSketch","l":"wrap(MemorySegment, long)","u":"wrap(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaIntersection","l":"wrap(MemorySegment, long)","u":"wrap(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSetOperation","l":"wrap(MemorySegment, long)","u":"wrap(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaSketch","l":"wrap(MemorySegment, long)","u":"wrap(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.theta","c":"ThetaUnion","l":"wrap(MemorySegment, long)","u":"wrap(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"wrap(MemorySegment, long)","u":"wrap(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUnion","l":"wrap(MemorySegment, long)","u":"wrap(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesUpdatableSketch","l":"wrap(MemorySegment, long)","u":"wrap(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllDoublesSketch","l":"wrap(MemorySegment, MemorySegmentRequest)","u":"wrap(java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllFloatsSketch","l":"wrap(MemorySegment, MemorySegmentRequest)","u":"wrap(java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)","k":"6"},{"p":"org.apache.datasketches.kll","c":"KllLongsSketch","l":"wrap(MemorySegment, MemorySegmentRequest)","u":"wrap(java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesUnion","l":"wrap(MemorySegment, MemorySegmentRequest)","u":"wrap(java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"UpdatableQuantilesDoublesSketch","l":"wrap(MemorySegment, MemorySegmentRequest)","u":"wrap(java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)","k":"6"},{"p":"org.apache.datasketches.theta","c":"UpdatableThetaSketch","l":"wrap(MemorySegment, MemorySegmentRequest, long)","u":"wrap(java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest,long)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"wrapSketch(MemorySegment)","u":"wrapSketch(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"wrapSketch(MemorySegment, long)","u":"wrapSketch(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"wrapUnion(MemorySegment)","u":"wrapUnion(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"wrapUnion(MemorySegment, long)","u":"wrapUnion(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"wrapUpdatableSketch(MemorySegment)","u":"wrapUpdatableSketch(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.tuple.arrayofdoubles","c":"ArrayOfDoublesSketch","l":"wrapUpdatableSketch(MemorySegment, long)","u":"wrapUpdatableSketch(java.lang.foreign.MemorySegment,long)","k":"6"},{"p":"org.apache.datasketches.filters.bloomfilter","c":"BloomFilter","l":"writableWrap(MemorySegment)","u":"writableWrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllSketch","l":"writableWrap(MemorySegment)","u":"writableWrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.hll","c":"HllUnion","l":"writableWrap(MemorySegment)","u":"writableWrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"writableWrap(MemorySegment)","u":"writableWrap(java.lang.foreign.MemorySegment)","k":"6"},{"p":"org.apache.datasketches.quantiles","c":"QuantilesDoublesSketch","l":"writableWrap(MemorySegment, MemorySegmentRequest)","u":"writableWrap(java.lang.foreign.MemorySegment,org.apache.datasketches.common.MemorySegmentRequest)","k":"6"},{"p":"org.apache.datasketches.common","c":"ResizeFactor","l":"X1","k":"0"},{"p":"org.apache.datasketches.common","c":"ResizeFactor","l":"X2","k":"0"},{"p":"org.apache.datasketches.common","c":"ResizeFactor","l":"X4","k":"0"},{"p":"org.apache.datasketches.common","c":"ResizeFactor","l":"X8","k":"0"},{"p":"org.apache.datasketches.common","c":"Util","l":"zeroPad(String, int)","u":"zeroPad(java.lang.String,int)","k":"6"}];updateSearchResults(); \ No newline at end of file diff --git a/target/site/apidocs/module-search-index.js b/target/site/apidocs/module-search-index.js new file mode 100644 index 000000000..0d59754fc --- /dev/null +++ b/target/site/apidocs/module-search-index.js @@ -0,0 +1 @@ +moduleSearchIndex = [];updateSearchResults(); \ No newline at end of file diff --git a/target/site/apidocs/org/apache/datasketches/common/ArrayOfBooleansSerDe.html b/target/site/apidocs/org/apache/datasketches/common/ArrayOfBooleansSerDe.html new file mode 100644 index 000000000..f8dcb3574 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/ArrayOfBooleansSerDe.html @@ -0,0 +1,431 @@ + + + + +ArrayOfBooleansSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfBooleansSerDe

+
+
java.lang.Object +
org.apache.datasketches.common.ArrayOfItemsSerDe<Boolean> +
org.apache.datasketches.common.ArrayOfBooleansSerDe
+
+
+
+
+
+
public class ArrayOfBooleansSerDe +extends ArrayOfItemsSerDe<Boolean>
+
Methods of serializing and deserializing arrays of Boolean as a bit array.
+
+
Author:
+
Jon Malkin
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    No argument constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static int
    +
    computeBytesNeeded(int arrayLength)
    +
    +
    Computes number of bytes needed for packed bit encoding of the array of booleans.
    +
    + + +
    +
    Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
    +
    + +
    deserializeFromMemorySegment(MemorySegment seg, + long offsetBytes, + int numItems)
    +
    +
    Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
    +
    + + +
    +
    Returns the concrete class of type T
    +
    +
    byte[]
    + +
    +
    Serialize a single unserialized item to a byte array.
    +
    +
    byte[]
    + +
    +
    Serialize an array of unserialized items to a byte array of contiguous serialized items.
    +
    +
    int
    + +
    +
    Returns the serialized size in bytes of a single unserialized item.
    +
    +
    int
    +
    sizeOf(Boolean[] items)
    +
    +
    Returns the serialized size in bytes of the array of items.
    +
    +
    int
    +
    sizeOf(MemorySegment seg, + long offsetBytes, + int numItems)
    +
    +
    Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment.
    +
    + + +
    +
    Returns a human readable string of an item.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfBooleansSerDe

      +
      +
      public ArrayOfBooleansSerDe()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      computeBytesNeeded

      +
      +
      public static int computeBytesNeeded(int arrayLength)
      +
      Computes number of bytes needed for packed bit encoding of the array of booleans. Rounds +partial bytes up to return a whole number of bytes.
      +
      +
      Parameters:
      +
      arrayLength - Number of items in the array to serialize
      +
      Returns:
      +
      Number of bytes needed to encode the array
      +
      +
      +
      +
    • +
    • +
      +

      serializeToByteArray

      +
      +
      public byte[] serializeToByteArray(Boolean item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Serialize a single unserialized item to a byte array.
      +
      +
      Specified by:
      +
      serializeToByteArray in class ArrayOfItemsSerDe<Boolean>
      +
      Parameters:
      +
      item - the item to be serialized
      +
      Returns:
      +
      serialized representation of the given item
      +
      +
      +
      +
    • +
    • +
      +

      serializeToByteArray

      +
      +
      public byte[] serializeToByteArray(Boolean[] items)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Serialize an array of unserialized items to a byte array of contiguous serialized items.
      +
      +
      Specified by:
      +
      serializeToByteArray in class ArrayOfItemsSerDe<Boolean>
      +
      Parameters:
      +
      items - array of items to be serialized
      +
      Returns:
      +
      contiguous, serialized representation of the given array of unserialized items
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public Boolean[] deserializeFromMemorySegment(MemorySegment seg, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
      +
      +
      Overrides:
      +
      deserializeFromMemorySegment in class ArrayOfItemsSerDe<Boolean>
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public Boolean[] deserializeFromMemorySegment(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
      +
      +
      Specified by:
      +
      deserializeFromMemorySegment in class ArrayOfItemsSerDe<Boolean>
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(Boolean item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of a single unserialized item.
      +
      +
      Specified by:
      +
      sizeOf in class ArrayOfItemsSerDe<Boolean>
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      the serialized size in bytes of a single unserialized item.
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(Boolean[] items)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of the array of items.
      +
      +
      Overrides:
      +
      sizeOf in class ArrayOfItemsSerDe<Boolean>
      +
      Parameters:
      +
      items - an array of items.
      +
      Returns:
      +
      the serialized size in bytes of the array of items.
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment. +The capacity of the given MemorySegment can be much larger that the required size of the items.
      +
      +
      Specified by:
      +
      sizeOf in class ArrayOfItemsSerDe<Boolean>
      +
      Parameters:
      +
      seg - the given MemorySegment.
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - the number of serialized items contained in the MemorySegment
      +
      Returns:
      +
      the serialized size in bytes of the given number of items.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(Boolean item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns a human readable string of an item.
      +
      +
      Specified by:
      +
      toString in class ArrayOfItemsSerDe<Boolean>
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      a human readable string of an item.
      +
      +
      +
      +
    • +
    • +
      +

      getClassOfT

      +
      +
      public Class<Boolean> getClassOfT()
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the concrete class of type T
      +
      +
      Specified by:
      +
      getClassOfT in class ArrayOfItemsSerDe<Boolean>
      +
      Returns:
      +
      the concrete class of type T
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/ArrayOfDoublesSerDe.html b/target/site/apidocs/org/apache/datasketches/common/ArrayOfDoublesSerDe.html new file mode 100644 index 000000000..c603c9aa0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/ArrayOfDoublesSerDe.html @@ -0,0 +1,409 @@ + + + + +ArrayOfDoublesSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfDoublesSerDe

+
+
java.lang.Object +
org.apache.datasketches.common.ArrayOfItemsSerDe<Double> +
org.apache.datasketches.common.ArrayOfDoublesSerDe
+
+
+
+
+
+
public class ArrayOfDoublesSerDe +extends ArrayOfItemsSerDe<Double>
+
Methods of serializing and deserializing arrays of Double.
+
+
Author:
+
Alexander Saydakov
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    No argument constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
    +
    + +
    deserializeFromMemorySegment(MemorySegment seg, + long offsetBytes, + int numItems)
    +
    +
    Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
    +
    + + +
    +
    Returns the concrete class of type T
    +
    +
    byte[]
    + +
    +
    Serialize a single unserialized item to a byte array.
    +
    +
    byte[]
    + +
    +
    Serialize an array of unserialized items to a byte array of contiguous serialized items.
    +
    +
    int
    +
    sizeOf(Double item)
    +
    +
    Returns the serialized size in bytes of a single unserialized item.
    +
    +
    int
    +
    sizeOf(Double[] items)
    +
    +
    Returns the serialized size in bytes of the array of items.
    +
    +
    int
    +
    sizeOf(MemorySegment seg, + long offsetBytes, + int numItems)
    +
    +
    Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment.
    +
    + + +
    +
    Returns a human readable string of an item.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfDoublesSerDe

      +
      +
      public ArrayOfDoublesSerDe()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      serializeToByteArray

      +
      +
      public byte[] serializeToByteArray(Double item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Serialize a single unserialized item to a byte array.
      +
      +
      Specified by:
      +
      serializeToByteArray in class ArrayOfItemsSerDe<Double>
      +
      Parameters:
      +
      item - the item to be serialized
      +
      Returns:
      +
      serialized representation of the given item
      +
      +
      +
      +
    • +
    • +
      +

      serializeToByteArray

      +
      +
      public byte[] serializeToByteArray(Double[] items)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Serialize an array of unserialized items to a byte array of contiguous serialized items.
      +
      +
      Specified by:
      +
      serializeToByteArray in class ArrayOfItemsSerDe<Double>
      +
      Parameters:
      +
      items - array of items to be serialized
      +
      Returns:
      +
      contiguous, serialized representation of the given array of unserialized items
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public Double[] deserializeFromMemorySegment(MemorySegment seg, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
      +
      +
      Overrides:
      +
      deserializeFromMemorySegment in class ArrayOfItemsSerDe<Double>
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public Double[] deserializeFromMemorySegment(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
      +
      +
      Specified by:
      +
      deserializeFromMemorySegment in class ArrayOfItemsSerDe<Double>
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(Double item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of a single unserialized item.
      +
      +
      Specified by:
      +
      sizeOf in class ArrayOfItemsSerDe<Double>
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      the serialized size in bytes of a single unserialized item.
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(Double[] items)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of the array of items.
      +
      +
      Overrides:
      +
      sizeOf in class ArrayOfItemsSerDe<Double>
      +
      Parameters:
      +
      items - an array of items.
      +
      Returns:
      +
      the serialized size in bytes of the array of items.
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment. +The capacity of the given MemorySegment can be much larger that the required size of the items.
      +
      +
      Specified by:
      +
      sizeOf in class ArrayOfItemsSerDe<Double>
      +
      Parameters:
      +
      seg - the given MemorySegment.
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - the number of serialized items contained in the MemorySegment
      +
      Returns:
      +
      the serialized size in bytes of the given number of items.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(Double item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns a human readable string of an item.
      +
      +
      Specified by:
      +
      toString in class ArrayOfItemsSerDe<Double>
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      a human readable string of an item.
      +
      +
      +
      +
    • +
    • +
      +

      getClassOfT

      +
      +
      public Class<Double> getClassOfT()
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the concrete class of type T
      +
      +
      Specified by:
      +
      getClassOfT in class ArrayOfItemsSerDe<Double>
      +
      Returns:
      +
      the concrete class of type T
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/ArrayOfItemsSerDe.html b/target/site/apidocs/org/apache/datasketches/common/ArrayOfItemsSerDe.html new file mode 100644 index 000000000..3c7148113 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/ArrayOfItemsSerDe.html @@ -0,0 +1,388 @@ + + + + +ArrayOfItemsSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfItemsSerDe<T>

+
+
java.lang.Object +
org.apache.datasketches.common.ArrayOfItemsSerDe<T>
+
+
+
+
Type Parameters:
+
T - Type of item
+
+
+
Direct Known Subclasses:
+
ArrayOfBooleansSerDe, ArrayOfDoublesSerDe, ArrayOfLongsSerDe, ArrayOfNumbersSerDe, ArrayOfStringsSerDe, ArrayOfUtf16StringsSerDe
+
+
+
+
public abstract class ArrayOfItemsSerDe<T> +extends Object
+
Base class for serializing and deserializing custom types.
+
+
Author:
+
Alexander Saydakov
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    No argument constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    T[]
    + +
    +
    Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
    +
    +
    abstract T[]
    +
    deserializeFromMemorySegment(MemorySegment seg, + long offsetBytes, + int numItems)
    +
    +
    Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
    +
    +
    abstract Class<T>
    + +
    +
    Returns the concrete class of type T
    +
    +
    abstract byte[]
    + +
    +
    Serialize a single unserialized item to a byte array.
    +
    +
    abstract byte[]
    + +
    +
    Serialize an array of unserialized items to a byte array of contiguous serialized items.
    +
    +
    abstract int
    +
    sizeOf(MemorySegment seg, + long offsetBytes, + int numItems)
    +
    +
    Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment.
    +
    +
    abstract int
    +
    sizeOf(T item)
    +
    +
    Returns the serialized size in bytes of a single unserialized item.
    +
    +
    int
    +
    sizeOf(T[] items)
    +
    +
    Returns the serialized size in bytes of the array of items.
    +
    +
    abstract String
    +
    toString(T item)
    +
    +
    Returns a human readable string of an item.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfItemsSerDe

      +
      +
      public ArrayOfItemsSerDe()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      serializeToByteArray

      +
      +
      public abstract byte[] serializeToByteArray(T item)
      +
      Serialize a single unserialized item to a byte array.
      +
      +
      Parameters:
      +
      item - the item to be serialized
      +
      Returns:
      +
      serialized representation of the given item
      +
      +
      +
      +
    • +
    • +
      +

      serializeToByteArray

      +
      +
      public abstract byte[] serializeToByteArray(T[] items)
      +
      Serialize an array of unserialized items to a byte array of contiguous serialized items.
      +
      +
      Parameters:
      +
      items - array of items to be serialized
      +
      Returns:
      +
      contiguous, serialized representation of the given array of unserialized items
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public T[] deserializeFromMemorySegment(MemorySegment seg, + int numItems)
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
      +
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public abstract T[] deserializeFromMemorySegment(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
      +
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public abstract int sizeOf(T item)
      +
      Returns the serialized size in bytes of a single unserialized item.
      +
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      the serialized size in bytes of a single unserialized item.
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(T[] items)
      +
      Returns the serialized size in bytes of the array of items.
      +
      +
      Parameters:
      +
      items - an array of items.
      +
      Returns:
      +
      the serialized size in bytes of the array of items.
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public abstract int sizeOf(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment. +The capacity of the given MemorySegment can be much larger that the required size of the items.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment.
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - the number of serialized items contained in the MemorySegment
      +
      Returns:
      +
      the serialized size in bytes of the given number of items.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public abstract String toString(T item)
      +
      Returns a human readable string of an item.
      +
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      a human readable string of an item.
      +
      +
      +
      +
    • +
    • +
      +

      getClassOfT

      +
      +
      public abstract Class<T> getClassOfT()
      +
      Returns the concrete class of type T
      +
      +
      Returns:
      +
      the concrete class of type T
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/ArrayOfLongsSerDe.html b/target/site/apidocs/org/apache/datasketches/common/ArrayOfLongsSerDe.html new file mode 100644 index 000000000..4607686d1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/ArrayOfLongsSerDe.html @@ -0,0 +1,409 @@ + + + + +ArrayOfLongsSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfLongsSerDe

+
+
java.lang.Object +
org.apache.datasketches.common.ArrayOfItemsSerDe<Long> +
org.apache.datasketches.common.ArrayOfLongsSerDe
+
+
+
+
+
+
public class ArrayOfLongsSerDe +extends ArrayOfItemsSerDe<Long>
+
Methods of serializing and deserializing arrays of Long.
+
+
Author:
+
Alexander Saydakov
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    No argument constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
    +
    + +
    deserializeFromMemorySegment(MemorySegment seg, + long offsetBytes, + int numItems)
    +
    +
    Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
    +
    + + +
    +
    Returns the concrete class of type T
    +
    +
    byte[]
    + +
    +
    Serialize a single unserialized item to a byte array.
    +
    +
    byte[]
    + +
    +
    Serialize an array of unserialized items to a byte array of contiguous serialized items.
    +
    +
    int
    +
    sizeOf(MemorySegment seg, + long offsetBytes, + int numItems)
    +
    +
    Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment.
    +
    +
    int
    +
    sizeOf(Long item)
    +
    +
    Returns the serialized size in bytes of a single unserialized item.
    +
    +
    int
    +
    sizeOf(Long[] items)
    +
    +
    Returns the serialized size in bytes of the array of items.
    +
    + +
    toString(Long item)
    +
    +
    Returns a human readable string of an item.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfLongsSerDe

      +
      +
      public ArrayOfLongsSerDe()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      serializeToByteArray

      +
      +
      public byte[] serializeToByteArray(Long item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Serialize a single unserialized item to a byte array.
      +
      +
      Specified by:
      +
      serializeToByteArray in class ArrayOfItemsSerDe<Long>
      +
      Parameters:
      +
      item - the item to be serialized
      +
      Returns:
      +
      serialized representation of the given item
      +
      +
      +
      +
    • +
    • +
      +

      serializeToByteArray

      +
      +
      public byte[] serializeToByteArray(Long[] items)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Serialize an array of unserialized items to a byte array of contiguous serialized items.
      +
      +
      Specified by:
      +
      serializeToByteArray in class ArrayOfItemsSerDe<Long>
      +
      Parameters:
      +
      items - array of items to be serialized
      +
      Returns:
      +
      contiguous, serialized representation of the given array of unserialized items
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public Long[] deserializeFromMemorySegment(MemorySegment seg, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
      +
      +
      Overrides:
      +
      deserializeFromMemorySegment in class ArrayOfItemsSerDe<Long>
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public Long[] deserializeFromMemorySegment(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
      +
      +
      Specified by:
      +
      deserializeFromMemorySegment in class ArrayOfItemsSerDe<Long>
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(Long item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of a single unserialized item.
      +
      +
      Specified by:
      +
      sizeOf in class ArrayOfItemsSerDe<Long>
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      the serialized size in bytes of a single unserialized item.
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(Long[] items)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of the array of items.
      +
      +
      Overrides:
      +
      sizeOf in class ArrayOfItemsSerDe<Long>
      +
      Parameters:
      +
      items - an array of items.
      +
      Returns:
      +
      the serialized size in bytes of the array of items.
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment. +The capacity of the given MemorySegment can be much larger that the required size of the items.
      +
      +
      Specified by:
      +
      sizeOf in class ArrayOfItemsSerDe<Long>
      +
      Parameters:
      +
      seg - the given MemorySegment.
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - the number of serialized items contained in the MemorySegment
      +
      Returns:
      +
      the serialized size in bytes of the given number of items.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(Long item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns a human readable string of an item.
      +
      +
      Specified by:
      +
      toString in class ArrayOfItemsSerDe<Long>
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      a human readable string of an item.
      +
      +
      +
      +
    • +
    • +
      +

      getClassOfT

      +
      +
      public Class<Long> getClassOfT()
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the concrete class of type T
      +
      +
      Specified by:
      +
      getClassOfT in class ArrayOfItemsSerDe<Long>
      +
      Returns:
      +
      the concrete class of type T
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/ArrayOfNumbersSerDe.html b/target/site/apidocs/org/apache/datasketches/common/ArrayOfNumbersSerDe.html new file mode 100644 index 000000000..e4e93b090 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/ArrayOfNumbersSerDe.html @@ -0,0 +1,417 @@ + + + + +ArrayOfNumbersSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfNumbersSerDe

+
+
java.lang.Object +
org.apache.datasketches.common.ArrayOfItemsSerDe<Number> +
org.apache.datasketches.common.ArrayOfNumbersSerDe
+
+
+
+
+
+
public class ArrayOfNumbersSerDe +extends ArrayOfItemsSerDe<Number>
+
Methods of serializing and deserializing arrays of the object version of primitive types of +Number. The array can be a mix of primitive object types. + +

This class serializes numbers with a leading byte (ASCII character) indicating the type. +The class keeps the values byte aligned, even though only 3 bits are strictly necessary to +encode one of the 6 different primitives with object types that extend Number.

+ +

Classes handled are: Long, Integer, Short, +Byte, Double, and Float.

+
+
Author:
+
Jon Malkin
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    No argument constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
    +
    + +
    deserializeFromMemorySegment(MemorySegment seg, + long offsetBytes, + int numItems)
    +
    +
    Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
    +
    + + +
    +
    Returns the concrete class of type T
    +
    +
    byte[]
    + +
    +
    Serialize a single unserialized item to a byte array.
    +
    +
    byte[]
    + +
    +
    Serialize an array of unserialized items to a byte array of contiguous serialized items.
    +
    +
    int
    +
    sizeOf(MemorySegment seg, + long offsetBytes, + int numItems)
    +
    +
    Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment.
    +
    +
    int
    +
    sizeOf(Number item)
    +
    +
    Returns the serialized size in bytes of a single unserialized item.
    +
    +
    int
    +
    sizeOf(Number[] items)
    +
    +
    Returns the serialized size in bytes of the array of items.
    +
    + + +
    +
    Returns a human readable string of an item.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfNumbersSerDe

      +
      +
      public ArrayOfNumbersSerDe()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      serializeToByteArray

      +
      +
      public byte[] serializeToByteArray(Number item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Serialize a single unserialized item to a byte array.
      +
      +
      Specified by:
      +
      serializeToByteArray in class ArrayOfItemsSerDe<Number>
      +
      Parameters:
      +
      item - the item to be serialized
      +
      Returns:
      +
      serialized representation of the given item
      +
      +
      +
      +
    • +
    • +
      +

      serializeToByteArray

      +
      +
      public byte[] serializeToByteArray(Number[] items)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Serialize an array of unserialized items to a byte array of contiguous serialized items.
      +
      +
      Specified by:
      +
      serializeToByteArray in class ArrayOfItemsSerDe<Number>
      +
      Parameters:
      +
      items - array of items to be serialized
      +
      Returns:
      +
      contiguous, serialized representation of the given array of unserialized items
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public Number[] deserializeFromMemorySegment(MemorySegment seg, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
      +
      +
      Overrides:
      +
      deserializeFromMemorySegment in class ArrayOfItemsSerDe<Number>
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public Number[] deserializeFromMemorySegment(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
      +
      +
      Specified by:
      +
      deserializeFromMemorySegment in class ArrayOfItemsSerDe<Number>
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(Number item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of a single unserialized item.
      +
      +
      Specified by:
      +
      sizeOf in class ArrayOfItemsSerDe<Number>
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      the serialized size in bytes of a single unserialized item.
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(Number[] items)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of the array of items.
      +
      +
      Overrides:
      +
      sizeOf in class ArrayOfItemsSerDe<Number>
      +
      Parameters:
      +
      items - an array of items.
      +
      Returns:
      +
      the serialized size in bytes of the array of items.
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment. +The capacity of the given MemorySegment can be much larger that the required size of the items.
      +
      +
      Specified by:
      +
      sizeOf in class ArrayOfItemsSerDe<Number>
      +
      Parameters:
      +
      seg - the given MemorySegment.
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - the number of serialized items contained in the MemorySegment
      +
      Returns:
      +
      the serialized size in bytes of the given number of items.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(Number item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns a human readable string of an item.
      +
      +
      Specified by:
      +
      toString in class ArrayOfItemsSerDe<Number>
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      a human readable string of an item.
      +
      +
      +
      +
    • +
    • +
      +

      getClassOfT

      +
      +
      public Class<Number> getClassOfT()
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the concrete class of type T
      +
      +
      Specified by:
      +
      getClassOfT in class ArrayOfItemsSerDe<Number>
      +
      Returns:
      +
      the concrete class of type T
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/ArrayOfStringsSerDe.html b/target/site/apidocs/org/apache/datasketches/common/ArrayOfStringsSerDe.html new file mode 100644 index 000000000..c86b8a1a8 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/ArrayOfStringsSerDe.html @@ -0,0 +1,394 @@ + + + + +ArrayOfStringsSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfStringsSerDe

+
+
java.lang.Object +
org.apache.datasketches.common.ArrayOfItemsSerDe<String> +
org.apache.datasketches.common.ArrayOfStringsSerDe
+
+
+
+
+
+
public class ArrayOfStringsSerDe +extends ArrayOfItemsSerDe<String>
+
Methods of serializing and deserializing arrays of String. +This class serializes strings in UTF-8 format, which is more compact compared to +ArrayOfUtf16StringsSerDe. In an extreme case when all strings are in ASCII, +this method is 2 times more compact, but it takes more time to encode and decode +by a factor of 1.5 to 2. + +

The serialization

+
+
Author:
+
Alexander Saydakov
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfStringsSerDe

      +
      +
      public ArrayOfStringsSerDe()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      serializeToByteArray

      +
      +
      public byte[] serializeToByteArray(String item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Serialize a single unserialized item to a byte array.
      +
      +
      Specified by:
      +
      serializeToByteArray in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      item - the item to be serialized
      +
      Returns:
      +
      serialized representation of the given item
      +
      +
      +
      +
    • +
    • +
      +

      serializeToByteArray

      +
      +
      public byte[] serializeToByteArray(String[] items)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Serialize an array of unserialized items to a byte array of contiguous serialized items.
      +
      +
      Specified by:
      +
      serializeToByteArray in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      items - array of items to be serialized
      +
      Returns:
      +
      contiguous, serialized representation of the given array of unserialized items
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public String[] deserializeFromMemorySegment(MemorySegment seg, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
      +
      +
      Overrides:
      +
      deserializeFromMemorySegment in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public String[] deserializeFromMemorySegment(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
      +
      +
      Specified by:
      +
      deserializeFromMemorySegment in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(String item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of a single unserialized item.
      +
      +
      Specified by:
      +
      sizeOf in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      the serialized size in bytes of a single unserialized item.
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment. +The capacity of the given MemorySegment can be much larger that the required size of the items.
      +
      +
      Specified by:
      +
      sizeOf in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      seg - the given MemorySegment.
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - the number of serialized items contained in the MemorySegment
      +
      Returns:
      +
      the serialized size in bytes of the given number of items.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(String item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns a human readable string of an item.
      +
      +
      Specified by:
      +
      toString in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      a human readable string of an item.
      +
      +
      +
      +
    • +
    • +
      +

      getClassOfT

      +
      +
      public Class<String> getClassOfT()
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the concrete class of type T
      +
      +
      Specified by:
      +
      getClassOfT in class ArrayOfItemsSerDe<String>
      +
      Returns:
      +
      the concrete class of type T
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/ArrayOfUtf16StringsSerDe.html b/target/site/apidocs/org/apache/datasketches/common/ArrayOfUtf16StringsSerDe.html new file mode 100644 index 000000000..2a3ab6c61 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/ArrayOfUtf16StringsSerDe.html @@ -0,0 +1,392 @@ + + + + +ArrayOfUtf16StringsSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfUtf16StringsSerDe

+
+
java.lang.Object +
org.apache.datasketches.common.ArrayOfItemsSerDe<String> +
org.apache.datasketches.common.ArrayOfUtf16StringsSerDe
+
+
+
+
+
+
public class ArrayOfUtf16StringsSerDe +extends ArrayOfItemsSerDe<String>
+
Methods of serializing and deserializing arrays of String. +This class serializes strings using internal Java representation as char[], where each char +is a 16-bit code. The result is larger than one from ArrayOfStringsSerDe. +In an extreme case when all strings are in ASCII, the size is doubled. However it takes +less time to serialize and deserialize by a factor of 1.5 to 2.
+
+
Author:
+
Alexander Saydakov
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfUtf16StringsSerDe

      +
      +
      public ArrayOfUtf16StringsSerDe()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      serializeToByteArray

      +
      +
      public byte[] serializeToByteArray(String item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Serialize a single unserialized item to a byte array.
      +
      +
      Specified by:
      +
      serializeToByteArray in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      item - the item to be serialized
      +
      Returns:
      +
      serialized representation of the given item
      +
      +
      +
      +
    • +
    • +
      +

      serializeToByteArray

      +
      +
      public byte[] serializeToByteArray(String[] items)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Serialize an array of unserialized items to a byte array of contiguous serialized items.
      +
      +
      Specified by:
      +
      serializeToByteArray in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      items - array of items to be serialized
      +
      Returns:
      +
      contiguous, serialized representation of the given array of unserialized items
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public String[] deserializeFromMemorySegment(MemorySegment seg, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at a MemorySegment offset of zero and extending numItems.
      +
      +
      Overrides:
      +
      deserializeFromMemorySegment in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      deserializeFromMemorySegment

      +
      +
      public String[] deserializeFromMemorySegment(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Deserialize a contiguous sequence of serialized items from the given MemorySegment +starting at the given MemorySegment offsetBytes and extending numItems.
      +
      +
      Specified by:
      +
      deserializeFromMemorySegment in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      seg - MemorySegment containing a contiguous sequence of serialized items
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - number of items in the contiguous serialized sequence.
      +
      Returns:
      +
      array of deserialized items
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(String item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of a single unserialized item.
      +
      +
      Specified by:
      +
      sizeOf in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      the serialized size in bytes of a single unserialized item.
      +
      +
      +
      +
    • +
    • +
      +

      sizeOf

      +
      +
      public int sizeOf(MemorySegment seg, + long offsetBytes, + int numItems)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the serialized size in bytes of the number of contiguous serialized items in MemorySegment. +The capacity of the given MemorySegment can be much larger that the required size of the items.
      +
      +
      Specified by:
      +
      sizeOf in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      seg - the given MemorySegment.
      +
      offsetBytes - the starting offset in the given MemorySegment.
      +
      numItems - the number of serialized items contained in the MemorySegment
      +
      Returns:
      +
      the serialized size in bytes of the given number of items.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(String item)
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns a human readable string of an item.
      +
      +
      Specified by:
      +
      toString in class ArrayOfItemsSerDe<String>
      +
      Parameters:
      +
      item - a specific item
      +
      Returns:
      +
      a human readable string of an item.
      +
      +
      +
      +
    • +
    • +
      +

      getClassOfT

      +
      +
      public Class<String> getClassOfT()
      +
      Description copied from class: ArrayOfItemsSerDe
      +
      Returns the concrete class of type T
      +
      +
      Specified by:
      +
      getClassOfT in class ArrayOfItemsSerDe<String>
      +
      Returns:
      +
      the concrete class of type T
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/BoundsOnBinomialProportions.html b/target/site/apidocs/org/apache/datasketches/common/BoundsOnBinomialProportions.html new file mode 100644 index 000000000..c18009f60 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/BoundsOnBinomialProportions.html @@ -0,0 +1,334 @@ + + + + +BoundsOnBinomialProportions (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class BoundsOnBinomialProportions

+
+
java.lang.Object +
org.apache.datasketches.common.BoundsOnBinomialProportions
+
+
+
+
+
public final class BoundsOnBinomialProportions +extends Object
+
Confidence intervals for binomial proportions. + +

This class computes an approximation to the Clopper-Pearson confidence interval +for a binomial proportion. Exact Clopper-Pearson intervals are strictly +conservative, but these approximations are not.

+ +

The main inputs are numbers n and k, which are not the same as other things +that are called n and k in our sketching library. There is also a third +parameter, numStdDev, that specifies the desired confidence level.

+
    +
  • n is the number of independent randomized trials. It is given and therefore known.
  • +
  • p is the probability of a trial being a success. It is unknown.
  • +
  • k is the number of trials (out of n) that turn out to be successes. It is +a random variable governed by a binomial distribution. After any given +batch of n independent trials, the random variable k has a specific +value which is observed and is therefore known.
  • +
  • pHat = k / n is an unbiased estimate of the unknown success +probability p.
  • +
+ +

Alternatively, consider a coin with unknown heads probability p. Where +n is the number of independent flips of that coin, and k is the number +of times that the coin comes up heads during a given batch of n flips. +This class computes a frequentist confidence interval [lowerBoundOnP, upperBoundOnP] for the +unknown p.

+ +

Conceptually, the desired confidence level is specified by a tail probability delta.

+ +

Ideally, over a large ensemble of independent batches of trials, +the fraction of batches in which the true p lies below lowerBoundOnP would be at most +delta, and the fraction of batches in which the true p lies above upperBoundOnP +would also be at most delta. + +

Setting aside the philosophical difficulties attaching to that statement, it isn't quite +true because we are approximating the Clopper-Pearson interval.

+ +

Finally, we point out that in this class's interface, the confidence parameter delta is +not specified directly, but rather through a "number of standard deviations" numStdDev. +The library effectively converts that to a delta via delta = normalCDF (-1.0 * numStdDev).

+ +

It is perhaps worth emphasizing that the library is NOT merely adding and subtracting +numStdDev standard deviations to the estimate. It is doing something better, that to some +extent accounts for the fact that the binomial distribution has a non-gaussian shape.

+ +

In particular, it is using an approximation to the inverse of the incomplete beta function +that appears as formula 26.5.22 on page 945 of the "Handbook of Mathematical Functions" +by Abramowitz and Stegun.

+
+
Author:
+
Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static double
    +
    approximateLowerBoundOnP(long n, + long k, + double numStdDevs)
    +
    +
    Computes lower bound of approximate Clopper-Pearson confidence interval for a binomial +proportion.
    +
    +
    static double
    +
    approximateUpperBoundOnP(long n, + long k, + double numStdDevs)
    +
    +
    Computes upper bound of approximate Clopper-Pearson confidence interval for a binomial +proportion.
    +
    +
    static double
    +
    erf(double x)
    +
    +
    Computes an approximation to the erf() function.
    +
    +
    static double
    +
    estimateUnknownP(long n, + long k)
    +
    +
    Computes an estimate of an unknown binomial proportion.
    +
    +
    static double
    +
    normalCDF(double x)
    +
    +
    Computes an approximation to normalCDF(x).
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      approximateLowerBoundOnP

      +
      +
      public static double approximateLowerBoundOnP(long n, + long k, + double numStdDevs)
      +
      Computes lower bound of approximate Clopper-Pearson confidence interval for a binomial +proportion. + +

      Implementation Notes:
      +The approximateLowerBoundOnP is defined with respect to the right tail of the binomial +distribution.

      +
        +
      • We want to solve for the p for which sumj,k,nbino(j;n,p) += delta.
      • +
      • We now restate that in terms of the left tail.
      • +
      • We want to solve for the p for which sumj,0,(k-1)bino(j;n,p) += 1 - delta.
      • +
      • Define x = 1-p.
      • +
      • We want to solve for the x for which Ix(n-k+1,k) = 1 - delta.
      • +
      • We specify 1-delta via numStdDevs through the right tail of the standard normal +distribution.
      • +
      • Smaller values of numStdDevs correspond to bigger values of 1-delta and hence to smaller +values of delta. In fact, usefully small values of delta correspond to negative values of +numStdDevs.
      • +
      • return p = 1-x.
      • +
      +
      +
      Parameters:
      +
      n - is the number of trials. Must be non-negative.
      +
      k - is the number of successes. Must be non-negative, and cannot exceed n.
      +
      numStdDevs - the number of standard deviations defining the confidence interval
      +
      Returns:
      +
      the lower bound of the approximate Clopper-Pearson confidence interval for the +unknown success probability.
      +
      +
      +
      +
    • +
    • +
      +

      approximateUpperBoundOnP

      +
      +
      public static double approximateUpperBoundOnP(long n, + long k, + double numStdDevs)
      +
      Computes upper bound of approximate Clopper-Pearson confidence interval for a binomial +proportion. + +

      Implementation Notes:
      +The approximateUpperBoundOnP is defined with respect to the left tail of the binomial +distribution.

      +
        +
      • We want to solve for the p for which sumj,0,kbino(j;n,p) += delta.
      • +
      • Define x = 1-p.
      • +
      • We want to solve for the x for which Ix(n-k,k+1) = delta.
      • +
      • We specify delta via numStdDevs through the right tail of the standard normal +distribution.
      • +
      • Bigger values of numStdDevs correspond to smaller values of delta.
      • +
      • return p = 1-x.
      • +
      +
      +
      Parameters:
      +
      n - is the number of trials. Must be non-negative.
      +
      k - is the number of successes. Must be non-negative, and cannot exceed n.
      +
      numStdDevs - the number of standard deviations defining the confidence interval
      +
      Returns:
      +
      the upper bound of the approximate Clopper-Pearson confidence interval for the +unknown success probability.
      +
      +
      +
      +
    • +
    • +
      +

      estimateUnknownP

      +
      +
      public static double estimateUnknownP(long n, + long k)
      +
      Computes an estimate of an unknown binomial proportion.
      +
      +
      Parameters:
      +
      n - is the number of trials. Must be non-negative.
      +
      k - is the number of successes. Must be non-negative, and cannot exceed n.
      +
      Returns:
      +
      the estimate of the unknown binomial proportion.
      +
      +
      +
      +
    • +
    • +
      +

      erf

      +
      +
      public static double erf(double x)
      +
      Computes an approximation to the erf() function.
      +
      +
      Parameters:
      +
      x - is the input to the erf function
      +
      Returns:
      +
      returns erf(x), accurate to roughly 7 decimal digits.
      +
      +
      +
      +
    • +
    • +
      +

      normalCDF

      +
      +
      public static double normalCDF(double x)
      +
      Computes an approximation to normalCDF(x).
      +
      +
      Parameters:
      +
      x - is the input to the normalCDF function
      +
      Returns:
      +
      returns the approximation to normalCDF(x).
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/BoundsOnRatiosInSampledSets.html b/target/site/apidocs/org/apache/datasketches/common/BoundsOnRatiosInSampledSets.html new file mode 100644 index 000000000..dec2e5e6e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/BoundsOnRatiosInSampledSets.html @@ -0,0 +1,265 @@ + + + + +BoundsOnRatiosInSampledSets (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class BoundsOnRatiosInSampledSets

+
+
java.lang.Object +
org.apache.datasketches.common.BoundsOnRatiosInSampledSets
+
+
+
+
+
public final class BoundsOnRatiosInSampledSets +extends Object
+
This class is used to compute the bounds on the estimate of the ratio |B| / |A|, where: +
    +
  • |A| is the unknown size of a set A of unique identifiers.
  • +
  • |B| is the unknown size of a subset B of A.
  • +
  • a = |SA| is the observed size of a sample of A +that was obtained by Bernoulli sampling with a known inclusion probability f.
  • +
  • b = |SA ∩ B| is the observed size of a subset +of SA.
  • +
+
+
Author:
+
Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static double
    +
    getEstimateOfA(long a, + double f)
    +
    +
    Return the estimate of A.
    +
    +
    static double
    +
    getEstimateOfB(long b, + double f)
    +
    +
    Return the estimate of B.
    +
    +
    static double
    +
    getEstimateOfBoverA(long a, + long b)
    +
    +
    Return the estimate of b over a
    +
    +
    static double
    +
    getLowerBoundForBoverA(long a, + long b, + double f)
    +
    +
    Return the approximate lower bound based on a 95% confidence interval
    +
    +
    static double
    +
    getUpperBoundForBoverA(long a, + long b, + double f)
    +
    +
    Return the approximate upper bound based on a 95% confidence interval
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getLowerBoundForBoverA

      +
      +
      public static double getLowerBoundForBoverA(long a, + long b, + double f)
      +
      Return the approximate lower bound based on a 95% confidence interval
      +
      +
      Parameters:
      +
      a - See class javadoc
      +
      b - See class javadoc
      +
      f - the inclusion probability used to produce the set with size a and should +generally be less than 0.5. Above this value, the results not be reliable. +When f = 1.0 this returns the estimate.
      +
      Returns:
      +
      the approximate upper bound
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBoundForBoverA

      +
      +
      public static double getUpperBoundForBoverA(long a, + long b, + double f)
      +
      Return the approximate upper bound based on a 95% confidence interval
      +
      +
      Parameters:
      +
      a - See class javadoc
      +
      b - See class javadoc
      +
      f - the inclusion probability used to produce the set with size a.
      +
      Returns:
      +
      the approximate lower bound
      +
      +
      +
      +
    • +
    • +
      +

      getEstimateOfBoverA

      +
      +
      public static double getEstimateOfBoverA(long a, + long b)
      +
      Return the estimate of b over a
      +
      +
      Parameters:
      +
      a - See class javadoc
      +
      b - See class javadoc
      +
      Returns:
      +
      the estimate of b over a
      +
      +
      +
      +
    • +
    • +
      +

      getEstimateOfA

      +
      +
      public static double getEstimateOfA(long a, + double f)
      +
      Return the estimate of A. See class javadoc.
      +
      +
      Parameters:
      +
      a - See class javadoc
      +
      f - the inclusion probability used to produce the set with size a.
      +
      Returns:
      +
      the approximate lower bound
      +
      +
      +
      +
    • +
    • +
      +

      getEstimateOfB

      +
      +
      public static double getEstimateOfB(long b, + double f)
      +
      Return the estimate of B. See class javadoc.
      +
      +
      Parameters:
      +
      b - See class javadoc
      +
      f - the inclusion probability used to produce the set with size b.
      +
      Returns:
      +
      the approximate lower bound
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/ByteArrayUtil.html b/target/site/apidocs/org/apache/datasketches/common/ByteArrayUtil.html new file mode 100644 index 000000000..49ea4d53a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/ByteArrayUtil.html @@ -0,0 +1,748 @@ + + + + +ByteArrayUtil (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ByteArrayUtil

+
+
java.lang.Object +
org.apache.datasketches.common.ByteArrayUtil
+
+
+
+
+
public final class ByteArrayUtil +extends Object
+
Useful methods for byte arrays.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    No argument constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static void
    +
    copyBytes(byte[] source, + int srcStart, + byte[] target, + int tgtStart, + int numBytes)
    +
    +
    Copies bytes from source to target with offsets on both the source and target.
    +
    +
    static double
    +
    getDoubleBE(byte[] array, + int offset)
    +
    +
    Get a double from the given byte array starting at the given offset +in big endian order.
    +
    +
    static double
    +
    getDoubleLE(byte[] array, + int offset)
    +
    +
    Get a double from the given byte array starting at the given offset +in little endian order.
    +
    +
    static float
    +
    getFloatBE(byte[] array, + int offset)
    +
    +
    Get a float from the given byte array starting at the given offset +in big endian order.
    +
    +
    static float
    +
    getFloatLE(byte[] array, + int offset)
    +
    +
    Get a float from the given byte array starting at the given offset +in little endian order.
    +
    +
    static int
    +
    getIntBE(byte[] array, + int offset)
    +
    +
    Get a int from the given byte array starting at the given offset +in big endian order.
    +
    +
    static int
    +
    getIntLE(byte[] array, + int offset)
    +
    +
    Get a int from the given byte array starting at the given offset +in little endian order.
    +
    +
    static long
    +
    getLongBE(byte[] array, + int offset)
    +
    +
    Get a long from the source byte array starting at the given offset +in big endian order.
    +
    +
    static long
    +
    getLongLE(byte[] array, + int offset)
    +
    +
    Get a long from the given byte array starting at the given offset +in little endian order.
    +
    +
    static short
    +
    getShortBE(byte[] array, + int offset)
    +
    +
    Get a short from the given byte array starting at the given offset +in big endian order.
    +
    +
    static short
    +
    getShortLE(byte[] array, + int offset)
    +
    +
    Get a short from the given byte array starting at the given offset +in little endian order.
    +
    +
    static void
    +
    putDoubleBE(byte[] array, + int offset, + double value)
    +
    +
    Put the source double into the destination byte array starting at the given offset +in big endian order.
    +
    +
    static void
    +
    putDoubleLE(byte[] array, + int offset, + double value)
    +
    +
    Put the source double into the destination byte array starting at the given offset +in little endian order.
    +
    +
    static void
    +
    putFloatBE(byte[] array, + int offset, + float value)
    +
    +
    Put the source float into the destination byte array starting at the given offset +in big endian order.
    +
    +
    static void
    +
    putFloatLE(byte[] array, + int offset, + float value)
    +
    +
    Put the source float into the destination byte array starting at the given offset +in little endian order.
    +
    +
    static void
    +
    putIntBE(byte[] array, + int offset, + int value)
    +
    +
    Put the source int into the destination byte array starting at the given offset +in big endian order.
    +
    +
    static void
    +
    putIntLE(byte[] array, + int offset, + int value)
    +
    +
    Put the source int into the destination byte array starting at the given offset +in little endian order.
    +
    +
    static void
    +
    putLongBE(byte[] array, + int offset, + long value)
    +
    +
    Put the source long into the destination byte array starting at the given offset +in big endian order.
    +
    +
    static void
    +
    putLongLE(byte[] array, + int offset, + long value)
    +
    +
    Put the source long into the destination byte array starting at the given offset +in little endian order.
    +
    +
    static void
    +
    putShortBE(byte[] array, + int offset, + short value)
    +
    +
    Put the source short into the destination byte array starting at the given offset +in big endian order.
    +
    +
    static void
    +
    putShortLE(byte[] array, + int offset, + short value)
    +
    +
    Put the source short into the destination byte array starting at the given offset +in little endian order.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ByteArrayUtil

      +
      +
      public ByteArrayUtil()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      copyBytes

      +
      +
      public static void copyBytes(byte[] source, + int srcStart, + byte[] target, + int tgtStart, + int numBytes)
      +
      Copies bytes from source to target with offsets on both the source and target.
      +
      +
      Parameters:
      +
      source - the given source
      +
      srcStart - the source starting index
      +
      target - the give target
      +
      tgtStart - the target starting index
      +
      numBytes - the number of bytes to be transferred.
      +
      +
      +
      +
    • +
    • +
      +

      getShortLE

      +
      +
      public static short getShortLE(byte[] array, + int offset)
      +
      Get a short from the given byte array starting at the given offset +in little endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - source byte array
      +
      offset - source offset
      +
      Returns:
      +
      the short
      +
      +
      +
      +
    • +
    • +
      +

      putShortLE

      +
      +
      public static void putShortLE(byte[] array, + int offset, + short value)
      +
      Put the source short into the destination byte array starting at the given offset +in little endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - destination byte array
      +
      offset - destination offset
      +
      value - source short
      +
      +
      +
      +
    • +
    • +
      +

      getShortBE

      +
      +
      public static short getShortBE(byte[] array, + int offset)
      +
      Get a short from the given byte array starting at the given offset +in big endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - source byte array
      +
      offset - source offset
      +
      Returns:
      +
      the short
      +
      +
      +
      +
    • +
    • +
      +

      putShortBE

      +
      +
      public static void putShortBE(byte[] array, + int offset, + short value)
      +
      Put the source short into the destination byte array starting at the given offset +in big endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - destination byte array
      +
      offset - destination offset
      +
      value - source short
      +
      +
      +
      +
    • +
    • +
      +

      getIntLE

      +
      +
      public static int getIntLE(byte[] array, + int offset)
      +
      Get a int from the given byte array starting at the given offset +in little endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - source byte array
      +
      offset - source offset
      +
      Returns:
      +
      the int
      +
      +
      +
      +
    • +
    • +
      +

      putIntLE

      +
      +
      public static void putIntLE(byte[] array, + int offset, + int value)
      +
      Put the source int into the destination byte array starting at the given offset +in little endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - destination byte array
      +
      offset - destination offset
      +
      value - source int
      +
      +
      +
      +
    • +
    • +
      +

      getIntBE

      +
      +
      public static int getIntBE(byte[] array, + int offset)
      +
      Get a int from the given byte array starting at the given offset +in big endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - source byte array
      +
      offset - source offset
      +
      Returns:
      +
      the int
      +
      +
      +
      +
    • +
    • +
      +

      putIntBE

      +
      +
      public static void putIntBE(byte[] array, + int offset, + int value)
      +
      Put the source int into the destination byte array starting at the given offset +in big endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - destination byte array
      +
      offset - destination offset
      +
      value - source int
      +
      +
      +
      +
    • +
    • +
      +

      getLongLE

      +
      +
      public static long getLongLE(byte[] array, + int offset)
      +
      Get a long from the given byte array starting at the given offset +in little endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - source byte array
      +
      offset - source offset
      +
      Returns:
      +
      the long
      +
      +
      +
      +
    • +
    • +
      +

      putLongLE

      +
      +
      public static void putLongLE(byte[] array, + int offset, + long value)
      +
      Put the source long into the destination byte array starting at the given offset +in little endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - destination byte array
      +
      offset - destination offset
      +
      value - source long
      +
      +
      +
      +
    • +
    • +
      +

      getLongBE

      +
      +
      public static long getLongBE(byte[] array, + int offset)
      +
      Get a long from the source byte array starting at the given offset +in big endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - source byte array
      +
      offset - source starting point
      +
      Returns:
      +
      the long
      +
      +
      +
      +
    • +
    • +
      +

      putLongBE

      +
      +
      public static void putLongBE(byte[] array, + int offset, + long value)
      +
      Put the source long into the destination byte array starting at the given offset +in big endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - destination byte array
      +
      offset - destination starting point
      +
      value - source long
      +
      +
      +
      +
    • +
    • +
      +

      getFloatLE

      +
      +
      public static float getFloatLE(byte[] array, + int offset)
      +
      Get a float from the given byte array starting at the given offset +in little endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - source byte array
      +
      offset - source offset
      +
      Returns:
      +
      the float
      +
      +
      +
      +
    • +
    • +
      +

      putFloatLE

      +
      +
      public static void putFloatLE(byte[] array, + int offset, + float value)
      +
      Put the source float into the destination byte array starting at the given offset +in little endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - destination byte array
      +
      offset - destination offset
      +
      value - source float
      +
      +
      +
      +
    • +
    • +
      +

      getFloatBE

      +
      +
      public static float getFloatBE(byte[] array, + int offset)
      +
      Get a float from the given byte array starting at the given offset +in big endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - source byte array
      +
      offset - source offset
      +
      Returns:
      +
      the float
      +
      +
      +
      +
    • +
    • +
      +

      putFloatBE

      +
      +
      public static void putFloatBE(byte[] array, + int offset, + float value)
      +
      Put the source float into the destination byte array starting at the given offset +in big endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - destination byte array
      +
      offset - destination offset
      +
      value - source float
      +
      +
      +
      +
    • +
    • +
      +

      getDoubleLE

      +
      +
      public static double getDoubleLE(byte[] array, + int offset)
      +
      Get a double from the given byte array starting at the given offset +in little endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - source byte array
      +
      offset - source offset
      +
      Returns:
      +
      the double
      +
      +
      +
      +
    • +
    • +
      +

      putDoubleLE

      +
      +
      public static void putDoubleLE(byte[] array, + int offset, + double value)
      +
      Put the source double into the destination byte array starting at the given offset +in little endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - destination byte array
      +
      offset - destination offset
      +
      value - source double
      +
      +
      +
      +
    • +
    • +
      +

      getDoubleBE

      +
      +
      public static double getDoubleBE(byte[] array, + int offset)
      +
      Get a double from the given byte array starting at the given offset +in big endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - source byte array
      +
      offset - source offset
      +
      Returns:
      +
      the double
      +
      +
      +
      +
    • +
    • +
      +

      putDoubleBE

      +
      +
      public static void putDoubleBE(byte[] array, + int offset, + double value)
      +
      Put the source double into the destination byte array starting at the given offset +in big endian order. +There is no bounds checking.
      +
      +
      Parameters:
      +
      array - destination byte array
      +
      offset - destination offset
      +
      value - source double
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/Family.html b/target/site/apidocs/org/apache/datasketches/common/Family.html new file mode 100644 index 000000000..3737dbdb5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/Family.html @@ -0,0 +1,701 @@ + + + + +Family (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class Family

+
+
java.lang.Object +
java.lang.Enum<Family> +
org.apache.datasketches.common.Family
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<Family>, Constable
+
+
+
+
public enum Family +extends Enum<Family>
+
Defines the various families of sketch and set operation classes. A family defines a set of +classes that share fundamental algorithms and behaviors. The classes within a family may +still differ by how they are stored and accessed. For example, internally there are separate +classes for the QuickSelect sketch algorithm that operate on the Java heap and off-heap. +Not all of these families have parallel forms on and off-heap but are included for completeness.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Nested Class Summary

    +
    +

    Nested classes/interfaces inherited from class Enum

    +Enum.EnumDesc<E>
    +
    +
  • + +
  • +
    +

    Enum Constant Summary

    +
    Enum Constants
    +
    +
    Enum Constant
    +
    Description
    + +
    +
    The A and not B family is an operation for the Theta Sketch Framework of sketches.
    +
    + +
    +
    The Alpha Sketch family is a member of the Theta Sketch Framework of sketches and is best +suited for real-time processes where both the updating of the sketch and getting the estimate +is performed directly on the sketch.
    +
    + +
    +
    Bloom Filter
    +
    + +
    +
    The Compact Sketch family is a member of the Theta Sketch Framework of sketches.
    +
    + +
    +
    CountMin Sketch
    +
    + +
    +
    Compressed Probabilistic Counting (CPC) Sketch
    +
    + +
    +
    Exact and Bounded, Probability Proportional to Size (EBPPS)
    +
    + +
    +
    The Frequency family of sketches.
    +
    + +
    +
    The HLL family of sketches.
    +
    + +
    +
    The Intersection family is an operation for the Theta Sketch Framework of sketches.
    +
    + +
    +
    KLL quantiles sketch
    +
    + +
    +
    The Quantiles family of sketches.
    +
    + +
    +
    The QuickSelect Sketch family is a member of the Theta Sketch Framework of sketches and +is the workhorse of the Theta Sketch Families and can be constructed for either on-heap or +off-heap operation.
    +
    + +
    +
    Relative Error Quantiles Sketch
    +
    + +
    +
    The Reservoir family of sketches.
    +
    + +
    +
    The reservoir sampling family of Union operations.
    +
    + +
    +
    t-Digest for estimating quantiles and ranks
    +
    + +
    +
    The Tuple family of sketches is a large family of sketches that are extensions of the +Theta Sketch Framework.
    +
    + +
    +
    The Union family is an operation for the Theta Sketch Framework of sketches.
    +
    + +
    +
    The VarOpt family of sketches.
    +
    + +
    +
    The VarOpt family of sketches.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    void
    +
    checkFamilyID(int id)
    +
    +
    Checks the given Family ID
    +
    + + +
    +
    Returns the name for this family
    +
    +
    int
    + +
    +
    Returns the byte ID for this family
    +
    +
    int
    + +
    +
    Returns the maximum preamble size for this family in longs
    +
    +
    int
    + +
    +
    Returns the minimum preamble size for this family in longs
    +
    +
    static Family
    +
    idToFamily(int id)
    +
    +
    Returns the Family given the ID
    +
    +
    static Family
    + +
    +
    Returns the Family given the family name
    +
    + + +
     
    +
    static Family
    + +
    +
    Returns the enum constant of this class with the specified name.
    +
    +
    static Family[]
    + +
    +
    Returns an array containing the constants of this enum class, in +the order they are declared.
    +
    +
    +
    +
    + +
    +

    Methods inherited from class Object

    +getClass, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Enum Constant Details

    +
      +
    • +
      +

      ALPHA

      +
      +
      public static final Family ALPHA
      +
      The Alpha Sketch family is a member of the Theta Sketch Framework of sketches and is best +suited for real-time processes where both the updating of the sketch and getting the estimate +is performed directly on the sketch. In this situation the AlphaSketch has roughly a +30% improvement (~1/sqrt(2*k)) in its error distribution as compared to the QuickSelect +(or similar KMV-derived) sketches. + +

      If the AlphaSketch is fed into any ThetaSetOperation, the error distribution reverts back to the +normal QuickSelect/KMV error distribution (~1/sqrt(k)). For this reason, the AlphaSketch +does not have a sister class for off-heap operation. The AlphaSketch has a roughly 30% faster +overall update time as compared to the QuickSelect sketch family.

      + +

      The AlphaSketch is created using the UpdatableThetaSketchBuilder(). +See Alpha TCF and +Theta Sketch Framework

      +
      +
      +
    • +
    • +
      +

      QUICKSELECT

      +
      +
      public static final Family QUICKSELECT
      +
      The QuickSelect Sketch family is a member of the Theta Sketch Framework of sketches and +is the workhorse of the Theta Sketch Families and can be constructed for either on-heap or +off-heap operation. +The QuickSelect Sketch is created using the UpdatableThetaSketchBuilder(). +See Quick Select TCF
      +
      +
      +
    • +
    • +
      +

      COMPACT

      +
      +
      public static final Family COMPACT
      +
      The Compact Sketch family is a member of the Theta Sketch Framework of sketches. +They are read-only and cannot be updated, but can participate in any of the Set Operations. +The compact sketches are never created directly with a constructor or builder. +Instead they are created as a result of the compact() +method of an UpdatableThetaSketch or as a result of a getSketchSamples() of a ThetaSetOperation.
      +
      +
      +
    • +
    • +
      +

      UNION

      +
      +
      public static final Family UNION
      +
      The Union family is an operation for the Theta Sketch Framework of sketches. +The Union is constructed using the ThetaSetOperationBuilder().
      +
      +
      +
    • +
    • +
      +

      INTERSECTION

      +
      +
      public static final Family INTERSECTION
      +
      The Intersection family is an operation for the Theta Sketch Framework of sketches. +The ThetaIntersection is constructed using the ThetaSetOperationBuilder().
      +
      +
      +
    • +
    • +
      +

      A_NOT_B

      +
      +
      public static final Family A_NOT_B
      +
      The A and not B family is an operation for the Theta Sketch Framework of sketches. +The ThetaAnotB operation is constructed using the ThetaSetOperationBuilder().
      +
      +
      +
    • +
    • +
      +

      HLL

      +
      +
      public static final Family HLL
      +
      The HLL family of sketches. (Not part of TSF.)
      +
      +
      +
    • +
    • +
      +

      QUANTILES

      +
      +
      public static final Family QUANTILES
      +
      The Quantiles family of sketches. (Not part of TSF.)
      +
      +
      +
    • +
    • +
      +

      TUPLE

      +
      +
      public static final Family TUPLE
      +
      The Tuple family of sketches is a large family of sketches that are extensions of the +Theta Sketch Framework.
      +
      +
      +
    • +
    • +
      +

      FREQUENCY

      +
      +
      public static final Family FREQUENCY
      +
      The Frequency family of sketches. (Not part of TSF.)
      +
      +
      +
    • +
    • +
      +

      RESERVOIR

      +
      +
      public static final Family RESERVOIR
      +
      The Reservoir family of sketches. (Not part of TSF.)
      +
      +
      +
    • +
    • +
      +

      RESERVOIR_UNION

      +
      +
      public static final Family RESERVOIR_UNION
      +
      The reservoir sampling family of Union operations. (Not part of TSF.)
      +
      +
      +
    • +
    • +
      +

      VAROPT

      +
      +
      public static final Family VAROPT
      +
      The VarOpt family of sketches. (Not part of TSF.)
      +
      +
      +
    • +
    • +
      +

      VAROPT_UNION

      +
      +
      public static final Family VAROPT_UNION
      +
      The VarOpt family of sketches. (Not part of TSF.)
      +
      +
      +
    • +
    • +
      +

      KLL

      +
      +
      public static final Family KLL
      +
      KLL quantiles sketch
      +
      +
      +
    • +
    • +
      +

      CPC

      +
      +
      public static final Family CPC
      +
      Compressed Probabilistic Counting (CPC) Sketch
      +
      +
      +
    • +
    • +
      +

      REQ

      +
      +
      public static final Family REQ
      +
      Relative Error Quantiles Sketch
      +
      +
      +
    • +
    • +
      +

      COUNTMIN

      +
      +
      public static final Family COUNTMIN
      +
      CountMin Sketch
      +
      +
      +
    • +
    • +
      +

      EBPPS

      +
      +
      public static final Family EBPPS
      +
      Exact and Bounded, Probability Proportional to Size (EBPPS)
      +
      +
      +
    • +
    • +
      +

      TDIGEST

      +
      +
      public static final Family TDIGEST
      +
      t-Digest for estimating quantiles and ranks
      +
      +
      +
    • +
    • +
      +

      BLOOMFILTER

      +
      +
      public static final Family BLOOMFILTER
      +
      Bloom Filter
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static Family[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static Family valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    • +
      +

      getID

      +
      +
      public int getID()
      +
      Returns the byte ID for this family
      +
      +
      Returns:
      +
      the byte ID for this family
      +
      +
      +
      +
    • +
    • +
      +

      checkFamilyID

      +
      +
      public void checkFamilyID(int id)
      +
      Checks the given Family ID
      +
      +
      Parameters:
      +
      id - the given id, a value < 128.
      +
      +
      +
      +
    • +
    • +
      +

      getFamilyName

      +
      +
      public String getFamilyName()
      +
      Returns the name for this family
      +
      +
      Returns:
      +
      the name for this family
      +
      +
      +
      +
    • +
    • +
      +

      getMinPreLongs

      +
      +
      public int getMinPreLongs()
      +
      Returns the minimum preamble size for this family in longs
      +
      +
      Returns:
      +
      the minimum preamble size for this family in longs
      +
      +
      +
      +
    • +
    • +
      +

      getMaxPreLongs

      +
      +
      public int getMaxPreLongs()
      +
      Returns the maximum preamble size for this family in longs
      +
      +
      Returns:
      +
      the maximum preamble size for this family in longs
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      +
      Overrides:
      +
      toString in class Enum<Family>
      +
      +
      +
      +
    • +
    • +
      +

      idToFamily

      +
      +
      public static Family idToFamily(int id)
      +
      Returns the Family given the ID
      +
      +
      Parameters:
      +
      id - the given ID
      +
      Returns:
      +
      the Family given the ID
      +
      +
      +
      +
    • +
    • +
      +

      stringToFamily

      +
      +
      public static Family stringToFamily(String famName)
      +
      Returns the Family given the family name
      +
      +
      Parameters:
      +
      famName - the family name
      +
      Returns:
      +
      the Family given the family name
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/MemorySegmentRequest.Default.html b/target/site/apidocs/org/apache/datasketches/common/MemorySegmentRequest.Default.html new file mode 100644 index 000000000..a4c576f21 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/MemorySegmentRequest.Default.html @@ -0,0 +1,178 @@ + + + + +MemorySegmentRequest.Default (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class MemorySegmentRequest.Default

+
+
java.lang.Object +
org.apache.datasketches.common.MemorySegmentRequest.Default
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentRequest
+
+
+
Enclosing interface:
+
MemorySegmentRequest
+
+
+
+
public static class MemorySegmentRequest.Default +extends Object +implements MemorySegmentRequest
+
A convenience class that implements a default implementation.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      Default

      +
      +
      public Default()
      +
      No argument constructor that creates the target for the static member DEFAULT.
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/MemorySegmentRequest.html b/target/site/apidocs/org/apache/datasketches/common/MemorySegmentRequest.html new file mode 100644 index 000000000..9de5be7a7 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/MemorySegmentRequest.html @@ -0,0 +1,228 @@ + + + + +MemorySegmentRequest (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface MemorySegmentRequest

+
+
+
+
All Known Implementing Classes:
+
MemorySegmentRequest.Default, MemorySegmentRequestExample
+
+
+
+
public interface MemorySegmentRequest
+
This is a callback interface to provide a means to request a new MemorySegment of a specified size.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Nested Class Summary

    +
    Nested Classes
    +
    +
    Modifier and Type
    +
    Interface
    +
    Description
    +
    static class 
    + +
    +
    A convenience class that implements a default implementation.
    +
    +
    +
    +
  • + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    + + +
    +
    Create Default as static member.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + +
    request(long newByteSize)
    +
    +
    Request a new heap MemorySegment with the given newByteSize.
    +
    +
    default void
    + +
    +
    Request to close the given MemorySegment.
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    + +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      request

      +
      +
      default MemorySegment request(long newByteSize)
      +
      Request a new heap MemorySegment with the given newByteSize. +Because we do not have a reference to an Arena, the default here is to +allocate a new MemorySegment on the heap. It is up to the user to override this as appropriate.
      +
      +
      Parameters:
      +
      newByteSize - The new byteSize being requested.
      +
      Returns:
      +
      new MemorySegment with the requested byteSize.
      +
      +
      +
      +
    • +
    • +
      +

      requestClose

      +
      +
      default void requestClose(MemorySegment prevSeg)
      +
      Request to close the given MemorySegment. +Because we do not have a reference to an Arena, the default here is to do nothing. +It is up to the user to override this as appropriate.
      +
      +
      Parameters:
      +
      prevSeg - the previous MemorySegment to be closed.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/MemorySegmentRequestExample.html b/target/site/apidocs/org/apache/datasketches/common/MemorySegmentRequestExample.html new file mode 100644 index 000000000..97d3da416 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/MemorySegmentRequestExample.html @@ -0,0 +1,255 @@ + + + + +MemorySegmentRequestExample (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class MemorySegmentRequestExample

+
+
java.lang.Object +
org.apache.datasketches.common.MemorySegmentRequestExample
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentRequest
+
+
+
+
public final class MemorySegmentRequestExample +extends Object +implements MemorySegmentRequest
+
This is an example of a possible implementation of the MemorySegmentRequest interface +where all requested segments are allocated off-heap. A local ConcurrentHashMap tracks a newly created +confined Arena for every new MemorySegment allocated off-heap. This allows individual segments to be freed +immediately upon receiving the requestClose(MemorySegment) call.
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      MemorySegmentRequestExample

      +
      +
      public MemorySegmentRequestExample()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      request

      +
      +
      public MemorySegment request(long newByteSize)
      +
      Request a new off-heap MemorySegment with the given newByteSeze. +An internal confined Arena is created to exclusively manage the new segment and it is associated +with the new segment with a ConcurrentHashMap.
      +
      +
      Specified by:
      +
      request in interface MemorySegmentRequest
      +
      Parameters:
      +
      newByteSize - The new byteSize being requested.
      +
      Returns:
      +
      new MemorySegment with the requested byteSize.
      +
      +
      +
      +
    • +
    • +
      +

      requestClose

      +
      +
      public void requestClose(MemorySegment segKey)
      +
      Description copied from interface: MemorySegmentRequest
      +
      Request to close the given MemorySegment. +Because we do not have a reference to an Arena, the default here is to do nothing. +It is up to the user to override this as appropriate.
      +
      +
      Specified by:
      +
      requestClose in interface MemorySegmentRequest
      +
      Parameters:
      +
      segKey - the previous MemorySegment to be closed.
      +
      +
      +
      +
    • +
    • +
      +

      cleanup

      +
      +
      public void cleanup()
      +
      This closes any unclosed, off-heap MemorySegments and removes all mappings from the map.
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/MemorySegmentStatus.html b/target/site/apidocs/org/apache/datasketches/common/MemorySegmentStatus.html new file mode 100644 index 000000000..5e1079191 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/MemorySegmentStatus.html @@ -0,0 +1,219 @@ + + + + +MemorySegmentStatus (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface MemorySegmentStatus

+
+
+
+
All Known Implementing Classes:
+
BloomFilter, CompactQuantilesDoublesSketch, CompactThetaSketch, DirectBitArrayR, HllSketch, HllUnion, KllDoublesSketch, KllFloatsSketch, KllItemsSketch, KllLongsSketch, KllSketch, QuantilesDoublesSketch, QuantilesDoublesUnion, ThetaAnotB, ThetaIntersection, ThetaSetOperation, ThetaSketch, ThetaUnion, UpdatableQuantilesDoublesSketch, UpdatableThetaSketch
+
+
+
+
public interface MemorySegmentStatus
+
Methods for inquiring the status of a backing MemorySegment.
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    boolean
    + +
    +
    Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
    +
    +
    boolean
    + +
    +
    Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
    +
    +
    boolean
    + +
    +
    Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap.
    +
    +
    static boolean
    + +
    +
    Returns true if the two given MemorySegments have to the same backing resource, or equivalently, +if the two memory regions overlap.
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      hasMemorySegment

      +
      +
      boolean hasMemorySegment()
      +
      Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
      +
      +
      Returns:
      +
      true if this object's internal data is backed by a MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isOffHeap

      +
      +
      boolean isOffHeap()
      +
      Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      Returns:
      +
      true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isSameResource

      +
      +
      boolean isSameResource(MemorySegment that)
      +
      Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap. This applies to both on-heap and off-heap MemorySegments. + +

      Note: If both segments are on-heap and not read-only, it can be determined if they were derived from +the same backing memory (array). However, this is not always possible off-heap. Because of this asymmetry, this definition +of "isSameResource" is confined to the existence of an overlap.

      +
      +
      Parameters:
      +
      that - The given MemorySegment.
      +
      Returns:
      +
      true if an internally referenced MemorySegment has the same backing resource as that.
      +
      +
      +
      +
    • +
    • +
      +

      isSameResource

      +
      +
      static boolean isSameResource(MemorySegment seg1, + MemorySegment seg2)
      +
      Returns true if the two given MemorySegments have to the same backing resource, or equivalently, +if the two memory regions overlap. This applies to both on-heap and off-heap MemorySegments. + +

      Note: If both segments are on-heap and not read-only, it can be determined if they were derived from +the same backing memory (array). However, this is not always possible off-heap. Because of this asymmetry, this definition +of "isSameResource" is confined to the existence of an overlap.

      +
      +
      Parameters:
      +
      seg1 - The first given MemorySegment
      +
      seg2 - The second given MemorySegment
      +
      Returns:
      +
      true if the two given MemorySegments have to the same backing resource.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/QuickSelect.html b/target/site/apidocs/org/apache/datasketches/common/QuickSelect.html new file mode 100644 index 000000000..a3e222051 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/QuickSelect.html @@ -0,0 +1,318 @@ + + + + +QuickSelect (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class QuickSelect

+
+
java.lang.Object +
org.apache.datasketches.common.QuickSelect
+
+
+
+
+
public final class QuickSelect +extends Object
+
QuickSelect algorithm improved from Sedgewick. Gets the kth order value +(1-based or 0-based) from the array. +Warning! This changes the ordering of elements in the given array!
+Also see:
+blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html
+See QuickSelectTest for examples and testNG tests.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static double
    +
    select(double[] arr, + int lo, + int hi, + int pivot)
    +
    +
    Gets the 0-based kth order statistic from the array.
    +
    +
    static long
    +
    select(long[] arr, + int lo, + int hi, + int pivot)
    +
    +
    Gets the 0-based kth order statistic from the array.
    +
    +
    static double
    +
    selectExcludingZeros(double[] arr, + int nonZeros, + int pivot)
    +
    +
    Gets the 1-based kth order statistic from the array excluding any zero values in the +array.
    +
    +
    static long
    +
    selectExcludingZeros(long[] arr, + int nonZeros, + int pivot)
    +
    +
    Gets the 1-based kth order statistic from the array excluding any zero values in the +array.
    +
    +
    static double
    +
    selectIncludingZeros(double[] arr, + int pivot)
    +
    +
    Gets the 1-based kth order statistic from the array including any zero values in the +array.
    +
    +
    static long
    +
    selectIncludingZeros(long[] arr, + int pivot)
    +
    +
    Gets the 1-based kth order statistic from the array including any zero values in the +array.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      select

      +
      +
      public static long select(long[] arr, + int lo, + int hi, + int pivot)
      +
      Gets the 0-based kth order statistic from the array. Warning! This changes the ordering +of elements in the given array!
      +
      +
      Parameters:
      +
      arr - The array to be re-arranged.
      +
      lo - The lowest 0-based index to be considered.
      +
      hi - The highest 0-based index to be considered.
      +
      pivot - The 0-based index of the value to pivot on.
      +
      Returns:
      +
      The value of the smallest (n)th element where n is 0-based.
      +
      +
      +
      +
    • +
    • +
      +

      selectIncludingZeros

      +
      +
      public static long selectIncludingZeros(long[] arr, + int pivot)
      +
      Gets the 1-based kth order statistic from the array including any zero values in the +array. Warning! This changes the ordering of elements in the given array!
      +
      +
      Parameters:
      +
      arr - The hash array.
      +
      pivot - The 1-based index of the value that is chosen as the pivot for the array. +After the operation all values below this 1-based index will be less than this value +and all values above this index will be greater. The 0-based index of the pivot will be +pivot-1.
      +
      Returns:
      +
      The value of the smallest (N)th element including zeros, where N is 1-based.
      +
      +
      +
      +
    • +
    • +
      +

      selectExcludingZeros

      +
      +
      public static long selectExcludingZeros(long[] arr, + int nonZeros, + int pivot)
      +
      Gets the 1-based kth order statistic from the array excluding any zero values in the +array. Warning! This changes the ordering of elements in the given array!
      +
      +
      Parameters:
      +
      arr - The hash array.
      +
      nonZeros - The number of non-zero values in the array.
      +
      pivot - The 1-based index of the value that is chosen as the pivot for the array. +After the operation all values below this 1-based index will be less than this value +and all values above this index will be greater. The 0-based index of the pivot will be +pivot+arr.length-nonZeros-1.
      +
      Returns:
      +
      The value of the smallest (N)th element excluding zeros, where N is 1-based.
      +
      +
      +
      +
    • +
    • +
      +

      select

      +
      +
      public static double select(double[] arr, + int lo, + int hi, + int pivot)
      +
      Gets the 0-based kth order statistic from the array. Warning! This changes the ordering +of elements in the given array!
      +
      +
      Parameters:
      +
      arr - The array to be re-arranged.
      +
      lo - The lowest 0-based index to be considered.
      +
      hi - The highest 0-based index to be considered.
      +
      pivot - The 0-based smallest value to pivot on.
      +
      Returns:
      +
      The value of the smallest (n)th element where n is 0-based.
      +
      +
      +
      +
    • +
    • +
      +

      selectIncludingZeros

      +
      +
      public static double selectIncludingZeros(double[] arr, + int pivot)
      +
      Gets the 1-based kth order statistic from the array including any zero values in the +array. Warning! This changes the ordering of elements in the given array!
      +
      +
      Parameters:
      +
      arr - The hash array.
      +
      pivot - The 1-based index of the value that is chosen as the pivot for the array. +After the operation all values below this 1-based index will be less than this value +and all values above this index will be greater. The 0-based index of the pivot will be +pivot-1.
      +
      Returns:
      +
      The value of the smallest (N)th element including zeros, where N is 1-based.
      +
      +
      +
      +
    • +
    • +
      +

      selectExcludingZeros

      +
      +
      public static double selectExcludingZeros(double[] arr, + int nonZeros, + int pivot)
      +
      Gets the 1-based kth order statistic from the array excluding any zero values in the +array. Warning! This changes the ordering of elements in the given array!
      +
      +
      Parameters:
      +
      arr - The hash array.
      +
      nonZeros - The number of non-zero values in the array.
      +
      pivot - The 1-based index of the value that is chosen as the pivot for the array. +After the operation all values below this 1-based index will be less than this value +and all values above this index will be greater. The 0-based index of the pivot will be +pivot+arr.length-nonZeros-1.
      +
      Returns:
      +
      The value of the smallest (N)th element excluding zeros, where N is 1-based.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/ResizeFactor.html b/target/site/apidocs/org/apache/datasketches/common/ResizeFactor.html new file mode 100644 index 000000000..b5c117cb1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/ResizeFactor.html @@ -0,0 +1,337 @@ + + + + +ResizeFactor (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class ResizeFactor

+
+
java.lang.Object +
java.lang.Enum<ResizeFactor> +
org.apache.datasketches.common.ResizeFactor
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<ResizeFactor>, Constable
+
+
+
+
public enum ResizeFactor +extends Enum<ResizeFactor>
+
For the Families that accept this configuration parameter, it controls the size multiple that +affects how fast the internal cache grows, when more space is required. +See Resize Factor
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Nested Class Summary

    +
    +

    Nested classes/interfaces inherited from class Enum

    +Enum.EnumDesc<E>
    +
    +
  • + +
  • +
    +

    Enum Constant Summary

    +
    Enum Constants
    +
    +
    Enum Constant
    +
    Description
    + +
    +
    Do not resize.
    +
    + +
    +
    Resize factor is 2.
    +
    + +
    +
    Resize factor is 4.
    +
    + +
    +
    Resize factor is 8.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + +
    getRF(int lg)
    +
    +
    Returns the Resize Factor given the Log-base 2 of the Resize Factor
    +
    +
    int
    + +
    +
    Returns the Resize Factor
    +
    +
    int
    +
    lg()
    +
    +
    Returns the Log-base 2 of the Resize Factor
    +
    + + +
    +
    Returns the enum constant of this class with the specified name.
    +
    +
    static ResizeFactor[]
    + +
    +
    Returns an array containing the constants of this enum class, in +the order they are declared.
    +
    +
    +
    +
    + +
    +

    Methods inherited from class Object

    +getClass, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Enum Constant Details

    +
      +
    • +
      +

      X1

      +
      +
      public static final ResizeFactor X1
      +
      Do not resize. Sketch will be configured to full size.
      +
      +
      +
    • +
    • +
      +

      X2

      +
      +
      public static final ResizeFactor X2
      +
      Resize factor is 2.
      +
      +
      +
    • +
    • +
      +

      X4

      +
      +
      public static final ResizeFactor X4
      +
      Resize factor is 4.
      +
      +
      +
    • +
    • +
      +

      X8

      +
      +
      public static final ResizeFactor X8
      +
      Resize factor is 8.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static ResizeFactor[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static ResizeFactor valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    • +
      +

      lg

      +
      +
      public int lg()
      +
      Returns the Log-base 2 of the Resize Factor
      +
      +
      Returns:
      +
      the Log-base 2 of the Resize Factor
      +
      +
      +
      +
    • +
    • +
      +

      getRF

      +
      +
      public static ResizeFactor getRF(int lg)
      +
      Returns the Resize Factor given the Log-base 2 of the Resize Factor
      +
      +
      Parameters:
      +
      lg - a value between zero and 3, inclusive.
      +
      Returns:
      +
      the Resize Factor given the Log-base 2 of the Resize Factor
      +
      +
      +
      +
    • +
    • +
      +

      getValue

      +
      +
      public int getValue()
      +
      Returns the Resize Factor
      +
      +
      Returns:
      +
      the Resize Factor
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/SketchesArgumentException.html b/target/site/apidocs/org/apache/datasketches/common/SketchesArgumentException.html new file mode 100644 index 000000000..522eb3285 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/SketchesArgumentException.html @@ -0,0 +1,173 @@ + + + + +SketchesArgumentException (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class SketchesArgumentException

+
+ +
+
+
All Implemented Interfaces:
+
Serializable
+
+
+
+
public class SketchesArgumentException +extends SketchesException
+
Illegal Arguments Exception class for the library
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      SketchesArgumentException

      +
      +
      public SketchesArgumentException(String message)
      +
      Constructs a new runtime exception with the specified detail message. The cause is not +initialized, and may subsequently be initialized by a call to +Throwable.initCause(java.lang.Throwable).
      +
      +
      Parameters:
      +
      message - the detail message. The detail message is saved for later retrieval by the +Throwable.getMessage() method.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/SketchesException.html b/target/site/apidocs/org/apache/datasketches/common/SketchesException.html new file mode 100644 index 000000000..50601c1ce --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/SketchesException.html @@ -0,0 +1,201 @@ + + + + +SketchesException (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class SketchesException

+
+
java.lang.Object +
java.lang.Throwable +
java.lang.Exception +
java.lang.RuntimeException +
org.apache.datasketches.common.SketchesException
+
+
+
+
+
+
+
All Implemented Interfaces:
+
Serializable
+
+
+
Direct Known Subclasses:
+
SketchesArgumentException, SketchesNotSupportedException, SketchesReadOnlyException, SketchesStateException
+
+
+
+
public class SketchesException +extends RuntimeException
+
Exception class for the library
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      SketchesException

      +
      +
      public SketchesException(String message)
      +
      Constructs a new runtime exception with the specified detail message. The cause is not +initialized, and may subsequently be initialized by a call to +Throwable.initCause(java.lang.Throwable).
      +
      +
      Parameters:
      +
      message - the detail message. The detail message is saved for later retrieval by the +Throwable.getMessage() method.
      +
      +
      +
      +
    • +
    • +
      +

      SketchesException

      +
      +
      public SketchesException(String message, + Throwable cause)
      +
      Constructs a new runtime exception with the specified detail message and cause. + +

      Note that the detail message associated with cause is not automatically incorporated +in this runtime exception's detail message.

      +
      +
      Parameters:
      +
      message - the detail message (which is saved for later retrieval by the +Throwable.getMessage() method).
      +
      cause - the cause (which is saved for later retrieval by the Throwable.getCause() +method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/SketchesNotSupportedException.html b/target/site/apidocs/org/apache/datasketches/common/SketchesNotSupportedException.html new file mode 100644 index 000000000..7305fe676 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/SketchesNotSupportedException.html @@ -0,0 +1,175 @@ + + + + +SketchesNotSupportedException (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class SketchesNotSupportedException

+
+ +
+
+
All Implemented Interfaces:
+
Serializable
+
+
+
+
public class SketchesNotSupportedException +extends SketchesException
+
This operation or mode is not supported.
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      SketchesNotSupportedException

      +
      +
      public SketchesNotSupportedException(String message)
      +
      Constructs a new runtime exception with the specified detail message. The cause is not +initialized, and may subsequently be initialized by a call to +Throwable.initCause(java.lang.Throwable).
      +
      +
      Parameters:
      +
      message - the detail message which is appended to the base message:
      +"This operation or mode is not supported: ". + +

      The detail message is saved for later retrieval by the Throwable.getMessage() method.

      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/SketchesReadOnlyException.html b/target/site/apidocs/org/apache/datasketches/common/SketchesReadOnlyException.html new file mode 100644 index 000000000..e9c86e5d1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/SketchesReadOnlyException.html @@ -0,0 +1,192 @@ + + + + +SketchesReadOnlyException (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class SketchesReadOnlyException

+
+ +
+
+
All Implemented Interfaces:
+
Serializable
+
+
+
+
public class SketchesReadOnlyException +extends SketchesException
+
Write operation attempted on a read-only class.
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      SketchesReadOnlyException

      +
      +
      public SketchesReadOnlyException()
      +
      Constructs a new runtime exception with the message: +"Write operation attempted on a read-only class." + +

      The cause is not initialized, and may subsequently be initialized by a call to +Throwable.initCause(java.lang.Throwable).

      +
      +
      +
    • +
    • +
      +

      SketchesReadOnlyException

      +
      +
      public SketchesReadOnlyException(String message)
      +
      Constructs a new runtime exception with the specified detail message. The cause is not +initialized, and may subsequently be initialized by a call to +Throwable.initCause(java.lang.Throwable).
      +
      +
      Parameters:
      +
      message - the detail message. The detail message is saved for later retrieval by the +Throwable.getMessage() method.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/SketchesStateException.html b/target/site/apidocs/org/apache/datasketches/common/SketchesStateException.html new file mode 100644 index 000000000..73934d598 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/SketchesStateException.html @@ -0,0 +1,173 @@ + + + + +SketchesStateException (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class SketchesStateException

+
+ +
+
+
All Implemented Interfaces:
+
Serializable
+
+
+
+
public class SketchesStateException +extends SketchesException
+
Illegal State Exception class for the library
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      SketchesStateException

      +
      +
      public SketchesStateException(String message)
      +
      Constructs a new runtime exception with the specified detail message. The cause is not +initialized, and may subsequently be initialized by a call to +Throwable.initCause(java.lang.Throwable).
      +
      +
      Parameters:
      +
      message - the detail message. The detail message is saved for later retrieval by the +Throwable.getMessage() method.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/SpecialValueLayouts.html b/target/site/apidocs/org/apache/datasketches/common/SpecialValueLayouts.html new file mode 100644 index 000000000..c9fad0534 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/SpecialValueLayouts.html @@ -0,0 +1,323 @@ + + + + +SpecialValueLayouts (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class SpecialValueLayouts

+
+
java.lang.Object +
org.apache.datasketches.common.SpecialValueLayouts
+
+
+
+
+
public final class SpecialValueLayouts +extends Object
+
Value Layouts for Non-native Endianness
+
+
+
+ +
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      NON_NATIVE_BYTE_ORDER

      +
      +
      public static final ByteOrder NON_NATIVE_BYTE_ORDER
      +
      The static final for NON ByteOrder.nativeOrder().
      +
      +
      +
    • +
    • +
      +

      JAVA_CHAR_UNALIGNED_NON_NATIVE

      +
      +
      public static final ValueLayout.OfChar JAVA_CHAR_UNALIGNED_NON_NATIVE
      +
      The static final for NON ByteOrder.nativeOrder() char.
      +
      +
      +
    • +
    • +
      +

      JAVA_DOUBLE_UNALIGNED_NON_NATIVE

      +
      +
      public static final ValueLayout.OfDouble JAVA_DOUBLE_UNALIGNED_NON_NATIVE
      +
      The static final for NON ByteOrder.nativeOrder() double.
      +
      +
      +
    • +
    • +
      +

      JAVA_FLOAT_UNALIGNED_NON_NATIVE

      +
      +
      public static final ValueLayout.OfFloat JAVA_FLOAT_UNALIGNED_NON_NATIVE
      +
      The static final for NON ByteOrder.nativeOrder() float.
      +
      +
      +
    • +
    • +
      +

      JAVA_INT_UNALIGNED_NON_NATIVE

      +
      +
      public static final ValueLayout.OfInt JAVA_INT_UNALIGNED_NON_NATIVE
      +
      The static final for NON ByteOrder.nativeOrder() int.
      +
      +
      +
    • +
    • +
      +

      JAVA_LONG_UNALIGNED_NON_NATIVE

      +
      +
      public static final ValueLayout.OfLong JAVA_LONG_UNALIGNED_NON_NATIVE
      +
      The static final for NON ByteOrder.nativeOrder() long.
      +
      +
      +
    • +
    • +
      +

      JAVA_SHORT_UNALIGNED_NON_NATIVE

      +
      +
      public static final ValueLayout.OfShort JAVA_SHORT_UNALIGNED_NON_NATIVE
      +
      The static final for NON ByteOrder.nativeOrder() short.
      +
      +
      +
    • +
    • +
      +

      JAVA_CHAR_UNALIGNED_BIG_ENDIAN

      +
      +
      public static final ValueLayout.OfChar JAVA_CHAR_UNALIGNED_BIG_ENDIAN
      +
      The static final for ByteOrder.BIG_ENDIAN char.
      +
      +
      +
    • +
    • +
      +

      JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN

      +
      +
      public static final ValueLayout.OfDouble JAVA_DOUBLE_UNALIGNED_BIG_ENDIAN
      +
      The static final for ByteOrder.BIG_ENDIAN double.
      +
      +
      +
    • +
    • +
      +

      JAVA_FLOAT_UNALIGNED_BIG_ENDIAN

      +
      +
      public static final ValueLayout.OfFloat JAVA_FLOAT_UNALIGNED_BIG_ENDIAN
      +
      The static final for ByteOrder.BIG_ENDIAN float.
      +
      +
      +
    • +
    • +
      +

      JAVA_INT_UNALIGNED_BIG_ENDIAN

      +
      +
      public static final ValueLayout.OfInt JAVA_INT_UNALIGNED_BIG_ENDIAN
      +
      The static final for ByteOrder.BIG_ENDIAN int.
      +
      +
      +
    • +
    • +
      +

      JAVA_LONG_UNALIGNED_BIG_ENDIAN

      +
      +
      public static final ValueLayout.OfLong JAVA_LONG_UNALIGNED_BIG_ENDIAN
      +
      The static final for ByteOrder.BIG_ENDIAN long.
      +
      +
      +
    • +
    • +
      +

      JAVA_SHORT_UNALIGNED_BIG_ENDIAN

      +
      +
      public static final ValueLayout.OfShort JAVA_SHORT_UNALIGNED_BIG_ENDIAN
      +
      The static final for ByteOrder.BIG_ENDIAN short.
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/SuppressFBWarnings.html b/target/site/apidocs/org/apache/datasketches/common/SuppressFBWarnings.html new file mode 100644 index 000000000..f7a4a4184 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/SuppressFBWarnings.html @@ -0,0 +1,167 @@ + + + + +SuppressFBWarnings (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Annotation Interface SuppressFBWarnings

+
+
+
+
+
@Retention(CLASS) +public @interface SuppressFBWarnings
+
Used to suppress SpotBug warnings.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Optional Element Summary

    +
    Optional Elements
    +
    +
    Modifier and Type
    +
    Optional Element
    +
    Description
    + + +
    +
    Optional explanation for the suppression.
    +
    + + +
    +
    A list of comma-separated, quoted SpotBugs warnings that are to be suppressed in the associated +annotated element.
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Element Details

    +
      +
    • +
      +

      value

      +
      +
      String[] value
      +
      A list of comma-separated, quoted SpotBugs warnings that are to be suppressed in the associated +annotated element. The value can be a bug category, kind or pattern.
      +
      +
      Returns:
      +
      list of relevant bug descriptors
      +
      +
      +
      Default:
      +
      {}
      +
      +
      +
      +
    • +
    • +
      +

      justification

      +
      +
      String justification
      +
      Optional explanation for the suppression.
      +
      +
      Returns:
      +
      explanation
      +
      +
      +
      Default:
      +
      ""
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/Util.html b/target/site/apidocs/org/apache/datasketches/common/Util.html new file mode 100644 index 000000000..8f371f1aa --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/Util.html @@ -0,0 +1,1765 @@ + + + + +Util (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class Util

+
+
java.lang.Object +
org.apache.datasketches.common.Util
+
+
+
+
+
public final class Util +extends Object
+
Common utility functions.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    static final long
    + +
    +
    The seed 9001 used in the sketch update methods is a prime number that +was chosen very early on in experimental testing.
    +
    +
    static final double
    + +
    +
    The inverse golden ratio as a fraction.
    +
    +
    static final long
    + +
    +
    The inverse golden ratio as an unsigned long.
    +
    +
    static final double
    + +
    +
    The natural logarithm of 2.0.
    +
    +
    static final double
    + +
    +
    Long.MAX_VALUE as a double.
    +
    +
    static final String
    + +
    +
    The java line separator character as a String.
    +
    +
    static final char
    + +
    +
    The tab character
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + +
    alignedHeapSegment(int capacityBytes, + boolean aligned)
    +
    +
    Request a new heap MemorySegment with the given capacityBytes and either 8-byte aligned or one byte aligned.
    +
    +
    static int
    +
    bitAt(long number, + int bitPos)
    +
    +
    Returns a one if the bit at bitPos is a one, otherwise zero.
    +
    +
    static int
    +
    bytesToInt(byte[] arr)
    +
    +
    Returns an int extracted from a Little-Endian byte array.
    +
    +
    static long
    +
    bytesToLong(byte[] arr)
    +
    +
    Returns a long extracted from a Little-Endian byte array.
    +
    +
    static String
    +
    bytesToString(byte[] arr, + boolean signed, + boolean littleEndian, + String sep)
    +
    +
    Returns a string view of a byte array
    +
    +
    static long
    +
    ceilingMultiple2expK(long n, + int k)
    +
    +
    This is a long integer equivalent to Math.ceil(n / (double)(1 << k)) +where: 0 < k ≤ 6 and n is a non-negative long.
    +
    +
    static double
    +
    ceilingPowerBaseOfDouble(double base, + double n)
    +
    +
    Returns the ceiling of a given n given a base, where the ceiling is an integral power of the base.
    +
    +
    static int
    + +
    +
    Computes the int ceiling power of 2 within the range [1, 2^30].
    +
    +
    static long
    + +
    +
    Computes the long ceiling power of 2 within the range [1, 2^62].
    +
    +
    static String
    +
    characterPad(String s, + int fieldLength, + char padChar, + boolean postpend)
    +
    +
    Prepend or postpend the given string with the given character to fill the given field length.
    +
    +
    static void
    +
    checkBounds(long reqOff, + long reqLen, + long allocSize)
    +
    +
    Check the requested offset and length against the allocated size.
    +
    +
    static void
    +
    checkIfMultipleOf8AndGT0(long v, + String argName)
    +
    +
    Checks if parameter v is a multiple of 8 and greater than zero.
    +
    +
    static void
    +
    checkIfPowerOf2(long n, + String argName)
    +
    +
    Checks the given long argument if it is a positive integer power of 2.
    +
    +
    static void
    +
    checkProbability(double p, + String argName)
    +
    +
    Checks the given parameter to make sure it is positive and between 0.0 inclusive and 1.0 +inclusive.
    +
    +
    static short
    +
    checkSeedHashes(short seedHashA, + short seedHashB)
    +
    +
    Check if the two seed hashes are equal.
    +
    +
    static void
    + +
    +
    Clears all bytes of this MemorySegment to zero.
    +
    +
    static void
    +
    clear(MemorySegment seg, + long offsetBytes, + long lengthBytes)
    +
    +
    Clears a portion of this MemorySegment to zero.
    +
    +
    static void
    +
    clearBits(MemorySegment seg, + long offsetBytes, + byte bitMask)
    +
    +
    Clears the bits defined by the bitMask
    +
    +
    static short
    +
    computeSeedHash(long seed)
    +
    +
    Computes and checks the 16-bit seed hash from the given long seed.
    +
    +
    static boolean
    +
    equalContents(MemorySegment seg1, + long seg1offsetBytes, + MemorySegment seg2, + long seg2offsetBytes, + long lengthBytes)
    +
    +
    Returns true if both segments have the same content for the specified region.
    +
    +
    static boolean
    + +
    +
    Returns true if both segments have the same contents and the same length.
    +
    +
    static int
    +
    exactLog2OfInt(int powerOf2)
    +
    +
    Returns the log2 of the given int value if it is an exact power of 2 and greater than zero.
    +
    +
    static int
    +
    exactLog2OfInt(int powerOf2, + String argName)
    +
    +
    Returns the log2 of the given int value if it is an exact power of 2 and greater than zero.
    +
    +
    static int
    +
    exactLog2OfLong(long powerOf2)
    +
    +
    Returns the log2 of the given long value if it is an exact power of 2 and greater than zero.
    +
    +
    static int
    +
    exactLog2OfLong(long powerOf2, + String argName)
    +
    +
    Returns the log2 of the given long value if it is an exact power of 2 and greater than zero.
    +
    +
    static void
    +
    fill(MemorySegment seg, + long offsetBytes, + long lengthBytes, + byte value)
    +
    +
    Fills a portion of this Memory region to the given byte value.
    +
    +
    static double
    +
    floorPowerBaseOfDouble(double base, + double n)
    +
    +
    Computes the floor of a given n given base, where the floor is an integral power of the base.
    +
    +
    static int
    + +
    +
    Computes the floor power of 2 given n is in the range [1, 2^31-1].
    +
    +
    static long
    +
    floorPowerOf2(long n)
    +
    +
    Computes the floor power of 2 given n is in the range [1, 2^63-1].
    +
    +
    static byte[]
    +
    intToBytes(int v, + byte[] arr)
    +
    +
    Returns a Little-Endian byte array extracted from the given int.
    +
    +
    static double
    +
    invPow2(int e)
    +
    +
    Computes the inverse integer power of 2: 1/(2^e) = 2^(-e).
    +
    +
    static boolean
    +
    isEven(long n)
    +
    +
    Returns true if given n is even.
    +
    +
    static boolean
    +
    isLessThanUnsigned(long n1, + long n2)
    +
    +
    Unsigned compare with longs.
    +
    +
    static boolean
    + +
    +
    Returns true if v is a multiple of 8 and greater than zero
    +
    +
    static boolean
    +
    isOdd(long n)
    +
    +
    Returns true if given n is odd.
    +
    +
    static boolean
    +
    isPowerOf2(long n)
    +
    +
    Returns true if given long argument is exactly a positive power of 2.
    +
    +
    static <T> boolean
    +
    le(Object item1, + Object item2, + Comparator<? super T> c)
    +
    +
    Is item1 Less-Than-Or-Equal-To item2?
    +
    +
    static double
    +
    log2(double value)
    +
    +
    The log2(value)
    +
    +
    static double
    +
    logBaseOfX(double base, + double x)
    +
    +
    Returns the logbase(x).
    +
    +
    static byte[]
    +
    longToBytes(long v, + byte[] arr)
    +
    +
    Returns a Little-Endian byte array extracted from the given long.
    +
    +
    static String
    +
    longToFixedLengthString(long number, + int length)
    +
    +
    Converts the given number to a string prepended with spaces, if necessary, to +match the given length.
    +
    +
    static String
    + +
    +
    Returns a string of spaced hex bytes in Big-Endian order.
    +
    +
    static <T> boolean
    +
    lt(Object item1, + Object item2, + Comparator<? super T> c)
    +
    +
    Is item1 Less-Than item2?
    +
    +
    static <T> Object
    +
    maxT(Object item1, + Object item2, + Comparator<? super T> c)
    +
    +
    Finds the maximum of two generic items
    +
    +
    static String
    + +
    +
    Returns the given time in milliseconds formatted as Hours:Min:Sec.mSec
    +
    +
    static <T> Object
    +
    minT(Object item1, + Object item2, + Comparator<? super T> c)
    +
    +
    Finds the minimum of two generic items
    +
    +
    static String
    +
    nanoSecToString(long nS)
    +
    +
    Returns the given time in nanoseconds formatted as Sec.mSec_uSec_nSec
    +
    +
    static int
    + +
    +
    Returns the number of one bits preceding the highest-order ("leftmost") zero-bit in the +two's complement binary representation of the specified long value, or 64 if the value is equal +to minus one.
    +
    +
    static int
    + +
    +
    Returns the number of one bits following the lowest-order ("rightmost") zero-bit in the +two's complement binary representation of the specified long value, or 64 if the value is equal +to minus one.
    +
    +
    static int
    +
    numDigits(long n)
    +
    +
    Computes the number of decimal digits of the number n
    +
    +
    static double
    +
    powerSeriesNextDouble(int ppb, + double curPoint, + boolean roundToLong, + double logBase)
    +
    +
    Computes the next larger double in the power series +point = logBase( i / ppb ) given the current point in the series.
    +
    +
    static long
    +
    pwr2SeriesNext(int ppo, + long curPoint)
    +
    +
    Computes the next larger integer point in the power series +point = 2( i / ppo ) given the current point in the series.
    +
    +
    static int
    +
    pwr2SeriesPrev(int ppo, + int curPoint)
    +
    +
    Computes the previous, smaller integer point in the power series +point = 2( i / ppo ) given the current point in the series.
    +
    +
    static void
    +
    setBits(MemorySegment seg, + long offsetBytes, + byte bitMask)
    +
    +
    Sets the bits defined by the bitMask
    +
    +
    static String
    +
    zeroPad(String s, + int fieldLength)
    +
    +
    Prepend the given string with zeros.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      LS

      +
      +
      public static final String LS
      +
      The java line separator character as a String.
      +
      +
      +
    • +
    • +
      +

      TAB

      +
      +
      public static final char TAB
      +
      The tab character
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      LOG2

      +
      +
      public static final double LOG2
      +
      The natural logarithm of 2.0.
      +
      +
      +
    • +
    • +
      +

      INVERSE_GOLDEN_U64

      +
      +
      public static final long INVERSE_GOLDEN_U64
      +
      The inverse golden ratio as an unsigned long.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      INVERSE_GOLDEN

      +
      +
      public static final double INVERSE_GOLDEN
      +
      The inverse golden ratio as a fraction. +This has more precision than using the formula: (Math.sqrt(5.0) - 1.0) / 2.0.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      LONG_MAX_VALUE_AS_DOUBLE

      +
      +
      public static final double LONG_MAX_VALUE_AS_DOUBLE
      +
      Long.MAX_VALUE as a double.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      DEFAULT_UPDATE_SEED

      +
      +
      public static final long DEFAULT_UPDATE_SEED
      +
      The seed 9001 used in the sketch update methods is a prime number that +was chosen very early on in experimental testing. Choosing a seed is somewhat arbitrary, and +the author cannot prove that this particular seed is somehow superior to other seeds. There +was some early Internet discussion that a seed of 0 did not produce as clean avalanche diagrams +as non-zero seeds, but this may have been more related to the MurmurHash2 release, which did +have some issues. As far as the author can determine, MurmurHash3 does not have these problems. + +

      In order to perform set operations on two sketches it is critical that the same hash +function and seed are identical for both sketches, otherwise the assumed 1:1 relationship +between the original source key value and the hashed bit string would be violated. Once +you have developed a history of stored sketches you are stuck with it. + +

      WARNING: This seed is used internally by library sketches in different +packages and thus must be declared public. However, this seed value must not be used by library +users with the MurmurHash3 function. It should be viewed as existing for exclusive, private +use by the library. + +

      See Default Update Seed

      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      bytesToInt

      +
      +
      public static int bytesToInt(byte[] arr)
      +
      Returns an int extracted from a Little-Endian byte array.
      +
      +
      Parameters:
      +
      arr - the given byte array
      +
      Returns:
      +
      an int extracted from a Little-Endian byte array.
      +
      +
      +
      +
    • +
    • +
      +

      bytesToLong

      +
      +
      public static long bytesToLong(byte[] arr)
      +
      Returns a long extracted from a Little-Endian byte array.
      +
      +
      Parameters:
      +
      arr - the given byte array
      +
      Returns:
      +
      a long extracted from a Little-Endian byte array.
      +
      +
      +
      +
    • +
    • +
      +

      intToBytes

      +
      +
      public static byte[] intToBytes(int v, + byte[] arr)
      +
      Returns a Little-Endian byte array extracted from the given int.
      +
      +
      Parameters:
      +
      v - the given int
      +
      arr - a given array of 4 bytes that will be returned with the data
      +
      Returns:
      +
      a Little-Endian byte array extracted from the given int.
      +
      +
      +
      +
    • +
    • +
      +

      longToBytes

      +
      +
      public static byte[] longToBytes(long v, + byte[] arr)
      +
      Returns a Little-Endian byte array extracted from the given long.
      +
      +
      Parameters:
      +
      v - the given long
      +
      arr - a given array of 8 bytes that will be returned with the data
      +
      Returns:
      +
      a Little-Endian byte array extracted from the given long.
      +
      +
      +
      +
    • +
    • +
      +

      longToHexBytes

      +
      +
      public static String longToHexBytes(long v)
      +
      Returns a string of spaced hex bytes in Big-Endian order.
      +
      +
      Parameters:
      +
      v - the given long
      +
      Returns:
      +
      string of spaced hex bytes in Big-Endian order.
      +
      +
      +
      +
    • +
    • +
      +

      bytesToString

      +
      +
      public static String bytesToString(byte[] arr, + boolean signed, + boolean littleEndian, + String sep)
      +
      Returns a string view of a byte array
      +
      +
      Parameters:
      +
      arr - the given byte array
      +
      signed - set true if you want the byte values signed.
      +
      littleEndian - set true if you want Little-Endian order
      +
      sep - the separator string between bytes
      +
      Returns:
      +
      a string view of a byte array
      +
      +
      +
      +
    • +
    • +
      +

      nanoSecToString

      +
      +
      public static String nanoSecToString(long nS)
      +
      Returns the given time in nanoseconds formatted as Sec.mSec_uSec_nSec
      +
      +
      Parameters:
      +
      nS - the given nanoseconds
      +
      Returns:
      +
      the given time in nanoseconds formatted as Sec.mSec_uSec_nSec
      +
      +
      +
      +
    • +
    • +
      +

      milliSecToString

      +
      +
      public static String milliSecToString(long mS)
      +
      Returns the given time in milliseconds formatted as Hours:Min:Sec.mSec
      +
      +
      Parameters:
      +
      mS - the given milliseconds
      +
      Returns:
      +
      the given time in milliseconds formatted as Hours:Min:Sec.mSec
      +
      +
      +
      +
    • +
    • +
      +

      zeroPad

      +
      +
      public static String zeroPad(String s, + int fieldLength)
      +
      Prepend the given string with zeros. If the given string is equal or greater than the given +field length, it will be returned without modification.
      +
      +
      Parameters:
      +
      s - the given string
      +
      fieldLength - desired total field length including the given string
      +
      Returns:
      +
      the given string prepended with zeros.
      +
      +
      +
      +
    • +
    • +
      +

      characterPad

      +
      +
      public static String characterPad(String s, + int fieldLength, + char padChar, + boolean postpend)
      +
      Prepend or postpend the given string with the given character to fill the given field length. +If the given string is equal to or greater than the given field length, it will be returned +without modification.
      +
      +
      Parameters:
      +
      s - the given string
      +
      fieldLength - the desired field length
      +
      padChar - the desired pad character
      +
      postpend - if true append the pacCharacters to the end of the string.
      +
      Returns:
      +
      prepended or postpended given string with the given character to fill the given field length.
      +
      +
      +
      +
    • +
    • +
      +

      checkIfMultipleOf8AndGT0

      +
      +
      public static void checkIfMultipleOf8AndGT0(long v, + String argName)
      +
      Checks if parameter v is a multiple of 8 and greater than zero.
      +
      +
      Parameters:
      +
      v - The parameter to check
      +
      argName - This name will be part of the error message if the check fails.
      +
      +
      +
      +
    • +
    • +
      +

      isMultipleOf8AndGT0

      +
      +
      public static boolean isMultipleOf8AndGT0(long v)
      +
      Returns true if v is a multiple of 8 and greater than zero
      +
      +
      Parameters:
      +
      v - The parameter to check
      +
      Returns:
      +
      true if v is a multiple of 8 and greater than zero
      +
      +
      +
      +
    • +
    • +
      +

      isPowerOf2

      +
      +
      public static boolean isPowerOf2(long n)
      +
      Returns true if given long argument is exactly a positive power of 2.
      +
      +
      Parameters:
      +
      n - The input argument.
      +
      Returns:
      +
      true if argument is exactly a positive power of 2.
      +
      +
      +
      +
    • +
    • +
      +

      checkIfPowerOf2

      +
      +
      public static void checkIfPowerOf2(long n, + String argName)
      +
      Checks the given long argument if it is a positive integer power of 2. +If not, it throws an exception with the user supplied local argument name, if not null.
      +
      +
      Parameters:
      +
      n - The input long argument must be a positive integer power of 2.
      +
      argName - Used in the thrown exception. It may be null.
      +
      Throws:
      +
      SketchesArgumentException - if not a positive integer power of 2.
      +
      +
      +
      +
    • +
    • +
      +

      ceilingPowerOf2

      +
      +
      public static int ceilingPowerOf2(int n)
      +
      Computes the int ceiling power of 2 within the range [1, 2^30]. This is the smallest positive power +of 2 that is equal to or greater than the given n and a positive integer. + +

      For: +

        +
      • n ≤ 1: returns 1
      • +
      • 2^30 ≤ n ≤ 2^31 -1 : returns 2^30
      • +
      • n == an exact power of 2 : returns n
      • +
      • otherwise returns the smallest power of 2 ≥ n and equal to a positive integer
      • +
      +
      +
      Parameters:
      +
      n - The input int argument.
      +
      Returns:
      +
      the ceiling power of 2.
      +
      +
      +
      +
    • +
    • +
      +

      ceilingPowerOf2

      +
      +
      public static long ceilingPowerOf2(long n)
      +
      Computes the long ceiling power of 2 within the range [1, 2^62]. This is the smallest positive power +of 2 that is equal to or greater than the given n and a positive long. + +

      For: +

        +
      • n ≤ 1: returns 1
      • +
      • 2^62 ≤ n ≤ 2^63 -1 : returns 2^62
      • +
      • n == an exact power of 2 : returns n
      • +
      • otherwise returns the smallest power of 2 ≥ n and equal to a positive long
      • +
      +
      +
      Parameters:
      +
      n - The input long argument.
      +
      Returns:
      +
      the ceiling power of 2.
      +
      +
      +
      +
    • +
    • +
      +

      floorPowerOf2

      +
      +
      public static int floorPowerOf2(int n)
      +
      Computes the floor power of 2 given n is in the range [1, 2^31-1]. +This is the largest positive power of 2 that equal to or less than the given n and equal +to a positive integer. + +

      For: +

        +
      • n ≤ 1: returns 1
      • +
      • 2^30 ≤ n ≤ 2^31 -1 : returns 2^30
      • +
      • n == a power of 2 : returns n
      • +
      • otherwise returns the largest power of 2 less than n and equal to a mathematical +integer.
      • +
      +
      +
      Parameters:
      +
      n - The given int argument.
      +
      Returns:
      +
      the floor power of 2 as an int.
      +
      +
      +
      +
    • +
    • +
      +

      floorPowerOf2

      +
      +
      public static long floorPowerOf2(long n)
      +
      Computes the floor power of 2 given n is in the range [1, 2^63-1]. +This is the largest positive power of 2 that is equal to or less than the given n and +equal to a positive integer. + +

      For: +

        +
      • n ≤ 1: returns 1
      • +
      • 2^62 ≤ n ≤ 2^63 -1 : returns 2^62
      • +
      • n == a power of 2 : returns n
      • +
      • otherwise returns the largest power of 2 less than n and equal to a mathematical +integer.
      • +
      +
      +
      Parameters:
      +
      n - The given long argument.
      +
      Returns:
      +
      the floor power of 2 as a long
      +
      +
      +
      +
    • +
    • +
      +

      ceilingMultiple2expK

      +
      +
      public static long ceilingMultiple2expK(long n, + int k)
      +
      This is a long integer equivalent to Math.ceil(n / (double)(1 << k)) +where: 0 < k ≤ 6 and n is a non-negative long. +These limits are not checked for speed reasons.
      +
      +
      Parameters:
      +
      n - the input dividend as a positive long greater than zero.
      +
      k - the input divisor exponent of 2 as a positive integer where 0 < k ≤ 6.
      +
      Returns:
      +
      the long integer equivalent to Math.ceil(n / 2^k).
      +
      +
      +
      +
    • +
    • +
      +

      invPow2

      +
      +
      public static double invPow2(int e)
      +
      Computes the inverse integer power of 2: 1/(2^e) = 2^(-e).
      +
      +
      Parameters:
      +
      e - a positive value between 0 and 1023 inclusive
      +
      Returns:
      +
      the inverse integer power of 2: 1/(2^e) = 2^(-e)
      +
      +
      +
      +
    • +
    • +
      +

      pwr2SeriesNext

      +
      +
      public static long pwr2SeriesNext(int ppo, + long curPoint)
      +
      Computes the next larger integer point in the power series +point = 2( i / ppo ) given the current point in the series. +For illustration, this can be used in a loop as follows: + +
          int maxP = 1024;
      +    int minP = 1;
      +    int ppo = 2;
      +
      +    for (int p = minP; p <= maxP; p = pwr2SeriesNext(ppo, p)) {
      +      System.out.print(p + " ");
      +    }
      +    //generates the following series:
      +    //1 2 3 4 6 8 11 16 23 32 45 64 91 128 181 256 362 512 724 1024
      +
      +
      +
      Parameters:
      +
      ppo - Points-Per-Octave, or the number of points per integer powers of 2 in the series.
      +
      curPoint - the current point of the series. Must be ≥ 1.
      +
      Returns:
      +
      the next point in the power series.
      +
      +
      +
      +
    • +
    • +
      +

      pwr2SeriesPrev

      +
      +
      public static int pwr2SeriesPrev(int ppo, + int curPoint)
      +
      Computes the previous, smaller integer point in the power series +point = 2( i / ppo ) given the current point in the series. +For illustration, this can be used in a loop as follows: + +
          int maxP = 1024;
      +    int minP = 1;
      +    int ppo = 2;
      +
      +    for (int p = maxP; p >= minP; p = pwr2SeriesPrev(ppo, p)) {
      +      System.out.print(p + " ");
      +    }
      +    //generates the following series:
      +    //1024 724 512 362 256 181 128 91 64 45 32 23 16 11 8 6 4 3 2 1
      +
      +
      +
      Parameters:
      +
      ppo - Points-Per-Octave, or the number of points per integer powers of 2 in the series.
      +
      curPoint - the current point of the series. Must be ≥ 1.
      +
      Returns:
      +
      the previous, smaller point in the power series. +A returned value of zero terminates the series.
      +
      +
      +
      +
    • +
    • +
      +

      powerSeriesNextDouble

      +
      +
      public static double powerSeriesNextDouble(int ppb, + double curPoint, + boolean roundToLong, + double logBase)
      +
      Computes the next larger double in the power series +point = logBase( i / ppb ) given the current point in the series. +For illustration, this can be used in a loop as follows: + +
          double maxP = 1024.0;
      +    double minP = 1.0;
      +    int ppb = 2;
      +    double logBase = 2.0;
      +
      +    for (double p = minP; p <= maxP; p = powerSeriesNextDouble(ppb, p, true, logBase)) {
      +      System.out.print(p + " ");
      +    }
      +    //generates the following series:
      +    //1 2 3 4 6 8 11 16 23 32 45 64 91 128 181 256 362 512 724 1024
      +
      +
      +
      Parameters:
      +
      ppb - Points-Per-Base, or the number of points per integer powers of base in the series.
      +
      curPoint - the current point of the series. Must be ≥ 1.0.
      +
      roundToLong - if true the output will be rounded to the nearest long.
      +
      logBase - the desired base of the logarithms
      +
      Returns:
      +
      the next point in the power series.
      +
      +
      +
      +
    • +
    • +
      +

      ceilingPowerBaseOfDouble

      +
      +
      public static double ceilingPowerBaseOfDouble(double base, + double n)
      +
      Returns the ceiling of a given n given a base, where the ceiling is an integral power of the base. +This is the smallest positive power of base that is equal to or greater than the given n +and equal to a mathematical integer. +The result of this function is consistent with ceilingPowerOf2(int) for values +less than one. I.e., if n < 1, the result is 1. + +

      The formula is: baseceiling(logbase(x))

      +
      +
      Parameters:
      +
      base - The number in the expression ⌈basen⌉.
      +
      n - The input argument.
      +
      Returns:
      +
      the ceiling power of base as a double and equal to a mathematical integer.
      +
      +
      +
      +
    • +
    • +
      +

      floorPowerBaseOfDouble

      +
      +
      public static double floorPowerBaseOfDouble(double base, + double n)
      +
      Computes the floor of a given n given base, where the floor is an integral power of the base. +This is the largest positive power of base that is equal to or less than the given n +and equal to a mathematical integer. +The result of this function is consistent with floorPowerOf2(int) for values +less than one. I.e., if n < 1, the result is 1. + +

      The formula is: basefloor(logbase(x))

      +
      +
      Parameters:
      +
      base - The number in the expression ⌊basen⌋.
      +
      n - The input argument.
      +
      Returns:
      +
      the floor power of 2 and equal to a mathematical integer.
      +
      +
      +
      +
    • +
    • +
      +

      log2

      +
      +
      public static double log2(double value)
      +
      The log2(value)
      +
      +
      Parameters:
      +
      value - the given value
      +
      Returns:
      +
      log2(value)
      +
      +
      +
      +
    • +
    • +
      +

      logBaseOfX

      +
      +
      public static double logBaseOfX(double base, + double x)
      +
      Returns the logbase(x). Example, if base = 2.0: logB(2.0, x) = log(x) / log(2.0).
      +
      +
      Parameters:
      +
      base - The number in the expression log(x) / log(base).
      +
      x - the given value
      +
      Returns:
      +
      the logbase(x)
      +
      +
      +
      +
    • +
    • +
      +

      numberOfTrailingOnes

      +
      +
      public static int numberOfTrailingOnes(long v)
      +
      Returns the number of one bits following the lowest-order ("rightmost") zero-bit in the +two's complement binary representation of the specified long value, or 64 if the value is equal +to minus one.
      +
      +
      Parameters:
      +
      v - the value whose number of trailing ones is to be computed.
      +
      Returns:
      +
      the number of one bits following the lowest-order ("rightmost") zero-bit in the +two's complement binary representation of the specified long value, or 64 if the value is equal +to minus one.
      +
      +
      +
      +
    • +
    • +
      +

      numberOfLeadingOnes

      +
      +
      public static int numberOfLeadingOnes(long v)
      +
      Returns the number of one bits preceding the highest-order ("leftmost") zero-bit in the +two's complement binary representation of the specified long value, or 64 if the value is equal +to minus one.
      +
      +
      Parameters:
      +
      v - the value whose number of leading ones is to be computed.
      +
      Returns:
      +
      the number of one bits preceding the lowest-order ("rightmost") zero-bit in the +two's complement binary representation of the specified long value, or 64 if the value is equal +to minus one.
      +
      +
      +
      +
    • +
    • +
      +

      exactLog2OfInt

      +
      +
      public static int exactLog2OfInt(int powerOf2, + String argName)
      +
      Returns the log2 of the given int value if it is an exact power of 2 and greater than zero. +If not, it throws an exception with the user supplied local argument name.
      +
      +
      Parameters:
      +
      powerOf2 - must be a power of 2 and greater than zero.
      +
      argName - the argument name used in the exception if thrown.
      +
      Returns:
      +
      the log2 of the given value if it is an exact power of 2 and greater than zero.
      +
      Throws:
      +
      SketchesArgumentException - if not a power of 2 nor greater than zero.
      +
      +
      +
      +
    • +
    • +
      +

      exactLog2OfLong

      +
      +
      public static int exactLog2OfLong(long powerOf2, + String argName)
      +
      Returns the log2 of the given long value if it is an exact power of 2 and greater than zero. +If not, it throws an exception with the user supplied local argument name.
      +
      +
      Parameters:
      +
      powerOf2 - must be a power of 2 and greater than zero.
      +
      argName - the argument name used in the exception if thrown.
      +
      Returns:
      +
      the log2 of the given value if it is an exact power of 2 and greater than zero.
      +
      Throws:
      +
      SketchesArgumentException - if not a power of 2 nor greater than zero.
      +
      +
      +
      +
    • +
    • +
      +

      exactLog2OfInt

      +
      +
      public static int exactLog2OfInt(int powerOf2)
      +
      Returns the log2 of the given int value if it is an exact power of 2 and greater than zero. +If not, it throws an exception.
      +
      +
      Parameters:
      +
      powerOf2 - must be a power of 2 and greater than zero.
      +
      Returns:
      +
      the log2 of the given int value if it is an exact power of 2 and greater than zero.
      +
      +
      +
      +
    • +
    • +
      +

      exactLog2OfLong

      +
      +
      public static int exactLog2OfLong(long powerOf2)
      +
      Returns the log2 of the given long value if it is an exact power of 2 and greater than zero. +If not, it throws an exception.
      +
      +
      Parameters:
      +
      powerOf2 - must be a power of 2 and greater than zero.
      +
      Returns:
      +
      the log2 of the given long value if it is an exact power of 2 and greater than zero.
      +
      +
      +
      +
    • +
    • +
      +

      checkBounds

      +
      +
      public static void checkBounds(long reqOff, + long reqLen, + long allocSize)
      +
      Check the requested offset and length against the allocated size. +The invariants equation is: 0 <= reqOff <= reqLen <= reqOff + reqLen <= allocSize. +If this equation is violated an SketchesArgumentException will be thrown.
      +
      +
      Parameters:
      +
      reqOff - the requested offset
      +
      reqLen - the requested length
      +
      allocSize - the allocated size.
      +
      +
      +
      +
    • +
    • +
      +

      checkProbability

      +
      +
      public static void checkProbability(double p, + String argName)
      +
      Checks the given parameter to make sure it is positive and between 0.0 inclusive and 1.0 +inclusive.
      +
      +
      Parameters:
      +
      p - See Sampling Probability, p
      +
      argName - Used in the thrown exception.
      +
      +
      +
      +
    • +
    • +
      +

      isLessThanUnsigned

      +
      +
      public static boolean isLessThanUnsigned(long n1, + long n2)
      +
      Unsigned compare with longs.
      +
      +
      Parameters:
      +
      n1 - A long to be treated as if unsigned.
      +
      n2 - A long to be treated as if unsigned.
      +
      Returns:
      +
      true if n1 > n2.
      +
      +
      +
      +
    • +
    • +
      +

      isEven

      +
      +
      public static boolean isEven(long n)
      +
      Returns true if given n is even.
      +
      +
      Parameters:
      +
      n - the given n
      +
      Returns:
      +
      true if given n is even.
      +
      +
      +
      +
    • +
    • +
      +

      isOdd

      +
      +
      public static boolean isOdd(long n)
      +
      Returns true if given n is odd.
      +
      +
      Parameters:
      +
      n - the given n
      +
      Returns:
      +
      true if given n is odd.
      +
      +
      +
      +
    • +
    • +
      +

      bitAt

      +
      +
      public static int bitAt(long number, + int bitPos)
      +
      Returns a one if the bit at bitPos is a one, otherwise zero.
      +
      +
      Parameters:
      +
      number - the number to examine
      +
      bitPos - the given zero-based bit position, where the least significant +bit is at position zero.
      +
      Returns:
      +
      a one if the bit at bitPos is a one, otherwise zero.
      +
      +
      +
      +
    • +
    • +
      +

      numDigits

      +
      +
      public static int numDigits(long n)
      +
      Computes the number of decimal digits of the number n
      +
      +
      Parameters:
      +
      n - the given number
      +
      Returns:
      +
      the number of decimal digits of the number n
      +
      +
      +
      +
    • +
    • +
      +

      longToFixedLengthString

      +
      +
      public static String longToFixedLengthString(long number, + int length)
      +
      Converts the given number to a string prepended with spaces, if necessary, to +match the given length. + +

      For example, assume a sequence of integers from 1 to 1000. The largest value has +four decimal digits. Convert the entire sequence of strings to the form " 1" to "1000". +When these strings are sorted they will be in numerical sequence: " 1", " 2", ... "1000".

      +
      +
      Parameters:
      +
      number - the given number
      +
      length - the desired string length.
      +
      Returns:
      +
      the given number to a string prepended with spaces
      +
      +
      +
      +
    • +
    • +
      +

      minT

      +
      +
      public static <T> Object minT(Object item1, + Object item2, + Comparator<? super T> c)
      +
      Finds the minimum of two generic items
      +
      +
      Type Parameters:
      +
      T - the type
      +
      Parameters:
      +
      item1 - item one
      +
      item2 - item two
      +
      c - the given comparator
      +
      Returns:
      +
      the minimum value
      +
      +
      +
      +
    • +
    • +
      +

      maxT

      +
      +
      public static <T> Object maxT(Object item1, + Object item2, + Comparator<? super T> c)
      +
      Finds the maximum of two generic items
      +
      +
      Type Parameters:
      +
      T - the type
      +
      Parameters:
      +
      item1 - item one
      +
      item2 - item two
      +
      c - the given comparator
      +
      Returns:
      +
      the maximum value
      +
      +
      +
      +
    • +
    • +
      +

      lt

      +
      +
      public static <T> boolean lt(Object item1, + Object item2, + Comparator<? super T> c)
      +
      Is item1 Less-Than item2?
      +
      +
      Type Parameters:
      +
      T - the type
      +
      Parameters:
      +
      item1 - item one
      +
      item2 - item two
      +
      c - the given comparator
      +
      Returns:
      +
      true if item1 Less-Than item2
      +
      +
      +
      +
    • +
    • +
      +

      le

      +
      +
      public static <T> boolean le(Object item1, + Object item2, + Comparator<? super T> c)
      +
      Is item1 Less-Than-Or-Equal-To item2?
      +
      +
      Type Parameters:
      +
      T - the type
      +
      Parameters:
      +
      item1 - item one
      +
      item2 - item two
      +
      c - the given comparator
      +
      Returns:
      +
      true if item1 Less-Than-Or-Equal-To item2
      +
      +
      +
      +
    • +
    • +
      +

      clear

      +
      +
      public static void clear(MemorySegment seg)
      +
      Clears all bytes of this MemorySegment to zero.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      clear

      +
      +
      public static void clear(MemorySegment seg, + long offsetBytes, + long lengthBytes)
      +
      Clears a portion of this MemorySegment to zero.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      lengthBytes - the length in bytes
      +
      +
      +
      +
    • +
    • +
      +

      clearBits

      +
      +
      public static void clearBits(MemorySegment seg, + long offsetBytes, + byte bitMask)
      +
      Clears the bits defined by the bitMask
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      offsetBytes - offset bytes relative to this Memory start.
      +
      bitMask - the bits set to one will be cleared
      +
      +
      +
      +
    • +
    • +
      +

      equalContents

      +
      +
      public static boolean equalContents(MemorySegment seg1, + MemorySegment seg2)
      +
      Returns true if both segments have the same contents and the same length.
      +
      +
      Parameters:
      +
      seg1 - the given MemorySegment #1
      +
      seg2 - the given MemorySegment #2
      +
      Returns:
      +
      true if both segments have the same contents and the same length.
      +
      +
      +
      +
    • +
    • +
      +

      equalContents

      +
      +
      public static boolean equalContents(MemorySegment seg1, + long seg1offsetBytes, + MemorySegment seg2, + long seg2offsetBytes, + long lengthBytes)
      +
      Returns true if both segments have the same content for the specified region.
      +
      +
      Parameters:
      +
      seg1 - the given MemorySegment #1
      +
      seg1offsetBytes - the starting offset for MemorySegment #1 in bytes.
      +
      seg2 - the given MemorySegment #2
      +
      seg2offsetBytes - the starting offset for MemorySegment #2 in bytes.
      +
      lengthBytes - the length of the region to be compared, in bytes.
      +
      Returns:
      +
      true, if both segments have the content for the specified region.
      +
      +
      +
      +
    • +
    • +
      +

      fill

      +
      +
      public static void fill(MemorySegment seg, + long offsetBytes, + long lengthBytes, + byte value)
      +
      Fills a portion of this Memory region to the given byte value.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      offsetBytes - offset bytes relative to this Memory start
      +
      lengthBytes - the length in bytes
      +
      value - the given byte value
      +
      +
      +
      +
    • +
    • +
      +

      alignedHeapSegment

      +
      +
      public static MemorySegment alignedHeapSegment(int capacityBytes, + boolean aligned)
      +
      Request a new heap MemorySegment with the given capacityBytes and either 8-byte aligned or one byte aligned. + +

      If aligned is true, the returned MemorySegment will be constructed from a long[] array, +and, as a result, it will have a memory alignment of 8 bytes. +If the requested capacity is not exactly divisible by eight, the returned size +will be rolled up to the next multiple of eight bytes.

      + +

      If aligned is false, the returned MemorySegment will be constructed from a byte[] array, +and have a memory alignment of 1 byte.

      +
      +
      Parameters:
      +
      capacityBytes - The new capacity being requested. It must not be negative and cannot exceed Integer.MAX_VALUE.
      +
      aligned - if true, the new heap segment will have an alignment of 8 bytes, otherwise the alignment will be 1 byte.
      +
      Returns:
      +
      a new MemorySegment with the requested capacity and alignment.
      +
      +
      +
      +
    • +
    • +
      +

      setBits

      +
      +
      public static void setBits(MemorySegment seg, + long offsetBytes, + byte bitMask)
      +
      Sets the bits defined by the bitMask
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      bitMask - the bits set to one will be set
      +
      +
      +
      +
    • +
    • +
      +

      computeSeedHash

      +
      +
      public static short computeSeedHash(long seed)
      +
      Computes and checks the 16-bit seed hash from the given long seed. +The seed hash may not be zero in order to maintain compatibility with older serialized +versions that did not have this concept.
      +
      +
      Parameters:
      +
      seed - See Update Hash Seed
      +
      Returns:
      +
      the seed hash.
      +
      +
      +
      +
    • +
    • +
      +

      checkSeedHashes

      +
      +
      public static short checkSeedHashes(short seedHashA, + short seedHashB)
      +
      Check if the two seed hashes are equal. If not, throw an SketchesArgumentException.
      +
      +
      Parameters:
      +
      seedHashA - the seedHash A
      +
      seedHashB - the seedHash B
      +
      Returns:
      +
      seedHashA if they are equal
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfBooleansSerDe.html b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfBooleansSerDe.html new file mode 100644 index 000000000..22118575b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfBooleansSerDe.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.ArrayOfBooleansSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.ArrayOfBooleansSerDe

+
+No usage of org.apache.datasketches.common.ArrayOfBooleansSerDe +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfDoublesSerDe.html b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfDoublesSerDe.html new file mode 100644 index 000000000..331dd8447 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfDoublesSerDe.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.ArrayOfDoublesSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.ArrayOfDoublesSerDe

+
+No usage of org.apache.datasketches.common.ArrayOfDoublesSerDe +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfItemsSerDe.html b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfItemsSerDe.html new file mode 100644 index 000000000..8a16d249b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfItemsSerDe.html @@ -0,0 +1,379 @@ + + + + +Uses of Class org.apache.datasketches.common.ArrayOfItemsSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.ArrayOfItemsSerDe

+
+
Packages that use ArrayOfItemsSerDe
+
+
Package
+
Description
+ +
+
This package is for common classes that may be used across all the sketch families.
+
+ +
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfLongsSerDe.html b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfLongsSerDe.html new file mode 100644 index 000000000..8a33d7f62 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfLongsSerDe.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.ArrayOfLongsSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.ArrayOfLongsSerDe

+
+No usage of org.apache.datasketches.common.ArrayOfLongsSerDe +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfNumbersSerDe.html b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfNumbersSerDe.html new file mode 100644 index 000000000..6ddffe3fa --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfNumbersSerDe.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.ArrayOfNumbersSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.ArrayOfNumbersSerDe

+
+No usage of org.apache.datasketches.common.ArrayOfNumbersSerDe +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfStringsSerDe.html b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfStringsSerDe.html new file mode 100644 index 000000000..cb32bbf0d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfStringsSerDe.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.ArrayOfStringsSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.ArrayOfStringsSerDe

+
+No usage of org.apache.datasketches.common.ArrayOfStringsSerDe +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfUtf16StringsSerDe.html b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfUtf16StringsSerDe.html new file mode 100644 index 000000000..178a91359 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/ArrayOfUtf16StringsSerDe.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.ArrayOfUtf16StringsSerDe (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.ArrayOfUtf16StringsSerDe

+
+No usage of org.apache.datasketches.common.ArrayOfUtf16StringsSerDe +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/BoundsOnBinomialProportions.html b/target/site/apidocs/org/apache/datasketches/common/class-use/BoundsOnBinomialProportions.html new file mode 100644 index 000000000..6d99a22b6 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/BoundsOnBinomialProportions.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.BoundsOnBinomialProportions (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.BoundsOnBinomialProportions

+
+No usage of org.apache.datasketches.common.BoundsOnBinomialProportions +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/BoundsOnRatiosInSampledSets.html b/target/site/apidocs/org/apache/datasketches/common/class-use/BoundsOnRatiosInSampledSets.html new file mode 100644 index 000000000..59b22ddaf --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/BoundsOnRatiosInSampledSets.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.BoundsOnRatiosInSampledSets (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.BoundsOnRatiosInSampledSets

+
+No usage of org.apache.datasketches.common.BoundsOnRatiosInSampledSets +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/ByteArrayUtil.html b/target/site/apidocs/org/apache/datasketches/common/class-use/ByteArrayUtil.html new file mode 100644 index 000000000..ee08b2617 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/ByteArrayUtil.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.ByteArrayUtil (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.ByteArrayUtil

+
+No usage of org.apache.datasketches.common.ByteArrayUtil +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/Family.html b/target/site/apidocs/org/apache/datasketches/common/class-use/Family.html new file mode 100644 index 000000000..ae09e3ef9 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/Family.html @@ -0,0 +1,218 @@ + + + + +Uses of Enum Class org.apache.datasketches.common.Family (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.common.Family

+
+
Packages that use Family
+
+
Package
+
Description
+ +
+
This package is for common classes that may be used across all the sketch families.
+
+ +
+
Compressed Probabilistic Counting sketch family
+
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/MemorySegmentRequest.Default.html b/target/site/apidocs/org/apache/datasketches/common/class-use/MemorySegmentRequest.Default.html new file mode 100644 index 000000000..21aeef314 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/MemorySegmentRequest.Default.html @@ -0,0 +1,96 @@ + + + + +Uses of Class org.apache.datasketches.common.MemorySegmentRequest.Default (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.MemorySegmentRequest.Default

+
+ +
+
Package
+
Description
+ +
+
This package is for common classes that may be used across all the sketch families.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/MemorySegmentRequest.html b/target/site/apidocs/org/apache/datasketches/common/class-use/MemorySegmentRequest.html new file mode 100644 index 000000000..b7f17b785 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/MemorySegmentRequest.html @@ -0,0 +1,262 @@ + + + + +Uses of Interface org.apache.datasketches.common.MemorySegmentRequest (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.common.MemorySegmentRequest

+
+
Packages that use MemorySegmentRequest
+
+
Package
+
Description
+ +
+
This package is for common classes that may be used across all the sketch families.
+
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/MemorySegmentRequestExample.html b/target/site/apidocs/org/apache/datasketches/common/class-use/MemorySegmentRequestExample.html new file mode 100644 index 000000000..8d11a0c08 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/MemorySegmentRequestExample.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.MemorySegmentRequestExample (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.MemorySegmentRequestExample

+
+No usage of org.apache.datasketches.common.MemorySegmentRequestExample +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/MemorySegmentStatus.html b/target/site/apidocs/org/apache/datasketches/common/class-use/MemorySegmentStatus.html new file mode 100644 index 000000000..115c0277c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/MemorySegmentStatus.html @@ -0,0 +1,257 @@ + + + + +Uses of Interface org.apache.datasketches.common.MemorySegmentStatus (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.common.MemorySegmentStatus

+
+
Packages that use MemorySegmentStatus
+
+
Package
+
Description
+ +
+
BloomFilter package
+
+ +
+
The DataSketches™ HllSketch family package
+
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/QuickSelect.html b/target/site/apidocs/org/apache/datasketches/common/class-use/QuickSelect.html new file mode 100644 index 000000000..758086175 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/QuickSelect.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.QuickSelect (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.QuickSelect

+
+No usage of org.apache.datasketches.common.QuickSelect +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/ResizeFactor.html b/target/site/apidocs/org/apache/datasketches/common/class-use/ResizeFactor.html new file mode 100644 index 000000000..858b263c9 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/ResizeFactor.html @@ -0,0 +1,275 @@ + + + + +Uses of Enum Class org.apache.datasketches.common.ResizeFactor (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.common.ResizeFactor

+
+
Packages that use ResizeFactor
+
+
Package
+
Description
+ +
+
This package is for common classes that may be used across all the sketch families.
+
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesArgumentException.html b/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesArgumentException.html new file mode 100644 index 000000000..e71c5597b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesArgumentException.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.SketchesArgumentException (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.SketchesArgumentException

+
+No usage of org.apache.datasketches.common.SketchesArgumentException +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesException.html b/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesException.html new file mode 100644 index 000000000..3ed350855 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesException.html @@ -0,0 +1,110 @@ + + + + +Uses of Class org.apache.datasketches.common.SketchesException (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.SketchesException

+
+
Packages that use SketchesException
+
+
Package
+
Description
+ +
+
This package is for common classes that may be used across all the sketch families.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesNotSupportedException.html b/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesNotSupportedException.html new file mode 100644 index 000000000..cdf13dbaa --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesNotSupportedException.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.SketchesNotSupportedException (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.SketchesNotSupportedException

+
+No usage of org.apache.datasketches.common.SketchesNotSupportedException +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesReadOnlyException.html b/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesReadOnlyException.html new file mode 100644 index 000000000..70bb84347 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesReadOnlyException.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.SketchesReadOnlyException (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.SketchesReadOnlyException

+
+No usage of org.apache.datasketches.common.SketchesReadOnlyException +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesStateException.html b/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesStateException.html new file mode 100644 index 000000000..3510fdbc0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/SketchesStateException.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.SketchesStateException (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.SketchesStateException

+
+No usage of org.apache.datasketches.common.SketchesStateException +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/SpecialValueLayouts.html b/target/site/apidocs/org/apache/datasketches/common/class-use/SpecialValueLayouts.html new file mode 100644 index 000000000..845859348 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/SpecialValueLayouts.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.SpecialValueLayouts (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.SpecialValueLayouts

+
+No usage of org.apache.datasketches.common.SpecialValueLayouts +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/SuppressFBWarnings.html b/target/site/apidocs/org/apache/datasketches/common/class-use/SuppressFBWarnings.html new file mode 100644 index 000000000..4845a429a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/SuppressFBWarnings.html @@ -0,0 +1,261 @@ + + + + +Uses of Annotation Interface org.apache.datasketches.common.SuppressFBWarnings (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Annotation Interface
org.apache.datasketches.common.SuppressFBWarnings

+
+
Packages that use SuppressFBWarnings
+
+
Package
+
Description
+ +
+
This package is for common classes that may be used across all the sketch families.
+
+ +
+
Compressed Probabilistic Counting sketch family
+
+ +
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/class-use/Util.html b/target/site/apidocs/org/apache/datasketches/common/class-use/Util.html new file mode 100644 index 000000000..66678fbe9 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/class-use/Util.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.Util (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.Util

+
+No usage of org.apache.datasketches.common.Util +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/package-summary.html b/target/site/apidocs/org/apache/datasketches/common/package-summary.html new file mode 100644 index 000000000..ac224ea10 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/package-summary.html @@ -0,0 +1,223 @@ + + + + +org.apache.datasketches.common (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.common

+
+
+
+
package org.apache.datasketches.common
+
+
This package is for common classes that may be used across all the sketch families.
+
+
+
+
    +
  • + +
  • +
  • +
    +
    +
    +
    +
    Class
    +
    Description
    + +
    +
    Methods of serializing and deserializing arrays of Boolean as a bit array.
    +
    + +
    +
    Methods of serializing and deserializing arrays of Double.
    +
    + +
    +
    Base class for serializing and deserializing custom types.
    +
    + +
    +
    Methods of serializing and deserializing arrays of Long.
    +
    + +
    +
    Methods of serializing and deserializing arrays of the object version of primitive types of +Number.
    +
    + +
    +
    Methods of serializing and deserializing arrays of String.
    +
    + +
    +
    Methods of serializing and deserializing arrays of String.
    +
    + +
    +
    Confidence intervals for binomial proportions.
    +
    + +
    +
    This class is used to compute the bounds on the estimate of the ratio |B| / |A|, where: + +|A| is the unknown size of a set A of unique identifiers. +|B| is the unknown size of a subset B of A. +a = |SA| is the observed size of a sample of A +that was obtained by Bernoulli sampling with a known inclusion probability f. +b = |SA ∩ B| is the observed size of a subset +of SA. +
    +
    + +
    +
    Useful methods for byte arrays.
    +
    + +
    +
    Defines the various families of sketch and set operation classes.
    +
    + +
    +
    This is a callback interface to provide a means to request a new MemorySegment of a specified size.
    +
    + +
    +
    A convenience class that implements a default implementation.
    +
    + +
    +
    This is an example of a possible implementation of the MemorySegmentRequest interface +where all requested segments are allocated off-heap.
    +
    + +
    +
    Methods for inquiring the status of a backing MemorySegment.
    +
    + +
    +
    QuickSelect algorithm improved from Sedgewick.
    +
    + +
    +
    For the Families that accept this configuration parameter, it controls the size multiple that +affects how fast the internal cache grows, when more space is required.
    +
    + +
    +
    Illegal Arguments Exception class for the library
    +
    + +
    +
    Exception class for the library
    +
    + +
    +
    This operation or mode is not supported.
    +
    + +
    +
    Write operation attempted on a read-only class.
    +
    + +
    +
    Illegal State Exception class for the library
    +
    + +
    +
    Value Layouts for Non-native Endianness
    +
    + +
    +
    Used to suppress SpotBug warnings.
    +
    + +
    +
    Common utility functions.
    +
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/package-tree.html b/target/site/apidocs/org/apache/datasketches/common/package-tree.html new file mode 100644 index 000000000..a5809774d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/package-tree.html @@ -0,0 +1,144 @@ + + + + +org.apache.datasketches.common Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.common

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Interface Hierarchy

+ +
+
+

Annotation Interface Hierarchy

+ +
+
+

Enum Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/package-use.html b/target/site/apidocs/org/apache/datasketches/common/package-use.html new file mode 100644 index 000000000..c6f6f9701 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/package-use.html @@ -0,0 +1,366 @@ + + + + +Uses of Package org.apache.datasketches.common (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.common

+
+ +
+
Package
+
Description
+ +
+
This package is for common classes that may be used across all the sketch families.
+
+ +
+
Compressed Probabilistic Counting sketch family
+
+ +
+
BloomFilter package
+
+ +
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+ +
+
The DataSketches™ HllSketch family package
+
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/positional/PositionInvariantsException.html b/target/site/apidocs/org/apache/datasketches/common/positional/PositionInvariantsException.html new file mode 100644 index 000000000..af90cf05b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/positional/PositionInvariantsException.html @@ -0,0 +1,170 @@ + + + + +PositionInvariantsException (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class PositionInvariantsException

+
+
java.lang.Object +
java.lang.Throwable +
java.lang.Exception +
java.lang.RuntimeException +
org.apache.datasketches.common.positional.PositionInvariantsException
+
+
+
+
+
+
+
All Implemented Interfaces:
+
Serializable
+
+
+
+
public class PositionInvariantsException +extends RuntimeException
+
Position operation violation.
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      PositionInvariantsException

      +
      +
      public PositionInvariantsException(String details)
      +
      The associated position operation violated one of the positional invariants. + +

      The invariants equation is 0 <= start <= position <= end <= capacity.

      +
      +
      Parameters:
      +
      details - of the violation.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/positional/Positional.html b/target/site/apidocs/org/apache/datasketches/common/positional/Positional.html new file mode 100644 index 000000000..7184e4988 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/positional/Positional.html @@ -0,0 +1,351 @@ + + + + +Positional (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface Positional

+
+
+
+
All Known Subinterfaces:
+
PositionalSegment
+
+
+
+
public interface Positional
+
Defines the relative positional API. +This is different from and simpler than Java ByteBuffer positional API. +
  • All based on longs instead of ints.
  • +
  • Eliminated "mark". Mark is rarely used and confusing with its silent side effects.
  • +
  • The invariants are 0 <= start <= position <= end <= capacity.
  • +
  • It always starts up as (0, 0, capacity, capacity).
  • +
  • You set (start, position, end) in one call with +setStartPositionEnd(long, long, long)
  • +
  • Position can be set directly or indirectly when using the positional get/put methods. +
  • Added incrementPosition(long), which is much easier when you know the increment.
  • +
  • This approach eliminated a number of methods and checks, and has no unseen side effects, +e.g., mark being invalidated.
  • +
  • Clearer method naming (IMHO).
  • +
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    long
    + +
    +
    Gets the end position
    +
    +
    static Positional
    +
    getInstance(long capacity)
    +
    +
    Gets an instance of this Positional.
    +
    +
    long
    + +
    +
    Gets the current position
    +
    +
    long
    + +
    +
    The number of elements remaining between the current position and the end position
    +
    +
    long
    + +
    +
    Gets start position
    +
    +
    boolean
    + +
    +
    Returns true if there are elements remaining between the current position and the end position
    +
    + +
    incrementPosition(long increment)
    +
    +
    Increments the current position by the given increment.
    +
    + + +
    +
    Resets the current position to the start position, +This does not modify any data.
    +
    + +
    setPosition(long position)
    +
    +
    Sets the current position.
    +
    + +
    setStartPositionEnd(long start, + long position, + long end)
    +
    +
    Sets start position, current position, and end position.
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getInstance

      +
      +
      static Positional getInstance(long capacity)
      +
      Gets an instance of this Positional.
      +
      +
      Parameters:
      +
      capacity - the upper limit of positional range.
      +
      Returns:
      +
      an instance of Positional.
      +
      +
      +
      +
    • +
    • +
      +

      incrementPosition

      +
      +
      Positional incrementPosition(long increment)
      +
      Increments the current position by the given increment.
      +
      +
      Parameters:
      +
      increment - the given increment
      +
      Returns:
      +
      this Positional
      +
      +
      +
      +
    • +
    • +
      +

      getEnd

      +
      +
      long getEnd()
      +
      Gets the end position
      +
      +
      Returns:
      +
      the end position
      +
      +
      +
      +
    • +
    • +
      +

      getPosition

      +
      +
      long getPosition()
      +
      Gets the current position
      +
      +
      Returns:
      +
      the current position
      +
      +
      +
      +
    • +
    • +
      +

      getStart

      +
      +
      long getStart()
      +
      Gets start position
      +
      +
      Returns:
      +
      start position
      +
      +
      +
      +
    • +
    • +
      +

      getRemaining

      +
      +
      long getRemaining()
      +
      The number of elements remaining between the current position and the end position
      +
      +
      Returns:
      +
      (end - position)
      +
      +
      +
      +
    • +
    • +
      +

      hasRemaining

      +
      +
      boolean hasRemaining()
      +
      Returns true if there are elements remaining between the current position and the end position
      +
      +
      Returns:
      +
      (end - position) > 0
      +
      +
      +
      +
    • +
    • +
      +

      resetPosition

      +
      +
      Positional resetPosition()
      +
      Resets the current position to the start position, +This does not modify any data.
      +
      +
      Returns:
      +
      this Positional
      +
      +
      +
      +
    • +
    • +
      +

      setPosition

      +
      +
      Positional setPosition(long position)
      +
      Sets the current position. +Checks that the positional invariants are not violated.
      +
      +
      Parameters:
      +
      position - the given current position.
      +
      Returns:
      +
      this Positional
      +
      Throws:
      +
      PositionInvariantsException - if positional invariants have been violated.
      +
      +
      +
      +
    • +
    • +
      +

      setStartPositionEnd

      +
      +
      Positional setStartPositionEnd(long start, + long position, + long end)
      +
      Sets start position, current position, and end position. +Checks that the positional invariants are not violated.
      +
      +
      Parameters:
      +
      start - the start position in the buffer
      +
      position - the current position between the start and end
      +
      end - the end position in the buffer
      +
      Returns:
      +
      this Positional
      +
      Throws:
      +
      PositionInvariantsException - if positional invariants have been violated.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/positional/PositionalSegment.html b/target/site/apidocs/org/apache/datasketches/common/positional/PositionalSegment.html new file mode 100644 index 000000000..b1ec86580 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/positional/PositionalSegment.html @@ -0,0 +1,1235 @@ + + + + +PositionalSegment (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface PositionalSegment

+
+
+
+
All Superinterfaces:
+
Positional
+
+
+
+
public interface PositionalSegment +extends Positional
+
Defines the API for relative positional access to a MemorySegment.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Returns a slice of this PositionalSegment at the current position.
    +
    +
    boolean
    + +
    +
    Gets the boolean value at the current position.
    +
    +
    boolean
    +
    getBoolean(long offsetBytes)
    +
    +
    Gets the boolean value at the given offset.
    +
    +
    byte
    + +
    +
    Gets the byte value at the current position.
    +
    +
    byte
    +
    getByte(long offsetBytes)
    +
    +
    Gets the byte value at the given offset.
    +
    +
    void
    +
    getByteArray(byte[] dstArray, + int dstOffsetBytes, + int lengthBytes)
    +
    +
    Gets the byte array at the current position.
    +
    +
    char
    + +
    +
    Gets the char value at the current position.
    +
    +
    char
    +
    getChar(long offsetBytes)
    +
    +
    Gets the char value at the given offset.
    +
    +
    void
    +
    getCharArray(char[] dstArray, + int dstOffsetChars, + int lengthChars)
    +
    +
    Gets the char array at the current position.
    +
    +
    double
    + +
    +
    Gets the double value at the current position.
    +
    +
    double
    +
    getDouble(long offsetBytes)
    +
    +
    Gets the double value at the given offset.
    +
    +
    void
    +
    getDoubleArray(double[] dstArray, + int dstOffsetDoubles, + int lengthDoubles)
    +
    +
    Gets the double array at the current position.
    +
    +
    float
    + +
    +
    Gets the float value at the current position.
    +
    +
    float
    +
    getFloat(long offsetBytes)
    +
    +
    Gets the float value at the given offset.
    +
    +
    void
    +
    getFloatArray(float[] dstArray, + int dstOffsetFloats, + int lengthFloats)
    +
    +
    Gets the float array at the current position.
    +
    +
    int
    + +
    +
    Gets the int value at the current position.
    +
    +
    int
    +
    getInt(long offsetBytes)
    +
    +
    Gets the int value at the given offset.
    +
    +
    void
    +
    getIntArray(int[] dstArray, + int dstOffsetInts, + int lengthInts)
    +
    +
    Gets the int array at the current position.
    +
    +
    long
    + +
    +
    Gets the long value at the current position.
    +
    +
    long
    +
    getLong(long offsetBytes)
    +
    +
    Gets the long value at the given offset.
    +
    +
    void
    +
    getLongArray(long[] dstArray, + int dstOffsetLongs, + int lengthLongs)
    +
    +
    Gets the long array at the current position.
    +
    + + +
    +
    Returns the underlying MemorySegment.
    +
    +
    short
    + +
    +
    Gets the short value at the current position.
    +
    +
    short
    +
    getShort(long offsetBytes)
    +
    +
    Gets the short value at the given offset.
    +
    +
    void
    +
    getShortArray(short[] dstArray, + int dstOffsetShorts, + int lengthShorts)
    +
    +
    Gets the short array at the current position.
    +
    +
    void
    +
    setBoolean(boolean value)
    +
    +
    Sets the boolean value at the current position.
    +
    +
    void
    +
    setBoolean(long offsetBytes, + boolean value)
    +
    +
    Sets the boolean value at the given offset.
    +
    +
    void
    +
    setByte(byte value)
    +
    +
    Sets the byte value at the current position.
    +
    +
    void
    +
    setByte(long offsetBytes, + byte value)
    +
    +
    Sets the byte value at the given offset.
    +
    +
    void
    +
    setByteArray(byte[] srcArray, + int srcOffsetBytes, + int lengthBytes)
    +
    +
    Sets the byte array at the current position.
    +
    +
    void
    +
    setChar(char value)
    +
    +
    Sets the char value at the current position.
    +
    +
    void
    +
    setChar(long offsetBytes, + char value)
    +
    +
    Sets the char value at the given offset.
    +
    +
    void
    +
    setCharArray(char[] srcArray, + int srcOffsetChars, + int lengthChars)
    +
    +
    Sets the char array at the current position.
    +
    +
    void
    +
    setDouble(double value)
    +
    +
    Sets the double value at the current position.
    +
    +
    void
    +
    setDouble(long offsetBytes, + double value)
    +
    +
    Sets the double value at the given offset.
    +
    +
    void
    +
    setDoubleArray(double[] srcArray, + int srcOffsetDoubles, + int lengthDoubles)
    +
    +
    Sets the double array at the current position.
    +
    +
    void
    +
    setFloat(float value)
    +
    +
    Sets the float value at the current position.
    +
    +
    void
    +
    setFloat(long offsetBytes, + float value)
    +
    +
    Sets the float value at the given offset.
    +
    +
    void
    +
    setFloatArray(float[] srcArray, + int srcOffsetFloats, + int lengthFloats)
    +
    +
    Sets the float array at the current position.
    +
    +
    void
    +
    setInt(int value)
    +
    +
    Sets the int value at the current position.
    +
    +
    void
    +
    setInt(long offsetBytes, + int value)
    +
    +
    Sets the int value at the given offset.
    +
    +
    void
    +
    setIntArray(int[] srcArray, + int srcOffsetInts, + int lengthInts)
    +
    +
    Sets the int array at the current position.
    +
    +
    void
    +
    setLong(long value)
    +
    +
    Sets the long value at the current position.
    +
    +
    void
    +
    setLong(long offsetBytes, + long value)
    +
    +
    Sets the long value at the given offset.
    +
    +
    void
    +
    setLongArray(long[] srcArray, + int srcOffsetLongs, + int lengthLongs)
    +
    +
    Sets the long array at the current position.
    +
    +
    void
    +
    setShort(long offsetBytes, + short value)
    +
    +
    Sets the short value at the given offset.
    +
    +
    void
    +
    setShort(short value)
    +
    +
    Sets the short value at the current position.
    +
    +
    void
    +
    setShortArray(short[] srcArray, + int srcOffsetShorts, + int lengthShorts)
    +
    +
    Sets the short array at the current position.
    +
    + + +
    +
    Gets an instance of this PositionalSegment.
    +
    +
    +
    +
    + +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      wrap

      +
      +
      static PositionalSegment wrap(MemorySegment seg)
      +
      Gets an instance of this PositionalSegment.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment to create the PositionalSegment from.
      +
      Returns:
      +
      a new PositionalSegment.
      +
      +
      +
      +
    • +
    • +
      +

      asSlice

      +
      + +
      Returns a slice of this PositionalSegment at the current position. +The end of the slice is the end of the underlying segment.
      +
      +
      Returns:
      +
      a slice of this PositionalSegment at the current position.
      +
      +
      +
      +
    • +
    • +
      +

      getMemorySegment

      +
      +
      MemorySegment getMemorySegment()
      +
      Returns the underlying MemorySegment. +The current start, position and end are ignored.
      +
      +
      Returns:
      +
      the underlying MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      getBoolean

      +
      +
      boolean getBoolean()
      +
      Gets the boolean value at the current position. +Increments the position by Byte.BYTES.
      +
      +
      Returns:
      +
      the boolean at the current position
      +
      +
      +
      +
    • +
    • +
      +

      getBoolean

      +
      +
      boolean getBoolean(long offsetBytes)
      +
      Gets the boolean value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      Returns:
      +
      the boolean at the given offset
      +
      +
      +
      +
    • +
    • +
      +

      getByte

      +
      +
      byte getByte()
      +
      Gets the byte value at the current position. +Increments the position by Byte.BYTES.
      +
      +
      Returns:
      +
      the byte at the current position
      +
      +
      +
      +
    • +
    • +
      +

      getByte

      +
      +
      byte getByte(long offsetBytes)
      +
      Gets the byte value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      Returns:
      +
      the byte at the given offset
      +
      +
      +
      +
    • +
    • +
      +

      getByteArray

      +
      +
      void getByteArray(byte[] dstArray, + int dstOffsetBytes, + int lengthBytes)
      +
      Gets the byte array at the current position. +Increments the position by Byte.BYTES * (lengthBytes - dstOffsetBytes).
      +
      +
      Parameters:
      +
      dstArray - The preallocated destination array.
      +
      dstOffsetBytes - offset in array units
      +
      lengthBytes - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      getChar

      +
      +
      char getChar()
      +
      Gets the char value at the current position. +Increments the position by Character.BYTES.
      +
      +
      Returns:
      +
      the char at the current position
      +
      +
      +
      +
    • +
    • +
      +

      getChar

      +
      +
      char getChar(long offsetBytes)
      +
      Gets the char value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      Returns:
      +
      the char at the given offset
      +
      +
      +
      +
    • +
    • +
      +

      getCharArray

      +
      +
      void getCharArray(char[] dstArray, + int dstOffsetChars, + int lengthChars)
      +
      Gets the char array at the current position. +Increments the position by Character.BYTES * (lengthChars - dstOffsetChars).
      +
      +
      Parameters:
      +
      dstArray - The preallocated destination array.
      +
      dstOffsetChars - offset in array units
      +
      lengthChars - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      getDouble

      +
      +
      double getDouble()
      +
      Gets the double value at the current position. +Increments the position by Double.BYTES.
      +
      +
      Returns:
      +
      the double at the current position
      +
      +
      +
      +
    • +
    • +
      +

      getDouble

      +
      +
      double getDouble(long offsetBytes)
      +
      Gets the double value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      Returns:
      +
      the double at the given offset
      +
      +
      +
      +
    • +
    • +
      +

      getDoubleArray

      +
      +
      void getDoubleArray(double[] dstArray, + int dstOffsetDoubles, + int lengthDoubles)
      +
      Gets the double array at the current position. +Increments the position by Double.BYTES * (lengthDoubles - dstOffsetDoubles).
      +
      +
      Parameters:
      +
      dstArray - The preallocated destination array.
      +
      dstOffsetDoubles - offset in array units
      +
      lengthDoubles - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      getFloat

      +
      +
      float getFloat()
      +
      Gets the float value at the current position. +Increments the position by Float.BYTES.
      +
      +
      Returns:
      +
      the float at the current position
      +
      +
      +
      +
    • +
    • +
      +

      getFloat

      +
      +
      float getFloat(long offsetBytes)
      +
      Gets the float value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      Returns:
      +
      the float at the given offset
      +
      +
      +
      +
    • +
    • +
      +

      getFloatArray

      +
      +
      void getFloatArray(float[] dstArray, + int dstOffsetFloats, + int lengthFloats)
      +
      Gets the float array at the current position. +Increments the position by Float.BYTES * (lengthFloats - dstOffsetFloats).
      +
      +
      Parameters:
      +
      dstArray - The preallocated destination array.
      +
      dstOffsetFloats - offset in array units
      +
      lengthFloats - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      getInt

      +
      +
      int getInt()
      +
      Gets the int value at the current position. +Increments the position by Integer.BYTES.
      +
      +
      Returns:
      +
      the int at the current position
      +
      +
      +
      +
    • +
    • +
      +

      getInt

      +
      +
      int getInt(long offsetBytes)
      +
      Gets the int value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      Returns:
      +
      the int at the given offset
      +
      +
      +
      +
    • +
    • +
      +

      getIntArray

      +
      +
      void getIntArray(int[] dstArray, + int dstOffsetInts, + int lengthInts)
      +
      Gets the int array at the current position. +Increments the position by Integer.BYTES * (lengthInts - dstOffsetInts).
      +
      +
      Parameters:
      +
      dstArray - The preallocated destination array.
      +
      dstOffsetInts - offset in array units
      +
      lengthInts - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      getLong

      +
      +
      long getLong()
      +
      Gets the long value at the current position. +Increments the position by Long.BYTES.
      +
      +
      Returns:
      +
      the long at the current position
      +
      +
      +
      +
    • +
    • +
      +

      getLong

      +
      +
      long getLong(long offsetBytes)
      +
      Gets the long value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      Returns:
      +
      the long at the given offset
      +
      +
      +
      +
    • +
    • +
      +

      getLongArray

      +
      +
      void getLongArray(long[] dstArray, + int dstOffsetLongs, + int lengthLongs)
      +
      Gets the long array at the current position. +Increments the position by Long.BYTES * (lengthLongs - dstOffsetLongs).
      +
      +
      Parameters:
      +
      dstArray - The preallocated destination array.
      +
      dstOffsetLongs - offset in array units
      +
      lengthLongs - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      getShort

      +
      +
      short getShort()
      +
      Gets the short value at the current position. +Increments the position by Short.BYTES.
      +
      +
      Returns:
      +
      the short at the current position
      +
      +
      +
      +
    • +
    • +
      +

      getShort

      +
      +
      short getShort(long offsetBytes)
      +
      Gets the short value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      Returns:
      +
      the short at the given offset
      +
      +
      +
      +
    • +
    • +
      +

      getShortArray

      +
      +
      void getShortArray(short[] dstArray, + int dstOffsetShorts, + int lengthShorts)
      +
      Gets the short array at the current position. +Increments the position by Short.BYTES * (lengthShorts - dstOffsetShorts).
      +
      +
      Parameters:
      +
      dstArray - The preallocated destination array.
      +
      dstOffsetShorts - offset in array units
      +
      lengthShorts - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      setBoolean

      +
      +
      void setBoolean(boolean value)
      +
      Sets the boolean value at the current position. +Increments the position by Byte.BYTES.
      +
      +
      Parameters:
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setBoolean

      +
      +
      void setBoolean(long offsetBytes, + boolean value)
      +
      Sets the boolean value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start.
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setByte

      +
      +
      void setByte(byte value)
      +
      Sets the byte value at the current position. +Increments the position by Byte.BYTES.
      +
      +
      Parameters:
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setByte

      +
      +
      void setByte(long offsetBytes, + byte value)
      +
      Sets the byte value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setByteArray

      +
      +
      void setByteArray(byte[] srcArray, + int srcOffsetBytes, + int lengthBytes)
      +
      Sets the byte array at the current position. +Increments the position by Byte.BYTES * (lengthBytes - srcOffsetBytes).
      +
      +
      Parameters:
      +
      srcArray - The source array.
      +
      srcOffsetBytes - offset in array units
      +
      lengthBytes - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      setChar

      +
      +
      void setChar(char value)
      +
      Sets the char value at the current position. +Increments the position by Character.BYTES.
      +
      +
      Parameters:
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setChar

      +
      +
      void setChar(long offsetBytes, + char value)
      +
      Sets the char value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setCharArray

      +
      +
      void setCharArray(char[] srcArray, + int srcOffsetChars, + int lengthChars)
      +
      Sets the char array at the current position. +Increments the position by Character.BYTES * (lengthChars - srcOffsetChars).
      +
      +
      Parameters:
      +
      srcArray - The source array.
      +
      srcOffsetChars - offset in array units
      +
      lengthChars - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      setDouble

      +
      +
      void setDouble(double value)
      +
      Sets the double value at the current position. +Increments the position by Double.BYTES.
      +
      +
      Parameters:
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setDouble

      +
      +
      void setDouble(long offsetBytes, + double value)
      +
      Sets the double value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setDoubleArray

      +
      +
      void setDoubleArray(double[] srcArray, + int srcOffsetDoubles, + int lengthDoubles)
      +
      Sets the double array at the current position. +Increments the position by Double.BYTES * (lengthDoubles - srcOffsetDoubles).
      +
      +
      Parameters:
      +
      srcArray - The source array.
      +
      srcOffsetDoubles - offset in array units
      +
      lengthDoubles - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      setFloat

      +
      +
      void setFloat(float value)
      +
      Sets the float value at the current position. +Increments the position by Float.BYTES.
      +
      +
      Parameters:
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setFloat

      +
      +
      void setFloat(long offsetBytes, + float value)
      +
      Sets the float value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setFloatArray

      +
      +
      void setFloatArray(float[] srcArray, + int srcOffsetFloats, + int lengthFloats)
      +
      Sets the float array at the current position. +Increments the position by Float.BYTES * (lengthFloats - srcOffsetFloats).
      +
      +
      Parameters:
      +
      srcArray - The source array.
      +
      srcOffsetFloats - offset in array units
      +
      lengthFloats - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      setInt

      +
      +
      void setInt(int value)
      +
      Sets the int value at the current position. +Increments the position by Integer.BYTES.
      +
      +
      Parameters:
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setInt

      +
      +
      void setInt(long offsetBytes, + int value)
      +
      Sets the int value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setIntArray

      +
      +
      void setIntArray(int[] srcArray, + int srcOffsetInts, + int lengthInts)
      +
      Sets the int array at the current position. +Increments the position by Integer.BYTES * (lengthInts - srcOffsetInts).
      +
      +
      Parameters:
      +
      srcArray - The source array.
      +
      srcOffsetInts - offset in array units
      +
      lengthInts - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      setLong

      +
      +
      void setLong(long value)
      +
      Sets the long value at the current position. +Increments the position by Long.BYTES.
      +
      +
      Parameters:
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setLong

      +
      +
      void setLong(long offsetBytes, + long value)
      +
      Sets the long value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setLongArray

      +
      +
      void setLongArray(long[] srcArray, + int srcOffsetLongs, + int lengthLongs)
      +
      Sets the long array at the current position. +Increments the position by Long.BYTES * (lengthLongs - srcOffsetLongs).
      +
      +
      Parameters:
      +
      srcArray - The source array.
      +
      srcOffsetLongs - offset in array units
      +
      lengthLongs - number of array units to transfer
      +
      +
      +
      +
    • +
    • +
      +

      setShort

      +
      +
      void setShort(short value)
      +
      Sets the short value at the current position. +Increments the position by Short.BYTES.
      +
      +
      Parameters:
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setShort

      +
      +
      void setShort(long offsetBytes, + short value)
      +
      Sets the short value at the given offset. +This does not change the position.
      +
      +
      Parameters:
      +
      offsetBytes - offset bytes relative to this MemorySegment start
      +
      value - the value to put
      +
      +
      +
      +
    • +
    • +
      +

      setShortArray

      +
      +
      void setShortArray(short[] srcArray, + int srcOffsetShorts, + int lengthShorts)
      +
      Sets the short array at the current position. +Increments the position by Short.BYTES * (lengthShorts - srcOffsetShorts).
      +
      +
      Parameters:
      +
      srcArray - The source array.
      +
      srcOffsetShorts - offset in array units
      +
      lengthShorts - number of array units to transfer
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/positional/class-use/PositionInvariantsException.html b/target/site/apidocs/org/apache/datasketches/common/positional/class-use/PositionInvariantsException.html new file mode 100644 index 000000000..2abd44711 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/positional/class-use/PositionInvariantsException.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.common.positional.PositionInvariantsException (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.common.positional.PositionInvariantsException

+
+No usage of org.apache.datasketches.common.positional.PositionInvariantsException +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/positional/class-use/Positional.html b/target/site/apidocs/org/apache/datasketches/common/positional/class-use/Positional.html new file mode 100644 index 000000000..4bfdb3790 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/positional/class-use/Positional.html @@ -0,0 +1,129 @@ + + + + +Uses of Interface org.apache.datasketches.common.positional.Positional (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.common.positional.Positional

+
+
Packages that use Positional
+
+
Package
+
Description
+ +
+
This package provides the classes that define and implement a relative positional API.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/positional/class-use/PositionalSegment.html b/target/site/apidocs/org/apache/datasketches/common/positional/class-use/PositionalSegment.html new file mode 100644 index 000000000..2598b1e11 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/positional/class-use/PositionalSegment.html @@ -0,0 +1,100 @@ + + + + +Uses of Interface org.apache.datasketches.common.positional.PositionalSegment (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.common.positional.PositionalSegment

+
+
Packages that use PositionalSegment
+
+
Package
+
Description
+ +
+
This package provides the classes that define and implement a relative positional API.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/positional/package-summary.html b/target/site/apidocs/org/apache/datasketches/common/positional/package-summary.html new file mode 100644 index 000000000..fd4e92fa2 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/positional/package-summary.html @@ -0,0 +1,130 @@ + + + + +org.apache.datasketches.common.positional (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.common.positional

+
+
+
+
package org.apache.datasketches.common.positional
+
+
This package provides the classes that define and implement a relative positional API.
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+
    +
  • + +
  • +
  • +
    +
    +
    +
    +
    Class
    +
    Description
    + +
    +
    Defines the relative positional API.
    +
    + +
    +
    Defines the API for relative positional access to a MemorySegment.
    +
    + +
    +
    Position operation violation.
    +
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/positional/package-tree.html b/target/site/apidocs/org/apache/datasketches/common/positional/package-tree.html new file mode 100644 index 000000000..fc18153f2 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/positional/package-tree.html @@ -0,0 +1,101 @@ + + + + +org.apache.datasketches.common.positional Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.common.positional

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Interface Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/common/positional/package-use.html b/target/site/apidocs/org/apache/datasketches/common/positional/package-use.html new file mode 100644 index 000000000..21e227845 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/common/positional/package-use.html @@ -0,0 +1,95 @@ + + + + +Uses of Package org.apache.datasketches.common.positional (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.common.positional

+
+ +
+
Package
+
Description
+ +
+
This package provides the classes that define and implement a relative positional API.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/count/CountMinSketch.html b/target/site/apidocs/org/apache/datasketches/count/CountMinSketch.html new file mode 100644 index 000000000..81a3f6b72 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/count/CountMinSketch.html @@ -0,0 +1,605 @@ + + + + +CountMinSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class CountMinSketch

+
+
java.lang.Object +
org.apache.datasketches.count.CountMinSketch
+
+
+
+
+
public class CountMinSketch +extends Object
+
Java implementation of the CountMin sketch data structure of Cormode and Muthukrishnan. +This implementation is inspired by and compatible with the datasketches-cpp version by Charlie Dickens. + +The CountMin sketch is a probabilistic data structure that provides frequency estimates for items +in a data stream. It uses multiple hash functions to distribute items across a two-dimensional array, +providing approximate counts with configurable error bounds. + +Reference: http://dimacs.rutgers.edu/~graham/pubs/papers/cm-full.pdf
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + +
    deserialize(byte[] b, + long seed)
    +
    +
    Deserializes a CountMinSketch from the provided byte array.
    +
    +
    long
    +
    getEstimate(byte[] item)
    +
    +
    Returns the estimated frequency for the given item.
    +
    +
    long
    +
    getEstimate(long item)
    +
    +
    Returns the estimated frequency for the given item.
    +
    +
    long
    + +
    +
    Returns the estimated frequency for the given item.
    +
    +
    long
    +
    getLowerBound(byte[] item)
    +
    +
    Returns the lower bound of the estimated frequency for the given item.
    +
    +
    long
    +
    getLowerBound(long item)
    +
    +
    Returns the lower bound of the estimated frequency for the given item.
    +
    +
    long
    + +
    +
    Returns the lower bound of the estimated frequency for the given item.
    +
    +
    int
    + +
    +
    Returns the number of buckets per hash function.
    +
    +
    byte
    + +
    +
    Returns the number of hash functions used in this sketch.
    +
    +
    double
    + +
    +
    Returns the relative error of the sketch.
    +
    +
    long
    + +
    +
    Returns the hash seed used by this sketch.
    +
    +
    long
    + +
    +
    Returns the total weight of all items inserted into the sketch.
    +
    +
    long
    +
    getUpperBound(byte[] item)
    +
    +
    Returns the upper bound of the estimated frequency for the given item.
    +
    +
    long
    +
    getUpperBound(long item)
    +
    +
    Returns the upper bound of the estimated frequency for the given item.
    +
    +
    long
    + +
    +
    Returns the upper bound of the estimated frequency for the given item.
    +
    +
    boolean
    + +
    +
    Checks if the CountMinSketch has processed any items.
    +
    +
    void
    + +
    +
    Merges another CountMinSketch into this one.
    +
    +
    static int
    +
    suggestNumBuckets(double relativeError)
    +
    +
    Suggests an appropriate number of buckets per hash function for a given relative error.
    +
    +
    static byte
    +
    suggestNumHashes(double confidence)
    +
    +
    Suggests an appropriate number of hash functions to use for a given confidence level.
    +
    +
    byte[]
    + +
    +
    Returns the sketch as a byte array.
    +
    +
    void
    +
    update(byte[] item, + long weight)
    +
    +
    Updates the sketch with the provided item and weight.
    +
    +
    void
    +
    update(long item, + long weight)
    +
    +
    Updates the sketch with the provided item and weight.
    +
    +
    void
    +
    update(String item, + long weight)
    +
    +
    Updates the sketch with the provided item and weight.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Checks if the CountMinSketch has processed any items.
      +
      +
      Returns:
      +
      True if the sketch is empty, otherwise false.
      +
      +
      +
      +
    • +
    • +
      +

      getNumHashes_

      +
      +
      public byte getNumHashes_()
      +
      Returns the number of hash functions used in this sketch.
      +
      +
      Returns:
      +
      The number of hash functions.
      +
      +
      +
      +
    • +
    • +
      +

      getNumBuckets_

      +
      +
      public int getNumBuckets_()
      +
      Returns the number of buckets per hash function.
      +
      +
      Returns:
      +
      The number of buckets.
      +
      +
      +
      +
    • +
    • +
      +

      getSeed_

      +
      +
      public long getSeed_()
      +
      Returns the hash seed used by this sketch.
      +
      +
      Returns:
      +
      The seed value.
      +
      +
      +
      +
    • +
    • +
      +

      getTotalWeight_

      +
      +
      public long getTotalWeight_()
      +
      Returns the total weight of all items inserted into the sketch.
      +
      +
      Returns:
      +
      The total weight.
      +
      +
      +
      +
    • +
    • +
      +

      getRelativeError

      +
      +
      public double getRelativeError()
      +
      Returns the relative error of the sketch.
      +
      +
      Returns:
      +
      The relative error.
      +
      +
      +
      +
    • +
    • +
      +

      suggestNumHashes

      +
      +
      public static byte suggestNumHashes(double confidence)
      +
      Suggests an appropriate number of hash functions to use for a given confidence level.
      +
      +
      Parameters:
      +
      confidence - The desired confidence level between 0 and 1.
      +
      Returns:
      +
      Suggested number of hash functions.
      +
      +
      +
      +
    • +
    • +
      +

      suggestNumBuckets

      +
      +
      public static int suggestNumBuckets(double relativeError)
      +
      Suggests an appropriate number of buckets per hash function for a given relative error.
      +
      +
      Parameters:
      +
      relativeError - The desired relative error.
      +
      Returns:
      +
      Suggested number of buckets.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long item, + long weight)
      +
      Updates the sketch with the provided item and weight.
      +
      +
      Parameters:
      +
      item - The item to update.
      +
      weight - The weight of the item.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(String item, + long weight)
      +
      Updates the sketch with the provided item and weight.
      +
      +
      Parameters:
      +
      item - The item to update.
      +
      weight - The weight of the item.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(byte[] item, + long weight)
      +
      Updates the sketch with the provided item and weight.
      +
      +
      Parameters:
      +
      item - The item to update.
      +
      weight - The weight of the item.
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public long getEstimate(long item)
      +
      Returns the estimated frequency for the given item.
      +
      +
      Parameters:
      +
      item - The item to estimate.
      +
      Returns:
      +
      Estimated frequency.
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public long getEstimate(String item)
      +
      Returns the estimated frequency for the given item.
      +
      +
      Parameters:
      +
      item - The item to estimate.
      +
      Returns:
      +
      Estimated frequency.
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public long getEstimate(byte[] item)
      +
      Returns the estimated frequency for the given item.
      +
      +
      Parameters:
      +
      item - The item to estimate.
      +
      Returns:
      +
      Estimated frequency.
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public long getUpperBound(long item)
      +
      Returns the upper bound of the estimated frequency for the given item.
      +
      +
      Parameters:
      +
      item - The item to estimate.
      +
      Returns:
      +
      Upper bound of estimated frequency.
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public long getUpperBound(String item)
      +
      Returns the upper bound of the estimated frequency for the given item.
      +
      +
      Parameters:
      +
      item - The item to estimate.
      +
      Returns:
      +
      Upper bound of estimated frequency.
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public long getUpperBound(byte[] item)
      +
      Returns the upper bound of the estimated frequency for the given item.
      +
      +
      Parameters:
      +
      item - The item to estimate.
      +
      Returns:
      +
      Upper bound of estimated frequency.
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public long getLowerBound(long item)
      +
      Returns the lower bound of the estimated frequency for the given item.
      +
      +
      Parameters:
      +
      item - The item to estimate.
      +
      Returns:
      +
      Lower bound of estimated frequency.
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public long getLowerBound(String item)
      +
      Returns the lower bound of the estimated frequency for the given item.
      +
      +
      Parameters:
      +
      item - The item to estimate.
      +
      Returns:
      +
      Lower bound of estimated frequency.
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public long getLowerBound(byte[] item)
      +
      Returns the lower bound of the estimated frequency for the given item.
      +
      +
      Parameters:
      +
      item - The item to estimate.
      +
      Returns:
      +
      Lower bound of estimated frequency.
      +
      +
      +
      +
    • +
    • +
      +

      merge

      +
      +
      public void merge(CountMinSketch other)
      +
      Merges another CountMinSketch into this one. The sketches must have the same configuration.
      +
      +
      Parameters:
      +
      other - The other sketch to merge.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Returns the sketch as a byte array.
      +
      +
      Returns:
      +
      the result byte array
      +
      +
      +
      +
    • +
    • +
      +

      deserialize

      +
      +
      public static CountMinSketch deserialize(byte[] b, + long seed)
      +
      Deserializes a CountMinSketch from the provided byte array.
      +
      +
      Parameters:
      +
      b - The byte array containing the serialized sketch.
      +
      seed - The seed used during serialization.
      +
      Returns:
      +
      The deserialized CountMinSketch.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/count/class-use/CountMinSketch.html b/target/site/apidocs/org/apache/datasketches/count/class-use/CountMinSketch.html new file mode 100644 index 000000000..262ade4a3 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/count/class-use/CountMinSketch.html @@ -0,0 +1,108 @@ + + + + +Uses of Class org.apache.datasketches.count.CountMinSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.count.CountMinSketch

+
+
Packages that use CountMinSketch
+
+
Package
+
Description
+ +
+
This package in intended for implementations of the the Count Sketch and the Count-min Sketch both of which can be used to estimate +frequency-moments of a stream of distinct elements.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/count/package-summary.html b/target/site/apidocs/org/apache/datasketches/count/package-summary.html new file mode 100644 index 000000000..7eaac0800 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/count/package-summary.html @@ -0,0 +1,131 @@ + + + + +org.apache.datasketches.count (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.count

+
+
+
+
package org.apache.datasketches.count
+
+
This package in intended for implementations of the the Count Sketch and the Count-min Sketch both of which can be used to estimate +frequency-moments of a stream of distinct elements. They are different from the unique counting sketches (HLL, Theta, CPC, etc.) +and different from the Frequent-Items Sketch. + +

A Count-Min sketch is a probabilistic data structure that estimates the frequency of items in a large data stream using a +fixed amount of memory. It uses a 2D array of counters and multiple hash functions to map each item to a position in every row. +To estimate an item's frequency, it takes the minimum count from all the positions it hashes to, which provides an overestimate +that is guaranteed to be greater than or equal to the true count.

+ +

A Count sketch is a type of dimensionality reduction that is particularly efficient in statistics, machine learning and +algorithms. It was invented by Moses Charikar, Kevin Chen and Martin Farach-Colton in an effort to speed up the AMS Sketch by +Alon, Matias and Szegedy for approximating the frequency moments of streams[4] (these calculations require counting of the +number of occurrences for the distinct elements of the stream).

+
+
See Also:
+
+ +
+
+
+
+
+
    +
  • + +
  • +
  • +
    +
    Classes
    +
    +
    Class
    +
    Description
    + +
    +
    Java implementation of the CountMin sketch data structure of Cormode and Muthukrishnan.
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/count/package-tree.html b/target/site/apidocs/org/apache/datasketches/count/package-tree.html new file mode 100644 index 000000000..cde84f0cb --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/count/package-tree.html @@ -0,0 +1,79 @@ + + + + +org.apache.datasketches.count Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.count

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/count/package-use.html b/target/site/apidocs/org/apache/datasketches/count/package-use.html new file mode 100644 index 000000000..8a8d81b7b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/count/package-use.html @@ -0,0 +1,92 @@ + + + + +Uses of Package org.apache.datasketches.count (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.count

+
+ +
+
Package
+
Description
+ +
+
This package in intended for implementations of the the Count Sketch and the Count-min Sketch both of which can be used to estimate +frequency-moments of a stream of distinct elements.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/CompressionCharacterization.html b/target/site/apidocs/org/apache/datasketches/cpc/CompressionCharacterization.html new file mode 100644 index 000000000..48354103f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/CompressionCharacterization.html @@ -0,0 +1,213 @@ + + + + +CompressionCharacterization (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class CompressionCharacterization

+
+
java.lang.Object +
org.apache.datasketches.cpc.CompressionCharacterization
+
+
+
+
+
public class CompressionCharacterization +extends Object
+
This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing. To be +accessible for both, this code is part of the main hierarchy. It is not used during normal +production runtime.
+
+
Author:
+
Lee Rhodes, Kevin Lang
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      CompressionCharacterization

      +
      +
      public CompressionCharacterization(int lgMinK, + int lgMaxK, + int lgMinT, + int lgMaxT, + int lgMulK, + int uPPO, + int incLgK, + PrintStream pS, + PrintWriter pW)
      +
      Only used in test.
      +
      +
      Parameters:
      +
      lgMinK - min lgK
      +
      lgMaxK - max lgK
      +
      lgMinT - min lgTrials
      +
      lgMaxT - max lgTrials
      +
      lgMulK - lg multiple
      +
      uPPO - unique axis Points Per Octave
      +
      incLgK - increment lgK
      +
      pS - PrintStream
      +
      pW - PrintWriter
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      start

      +
      +
      public void start()
      +
      Only used in test
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/CpcSketch.html b/target/site/apidocs/org/apache/datasketches/cpc/CpcSketch.html new file mode 100644 index 000000000..9363cfc5f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/CpcSketch.html @@ -0,0 +1,832 @@ + + + + +CpcSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class CpcSketch

+
+
java.lang.Object +
org.apache.datasketches.cpc.CpcSketch
+
+
+
+
+
public final class CpcSketch +extends Object
+
This is a unique-counting sketch that implements the +Compressed Probabilistic Counting (CPC, a.k.a FM85) algorithms developed by Kevin Lang in +his paper +Back to the Future: an Even More Nearly +Optimal Cardinality Estimation Algorithm. + +

This sketch is extremely space-efficient when serialized. In an apples-to-apples empirical +comparison against compressed HyperLogLog sketches, this new algorithm simultaneously wins on +the two dimensions of the space/accuracy tradeoff and produces sketches that are +smaller than the entropy of HLL, so no possible implementation of compressed HLL can match its +space efficiency for a given accuracy. As described in the paper this sketch implements a newly +developed ICON estimator algorithm that survives unioning operations, another +well-known estimator, the +Historical Inverse Probability (HIP) estimator +does not. +The update speed performance of this sketch is quite fast and is comparable to the speed of HLL. +The unioning (merging) capability of this sketch also allows for merging of sketches with +different configurations of K. + +

For additional security this sketch can be configured with a user-specified hash seed.

+
+
Author:
+
Lee Rhodes, Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    static final int
    + +
    +
    The default Log_base2 of K
    +
    +
    +
    +
  • + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    Constructor with default log_base2 of k
    +
    +
    CpcSketch(int lgK)
    +
    +
    Constructor with log_base2 of k.
    +
    +
    CpcSketch(int lgK, + long seed)
    +
    +
    Constructor with log_base2 of k and seed.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    double
    + +
    +
    Returns the best estimate of the cardinality of the sketch.
    +
    +
    static Family
    + +
    +
    Return the DataSketches identifier for this CPC family of sketches.
    +
    +
    int
    + +
    +
    Return the parameter LgK.
    +
    +
    double
    +
    getLowerBound(int kappa)
    +
    +
    Returns the best estimate of the lower bound of the confidence interval given kappa, +the number of standard deviations from the mean.
    +
    +
    static int
    + +
    +
    The actual size of a compressed CPC sketch has a small random variance, but the following +empirically measured size should be large enough for at least 99.9 percent of sketches.
    +
    +
    double
    +
    getUpperBound(int kappa)
    +
    +
    Returns the best estimate of the upper bound of the confidence interval given kappa, +the number of standard deviations from the mean.
    +
    +
    static CpcSketch
    +
    heapify(byte[] byteArray)
    +
    +
    Return the given byte array as a CpcSketch on the Java heap using the DEFAULT_UPDATE_SEED.
    +
    +
    static CpcSketch
    +
    heapify(byte[] byteArray, + long seed)
    +
    +
    Return the given byte array as a CpcSketch on the Java heap.
    +
    +
    static CpcSketch
    + +
    +
    Return the given MemorySegment as a CpcSketch on the Java heap using the DEFAULT_UPDATE_SEED.
    +
    +
    static CpcSketch
    +
    heapify(MemorySegment seg, + long seed)
    +
    +
    Return the given MemorySegment as a CpcSketch on the Java heap.
    +
    +
    boolean
    + +
    +
    Return true if this sketch is empty
    +
    +
    void
    + +
    +
    Resets this sketch to empty but retains the original LgK and Seed.
    +
    +
    byte[]
    + +
    +
    Return this sketch as a compressed byte array.
    +
    + + +
    +
    Return a human-readable string summary of this sketch
    +
    + +
    toString(boolean detail)
    +
    +
    Return a human-readable string summary of this sketch
    +
    +
    static String
    +
    toString(byte[] byteArr, + boolean detail)
    +
    +
    Returns a human readable string of the preamble of a byte array image of a CpcSketch.
    +
    +
    static String
    +
    toString(MemorySegment seg, + boolean detail)
    +
    +
    Returns a human readable string of the preamble of a MemorySegment image of a CpcSketch.
    +
    +
    void
    +
    update(byte[] data)
    +
    +
    Present the given byte array as a potential unique item.
    +
    +
    void
    +
    update(char[] data)
    +
    +
    Present the given char array as a potential unique item.
    +
    +
    void
    +
    update(double datum)
    +
    +
    Present the given double (or float) datum as a potential unique item.
    +
    +
    void
    +
    update(int[] data)
    +
    +
    Present the given integer array as a potential unique item.
    +
    +
    void
    +
    update(long datum)
    +
    +
    Present the given long as a potential unique item.
    +
    +
    void
    +
    update(long[] data)
    +
    +
    Present the given long array as a potential unique item.
    +
    +
    void
    +
    update(String datum)
    +
    +
    Present the given String as a potential unique item.
    +
    +
    void
    + +
    +
    Present the given ByteBuffer as a potential unique item +If the ByteBuffer is null or empty no update attempt is made and the method returns
    +
    +
    boolean
    + +
    +
    Convience function that this Sketch is valid.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      DEFAULT_LG_K

      +
      +
      public static final int DEFAULT_LG_K
      +
      The default Log_base2 of K
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      CpcSketch

      +
      +
      public CpcSketch()
      +
      Constructor with default log_base2 of k
      +
      +
      +
    • +
    • +
      +

      CpcSketch

      +
      +
      public CpcSketch(int lgK)
      +
      Constructor with log_base2 of k.
      +
      +
      Parameters:
      +
      lgK - the given log_base2 of k
      +
      +
      +
      +
    • +
    • +
      +

      CpcSketch

      +
      +
      public CpcSketch(int lgK, + long seed)
      +
      Constructor with log_base2 of k and seed.
      +
      +
      Parameters:
      +
      lgK - the given log_base2 of k
      +
      seed - the given seed
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getEstimate

      +
      +
      public double getEstimate()
      +
      Returns the best estimate of the cardinality of the sketch.
      +
      +
      Returns:
      +
      the best estimate of the cardinality of the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getFamily

      +
      +
      public static Family getFamily()
      +
      Return the DataSketches identifier for this CPC family of sketches.
      +
      +
      Returns:
      +
      the DataSketches identifier for this CPC family of sketches.
      +
      +
      +
      +
    • +
    • +
      +

      getLgK

      +
      +
      public int getLgK()
      +
      Return the parameter LgK.
      +
      +
      Returns:
      +
      the parameter LgK.
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public double getLowerBound(int kappa)
      +
      Returns the best estimate of the lower bound of the confidence interval given kappa, +the number of standard deviations from the mean.
      +
      +
      Parameters:
      +
      kappa - the given number of standard deviations from the mean: 1, 2 or 3.
      +
      Returns:
      +
      the best estimate of the lower bound of the confidence interval given kappa.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxSerializedBytes

      +
      +
      public static int getMaxSerializedBytes(int lgK)
      +
      The actual size of a compressed CPC sketch has a small random variance, but the following +empirically measured size should be large enough for at least 99.9 percent of sketches. + +

      For small values of n the size can be much smaller.

      +
      +
      Parameters:
      +
      lgK - the given value of lgK.
      +
      Returns:
      +
      the estimated maximum compressed serialized size of a sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public double getUpperBound(int kappa)
      +
      Returns the best estimate of the upper bound of the confidence interval given kappa, +the number of standard deviations from the mean.
      +
      +
      Parameters:
      +
      kappa - the given number of standard deviations from the mean: 1, 2 or 3.
      +
      Returns:
      +
      the best estimate of the upper bound of the confidence interval given kappa.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static CpcSketch heapify(MemorySegment seg)
      +
      Return the given MemorySegment as a CpcSketch on the Java heap using the DEFAULT_UPDATE_SEED.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      the given MemorySegment as a CpcSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static CpcSketch heapify(byte[] byteArray)
      +
      Return the given byte array as a CpcSketch on the Java heap using the DEFAULT_UPDATE_SEED.
      +
      +
      Parameters:
      +
      byteArray - the given byte array
      +
      Returns:
      +
      the given byte array as a CpcSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static CpcSketch heapify(MemorySegment seg, + long seed)
      +
      Return the given MemorySegment as a CpcSketch on the Java heap.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      seed - the seed used to create the original sketch from which the MemorySegment was derived.
      +
      Returns:
      +
      the given MemorySegment as a CpcSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static CpcSketch heapify(byte[] byteArray, + long seed)
      +
      Return the given byte array as a CpcSketch on the Java heap.
      +
      +
      Parameters:
      +
      byteArray - the given byte array
      +
      seed - the seed used to create the original sketch from which the byte array was derived.
      +
      Returns:
      +
      the given byte array as a CpcSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Return true if this sketch is empty
      +
      +
      Returns:
      +
      true if this sketch is empty
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch to empty but retains the original LgK and Seed.
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Return this sketch as a compressed byte array.
      +
      +
      Returns:
      +
      this sketch as a compressed byte array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long datum)
      +
      Present the given long as a potential unique item.
      +
      +
      Parameters:
      +
      datum - The given long datum.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(double datum)
      +
      Present the given double (or float) datum as a potential unique item. +The double will be converted to a long using Double.doubleToLongBits(datum), +which normalizes all NaN values to a single NaN representation. +Plus and minus zero will be normalized to plus zero. +The special floating-point values NaN and +/- Infinity are treated as distinct.
      +
      +
      Parameters:
      +
      datum - The given double datum.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(String datum)
      +
      Present the given String as a potential unique item. +The string is converted to a byte array using UTF8 encoding. +If the string is null or empty no update attempt is made and the method returns. + +

      Note: About 2X faster performance can be obtained by first converting the String to a +char[] and updating the sketch with that. This bypasses the complexity of the Java UTF_8 +encoding. This, of course, will not produce the same internal hash values as updating directly +with a String. So be consistent! Unioning two sketches, one fed with strings and the other +fed with char[] will be meaningless. +

      +
      +
      Parameters:
      +
      datum - The given String.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(byte[] data)
      +
      Present the given byte array as a potential unique item. +If the byte array is null or empty no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      data - The given byte array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(ByteBuffer data)
      +
      Present the given ByteBuffer as a potential unique item +If the ByteBuffer is null or empty no update attempt is made and the method returns
      +
      +
      Parameters:
      +
      data - The given ByteBuffer
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(char[] data)
      +
      Present the given char array as a potential unique item. +If the char array is null or empty no update attempt is made and the method returns. + +

      Note: this will not produce the same output hash values as the update(String) +method but will be a little faster as it avoids the complexity of the UTF8 encoding.

      +
      +
      Parameters:
      +
      data - The given char array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(int[] data)
      +
      Present the given integer array as a potential unique item. +If the integer array is null or empty no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      data - The given int array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long[] data)
      +
      Present the given long array as a potential unique item. +If the long array is null or empty no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      data - The given long array.
      +
      +
      +
      +
    • +
    • +
      +

      validate

      +
      +
      public boolean validate()
      +
      Convience function that this Sketch is valid. This is a troubleshooting tool +for sketches that have been heapified from serialized images. + +

      If you are starting with a serialized image as a byte array, first heapify +the byte array to a sketch, which performs a number of checks. Then use this +function as one additional check on the sketch.

      +
      +
      Returns:
      +
      true if this sketch is validated.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Return a human-readable string summary of this sketch
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean detail)
      +
      Return a human-readable string summary of this sketch
      +
      +
      Parameters:
      +
      detail - include data detail
      +
      Returns:
      +
      a human-readable string summary of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(byte[] byteArr, + boolean detail)
      +
      Returns a human readable string of the preamble of a byte array image of a CpcSketch.
      +
      +
      Parameters:
      +
      byteArr - the given byte array
      +
      detail - if true, a dump of the compressed window and surprising value streams will be +included.
      +
      Returns:
      +
      a human readable string of the preamble of a byte array image of a CpcSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(MemorySegment seg, + boolean detail)
      +
      Returns a human readable string of the preamble of a MemorySegment image of a CpcSketch.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      detail - if true, a dump of the compressed window and surprising value streams will be +included.
      +
      Returns:
      +
      a human readable string of the preamble of a MemorySegment image of a CpcSketch.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/CpcUnion.html b/target/site/apidocs/org/apache/datasketches/cpc/CpcUnion.html new file mode 100644 index 000000000..44557cf81 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/CpcUnion.html @@ -0,0 +1,284 @@ + + + + +CpcUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class CpcUnion

+
+
java.lang.Object +
org.apache.datasketches.cpc.CpcUnion
+
+
+
+
+
public class CpcUnion +extends Object
+
The union (merge) operation for the CPC sketches.
+
+
Author:
+
Lee Rhodes, Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    Construct this unioning object with the default LgK and the default update seed.
    +
    +
    CpcUnion(int lgK)
    +
    +
    Construct this unioning object with LgK and the default update seed.
    +
    +
    CpcUnion(int lgK, + long seed)
    +
    +
    Construct this unioning object with LgK and a given seed.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static Family
    + +
    +
    Return the DataSketches identifier for this CPC family of sketches.
    +
    +
    int
    + +
    +
    Returns the current value of Log_base2 of K.
    +
    + + +
    +
    Returns the result of union operations as a CPC sketch.
    +
    +
    void
    +
    update(CpcSketch sketch)
    +
    +
    Update this union with a CpcSketch.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      CpcUnion

      +
      +
      public CpcUnion()
      +
      Construct this unioning object with the default LgK and the default update seed.
      +
      +
      +
    • +
    • +
      +

      CpcUnion

      +
      +
      public CpcUnion(int lgK)
      +
      Construct this unioning object with LgK and the default update seed.
      +
      +
      Parameters:
      +
      lgK - The given log2 of K.
      +
      +
      +
      +
    • +
    • +
      +

      CpcUnion

      +
      +
      public CpcUnion(int lgK, + long seed)
      +
      Construct this unioning object with LgK and a given seed.
      +
      +
      Parameters:
      +
      lgK - The given log2 of K.
      +
      seed - The given seed.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      update

      +
      +
      public void update(CpcSketch sketch)
      +
      Update this union with a CpcSketch.
      +
      +
      Parameters:
      +
      sketch - the given CpcSketch.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public CpcSketch getResult()
      +
      Returns the result of union operations as a CPC sketch.
      +
      +
      Returns:
      +
      the result of union operations as a CPC sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getLgK

      +
      +
      public int getLgK()
      +
      Returns the current value of Log_base2 of K. Note that due to merging with source sketches that +may have a lower value of LgK, this value can be less than what the union object was configured +with.
      +
      +
      Returns:
      +
      the current value of Log_base2 of K.
      +
      +
      +
      +
    • +
    • +
      +

      getFamily

      +
      +
      public static Family getFamily()
      +
      Return the DataSketches identifier for this CPC family of sketches.
      +
      +
      Returns:
      +
      the DataSketches identifier for this CPC family of sketches.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/CpcWrapper.html b/target/site/apidocs/org/apache/datasketches/cpc/CpcWrapper.html new file mode 100644 index 000000000..5b88f1e2f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/CpcWrapper.html @@ -0,0 +1,293 @@ + + + + +CpcWrapper (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class CpcWrapper

+
+
java.lang.Object +
org.apache.datasketches.cpc.CpcWrapper
+
+
+
+
+
public final class CpcWrapper +extends Object
+
This provides a read-only view of a serialized image of a CpcSketch, which can be +on-heap or off-heap represented as a MemorySegment object, or on-heap represented as a byte array.
+
+
Author:
+
Lee Rhodes, Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    +
    CpcWrapper(byte[] byteArray)
    +
    +
    Construct a read-only view of the given byte array that contains a CpcSketch.
    +
    + +
    +
    Construct a read-only view of the given MemorySegment that contains a CpcSketch
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    double
    + +
    +
    Returns the best estimate of the cardinality of the sketch.
    +
    +
    static Family
    + +
    +
    Return the DataSketches identifier for this CPC family of sketches.
    +
    +
    int
    + +
    +
    Returns the configured Log_base2 of K of this sketch.
    +
    +
    double
    +
    getLowerBound(int kappa)
    +
    +
    Returns the best estimate of the lower bound of the confidence interval given kappa, +the number of standard deviations from the mean.
    +
    +
    double
    +
    getUpperBound(int kappa)
    +
    +
    Returns the best estimate of the upper bound of the confidence interval given kappa, +the number of standard deviations from the mean.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      CpcWrapper

      +
      +
      public CpcWrapper(MemorySegment seg)
      +
      Construct a read-only view of the given MemorySegment that contains a CpcSketch
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      CpcWrapper

      +
      +
      public CpcWrapper(byte[] byteArray)
      +
      Construct a read-only view of the given byte array that contains a CpcSketch.
      +
      +
      Parameters:
      +
      byteArray - the given byte array
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getEstimate

      +
      +
      public double getEstimate()
      +
      Returns the best estimate of the cardinality of the sketch.
      +
      +
      Returns:
      +
      the best estimate of the cardinality of the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getFamily

      +
      +
      public static Family getFamily()
      +
      Return the DataSketches identifier for this CPC family of sketches.
      +
      +
      Returns:
      +
      the DataSketches identifier for this CPC family of sketches.
      +
      +
      +
      +
    • +
    • +
      +

      getLgK

      +
      +
      public int getLgK()
      +
      Returns the configured Log_base2 of K of this sketch.
      +
      +
      Returns:
      +
      the configured Log_base2 of K of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public double getLowerBound(int kappa)
      +
      Returns the best estimate of the lower bound of the confidence interval given kappa, +the number of standard deviations from the mean.
      +
      +
      Parameters:
      +
      kappa - the given number of standard deviations from the mean: 1, 2 or 3.
      +
      Returns:
      +
      the best estimate of the lower bound of the confidence interval given kappa.
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public double getUpperBound(int kappa)
      +
      Returns the best estimate of the upper bound of the confidence interval given kappa, +the number of standard deviations from the mean.
      +
      +
      Parameters:
      +
      kappa - the given number of standard deviations from the mean: 1, 2 or 3.
      +
      Returns:
      +
      the best estimate of the upper bound of the confidence interval given kappa.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/MergingValidation.html b/target/site/apidocs/org/apache/datasketches/cpc/MergingValidation.html new file mode 100644 index 000000000..2dbec6c48 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/MergingValidation.html @@ -0,0 +1,207 @@ + + + + +MergingValidation (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class MergingValidation

+
+
java.lang.Object +
org.apache.datasketches.cpc.MergingValidation
+
+
+
+
+
public class MergingValidation +extends Object
+
This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing. To be +accessible for both, this code is part of the main hierarchy. It is not used during normal +production runtime.
+
+
Author:
+
Lee Rhodes, Kevin Lang
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      MergingValidation

      +
      +
      public MergingValidation(int lgMinK, + int lgMaxK, + int lgMulK, + int uPPO, + int incLgK, + PrintStream pS, + PrintWriter pW)
      +
      Constructor
      +
      +
      Parameters:
      +
      lgMinK - lgMinK
      +
      lgMaxK - lgMaxK
      +
      lgMulK - lgMulK
      +
      uPPO - uPPO
      +
      incLgK - incLgK
      +
      pS - pS
      +
      pW - pW
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      start

      +
      +
      public void start()
      +
      Start the merging validation process
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/QuickMergingValidation.html b/target/site/apidocs/org/apache/datasketches/cpc/QuickMergingValidation.html new file mode 100644 index 000000000..3e1b3e925 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/QuickMergingValidation.html @@ -0,0 +1,204 @@ + + + + +QuickMergingValidation (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class QuickMergingValidation

+
+
java.lang.Object +
org.apache.datasketches.cpc.QuickMergingValidation
+
+
+
+
+
public class QuickMergingValidation +extends Object
+
This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing. To be +accessible for both, this code is part of the main hierarchy. It is not used during normal +production runtime. + +

This test of merging is the equal K case and is less exhaustive than TestAlltest +but is more practical for large values of K.

+
+
Author:
+
Lee Rhodes, Kevin Lang
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      QuickMergingValidation

      +
      +
      public QuickMergingValidation(int lgMinK, + int lgMaxK, + int incLgK, + PrintStream ps, + PrintWriter pw)
      +
      Constructor
      +
      +
      Parameters:
      +
      lgMinK - lgMinK
      +
      lgMaxK - lgMaxK
      +
      incLgK - incLgK
      +
      ps - ps
      +
      pw - pw
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      start

      +
      +
      public void start()
      +
      Start the Quick Merging Validation process
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/StreamingValidation.html b/target/site/apidocs/org/apache/datasketches/cpc/StreamingValidation.html new file mode 100644 index 000000000..74e6a9dc6 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/StreamingValidation.html @@ -0,0 +1,204 @@ + + + + +StreamingValidation (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class StreamingValidation

+
+
java.lang.Object +
org.apache.datasketches.cpc.StreamingValidation
+
+
+
+
+
public class StreamingValidation +extends Object
+
This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing. To be +accessible for both, this code is part of the main hierarchy. It is not used during normal +production runtime.
+
+
Author:
+
Lee Rhodes, Kevin Lang
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      StreamingValidation

      +
      +
      public StreamingValidation(int lgMinK, + int lgMaxK, + int trials, + int ppoN, + PrintStream pS, + PrintWriter pW)
      +
      Constructor
      +
      +
      Parameters:
      +
      lgMinK - lgMinK
      +
      lgMaxK - lgMaxK
      +
      trials - trials
      +
      ppoN - ppoN
      +
      pS - pS
      +
      pW - pW
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      start

      +
      +
      public void start()
      +
      Start the streaming validation process
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/TestUtil.html b/target/site/apidocs/org/apache/datasketches/cpc/TestUtil.html new file mode 100644 index 000000000..350edfdbe --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/TestUtil.html @@ -0,0 +1,145 @@ + + + + +TestUtil (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class TestUtil

+
+
java.lang.Object +
org.apache.datasketches.cpc.TestUtil
+
+
+
+
+
public class TestUtil +extends Object
+
Utility methods for Test
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      TestUtil

      +
      +
      public TestUtil()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/class-use/CompressionCharacterization.html b/target/site/apidocs/org/apache/datasketches/cpc/class-use/CompressionCharacterization.html new file mode 100644 index 000000000..374468cd1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/class-use/CompressionCharacterization.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.cpc.CompressionCharacterization (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.cpc.CompressionCharacterization

+
+No usage of org.apache.datasketches.cpc.CompressionCharacterization +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/class-use/CpcSketch.html b/target/site/apidocs/org/apache/datasketches/cpc/class-use/CpcSketch.html new file mode 100644 index 000000000..d34749395 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/class-use/CpcSketch.html @@ -0,0 +1,128 @@ + + + + +Uses of Class org.apache.datasketches.cpc.CpcSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.cpc.CpcSketch

+
+
Packages that use CpcSketch
+
+
Package
+
Description
+ +
+
Compressed Probabilistic Counting sketch family
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/class-use/CpcUnion.html b/target/site/apidocs/org/apache/datasketches/cpc/class-use/CpcUnion.html new file mode 100644 index 000000000..0045a06f5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/class-use/CpcUnion.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.cpc.CpcUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.cpc.CpcUnion

+
+No usage of org.apache.datasketches.cpc.CpcUnion +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/class-use/CpcWrapper.html b/target/site/apidocs/org/apache/datasketches/cpc/class-use/CpcWrapper.html new file mode 100644 index 000000000..a3a0d4549 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/class-use/CpcWrapper.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.cpc.CpcWrapper (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.cpc.CpcWrapper

+
+No usage of org.apache.datasketches.cpc.CpcWrapper +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/class-use/MergingValidation.html b/target/site/apidocs/org/apache/datasketches/cpc/class-use/MergingValidation.html new file mode 100644 index 000000000..5c2b4ed86 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/class-use/MergingValidation.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.cpc.MergingValidation (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.cpc.MergingValidation

+
+No usage of org.apache.datasketches.cpc.MergingValidation +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/class-use/QuickMergingValidation.html b/target/site/apidocs/org/apache/datasketches/cpc/class-use/QuickMergingValidation.html new file mode 100644 index 000000000..6189d9c90 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/class-use/QuickMergingValidation.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.cpc.QuickMergingValidation (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.cpc.QuickMergingValidation

+
+No usage of org.apache.datasketches.cpc.QuickMergingValidation +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/class-use/StreamingValidation.html b/target/site/apidocs/org/apache/datasketches/cpc/class-use/StreamingValidation.html new file mode 100644 index 000000000..bf565cd02 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/class-use/StreamingValidation.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.cpc.StreamingValidation (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.cpc.StreamingValidation

+
+No usage of org.apache.datasketches.cpc.StreamingValidation +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/class-use/TestUtil.html b/target/site/apidocs/org/apache/datasketches/cpc/class-use/TestUtil.html new file mode 100644 index 000000000..7b74c0e19 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/class-use/TestUtil.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.cpc.TestUtil (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.cpc.TestUtil

+
+No usage of org.apache.datasketches.cpc.TestUtil +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/package-summary.html b/target/site/apidocs/org/apache/datasketches/cpc/package-summary.html new file mode 100644 index 000000000..9a4afd19e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/package-summary.html @@ -0,0 +1,147 @@ + + + + +org.apache.datasketches.cpc (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.cpc

+
+
+
+
package org.apache.datasketches.cpc
+
+
Compressed Probabilistic Counting sketch family
+
+
+
+
    +
  • + +
  • +
  • +
    +
    Classes
    +
    +
    Class
    +
    Description
    + +
    +
    This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing.
    +
    + +
    +
    This is a unique-counting sketch that implements the +Compressed Probabilistic Counting (CPC, a.k.a FM85) algorithms developed by Kevin Lang in +his paper +Back to the Future: an Even More Nearly +Optimal Cardinality Estimation Algorithm.
    +
    + +
    +
    The union (merge) operation for the CPC sketches.
    +
    + +
    +
    This provides a read-only view of a serialized image of a CpcSketch, which can be +on-heap or off-heap represented as a MemorySegment object, or on-heap represented as a byte array.
    +
    + +
    +
    This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing.
    +
    + +
    +
    This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing.
    +
    + +
    +
    This code is used both by unit tests, for short running tests, +and by the characterization repository for longer running, more exhaustive testing.
    +
    + +
    +
    Utility methods for Test
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/package-tree.html b/target/site/apidocs/org/apache/datasketches/cpc/package-tree.html new file mode 100644 index 000000000..2a87e1800 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/package-tree.html @@ -0,0 +1,86 @@ + + + + +org.apache.datasketches.cpc Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.cpc

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/cpc/package-use.html b/target/site/apidocs/org/apache/datasketches/cpc/package-use.html new file mode 100644 index 000000000..b19a9599e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/cpc/package-use.html @@ -0,0 +1,95 @@ + + + + +Uses of Package org.apache.datasketches.cpc (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.cpc

+
+
Packages that use org.apache.datasketches.cpc
+
+
Package
+
Description
+ +
+
Compressed Probabilistic Counting sketch family
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/fdt/FdtSketch.html b/target/site/apidocs/org/apache/datasketches/fdt/FdtSketch.html new file mode 100644 index 000000000..ef4579313 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/fdt/FdtSketch.html @@ -0,0 +1,606 @@ + + + + +FdtSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class FdtSketch

+
+ +
+
+
+
public final class FdtSketch +extends ArrayOfStringsTupleSketch
+
A Frequent Distinct Tuples sketch. + +

Suppose our data is a stream of pairs {IP address, User ID} and we want to identify the +IP addresses that have the most distinct User IDs. Or conversely, we would like to identify +the User IDs that have the most distinct IP addresses. This is a common challenge in the +analysis of big data and the FDT sketch helps solve this problem using probabilistic techniques. + +

More generally, given a multiset of tuples with dimensions {d1,d2, d3, ..., dN}, +and a primary subset of dimensions M < N, our task is to identify the combinations of +M subset dimensions that have the most frequent number of distinct combinations of +the N-M non-primary dimensions. + +

Please refer to the web page + +https://datasketches.apache.org/docs/Frequency/FrequentDistinctTuplesSketch.html for a more +complete discussion about this sketch.

+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      FdtSketch

      +
      +
      public FdtSketch(int lgK)
      +
      Create new instance of Frequent Distinct Tuples sketch with the given +Log-base2 of required nominal entries.
      +
      +
      Parameters:
      +
      lgK - Log-base2 of required nominal entries.
      +
      +
      +
      +
    • +
    • +
      +

      FdtSketch

      +
      +
      public FdtSketch(double threshold, + double rse)
      +
      Create a new instance of Frequent Distinct Tuples sketch with a size determined by the given +threshold and rse.
      +
      +
      Parameters:
      +
      threshold - : the fraction, between zero and 1.0, of the total distinct stream length +that defines a "Frequent" (or heavy) item.
      +
      rse - the maximum Relative Standard Error for the estimate of the distinct population of a +reported tuple (selected with a primary key) at the threshold.
      +
      +
      +
      +
    • +
    • +
      +

      FdtSketch

      +
      +
      public FdtSketch(FdtSketch sketch)
      +
      Copy Constructor
      +
      +
      Parameters:
      +
      sketch - the sketch to copy
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      copy

      +
      +
      public FdtSketch copy()
      +
      +
      Overrides:
      +
      copy in class ArrayOfStringsTupleSketch
      +
      Returns:
      +
      a deep copy of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(String[] tuple)
      +
      Update the sketch with the given string array tuple.
      +
      +
      Parameters:
      +
      tuple - the given string array tuple.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public List<Group> getResult(int[] priKeyIndices, + int limit, + int numStdDev, + char sep)
      +
      Returns an ordered List of Groups of the most frequent distinct population of subset tuples +represented by the count of entries of each group.
      +
      +
      Parameters:
      +
      priKeyIndices - these indices define the dimensions used for the Primary Keys.
      +
      limit - the maximum number of groups to return. If this value is ≤ 0, all +groups will be returned.
      +
      numStdDev - the number of standard deviations for the upper and lower error bounds, +this value is an integer and must be one of 1, 2, or 3. +See Number of Standard Deviations
      +
      sep - the separator character
      +
      Returns:
      +
      an ordered List of Groups of the most frequent distinct population of subset tuples +represented by the count of entries of each group.
      +
      +
      +
      +
    • +
    • +
      +

      getPostProcessor

      +
      +
      public PostProcessor getPostProcessor()
      +
      Returns the PostProcessor that enables multiple queries against the sketch results. +This assumes the default Group and the default separator character '|'.
      +
      +
      Returns:
      +
      the PostProcessor
      +
      +
      +
      +
    • +
    • +
      +

      getPostProcessor

      +
      +
      public PostProcessor getPostProcessor(Group group, + char sep)
      +
      Returns the PostProcessor that enables multiple queries against the sketch results.
      +
      +
      Parameters:
      +
      group - the Group class to use during post processing.
      +
      sep - the separator character.
      +
      Returns:
      +
      the PostProcessor
      +
      +
      +
      +
    • +
    • +
      +

      getRetainedEntries

      +
      +
      public int getRetainedEntries()
      +
      Description copied from class: TupleSketch
      +
      Returns number of retained entries
      +
      +
      Specified by:
      +
      getRetainedEntries in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      number of retained entries
      +
      +
      +
      +
    • +
    • +
      +

      getCountLessThanThetaLong

      +
      +
      public int getCountLessThanThetaLong(long thetaLong)
      +
      Description copied from class: TupleSketch
      +
      Gets the number of hash values less than the given theta expressed as a long.
      +
      +
      Specified by:
      +
      getCountLessThanThetaLong in class TupleSketch<S extends Summary>
      +
      Parameters:
      +
      thetaLong - the given theta as a long in the range (zero, Long.MAX_VALUE].
      +
      Returns:
      +
      the number of hash values less than the given thetaLong.
      +
      +
      +
      +
    • +
    • +
      +

      getNominalEntries

      +
      +
      public int getNominalEntries()
      +
      Get configured nominal number of entries
      +
      +
      Returns:
      +
      nominal number of entries
      +
      +
      +
      +
    • +
    • +
      +

      getLgK

      +
      +
      public int getLgK()
      +
      Get log_base2 of Nominal Entries
      +
      +
      Returns:
      +
      log_base2 of Nominal Entries
      +
      +
      +
      +
    • +
    • +
      +

      getSamplingProbability

      +
      +
      public float getSamplingProbability()
      +
      Get configured sampling probability
      +
      +
      Returns:
      +
      sampling probability
      +
      +
      +
      +
    • +
    • +
      +

      getCurrentCapacity

      +
      +
      public int getCurrentCapacity()
      +
      Get current capacity
      +
      +
      Returns:
      +
      current capacity
      +
      +
      +
      +
    • +
    • +
      +

      getResizeFactor

      +
      +
      public ResizeFactor getResizeFactor()
      +
      Get configured resize factor
      +
      +
      Returns:
      +
      resize factor
      +
      +
      +
      +
    • +
    • +
      +

      trim

      +
      +
      public void trim()
      +
      Rebuilds reducing the actual number of entries to the nominal number of entries if needed
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch an empty state.
      +
      +
      +
    • +
    • +
      +

      compact

      +
      + +
      Converts the current state of the sketch into a compact sketch
      +
      +
      Specified by:
      +
      compact in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      compact sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      @Deprecated +public byte[] toByteArray()
      +
      Deprecated. +
      As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Serializing a CompactTupleSketch is not deprecated.
      +
      +
      This serializes an UpdatableTupleSketch (QuickSelectSketch).
      +
      +
      Specified by:
      +
      toByteArray in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      serialized representation of an UpdatableTupleSketch (QuickSelectSketch).
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Description copied from class: TupleSketch
      +
      Returns a SketchIterator
      +
      +
      Specified by:
      +
      iterator in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      a SketchIterator
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/fdt/Group.html b/target/site/apidocs/org/apache/datasketches/fdt/Group.html new file mode 100644 index 000000000..f4070ff49 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/fdt/Group.html @@ -0,0 +1,428 @@ + + + + +Group (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class Group

+
+
java.lang.Object +
org.apache.datasketches.fdt.Group
+
+
+
+
All Implemented Interfaces:
+
Comparable<Group>
+
+
+
+
public class Group +extends Object +implements Comparable<Group>
+
Defines a Group from a Frequent Distinct Tuple query. This class is called internally during +post processing and is not intended to be called by the user.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    Construct an empty Group
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    int
    + +
     
    +
    boolean
    +
    equals(Object that)
    +
     
    +
    int
    + +
    +
    Returns the count
    +
    +
    double
    + +
    +
    Returns the estimate
    +
    +
    double
    + +
    +
    Returns the fraction for this group
    +
    + + +
    +
    Returns the descriptive header
    +
    +
    double
    + +
    +
    Returns the lower bound
    +
    + + +
    +
    Gets the primary key of type String
    +
    +
    double
    + +
    +
    Returns the RSE
    +
    +
    double
    + +
    +
    Returns the upper bound
    +
    +
    int
    + +
     
    + +
    init(String priKey, + int count, + double estimate, + double ub, + double lb, + double fraction, + double rse)
    +
    +
    Specifies the parameters to be listed as columns
    +
    + + +
     
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +getClass, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      Group

      +
      +
      public Group()
      +
      Construct an empty Group
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      init

      +
      +
      public Group init(String priKey, + int count, + double estimate, + double ub, + double lb, + double fraction, + double rse)
      +
      Specifies the parameters to be listed as columns
      +
      +
      Parameters:
      +
      priKey - the primary key of the FDT sketch
      +
      count - the number of retained rows associated with this group
      +
      estimate - the estimate of the original population associated with this group
      +
      ub - the upper bound of the estimate
      +
      lb - the lower bound of the estimate
      +
      fraction - the fraction of all retained rows of the sketch associated with this group
      +
      rse - the estimated Relative Standard Error for this group.
      +
      Returns:
      +
      return this
      +
      +
      +
      +
    • +
    • +
      +

      getPrimaryKey

      +
      +
      public String getPrimaryKey()
      +
      Gets the primary key of type String
      +
      +
      Returns:
      +
      priKey of type String
      +
      +
      +
      +
    • +
    • +
      +

      getCount

      +
      +
      public int getCount()
      +
      Returns the count
      +
      +
      Returns:
      +
      the count
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public double getEstimate()
      +
      Returns the estimate
      +
      +
      Returns:
      +
      the estimate
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public double getUpperBound()
      +
      Returns the upper bound
      +
      +
      Returns:
      +
      the upper bound
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public double getLowerBound()
      +
      Returns the lower bound
      +
      +
      Returns:
      +
      the lower bound
      +
      +
      +
      +
    • +
    • +
      +

      getFraction

      +
      +
      public double getFraction()
      +
      Returns the fraction for this group
      +
      +
      Returns:
      +
      the fraction for this group
      +
      +
      +
      +
    • +
    • +
      +

      getRse

      +
      +
      public double getRse()
      +
      Returns the RSE
      +
      +
      Returns:
      +
      the RSE
      +
      +
      +
      +
    • +
    • +
      +

      getHeader

      +
      +
      public String getHeader()
      +
      Returns the descriptive header
      +
      +
      Returns:
      +
      the descriptive header
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    • +
      +

      compareTo

      +
      +
      public int compareTo(Group that)
      +
      +
      Specified by:
      +
      compareTo in interface Comparable<Group>
      +
      +
      +
      +
    • +
    • +
      +

      equals

      +
      +
      public boolean equals(Object that)
      +
      +
      Overrides:
      +
      equals in class Object
      +
      +
      +
      +
    • +
    • +
      +

      hashCode

      +
      +
      public int hashCode()
      +
      +
      Overrides:
      +
      hashCode in class Object
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/fdt/PostProcessor.html b/target/site/apidocs/org/apache/datasketches/fdt/PostProcessor.html new file mode 100644 index 000000000..b1ba01d4f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/fdt/PostProcessor.html @@ -0,0 +1,227 @@ + + + + +PostProcessor (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class PostProcessor

+
+
java.lang.Object +
org.apache.datasketches.fdt.PostProcessor
+
+
+
+
+
public class PostProcessor +extends Object
+
This processes the contents of a FDT sketch to extract the +primary keys with the most frequent unique combinations of the non-primary dimensions. +The source sketch is not modified.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    +
    PostProcessor(FdtSketch sketch, + Group group, + char sep)
    +
    +
    Construct with a populated FdtSketch
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    int
    + +
    +
    Returns the number of groups in the final sketch.
    +
    + +
    getGroupList(int[] priKeyIndices, + int numStdDev, + int limit)
    +
    +
    Return the most frequent Groups associated with Primary Keys based on the size of the groups.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      PostProcessor

      +
      +
      public PostProcessor(FdtSketch sketch, + Group group, + char sep)
      +
      Construct with a populated FdtSketch
      +
      +
      Parameters:
      +
      sketch - the given sketch to query.
      +
      group - the Group
      +
      sep - the separator character
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getGroupCount

      +
      +
      public int getGroupCount()
      +
      Returns the number of groups in the final sketch.
      +
      +
      Returns:
      +
      the number of groups in the final sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getGroupList

      +
      +
      public List<Group> getGroupList(int[] priKeyIndices, + int numStdDev, + int limit)
      +
      Return the most frequent Groups associated with Primary Keys based on the size of the groups.
      +
      +
      Parameters:
      +
      priKeyIndices - the indices of the primary dimensions
      +
      numStdDev - the number of standard deviations for the error bounds, this value is an +integer and must be one of 1, 2, or 3. +See Number of Standard Deviations
      +
      limit - the maximum number of rows to return. If ≤ 0, all rows will be returned.
      +
      Returns:
      +
      the most frequent Groups associated with Primary Keys based on the size of the groups.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/fdt/class-use/FdtSketch.html b/target/site/apidocs/org/apache/datasketches/fdt/class-use/FdtSketch.html new file mode 100644 index 000000000..9081add43 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/fdt/class-use/FdtSketch.html @@ -0,0 +1,111 @@ + + + + +Uses of Class org.apache.datasketches.fdt.FdtSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.fdt.FdtSketch

+
+
Packages that use FdtSketch
+
+
Package
+
Description
+ +
+
Frequent Distinct Tuples Sketch
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/fdt/class-use/Group.html b/target/site/apidocs/org/apache/datasketches/fdt/class-use/Group.html new file mode 100644 index 000000000..a0e307585 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/fdt/class-use/Group.html @@ -0,0 +1,162 @@ + + + + +Uses of Class org.apache.datasketches.fdt.Group (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.fdt.Group

+
+
Packages that use Group
+
+
Package
+
Description
+ +
+
Frequent Distinct Tuples Sketch
+
+
+
+
    +
  • +
    +

    Uses of Group in org.apache.datasketches.fdt

    +
    Classes in org.apache.datasketches.fdt that implement interfaces with type arguments of type Group
    +
    +
    Modifier and Type
    +
    Class
    +
    Description
    +
    class 
    + +
    +
    Defines a Group from a Frequent Distinct Tuple query.
    +
    +
    +
    Methods in org.apache.datasketches.fdt that return Group
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + +
    Group.init(String priKey, + int count, + double estimate, + double ub, + double lb, + double fraction, + double rse)
    +
    +
    Specifies the parameters to be listed as columns
    +
    +
    +
    Methods in org.apache.datasketches.fdt that return types with arguments of type Group
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + +
    PostProcessor.getGroupList(int[] priKeyIndices, + int numStdDev, + int limit)
    +
    +
    Return the most frequent Groups associated with Primary Keys based on the size of the groups.
    +
    + +
    FdtSketch.getResult(int[] priKeyIndices, + int limit, + int numStdDev, + char sep)
    +
    +
    Returns an ordered List of Groups of the most frequent distinct population of subset tuples +represented by the count of entries of each group.
    +
    +
    +
    Methods in org.apache.datasketches.fdt with parameters of type Group
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    int
    +
    Group.compareTo(Group that)
    +
     
    + +
    FdtSketch.getPostProcessor(Group group, + char sep)
    +
    +
    Returns the PostProcessor that enables multiple queries against the sketch results.
    +
    +
    +
    Constructors in org.apache.datasketches.fdt with parameters of type Group
    +
    +
    Modifier
    +
    Constructor
    +
    Description
    +
     
    +
    PostProcessor(FdtSketch sketch, + Group group, + char sep)
    +
    +
    Construct with a populated FdtSketch
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/fdt/class-use/PostProcessor.html b/target/site/apidocs/org/apache/datasketches/fdt/class-use/PostProcessor.html new file mode 100644 index 000000000..098a1a83e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/fdt/class-use/PostProcessor.html @@ -0,0 +1,101 @@ + + + + +Uses of Class org.apache.datasketches.fdt.PostProcessor (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.fdt.PostProcessor

+
+
Packages that use PostProcessor
+
+
Package
+
Description
+ +
+
Frequent Distinct Tuples Sketch
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/fdt/package-summary.html b/target/site/apidocs/org/apache/datasketches/fdt/package-summary.html new file mode 100644 index 000000000..9df83bef1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/fdt/package-summary.html @@ -0,0 +1,119 @@ + + + + +org.apache.datasketches.fdt (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.fdt

+
+
+
+
package org.apache.datasketches.fdt
+
+
Frequent Distinct Tuples Sketch
+
+
+
+
    +
  • + +
  • +
  • +
    +
    Classes
    +
    +
    Class
    +
    Description
    + +
    +
    A Frequent Distinct Tuples sketch.
    +
    + +
    +
    Defines a Group from a Frequent Distinct Tuple query.
    +
    + +
    +
    This processes the contents of a FDT sketch to extract the +primary keys with the most frequent unique combinations of the non-primary dimensions.
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/fdt/package-tree.html b/target/site/apidocs/org/apache/datasketches/fdt/package-tree.html new file mode 100644 index 000000000..3e916e5a0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/fdt/package-tree.html @@ -0,0 +1,93 @@ + + + + +org.apache.datasketches.fdt Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.fdt

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/fdt/package-use.html b/target/site/apidocs/org/apache/datasketches/fdt/package-use.html new file mode 100644 index 000000000..8d5162609 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/fdt/package-use.html @@ -0,0 +1,100 @@ + + + + +Uses of Package org.apache.datasketches.fdt (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.fdt

+
+
Packages that use org.apache.datasketches.fdt
+
+
Package
+
Description
+ +
+
Frequent Distinct Tuples Sketch
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/BloomFilter.html b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/BloomFilter.html new file mode 100644 index 000000000..808a1937e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/BloomFilter.html @@ -0,0 +1,1275 @@ + + + + +BloomFilter (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class BloomFilter

+
+
java.lang.Object +
org.apache.datasketches.filters.bloomfilter.BloomFilter
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus
+
+
+
+
public final class BloomFilter +extends Object +implements MemorySegmentStatus
+
A Bloom filter is a data structure that can be used for probabilistic +set membership. + +

When querying a Bloom filter, there are no false positives. Specifically: +When querying an item that has already been inserted to the filter, the filter will +always indicate that the item is present. There is a chance of false positives, where +querying an item that has never been presented to the filter will indicate that the +item has already been seen. Consequently, any query should be interpreted as +"might have seen."

+ +

A standard Bloom filter is unlike typical sketches in that it is not sub-linear +in size and does not resize itself. A Bloom filter will work up to a target number of +distinct items, beyond which it will saturate and the false positive rate will start to +increase. The size of a Bloom filter will be linear in the expected number of +distinct items.

+ +

See the BloomFilterBuilder class for methods to create a filter, especially +one sized correctly for a target number of distinct elements and a target +false positive probability.

+ +

This implementation uses xxHash64 and follows the approach in Kirsch and Mitzenmacher, +"Less Hashing, Same Performance: Building a Better Bloom Filter," Wiley Interscience, 2008, pp. 187-218.

+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    static final long
    + +
    +
    The maximum size of a bloom filter in bits.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    long
    + +
    +
    Returns the number of bits in the BloomFilter that are set to 1.
    +
    +
    long
    + +
    +
    Returns the total number of bits in the BloomFilter.
    +
    +
    double
    + +
    +
    Returns the percentage of all bits in the BloomFilter set to 1.
    +
    +
    short
    + +
    +
    Returns the configured number of hash functions for this BloomFilter
    +
    +
    long
    + +
    +
    Returns the hash seed for this BloomFilter.
    +
    +
    static long
    +
    getSerializedSize(long numBits)
    +
    +
    Returns the serialized length of a non-empty BloomFilter of the given size, in bytes
    +
    +
    long
    + +
    +
    Returns the length of this BloomFilter when serialized, in bytes
    +
    +
    boolean
    + +
    +
    Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
    +
    + + +
    +
    Reads a serialized image of a BloomFilter from the provided MemorySegment
    +
    +
    void
    + +
    +
    Intersects two BloomFilters by applying a logical AND.
    +
    +
    void
    + +
    +
    Inverts all the bits of the BloomFilter.
    +
    +
    boolean
    + +
    +
    Helps identify if two BloomFilters may be unioned or intersected.
    +
    +
    boolean
    + +
    +
    Checks if the BloomFilter has processed any items
    +
    +
    boolean
    + +
    +
    Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
    +
    +
    boolean
    + +
    +
    Returns whether the filter is in read-only mode.
    +
    +
    boolean
    + +
    +
    Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap.
    +
    +
    boolean
    +
    query(byte[] data)
    +
    +
    Queries the filter with the provided byte[] and returns whether the +array might have been seen previously.
    +
    +
    boolean
    +
    query(char[] data)
    +
    +
    Queries the filter with the provided char[] and returns whether the +array might have been seen previously.
    +
    +
    boolean
    +
    query(double item)
    +
    +
    Queries the filter with the provided double and returns whether the +value might have been seen previously.
    +
    +
    boolean
    +
    query(int[] data)
    +
    +
    Queries the filter with the provided int[] and returns whether the +array might have been seen previously.
    +
    +
    boolean
    +
    query(long item)
    +
    +
    Queries the filter with the provided long and returns whether the +value might have been seen previously.
    +
    +
    boolean
    +
    query(long[] data)
    +
    +
    Queries the filter with the provided long[] and returns whether the +array might have been seen previously.
    +
    +
    boolean
    +
    query(short[] data)
    +
    +
    Queries the filter with the provided short[] and returns whether the +array might have been seen previously.
    +
    +
    boolean
    + +
    +
    Queries the filter with the provided MemorySegment and returns whether the +data might have been seen previously.
    +
    +
    boolean
    +
    query(String item)
    +
    +
    Queries the filter with the provided double and returns whether the +value might have been seen previously.
    +
    +
    boolean
    +
    queryAndUpdate(byte[] data)
    +
    +
    Updates the filter with the provided byte[] and +returns the result from querying that array prior to the update.
    +
    +
    boolean
    +
    queryAndUpdate(char[] data)
    +
    +
    Updates the filter with the provided char[] and +returns the result from querying that array prior to the update.
    +
    +
    boolean
    +
    queryAndUpdate(double item)
    +
    +
    Updates the filter with the provided double and +returns the result from querying that value prior to the update.
    +
    +
    boolean
    +
    queryAndUpdate(int[] data)
    +
    +
    Updates the filter with the provided int[] and +returns the result from querying that array prior to the update.
    +
    +
    boolean
    +
    queryAndUpdate(long item)
    +
    +
    Updates the filter with the provided long and +returns the result from querying that value prior to the update.
    +
    +
    boolean
    +
    queryAndUpdate(long[] data)
    +
    +
    Updates the filter with the provided long[] and +returns the result from querying that array prior to the update.
    +
    +
    boolean
    +
    queryAndUpdate(short[] data)
    +
    +
    Updates the filter with the provided short[] and +returns the result from querying that array prior to the update.
    +
    +
    boolean
    + +
    +
    Updates the filter with the provided MemorySegment and +returns the result from querying that MemorySegment prior to the update.
    +
    +
    boolean
    + +
    +
    Updates the filter with the provided String and +returns the result from querying that value prior to the update.
    +
    +
    void
    + +
    +
    Resets the BloomFilter to an empty state
    +
    +
    byte[]
    + +
    +
    Serializes the current BloomFilter to an array of bytes.
    +
    +
    long[]
    + +
    +
    Serializes the current BloomFilter to an array of longs.
    +
    + + +
     
    +
    void
    + +
    +
    Unions two BloomFilters by applying a logical OR.
    +
    +
    void
    +
    update(byte[] data)
    +
    +
    Updates the filter with the provided byte[].
    +
    +
    void
    +
    update(char[] data)
    +
    +
    Updates the filter with the provided char[].
    +
    +
    void
    +
    update(double item)
    +
    +
    Updates the filter with the provided double value.
    +
    +
    void
    +
    update(int[] data)
    +
    +
    Updates the filter with the provided int[].
    +
    +
    void
    +
    update(long item)
    +
    +
    Updates the filter with the provided long value.
    +
    +
    void
    +
    update(long[] data)
    +
    +
    Updates the filter with the provided long[].
    +
    +
    void
    +
    update(short[] data)
    +
    +
    Updates the filter with the provided short[].
    +
    +
    void
    + +
    +
    Updates the filter with the data in the provided MemorySegment.
    +
    +
    void
    +
    update(String item)
    +
    +
    Updates the filter with the provided String.
    +
    + + +
    +
    Wraps the given MemorySegment into this filter class.
    +
    + + +
    +
    Wraps the given MemorySegment into this filter class.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      MAX_SIZE_BITS

      +
      +
      public static final long MAX_SIZE_BITS
      +
      The maximum size of a bloom filter in bits.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapify

      +
      +
      public static BloomFilter heapify(MemorySegment seg)
      +
      Reads a serialized image of a BloomFilter from the provided MemorySegment
      +
      +
      Parameters:
      +
      seg - MemorySegment containing a previously serialized BloomFilter
      +
      Returns:
      +
      a BloomFilter object
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static BloomFilter wrap(MemorySegment seg)
      +
      Wraps the given MemorySegment into this filter class. The class itself only contains a few metadata items and holds +a reference to the MemorySegment object, which contains all the data.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment object
      +
      Returns:
      +
      the wrapping BloomFilter class.
      +
      +
      +
      +
    • +
    • +
      +

      writableWrap

      +
      +
      public static BloomFilter writableWrap(MemorySegment wseg)
      +
      Wraps the given MemorySegment into this filter class. The class itself only contains a few metadata items and holds +a reference to the MemorySegment object, which contains all the data.
      +
      +
      Parameters:
      +
      wseg - the given MemorySegment object
      +
      Returns:
      +
      the wrapping BloomFilter class.
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets the BloomFilter to an empty state
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Checks if the BloomFilter has processed any items
      +
      +
      Returns:
      +
      True if the BloomFilter is empty, otherwise False
      +
      +
      +
      +
    • +
    • +
      +

      getBitsUsed

      +
      +
      public long getBitsUsed()
      +
      Returns the number of bits in the BloomFilter that are set to 1.
      +
      +
      Returns:
      +
      The number of bits in use in this filter
      +
      +
      +
      +
    • +
    • +
      +

      getCapacity

      +
      +
      public long getCapacity()
      +
      Returns the total number of bits in the BloomFilter.
      +
      +
      Returns:
      +
      The total size of the BloomFilter
      +
      +
      +
      +
    • +
    • +
      +

      getNumHashes

      +
      +
      public short getNumHashes()
      +
      Returns the configured number of hash functions for this BloomFilter
      +
      +
      Returns:
      +
      The number of hash functions to apply to inputs
      +
      +
      +
      +
    • +
    • +
      +

      getSeed

      +
      +
      public long getSeed()
      +
      Returns the hash seed for this BloomFilter.
      +
      +
      Returns:
      +
      The hash seed for this filter
      +
      +
      +
      +
    • +
    • +
      +

      hasMemorySegment

      +
      +
      public boolean hasMemorySegment()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
      +
      +
      Specified by:
      +
      hasMemorySegment in interface MemorySegmentStatus
      +
      Returns:
      +
      true if this object's internal data is backed by a MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isReadOnly

      +
      +
      public boolean isReadOnly()
      +
      Returns whether the filter is in read-only mode. That is possible +only if there is a backing MemorySegment in read-only mode.
      +
      +
      Returns:
      +
      true if read-only, otherwise false
      +
      +
      +
      +
    • +
    • +
      +

      isOffHeap

      +
      +
      public boolean isOffHeap()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      Specified by:
      +
      isOffHeap in interface MemorySegmentStatus
      +
      Returns:
      +
      true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isSameResource

      +
      +
      public boolean isSameResource(MemorySegment that)
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap. This applies to both on-heap and off-heap MemorySegments. + +

      Note: If both segments are on-heap and not read-only, it can be determined if they were derived from +the same backing memory (array). However, this is not always possible off-heap. Because of this asymmetry, this definition +of "isSameResource" is confined to the existence of an overlap.

      +
      +
      Specified by:
      +
      isSameResource in interface MemorySegmentStatus
      +
      Parameters:
      +
      that - The given MemorySegment.
      +
      Returns:
      +
      true if an internally referenced MemorySegment has the same backing resource as that.
      +
      +
      +
      +
    • +
    • +
      +

      getFillPercentage

      +
      +
      public double getFillPercentage()
      +
      Returns the percentage of all bits in the BloomFilter set to 1.
      +
      +
      Returns:
      +
      the percentage of bits in the filter set to 1
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long item)
      +
      Updates the filter with the provided long value.
      +
      +
      Parameters:
      +
      item - an item with which to update the filter
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(double item)
      +
      Updates the filter with the provided double value. The value is +canonicalized (NaN and infinities) prior to updating.
      +
      +
      Parameters:
      +
      item - an item with which to update the filter
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(String item)
      +
      Updates the filter with the provided String. +The string is converted to a byte array using UTF8 encoding. + +

      Note: this will not produce the same output hash values as the update(char[]) +method and will generally be a little slower depending on the complexity of the UTF8 encoding. +

      +
      +
      Parameters:
      +
      item - an item with which to update the filter
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(byte[] data)
      +
      Updates the filter with the provided byte[].
      +
      +
      Parameters:
      +
      data - an array with which to update the filter
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(char[] data)
      +
      Updates the filter with the provided char[].
      +
      +
      Parameters:
      +
      data - an array with which to update the filter
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(short[] data)
      +
      Updates the filter with the provided short[].
      +
      +
      Parameters:
      +
      data - an array with which to update the filter
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(int[] data)
      +
      Updates the filter with the provided int[].
      +
      +
      Parameters:
      +
      data - an array with which to update the filter
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long[] data)
      +
      Updates the filter with the provided long[].
      +
      +
      Parameters:
      +
      data - an array with which to update the filter
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(MemorySegment seg)
      +
      Updates the filter with the data in the provided MemorySegment.
      +
      +
      Parameters:
      +
      seg - a MemorySegment object with which to update the filter
      +
      +
      +
      +
    • +
    • +
      +

      queryAndUpdate

      +
      +
      public boolean queryAndUpdate(long item)
      +
      Updates the filter with the provided long and +returns the result from querying that value prior to the update.
      +
      +
      Parameters:
      +
      item - an item with which to update the filter
      +
      Returns:
      +
      The query result prior to applying the update
      +
      +
      +
      +
    • +
    • +
      +

      queryAndUpdate

      +
      +
      public boolean queryAndUpdate(double item)
      +
      Updates the filter with the provided double and +returns the result from querying that value prior to the update. +The double is canonicalized (NaN and +/- infinity) in the call.
      +
      +
      Parameters:
      +
      item - an item with which to update the filter
      +
      Returns:
      +
      The query result prior to applying the update
      +
      +
      +
      +
    • +
    • +
      +

      queryAndUpdate

      +
      +
      public boolean queryAndUpdate(String item)
      +
      Updates the filter with the provided String and +returns the result from querying that value prior to the update. +The string is converted to a byte array using UTF8 encoding. + +

      Note: this will not produce the same output hash values as the queryAndUpdate(char[]) +method and will generally be a little slower depending on the complexity of the UTF8 encoding. +

      +
      +
      Parameters:
      +
      item - an item with which to update the filter
      +
      Returns:
      +
      The query result prior to applying the update, or false if item is null
      +
      +
      +
      +
    • +
    • +
      +

      queryAndUpdate

      +
      +
      public boolean queryAndUpdate(byte[] data)
      +
      Updates the filter with the provided byte[] and +returns the result from querying that array prior to the update.
      +
      +
      Parameters:
      +
      data - an array with which to update the filter
      +
      Returns:
      +
      The query result prior to applying the update, or false if data is null
      +
      +
      +
      +
    • +
    • +
      +

      queryAndUpdate

      +
      +
      public boolean queryAndUpdate(char[] data)
      +
      Updates the filter with the provided char[] and +returns the result from querying that array prior to the update.
      +
      +
      Parameters:
      +
      data - an array with which to update the filter
      +
      Returns:
      +
      The query result prior to applying the update, or false if data is null
      +
      +
      +
      +
    • +
    • +
      +

      queryAndUpdate

      +
      +
      public boolean queryAndUpdate(short[] data)
      +
      Updates the filter with the provided short[] and +returns the result from querying that array prior to the update.
      +
      +
      Parameters:
      +
      data - an array with which to update the filter
      +
      Returns:
      +
      The query result prior to applying the update, or false if data is null
      +
      +
      +
      +
    • +
    • +
      +

      queryAndUpdate

      +
      +
      public boolean queryAndUpdate(int[] data)
      +
      Updates the filter with the provided int[] and +returns the result from querying that array prior to the update.
      +
      +
      Parameters:
      +
      data - an array with which to update the filter
      +
      Returns:
      +
      The query result prior to applying the update, or false if data is null
      +
      +
      +
      +
    • +
    • +
      +

      queryAndUpdate

      +
      +
      public boolean queryAndUpdate(long[] data)
      +
      Updates the filter with the provided long[] and +returns the result from querying that array prior to the update.
      +
      +
      Parameters:
      +
      data - an array with which to update the filter
      +
      Returns:
      +
      The query result prior to applying the update, or false if data is null
      +
      +
      +
      +
    • +
    • +
      +

      queryAndUpdate

      +
      +
      public boolean queryAndUpdate(MemorySegment seg)
      +
      Updates the filter with the provided MemorySegment and +returns the result from querying that MemorySegment prior to the update.
      +
      +
      Parameters:
      +
      seg - an array with which to update the filter
      +
      Returns:
      +
      The query result prior to applying the update, or false if MemorySegment is null
      +
      +
      +
      +
    • +
    • +
      +

      query

      +
      +
      public boolean query(long item)
      +
      Queries the filter with the provided long and returns whether the +value might have been seen previously. The filter's expected +False Positive Probability determines the chances of a true result being +a false positive. False negatives are never possible.
      +
      +
      Parameters:
      +
      item - an item with which to query the filter
      +
      Returns:
      +
      The result of querying the filter with the given item
      +
      +
      +
      +
    • +
    • +
      +

      query

      +
      +
      public boolean query(double item)
      +
      Queries the filter with the provided double and returns whether the +value might have been seen previously. The filter's expected +False Positive Probability determines the chances of a true result being +a false positive. False negatives are never possible. Double values are +canonicalized (NaN and +/- infinity) before querying.
      +
      +
      Parameters:
      +
      item - an item with which to query the filter
      +
      Returns:
      +
      The result of querying the filter with the given item
      +
      +
      +
      +
    • +
    • +
      +

      query

      +
      +
      public boolean query(String item)
      +
      Queries the filter with the provided double and returns whether the +value might have been seen previously. The filter's expected +False Positive Probability determines the chances of a true result being +a false positive. False negatives are never possible. +The string is converted to a byte array using UTF8 encoding. + +

      Note: this will not produce the same output hash values as the update(char[]) +method and will generally be a little slower depending on the complexity of the UTF8 encoding. +

      +
      +
      Parameters:
      +
      item - an item with which to query the filter
      +
      Returns:
      +
      The result of querying the filter with the given item, or false if item is null
      +
      +
      +
      +
    • +
    • +
      +

      query

      +
      +
      public boolean query(byte[] data)
      +
      Queries the filter with the provided byte[] and returns whether the +array might have been seen previously. The filter's expected +False Positive Probability determines the chances of a true result being +a false positive. False negatives are never possible.
      +
      +
      Parameters:
      +
      data - an array with which to query the filter
      +
      Returns:
      +
      The result of querying the filter with the given data, or false if data is null
      +
      +
      +
      +
    • +
    • +
      +

      query

      +
      +
      public boolean query(char[] data)
      +
      Queries the filter with the provided char[] and returns whether the +array might have been seen previously. The filter's expected +False Positive Probability determines the chances of a true result being +a false positive. False negatives are never possible.
      +
      +
      Parameters:
      +
      data - an array with which to query the filter
      +
      Returns:
      +
      The result of querying the filter with the given data, or false if data is null
      +
      +
      +
      +
    • +
    • +
      +

      query

      +
      +
      public boolean query(short[] data)
      +
      Queries the filter with the provided short[] and returns whether the +array might have been seen previously. The filter's expected +False Positive Probability determines the chances of a true result being +a false positive. False negatives are never possible.
      +
      +
      Parameters:
      +
      data - an array with which to query the filter
      +
      Returns:
      +
      The result of querying the filter with the given data, or false if data is null
      +
      +
      +
      +
    • +
    • +
      +

      query

      +
      +
      public boolean query(int[] data)
      +
      Queries the filter with the provided int[] and returns whether the +array might have been seen previously. The filter's expected +False Positive Probability determines the chances of a true result being +a false positive. False negatives are never possible.
      +
      +
      Parameters:
      +
      data - an array with which to query the filter
      +
      Returns:
      +
      The result of querying the filter with the given data, or false if data is null
      +
      +
      +
      +
    • +
    • +
      +

      query

      +
      +
      public boolean query(long[] data)
      +
      Queries the filter with the provided long[] and returns whether the +array might have been seen previously. The filter's expected +False Positive Probability determines the chances of a true result being +a false positive. False negatives are never possible.
      +
      +
      Parameters:
      +
      data - an array with which to query the filter
      +
      Returns:
      +
      The result of querying the filter with the given data, or false if data is null
      +
      +
      +
      +
    • +
    • +
      +

      query

      +
      +
      public boolean query(MemorySegment seg)
      +
      Queries the filter with the provided MemorySegment and returns whether the +data might have been seen previously. The filter's expected +False Positive Probability determines the chances of a true result being +a false positive. False negatives are never possible.
      +
      +
      Parameters:
      +
      seg - a MemorySegment array with which to query the filter
      +
      Returns:
      +
      The result of querying the filter with the given MemorySegment, or false if data is null
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public void union(BloomFilter other)
      +
      Unions two BloomFilters by applying a logical OR. The result will recognized +any values seen by either filter (as well as false positives).
      +
      +
      Parameters:
      +
      other - A BloomFilter to union with this one
      +
      +
      +
      +
    • +
    • +
      +

      intersect

      +
      +
      public void intersect(BloomFilter other)
      +
      Intersects two BloomFilters by applying a logical AND. The result will recognize +only values seen by both filters (as well as false positives).
      +
      +
      Parameters:
      +
      other - A BloomFilter to union with this one
      +
      +
      +
      +
    • +
    • +
      +

      invert

      +
      +
      public void invert()
      +
      Inverts all the bits of the BloomFilter. Approximately inverts the notion of set-membership.
      +
      +
      +
    • +
    • +
      +

      isCompatible

      +
      +
      public boolean isCompatible(BloomFilter other)
      +
      Helps identify if two BloomFilters may be unioned or intersected.
      +
      +
      Parameters:
      +
      other - A BloomFilter to check for compatibility with this one
      +
      Returns:
      +
      True if the filters are compatible, otherwise false
      +
      +
      +
      +
    • +
    • +
      +

      getSerializedSizeBytes

      +
      +
      public long getSerializedSizeBytes()
      +
      Returns the length of this BloomFilter when serialized, in bytes
      +
      +
      Returns:
      +
      The length of this BloomFilter when serialized, in bytes
      +
      +
      +
      +
    • +
    • +
      +

      getSerializedSize

      +
      +
      public static long getSerializedSize(long numBits)
      +
      Returns the serialized length of a non-empty BloomFilter of the given size, in bytes
      +
      +
      Parameters:
      +
      numBits - The number of bits of to use for size computation
      +
      Returns:
      +
      The serialized length of a non-empty BloomFilter of the given size, in bytes
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Serializes the current BloomFilter to an array of bytes. + +

      Note: Method throws if the serialized size exceeds Integer.MAX_VALUE.

      +
      +
      Returns:
      +
      A serialized image of the current BloomFilter as byte[]
      +
      +
      +
      +
    • +
    • +
      +

      toLongArray

      +
      +
      public long[] toLongArray()
      +
      Serializes the current BloomFilter to an array of longs. Unlike toByteArray(), +this method can handle any size filter.
      +
      +
      Returns:
      +
      A serialized image of the current BloomFilter as long[]
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/BloomFilterBuilder.html b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/BloomFilterBuilder.html new file mode 100644 index 000000000..fdea49874 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/BloomFilterBuilder.html @@ -0,0 +1,523 @@ + + + + +BloomFilterBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class BloomFilterBuilder

+
+
java.lang.Object +
org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder
+
+
+
+
+
public final class BloomFilterBuilder +extends Object
+
This class provides methods to help estimate the correct parameters when +creating a Bloom filter, and methods to create the filter using those values. + +

The underlying math is described in the + +Wikipedia article on Bloom filters.

+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    No argument constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + +
    createByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb)
    +
    +
    Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using a random base seed for the hash function.
    +
    + +
    createByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb, + long seed)
    +
    +
    Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using the provided base seed for the hash function.
    +
    + +
    createBySize(long numBits, + int numHashes)
    +
    +
    Creates a BloomFilter with given number of bits and number of hash functions, +using a random base seed for the hash function.
    +
    + +
    createBySize(long numBits, + int numHashes, + long seed)
    +
    +
    Creates a BloomFilter with given number of bits and number of hash functions, +using the provided base seed for the hash function.
    +
    +
    static long
    + +
    +
    Returns the minimum MemorySegment size, in bytes, needed for a serialized BloomFilter with the given number of bits.
    +
    +
    static long
    +
    getSerializedFilterSizeByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb)
    +
    +
    Returns the minimum MemorySegment size, in bytes, needed for a serialized BloomFilter with an optimal number of bits +and hash functions for the given inputs.
    +
    + +
    initializeByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb, + long seed, + MemorySegment dstSeg)
    +
    +
    Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using the provided base seed for the hash function and writing into the provided MemorySegment.
    +
    + +
    initializeByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb, + MemorySegment dstSeg)
    +
    +
    Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using a random base seed for the hash function and writing into the provided MemorySegment.
    +
    + +
    initializeBySize(long numBits, + int numHashes, + long seed, + MemorySegment dstSeg)
    +
    +
    Initializes a BloomFilter with given number of bits and number of hash functions, +using the provided base seed for the hash function and writing into the provided MemorySegment.
    +
    + +
    initializeBySize(long numBits, + int numHashes, + MemorySegment dstSeg)
    +
    +
    Initializes a BloomFilter with given number of bits and number of hash functions, +using a random base seed for the hash function and writing into the provided MemorySegment.
    +
    +
    static long
    +
    suggestNumFilterBits(long maxDistinctItems, + double targetFalsePositiveProb)
    +
    +
    Returns the optimal number of bits to use in a Bloom Filter given a target number of distinct +items and a target false positive probability.
    +
    +
    static short
    +
    suggestNumHashes(double targetFalsePositiveProb)
    +
    +
    Returns the optimal number of hash functions to achieve a target false positive probability.
    +
    +
    static short
    +
    suggestNumHashes(long maxDistinctItems, + long numFilterBits)
    +
    +
    Returns the optimal number of hash functions to given target numbers of distinct items +and the BloomFilter size in bits.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      BloomFilterBuilder

      +
      +
      public BloomFilterBuilder()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      suggestNumHashes

      +
      +
      public static short suggestNumHashes(long maxDistinctItems, + long numFilterBits)
      +
      Returns the optimal number of hash functions to given target numbers of distinct items +and the BloomFilter size in bits. This function will provide a result even if the input +values exceed the capacity of a single BloomFilter.
      +
      +
      Parameters:
      +
      maxDistinctItems - The maximum expected number of distinct items to add to the filter
      +
      numFilterBits - The intended size of the Bloom Filter in bits
      +
      Returns:
      +
      The suggested number of hash functions to use with the filter
      +
      +
      +
      +
    • +
    • +
      +

      suggestNumHashes

      +
      +
      public static short suggestNumHashes(double targetFalsePositiveProb)
      +
      Returns the optimal number of hash functions to achieve a target false positive probability.
      +
      +
      Parameters:
      +
      targetFalsePositiveProb - A desired false positive probability per item
      +
      Returns:
      +
      The suggested number of hash functions to use with the filter.
      +
      +
      +
      +
    • +
    • +
      +

      suggestNumFilterBits

      +
      +
      public static long suggestNumFilterBits(long maxDistinctItems, + double targetFalsePositiveProb)
      +
      Returns the optimal number of bits to use in a Bloom Filter given a target number of distinct +items and a target false positive probability.
      +
      +
      Parameters:
      +
      maxDistinctItems - The maximum expected number of distinct items to add to the filter
      +
      targetFalsePositiveProb - A desired false positive probability per item
      +
      Returns:
      +
      The suggested number of bits to use with the filter
      +
      +
      +
      +
    • +
    • +
      +

      getSerializedFilterSizeByAccuracy

      +
      +
      public static long getSerializedFilterSizeByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb)
      +
      Returns the minimum MemorySegment size, in bytes, needed for a serialized BloomFilter with an optimal number of bits +and hash functions for the given inputs. This is also the minimum size of a MemorySegment for +in-place filter initialization.
      +
      +
      Parameters:
      +
      maxDistinctItems - The maximum expected number of distinct items to add to the filter
      +
      targetFalsePositiveProb - A desired false positive probability per item
      +
      Returns:
      +
      The size, in bytes, required to hold the specified BloomFilter when serialized
      +
      +
      +
      +
    • +
    • +
      +

      getSerializedFilterSize

      +
      +
      public static long getSerializedFilterSize(long numBits)
      +
      Returns the minimum MemorySegment size, in bytes, needed for a serialized BloomFilter with the given number of bits. +This is also the minimum size of a MemorySegment for in-place filter initialization.
      +
      +
      Parameters:
      +
      numBits - The number of bits in the target BloomFilter's bit array.
      +
      Returns:
      +
      The size, in bytes, required to hold the specified BloomFilter when serialized
      +
      +
      +
      +
    • +
    • +
      +

      createByAccuracy

      +
      +
      public static BloomFilter createByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb)
      +
      Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using a random base seed for the hash function.
      +
      +
      Parameters:
      +
      maxDistinctItems - The maximum expected number of distinct items to add to the filter
      +
      targetFalsePositiveProb - A desired false positive probability per item
      +
      Returns:
      +
      A new BloomFilter configured for the given input parameters
      +
      +
      +
      +
    • +
    • +
      +

      createByAccuracy

      +
      +
      public static BloomFilter createByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb, + long seed)
      +
      Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using the provided base seed for the hash function.
      +
      +
      Parameters:
      +
      maxDistinctItems - The maximum expected number of distinct items to add to the filter
      +
      targetFalsePositiveProb - A desired false positive probability per item
      +
      seed - A base hash seed
      +
      Returns:
      +
      A new BloomFilter configured for the given input parameters
      +
      +
      +
      +
    • +
    • +
      +

      createBySize

      +
      +
      public static BloomFilter createBySize(long numBits, + int numHashes)
      +
      Creates a BloomFilter with given number of bits and number of hash functions, +using a random base seed for the hash function.
      +
      +
      Parameters:
      +
      numBits - The size of the BloomFilter, in bits
      +
      numHashes - The number of hash functions to apply to items
      +
      Returns:
      +
      A new BloomFilter configured for the given input parameters
      +
      +
      +
      +
    • +
    • +
      +

      createBySize

      +
      +
      public static BloomFilter createBySize(long numBits, + int numHashes, + long seed)
      +
      Creates a BloomFilter with given number of bits and number of hash functions, +using the provided base seed for the hash function.
      +
      +
      Parameters:
      +
      numBits - The size of the BloomFilter, in bits
      +
      numHashes - The number of hash functions to apply to items
      +
      seed - A base hash seed
      +
      Returns:
      +
      A new BloomFilter configured for the given input parameters
      +
      +
      +
      +
    • +
    • +
      +

      initializeByAccuracy

      +
      +
      public static BloomFilter initializeByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb, + MemorySegment dstSeg)
      +
      Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using a random base seed for the hash function and writing into the provided MemorySegment.
      +
      +
      Parameters:
      +
      maxDistinctItems - The maximum expected number of distinct items to add to the filter
      +
      targetFalsePositiveProb - A desired false positive probability per item
      +
      dstSeg - A MemorySegment to hold the initialized filter
      +
      Returns:
      +
      A new BloomFilter configured for the given input parameters
      +
      +
      +
      +
    • +
    • +
      +

      initializeByAccuracy

      +
      +
      public static BloomFilter initializeByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb, + long seed, + MemorySegment dstSeg)
      +
      Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using the provided base seed for the hash function and writing into the provided MemorySegment.
      +
      +
      Parameters:
      +
      maxDistinctItems - The maximum expected number of distinct items to add to the filter
      +
      targetFalsePositiveProb - A desired false positive probability per item
      +
      seed - A base hash seed
      +
      dstSeg - A MemorySegment to hold the initialized filter
      +
      Returns:
      +
      A new BloomFilter configured for the given input parameters
      +
      +
      +
      +
    • +
    • +
      +

      initializeBySize

      +
      +
      public static BloomFilter initializeBySize(long numBits, + int numHashes, + MemorySegment dstSeg)
      +
      Initializes a BloomFilter with given number of bits and number of hash functions, +using a random base seed for the hash function and writing into the provided MemorySegment.
      +
      +
      Parameters:
      +
      numBits - The size of the BloomFilter, in bits
      +
      numHashes - The number of hash functions to apply to items
      +
      dstSeg - A MemorySegment to hold the initialized filter
      +
      Returns:
      +
      A new BloomFilter configured for the given input parameters
      +
      +
      +
      +
    • +
    • +
      +

      initializeBySize

      +
      +
      public static BloomFilter initializeBySize(long numBits, + int numHashes, + long seed, + MemorySegment dstSeg)
      +
      Initializes a BloomFilter with given number of bits and number of hash functions, +using the provided base seed for the hash function and writing into the provided MemorySegment.
      +
      +
      Parameters:
      +
      numBits - The size of the BloomFilter, in bits
      +
      numHashes - The number of hash functions to apply to items
      +
      seed - A base hash seed
      +
      dstSeg - A MemorySegment to hold the initialized filter
      +
      Returns:
      +
      A new BloomFilter configured for the given input parameters
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/DirectBitArrayR.html b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/DirectBitArrayR.html new file mode 100644 index 000000000..3dc6d6c34 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/DirectBitArrayR.html @@ -0,0 +1,233 @@ + + + + +DirectBitArrayR (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class DirectBitArrayR

+
+
java.lang.Object +
org.apache.datasketches.filters.bloomfilter.DirectBitArrayR
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus
+
+
+
+
public class DirectBitArrayR +extends Object
+
This class can maintain the BitArray object off-heap.
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    boolean
    + +
    +
    Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
    +
    +
    boolean
    + +
    +
    Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
    +
    +
    boolean
    + +
     
    +
    boolean
    + +
    +
    Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap.
    +
    + + +
     
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      hasMemorySegment

      +
      +
      public boolean hasMemorySegment()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
      +
      +
      Specified by:
      +
      hasMemorySegment in interface MemorySegmentStatus
      +
      Returns:
      +
      true if this object's internal data is backed by a MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isOffHeap

      +
      +
      public boolean isOffHeap()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      Specified by:
      +
      isOffHeap in interface MemorySegmentStatus
      +
      Returns:
      +
      true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isReadOnly

      +
      +
      public boolean isReadOnly()
      +
      +
      +
    • +
    • +
      +

      isSameResource

      +
      +
      public boolean isSameResource(MemorySegment that)
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap. This applies to both on-heap and off-heap MemorySegments. + +

      Note: If both segments are on-heap and not read-only, it can be determined if they were derived from +the same backing memory (array). However, this is not always possible off-heap. Because of this asymmetry, this definition +of "isSameResource" is confined to the existence of an overlap.

      +
      +
      Specified by:
      +
      isSameResource in interface MemorySegmentStatus
      +
      Parameters:
      +
      that - The given MemorySegment.
      +
      Returns:
      +
      true if an internally referenced MemorySegment has the same backing resource as that.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/class-use/BloomFilter.html b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/class-use/BloomFilter.html new file mode 100644 index 000000000..98194c1de --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/class-use/BloomFilter.html @@ -0,0 +1,190 @@ + + + + +Uses of Class org.apache.datasketches.filters.bloomfilter.BloomFilter (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.filters.bloomfilter.BloomFilter

+
+
Packages that use BloomFilter
+
+
Package
+
Description
+ +
+
BloomFilter package
+
+
+
+
    +
  • +
    +

    Uses of BloomFilter in org.apache.datasketches.filters.bloomfilter

    + +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + +
    BloomFilterBuilder.createByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb)
    +
    +
    Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using a random base seed for the hash function.
    +
    + +
    BloomFilterBuilder.createByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb, + long seed)
    +
    +
    Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using the provided base seed for the hash function.
    +
    + +
    BloomFilterBuilder.createBySize(long numBits, + int numHashes)
    +
    +
    Creates a BloomFilter with given number of bits and number of hash functions, +using a random base seed for the hash function.
    +
    + +
    BloomFilterBuilder.createBySize(long numBits, + int numHashes, + long seed)
    +
    +
    Creates a BloomFilter with given number of bits and number of hash functions, +using the provided base seed for the hash function.
    +
    + +
    BloomFilter.heapify(MemorySegment seg)
    +
    +
    Reads a serialized image of a BloomFilter from the provided MemorySegment
    +
    + +
    BloomFilterBuilder.initializeByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb, + long seed, + MemorySegment dstSeg)
    +
    +
    Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using the provided base seed for the hash function and writing into the provided MemorySegment.
    +
    + +
    BloomFilterBuilder.initializeByAccuracy(long maxDistinctItems, + double targetFalsePositiveProb, + MemorySegment dstSeg)
    +
    +
    Creates a new BloomFilter with an optimal number of bits and hash functions for the given inputs, +using a random base seed for the hash function and writing into the provided MemorySegment.
    +
    + +
    BloomFilterBuilder.initializeBySize(long numBits, + int numHashes, + long seed, + MemorySegment dstSeg)
    +
    +
    Initializes a BloomFilter with given number of bits and number of hash functions, +using the provided base seed for the hash function and writing into the provided MemorySegment.
    +
    + +
    BloomFilterBuilder.initializeBySize(long numBits, + int numHashes, + MemorySegment dstSeg)
    +
    +
    Initializes a BloomFilter with given number of bits and number of hash functions, +using a random base seed for the hash function and writing into the provided MemorySegment.
    +
    + +
    BloomFilter.wrap(MemorySegment seg)
    +
    +
    Wraps the given MemorySegment into this filter class.
    +
    + +
    BloomFilter.writableWrap(MemorySegment wseg)
    +
    +
    Wraps the given MemorySegment into this filter class.
    +
    +
    +
    Methods in org.apache.datasketches.filters.bloomfilter with parameters of type BloomFilter
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    void
    +
    BloomFilter.intersect(BloomFilter other)
    +
    +
    Intersects two BloomFilters by applying a logical AND.
    +
    +
    boolean
    +
    BloomFilter.isCompatible(BloomFilter other)
    +
    +
    Helps identify if two BloomFilters may be unioned or intersected.
    +
    +
    void
    +
    BloomFilter.union(BloomFilter other)
    +
    +
    Unions two BloomFilters by applying a logical OR.
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/class-use/BloomFilterBuilder.html b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/class-use/BloomFilterBuilder.html new file mode 100644 index 000000000..fb5732b48 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/class-use/BloomFilterBuilder.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder

+
+No usage of org.apache.datasketches.filters.bloomfilter.BloomFilterBuilder +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/class-use/DirectBitArrayR.html b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/class-use/DirectBitArrayR.html new file mode 100644 index 000000000..58384365c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/class-use/DirectBitArrayR.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.filters.bloomfilter.DirectBitArrayR (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.filters.bloomfilter.DirectBitArrayR

+
+No usage of org.apache.datasketches.filters.bloomfilter.DirectBitArrayR +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/package-summary.html b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/package-summary.html new file mode 100644 index 000000000..131922b2e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/package-summary.html @@ -0,0 +1,121 @@ + + + + +org.apache.datasketches.filters.bloomfilter (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.filters.bloomfilter

+
+
+
+
package org.apache.datasketches.filters.bloomfilter
+
+
BloomFilter package
+
+
+
+
    +
  • + +
  • +
  • +
    +
    Classes
    +
    +
    Class
    +
    Description
    + +
    +
    A Bloom filter is a data structure that can be used for probabilistic +set membership.
    +
    + +
    +
    This class provides methods to help estimate the correct parameters when +creating a Bloom filter, and methods to create the filter using those values.
    +
    + +
    +
    This class can maintain the BitArray object off-heap.
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/package-tree.html b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/package-tree.html new file mode 100644 index 000000000..0c5a6cb88 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/package-tree.html @@ -0,0 +1,81 @@ + + + + +org.apache.datasketches.filters.bloomfilter Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.filters.bloomfilter

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/package-use.html b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/package-use.html new file mode 100644 index 000000000..42d12afc1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/filters/bloomfilter/package-use.html @@ -0,0 +1,92 @@ + + + + +Uses of Package org.apache.datasketches.filters.bloomfilter (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.filters.bloomfilter

+
+ +
+
Package
+
Description
+ +
+
BloomFilter package
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/filters/package-summary.html b/target/site/apidocs/org/apache/datasketches/filters/package-summary.html new file mode 100644 index 000000000..30126c84e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/filters/package-summary.html @@ -0,0 +1,104 @@ + + + + +org.apache.datasketches.filters (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.filters

+
+
+
+
package org.apache.datasketches.filters
+
+
The filters package contains data structures used to determine +approximate set-membership. Classes in this package may not follow +the standard sub-linear properties of other offerings in this +library, but they fit with the spirit of DataSketches by providing +fast and approximate answers to complex problems.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/filters/package-tree.html b/target/site/apidocs/org/apache/datasketches/filters/package-tree.html new file mode 100644 index 000000000..635b6dfeb --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/filters/package-tree.html @@ -0,0 +1,69 @@ + + + + +org.apache.datasketches.filters Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.filters

+
+Package Hierarchies: + +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/filters/package-use.html b/target/site/apidocs/org/apache/datasketches/filters/package-use.html new file mode 100644 index 000000000..8fb4c82fe --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/filters/package-use.html @@ -0,0 +1,66 @@ + + + + +Uses of Package org.apache.datasketches.filters (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.filters

+
+No usage of org.apache.datasketches.filters +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/ErrorType.html b/target/site/apidocs/org/apache/datasketches/frequencies/ErrorType.html new file mode 100644 index 000000000..1164946fe --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/ErrorType.html @@ -0,0 +1,254 @@ + + + + +ErrorType (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class ErrorType

+
+
java.lang.Object +
java.lang.Enum<ErrorType> +
org.apache.datasketches.frequencies.ErrorType
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<ErrorType>, Constable
+
+
+
+
public enum ErrorType +extends Enum<ErrorType>
+
Specifies one of two types of error regions of the statistical classification Confusion Matrix +that can be excluded from a returned sample of Frequent Items.
+
+
+
+
    + +
  • +
    +

    Nested Class Summary

    +
    +

    Nested classes/interfaces inherited from class Enum

    +Enum.EnumDesc<E>
    +
    +
  • + +
  • +
    +

    Enum Constant Summary

    +
    Enum Constants
    +
    +
    Enum Constant
    +
    Description
    + +
    +
    No Type II error samples will be excluded from the sample set, +which means all Truly Positive samples will be included in the sample set.
    +
    + +
    +
    No Type I error samples will be included in the sample set, +which means all Truly Negative samples will be excluded from the sample set.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static ErrorType
    + +
    +
    Returns the enum constant of this class with the specified name.
    +
    +
    static ErrorType[]
    + +
    +
    Returns an array containing the constants of this enum class, in +the order they are declared.
    +
    +
    +
    +
    + +
    +

    Methods inherited from class Object

    +getClass, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Enum Constant Details

    +
      +
    • +
      +

      NO_FALSE_POSITIVES

      +
      +
      public static final ErrorType NO_FALSE_POSITIVES
      +
      No Type I error samples will be included in the sample set, +which means all Truly Negative samples will be excluded from the sample set. +However, there may be Type II error samples (False Negatives) +that should have been included that were not. +This is a subset of the NO_FALSE_NEGATIVES ErrorType.
      +
      +
      +
    • +
    • +
      +

      NO_FALSE_NEGATIVES

      +
      +
      public static final ErrorType NO_FALSE_NEGATIVES
      +
      No Type II error samples will be excluded from the sample set, +which means all Truly Positive samples will be included in the sample set. +However, there may be Type I error samples (False Positives) +that were included that should not have been.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static ErrorType[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static ErrorType valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/FrequentItemsSketch.Row.html b/target/site/apidocs/org/apache/datasketches/frequencies/FrequentItemsSketch.Row.html new file mode 100644 index 000000000..97883ba11 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/FrequentItemsSketch.Row.html @@ -0,0 +1,331 @@ + + + + +FrequentItemsSketch.Row (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class FrequentItemsSketch.Row<T>

+
+
java.lang.Object +
org.apache.datasketches.frequencies.FrequentItemsSketch.Row<T>
+
+
+
+
Type Parameters:
+
T - type of item
+
+
+
All Implemented Interfaces:
+
Comparable<FrequentItemsSketch.Row<T>>
+
+
+
Enclosing class:
+
FrequentItemsSketch<T>
+
+
+
+
public static class FrequentItemsSketch.Row<T> +extends Object +implements Comparable<FrequentItemsSketch.Row<T>>
+
Row class that defines the return values from a getFrequentItems query.
+
+
Author:
+
Justin Thaler, Alexander Saydakov
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    int
    + +
    +
    This compareTo is strictly limited to the Row.getEstimate() value and does not imply any +ordering whatsoever to the other elements of the row: item and upper and lower bounds.
    +
    +
    boolean
    + +
    +
    This equals is computed only from the Row.getEstimate() value and does not imply equality +of the other items within the row: item and upper and lower bounds.
    +
    +
    long
    + +
    +
    Returns the estimate
    +
    + + +
    +
    Returns an item of type T
    +
    +
    long
    + +
    +
    Returns the lower bound
    +
    +
    static String
    + +
    +
    Returns the descriptive row header
    +
    +
    long
    + +
    +
    Returns the upper bound
    +
    +
    int
    + +
    +
    This hashCode is computed only from the Row.getEstimate() value.
    +
    + + +
     
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +getClass, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getItem

      +
      +
      public T getItem()
      +
      Returns an item of type T
      +
      +
      Returns:
      +
      item of type T
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public long getEstimate()
      +
      Returns the estimate
      +
      +
      Returns:
      +
      the estimate
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public long getUpperBound()
      +
      Returns the upper bound
      +
      +
      Returns:
      +
      the upper bound
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public long getLowerBound()
      +
      Returns the lower bound
      +
      +
      Returns:
      +
      return the lower bound
      +
      +
      +
      +
    • +
    • +
      +

      getRowHeader

      +
      +
      public static String getRowHeader()
      +
      Returns the descriptive row header
      +
      +
      Returns:
      +
      the descriptive row header
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    • +
      +

      compareTo

      +
      +
      public int compareTo(FrequentItemsSketch.Row<T> that)
      +
      This compareTo is strictly limited to the Row.getEstimate() value and does not imply any +ordering whatsoever to the other elements of the row: item and upper and lower bounds. +Defined this way, this compareTo will be consistent with hashCode() and equals(Object).
      +
      +
      Specified by:
      +
      compareTo in interface Comparable<T>
      +
      Parameters:
      +
      that - the other row to compare to.
      +
      Returns:
      +
      a negative integer, zero, or a positive integer as this.getEstimate() is less than, +equal to, or greater than that.getEstimate().
      +
      +
      +
      +
    • +
    • +
      +

      hashCode

      +
      +
      public int hashCode()
      +
      This hashCode is computed only from the Row.getEstimate() value. +Defined this way, this hashCode will be consistent with equals(Object):
      +If (x.equals(y)) implies: x.hashCode() == y.hashCode().
      +If (!x.equals(y)) does NOT imply: x.hashCode() != y.hashCode().
      +
      +
      Overrides:
      +
      hashCode in class Object
      +
      Returns:
      +
      the hashCode computed from getEstimate().
      +
      +
      +
      +
    • +
    • +
      +

      equals

      +
      +
      public boolean equals(Object obj)
      +
      This equals is computed only from the Row.getEstimate() value and does not imply equality +of the other items within the row: item and upper and lower bounds. +Defined this way, this equals will be consistent with compareTo(Row).
      +
      +
      Overrides:
      +
      equals in class Object
      +
      Parameters:
      +
      obj - the other row to determine equality with.
      +
      Returns:
      +
      true if this.getEstimate() equals ((Row<T>)obj).getEstimate().
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/FrequentItemsSketch.html b/target/site/apidocs/org/apache/datasketches/frequencies/FrequentItemsSketch.html new file mode 100644 index 000000000..674e6ecfb --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/FrequentItemsSketch.html @@ -0,0 +1,777 @@ + + + + +FrequentItemsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class FrequentItemsSketch<T>

+
+
java.lang.Object +
org.apache.datasketches.frequencies.FrequentItemsSketch<T>
+
+
+
+
Type Parameters:
+
T - The type of item to be tracked by this sketch
+
+
+
+
public class FrequentItemsSketch<T> +extends Object
+
This sketch is based on the paper https://arxiv.org/abs/1705.07001 +("A High-Performance Algorithm for Identifying Frequent Items in Data Streams" +by Daniel Anderson, Pryce Bevan, Kevin Lang, Edo Liberty, Lee Rhodes, and Justin Thaler) +and is useful for tracking approximate frequencies of items of type <T> +with optional associated counts (<T> item, long count) that are members of a +multiset of such items. The true frequency of an item is defined to be the sum of associated +counts. + +

This implementation provides the following capabilities:

+
    +
  • Estimate the frequency of an item.
  • +
  • Return upper and lower bounds of any item, such that the true frequency is always +between the upper and lower bounds.
  • +
  • Return a global maximum error that holds for all items in the stream.
  • +
  • Return an array of frequent items that qualify either a NO_FALSE_POSITIVES or a +NO_FALSE_NEGATIVES error type.
  • +
  • Merge itself with another sketch object created from this class.
  • +
  • Serialize/Deserialize to/from a byte array.
  • +
+ +

Space Usage

+ +

The sketch is initialized with a maxMapSize that specifies the maximum physical +length of the internal hash map of the form (<T> item, long count). +The maxMapSize must be a power of 2.

+ +

The hash map starts at a very small size (8 entries), and grows as needed up to the +specified maxMapSize.

+ +

Excluding external space required for the item objects, the internal memory space usage of +this sketch is 18 * mapSize bytes (assuming 8 bytes for each Java reference), plus a small +constant number of additional bytes. The internal memory space usage of this sketch will never +exceed 18 * maxMapSize bytes, plus a small constant number of additional bytes.

+ +

Maximum Capacity of the Sketch

+ +

The LOAD_FACTOR for the hash map is internally set at 75%, +which means at any time the map capacity of (item, count) pairs is mapCap = 0.75 * +mapSize. +The maximum capacity of (item, count) pairs of the sketch is maxMapCap = 0.75 * +maxMapSize.

+ +

Updating the sketch with (item, count) pairs

+ +

If the item is found in the hash map, the mapped count field (the "counter") is +incremented by the incoming count, otherwise, a new counter "(item, count) pair" is +created. If the number of tracked counters reaches the maximum capacity of the hash map +the sketch decrements all of the counters (by an approximately computed median), and +removes any non-positive counters.

+ +

Accuracy

+ +

If fewer than 0.75 * maxMapSize different items are inserted into the sketch the +estimated frequencies returned by the sketch will be exact.

+ +

The logic of the frequent items sketch is such that the stored counts and true counts are +never too different. +More specifically, for any item, the sketch can return an estimate of the +true frequency of item, along with upper and lower bounds on the frequency +(that hold deterministically).

+ +

For this implementation and for a specific active item, it is guaranteed that +the true frequency will be between the Upper Bound (UB) and the Lower Bound (LB) computed for +that item. Specifically, (UB- LB) ≤ W * epsilon, where W denotes the +sum of all item counts, and epsilon = 3.5/M, where M is the maxMapSize.

+ +

This is a worst case guarantee that applies to arbitrary inputs.1 +For inputs typically seen in practice (UB-LB) is usually much smaller. +

+ +

Background

+ +

This code implements a variant of what is commonly known as the "Misra-Gries +algorithm". Variants of it were discovered and rediscovered and redesigned several times +over the years:

+
  • "Finding repeated elements", Misra, Gries, 1982
  • +
  • "Frequency estimation of Internet packet streams with limited space" Demaine, +Lopez-Ortiz, Munro, 2002
  • +
  • "A simple algorithm for finding frequent elements in streams and bags" Karp, Shenker, +Papadimitriou, 2003
  • +
  • "Efficient Computation of Frequent and Top-k Elements in Data Streams" Metwally, +Agrawal, Abbadi, 2006
  • +
+ +1 For speed we do employ some randomization that introduces a small probability that +our proof of the worst-case bound might not apply to a given run. However, we have ensured +that this probability is extremely small. For example, if the stream causes one table purge +(rebuild), our proof of the worst case bound applies with probability at least 1 - 1E-14. +If the stream causes 1E9 purges, our proof applies with probability at least 1 - 1E-5.
+
+
Author:
+
Justin Thaler, Alexander Saydakov
+
+
+
+
+
    + +
  • +
    +

    Nested Class Summary

    +
    Nested Classes
    +
    +
    Modifier and Type
    +
    Class
    +
    Description
    +
    static class 
    + +
    +
    Row class that defines the return values from a getFrequentItems query.
    +
    +
    +
    +
  • + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    +
    FrequentItemsSketch(int maxMapSize)
    +
    +
    Construct this sketch with the parameter maxMapSize and the default initialMapSize (8).
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static double
    +
    getAprioriError(int maxMapSize, + long estimatedTotalStreamWeight)
    +
    +
    Returns the estimated a priori error given the maxMapSize for the sketch and the +estimatedTotalStreamWeight.
    +
    +
    int
    + +
    +
    Returns the current number of counters the sketch is configured to support.
    +
    +
    static double
    +
    getEpsilon(int maxMapSize)
    +
    +
    Returns epsilon used to compute a priori error.
    +
    +
    long
    +
    getEstimate(T item)
    +
    +
    Gets the estimate of the frequency of the given item.
    +
    + +
    getFrequentItems(long threshold, + ErrorType errorType)
    +
    +
    Returns an array of Rows that include frequent items, estimates, upper and lower bounds +given a threshold and an ErrorCondition.
    +
    + + +
    +
    Returns an array of Rows that include frequent items, estimates, upper and lower bounds +given an ErrorCondition and the default threshold.
    +
    +
    static <T> FrequentItemsSketch<T>
    + +
    +
    Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
    +
    +
    long
    + +
    +
    Gets the guaranteed lower bound frequency of the given item, which can never be +negative.
    +
    +
    long
    + +
    +
    Returns an upper bound on the maximum error of getEstimate(item) for any item.
    +
    +
    int
    + +
    +
    Returns the maximum number of counters the sketch is configured to support.
    +
    +
    int
    + +
    +
    Returns the number of active items in the sketch.
    +
    +
    long
    + +
    +
    Returns the sum of the frequencies in the stream seen so far by the sketch
    +
    +
    long
    + +
    +
    Gets the guaranteed upper bound frequency of the given item.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch is empty
    +
    + + +
    +
    This function merges the other sketch into this one.
    +
    +
    void
    + +
    +
    Resets this sketch to a virgin state.
    +
    +
    byte[]
    + +
    +
    Returns a byte array representation of this sketch
    +
    + + +
    +
    Returns a human readable summary of this sketch.
    +
    +
    static String
    +
    toString(byte[] byteArr)
    +
    +
    Returns a human readable string of the preamble of a byte array image of a FrequentItemsSketch.
    +
    +
    static String
    + +
    +
    Returns a human readable string of the preamble of a MemorySegment image of a FrequentItemsSketch.
    +
    +
    void
    +
    update(T item)
    +
    +
    Update this sketch with an item and a frequency count of one.
    +
    +
    void
    +
    update(T item, + long count)
    +
    +
    Update this sketch with an item and a positive frequency count.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      FrequentItemsSketch

      +
      +
      public FrequentItemsSketch(int maxMapSize)
      +
      Construct this sketch with the parameter maxMapSize and the default initialMapSize (8).
      +
      +
      Parameters:
      +
      maxMapSize - Determines the physical size of the internal hash map managed by this +sketch and must be a power of 2. The maximum capacity of this internal hash map is +0.75 times * maxMapSize. Both the ultimate accuracy and size of this sketch are +functions of maxMapSize.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getInstance

      +
      +
      public static <T> FrequentItemsSketch<T> getInstance(MemorySegment srcSeg, + ArrayOfItemsSerDe<T> serDe)
      +
      Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
      +
      +
      Type Parameters:
      +
      T - The type of item that this sketch will track
      +
      Parameters:
      +
      srcSeg - a MemorySegment representation of a sketch of this class.
      +
      serDe - an instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      a sketch instance of this class.
      +
      +
      +
      +
    • +
    • +
      +

      getAprioriError

      +
      +
      public static double getAprioriError(int maxMapSize, + long estimatedTotalStreamWeight)
      +
      Returns the estimated a priori error given the maxMapSize for the sketch and the +estimatedTotalStreamWeight.
      +
      +
      Parameters:
      +
      maxMapSize - the planned map size to be used when constructing this sketch.
      +
      estimatedTotalStreamWeight - the estimated total stream weight.
      +
      Returns:
      +
      the estimated a priori error.
      +
      +
      +
      +
    • +
    • +
      +

      getCurrentMapCapacity

      +
      +
      public int getCurrentMapCapacity()
      +
      Returns the current number of counters the sketch is configured to support.
      +
      +
      Returns:
      +
      the current number of counters the sketch is configured to support.
      +
      +
      +
      +
    • +
    • +
      +

      getEpsilon

      +
      +
      public static double getEpsilon(int maxMapSize)
      +
      Returns epsilon used to compute a priori error. +This is just the value 3.5 / maxMapSize.
      +
      +
      Parameters:
      +
      maxMapSize - the planned map size to be used when constructing this sketch.
      +
      Returns:
      +
      epsilon used to compute a priori error.
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public long getEstimate(T item)
      +
      Gets the estimate of the frequency of the given item. +Note: The true frequency of a item would be the sum of the counts as a result of the +two update functions.
      +
      +
      Parameters:
      +
      item - the given item
      +
      Returns:
      +
      the estimate of the frequency of the given item
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public long getLowerBound(T item)
      +
      Gets the guaranteed lower bound frequency of the given item, which can never be +negative.
      +
      +
      Parameters:
      +
      item - the given item.
      +
      Returns:
      +
      the guaranteed lower bound frequency of the given item. That is, a number which +is guaranteed to be no larger than the real frequency.
      +
      +
      +
      +
    • +
    • +
      +

      getFrequentItems

      +
      +
      public FrequentItemsSketch.Row<T>[] getFrequentItems(long threshold, + ErrorType errorType)
      +
      Returns an array of Rows that include frequent items, estimates, upper and lower bounds +given a threshold and an ErrorCondition. If the threshold is lower than getMaximumError(), +then getMaximumError() will be used instead. + +

      The method first examines all active items in the sketch (items that have a counter). + +

      If ErrorType = NO_FALSE_NEGATIVES, this will include an item in the result +list if getUpperBound(item) > threshold. +There will be no false negatives, i.e., no Type II error. +There may be items in the set with true frequencies less than the threshold +(false positives).

      + +

      If ErrorType = NO_FALSE_POSITIVES, this will include an item in the result +list if getLowerBound(item) > threshold. +There will be no false positives, i.e., no Type I error. +There may be items omitted from the set with true frequencies greater than the +threshold (false negatives).

      +
      +
      Parameters:
      +
      threshold - to include items in the result list
      +
      errorType - determines whether no false positives or no false negatives are +desired.
      +
      Returns:
      +
      an array of frequent items
      +
      +
      +
      +
    • +
    • +
      +

      getFrequentItems

      +
      +
      public FrequentItemsSketch.Row<T>[] getFrequentItems(ErrorType errorType)
      +
      Returns an array of Rows that include frequent items, estimates, upper and lower bounds +given an ErrorCondition and the default threshold. +This is the same as getFrequentItems(getMaximumError(), errorType)
      +
      +
      Parameters:
      +
      errorType - determines whether no false positives or no false negatives are +desired.
      +
      Returns:
      +
      an array of frequent items
      +
      +
      +
      +
    • +
    • +
      +

      getMaximumError

      +
      +
      public long getMaximumError()
      +
      Returns an upper bound on the maximum error of getEstimate(item) for any item.
      +
      +
      Returns:
      +
      An upper bound on the maximum error of getEstimate(item) for any item. +This is equivalent to the maximum distance between the upper bound and the lower bound +for any item.
      +
      +
      +
      +
    • +
    • +
      +

      getMaximumMapCapacity

      +
      +
      public int getMaximumMapCapacity()
      +
      Returns the maximum number of counters the sketch is configured to support.
      +
      +
      Returns:
      +
      the maximum number of counters the sketch is configured to support.
      +
      +
      +
      +
    • +
    • +
      +

      getNumActiveItems

      +
      +
      public int getNumActiveItems()
      +
      Returns the number of active items in the sketch.
      +
      +
      Returns:
      +
      the number of active items in the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getStreamLength

      +
      +
      public long getStreamLength()
      +
      Returns the sum of the frequencies in the stream seen so far by the sketch
      +
      +
      Returns:
      +
      the sum of the frequencies in the stream seen so far by the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public long getUpperBound(T item)
      +
      Gets the guaranteed upper bound frequency of the given item.
      +
      +
      Parameters:
      +
      item - the given item
      +
      Returns:
      +
      the guaranteed upper bound frequency of the given item. That is, a number which +is guaranteed to be no smaller than the real frequency.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Returns true if this sketch is empty
      +
      +
      Returns:
      +
      true if this sketch is empty
      +
      +
      +
      +
    • +
    • +
      +

      merge

      +
      +
      public FrequentItemsSketch<T> merge(FrequentItemsSketch<T> other)
      +
      This function merges the other sketch into this one. +The other sketch may be of a different size.
      +
      +
      Parameters:
      +
      other - sketch of this class
      +
      Returns:
      +
      a sketch whose estimates are within the guarantees of the +largest error tolerance of the two merged sketches.
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch to a virgin state.
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<T> serDe)
      +
      Returns a byte array representation of this sketch
      +
      +
      Parameters:
      +
      serDe - an instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      a byte array representation of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns a human readable summary of this sketch.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      a human readable summary of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(byte[] byteArr)
      +
      Returns a human readable string of the preamble of a byte array image of a FrequentItemsSketch.
      +
      +
      Parameters:
      +
      byteArr - the given byte array
      +
      Returns:
      +
      a human readable string of the preamble of a byte array image of a FrequentItemsSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(MemorySegment seg)
      +
      Returns a human readable string of the preamble of a MemorySegment image of a FrequentItemsSketch.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment object
      +
      Returns:
      +
      a human readable string of the preamble of a MemorySegment image of a FrequentItemsSketch.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(T item)
      +
      Update this sketch with an item and a frequency count of one.
      +
      +
      Parameters:
      +
      item - for which the frequency should be increased.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(T item, + long count)
      +
      Update this sketch with an item and a positive frequency count.
      +
      +
      Parameters:
      +
      item - for which the frequency should be increased. The sketch uses +hashCode() and equals() methods of the type T.
      +
      count - the amount by which the frequency of the item should be increased. +A count of zero is a no-op, and a negative count will throw an exception.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/FrequentLongsSketch.Row.html b/target/site/apidocs/org/apache/datasketches/frequencies/FrequentLongsSketch.Row.html new file mode 100644 index 000000000..c8f420e83 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/FrequentLongsSketch.Row.html @@ -0,0 +1,327 @@ + + + + +FrequentLongsSketch.Row (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class FrequentLongsSketch.Row

+
+
java.lang.Object +
org.apache.datasketches.frequencies.FrequentLongsSketch.Row
+
+
+
+
All Implemented Interfaces:
+
Comparable<FrequentLongsSketch.Row>
+
+
+
Enclosing class:
+
FrequentLongsSketch
+
+
+
+
public static class FrequentLongsSketch.Row +extends Object +implements Comparable<FrequentLongsSketch.Row>
+
Row class that defines the return values from a getFrequentItems query.
+
+
Author:
+
Justin Thaler, Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    int
    + +
    +
    This compareTo is strictly limited to the Row.getEstimate() value and does not imply any +ordering whatsoever to the other elements of the row: item and upper and lower bounds.
    +
    +
    boolean
    + +
    +
    This equals is computed only from the Row.getEstimate() value and does not imply equality +of the other items within the row: item and upper and lower bounds.
    +
    +
    long
    + +
    +
    Returns the estimate
    +
    +
    long
    + +
    +
    Returns item of type long
    +
    +
    long
    + +
    +
    Returns the lower bound
    +
    +
    static String
    + +
    +
    Returns the descriptive row header
    +
    +
    long
    + +
    +
    Returns the upper bound
    +
    +
    int
    + +
    +
    This hashCode is computed only from the Row.getEstimate() value.
    +
    + + +
     
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +getClass, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getItem

      +
      +
      public long getItem()
      +
      Returns item of type long
      +
      +
      Returns:
      +
      item of type long
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public long getEstimate()
      +
      Returns the estimate
      +
      +
      Returns:
      +
      the estimate
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public long getUpperBound()
      +
      Returns the upper bound
      +
      +
      Returns:
      +
      the upper bound
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public long getLowerBound()
      +
      Returns the lower bound
      +
      +
      Returns:
      +
      return the lower bound
      +
      +
      +
      +
    • +
    • +
      +

      getRowHeader

      +
      +
      public static String getRowHeader()
      +
      Returns the descriptive row header
      +
      +
      Returns:
      +
      the descriptive row header
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    • +
      +

      compareTo

      +
      +
      public int compareTo(FrequentLongsSketch.Row that)
      +
      This compareTo is strictly limited to the Row.getEstimate() value and does not imply any +ordering whatsoever to the other elements of the row: item and upper and lower bounds. +Defined this way, this compareTo will be consistent with hashCode() and equals(Object).
      +
      +
      Specified by:
      +
      compareTo in interface Comparable<FrequentLongsSketch.Row>
      +
      Parameters:
      +
      that - the other row to compare to.
      +
      Returns:
      +
      a negative integer, zero, or a positive integer as this.getEstimate() is less than, +equal to, or greater than that.getEstimate().
      +
      +
      +
      +
    • +
    • +
      +

      hashCode

      +
      +
      public int hashCode()
      +
      This hashCode is computed only from the Row.getEstimate() value. +Defined this way, this hashCode will be consistent with equals(Object):
      +If (x.equals(y)) implies: x.hashCode() == y.hashCode().
      +If (!x.equals(y)) does NOT imply: x.hashCode() != y.hashCode().
      +
      +
      Overrides:
      +
      hashCode in class Object
      +
      Returns:
      +
      the hashCode computed from getEstimate().
      +
      +
      +
      +
    • +
    • +
      +

      equals

      +
      +
      public boolean equals(Object obj)
      +
      This equals is computed only from the Row.getEstimate() value and does not imply equality +of the other items within the row: item and upper and lower bounds. +Defined this way, this equals will be consistent with compareTo(Row).
      +
      +
      Overrides:
      +
      equals in class Object
      +
      Parameters:
      +
      obj - the other row to determine equality with.
      +
      Returns:
      +
      true if this.getEstimate() equals ((Row)obj).getEstimate().
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/FrequentLongsSketch.html b/target/site/apidocs/org/apache/datasketches/frequencies/FrequentLongsSketch.html new file mode 100644 index 000000000..2f2da383a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/FrequentLongsSketch.html @@ -0,0 +1,826 @@ + + + + +FrequentLongsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class FrequentLongsSketch

+
+
java.lang.Object +
org.apache.datasketches.frequencies.FrequentLongsSketch
+
+
+
+
+
public class FrequentLongsSketch +extends Object
+
This sketch is based on the paper https://arxiv.org/abs/1705.07001 +("A High-Performance Algorithm for Identifying Frequent Items in Data Streams" +by Daniel Anderson, Pryce Bevan, Kevin Lang, Edo Liberty, Lee Rhodes, and Justin Thaler) +and is useful for tracking approximate frequencies of long items with optional +associated counts (long item, long count) that are members of a multiset of +such items. The true frequency of an item is defined to be the sum of associated counts. + +

This implementation provides the following capabilities:

+
    +
  • Estimate the frequency of an item.
  • +
  • Return upper and lower bounds of any item, such that the true frequency is always +between the upper and lower bounds.
  • +
  • Return a global maximum error that holds for all items in the stream.
  • +
  • Return an array of frequent items that qualify either a NO_FALSE_POSITIVES or a +NO_FALSE_NEGATIVES error type.
  • +
  • Merge itself with another sketch object created from this class.
  • +
  • Serialize/Deserialize to/from a String or byte array.
  • +
+ +

Space Usage

+ +

The sketch is initialized with a maxMapSize that specifies the maximum physical +length of the internal hash map of the form (long item, long count). +The maxMapSize must be a power of 2.

+ +

The hash map starts at a very small size (8 entries), and grows as needed up to the +specified maxMapSize.

+ +

At any moment the internal memory space usage of this sketch is 18 * mapSize bytes, +plus a small constant number of additional bytes. The maximum internal memory space usage of +this sketch will never exceed 18 * maxMapSize bytes, plus a small constant number of +additional bytes.

+ +

Maximum Capacity of the Sketch

+ +

The LOAD_FACTOR for the hash map is internally set at 75%, +which means at any time the map capacity of (item, count) pairs is mapCap = +0.75 * mapSize. +The maximum capacity of (item, count) pairs of the sketch is maxMapCap = +0.75 * maxMapSize.

+ +

Updating the sketch with (item, count) pairs

+ +

If the item is found in the hash map, the mapped count field (the "counter") is +incremented by the incoming count, otherwise, a new counter "(item, count) pair" is +created. If the number of tracked counters reaches the maximum capacity of the hash map +the sketch decrements all of the counters (by an approximately computed median), and +removes any non-positive counters.

+ +

Accuracy

+ +

If fewer than 0.75 * maxMapSize different items are inserted into the sketch the +estimated frequencies returned by the sketch will be exact.

+ +

The logic of the frequent items sketch is such that the stored counts and true counts are +never too different. +More specifically, for any item, the sketch can return an estimate of the +true frequency of item, along with upper and lower bounds on the frequency +(that hold deterministically).

+ +

For this implementation and for a specific active item, it is guaranteed that +the true frequency will be between the Upper Bound (UB) and the Lower Bound (LB) computed for +that item. Specifically, (UB- LB) ≤ W * epsilon, where W denotes the +sum of all item counts, and epsilon = 3.5/M, where M is the maxMapSize.

+ +

This is a worst case guarantee that applies to arbitrary inputs.1 +For inputs typically seen in practice (UB-LB) is usually much smaller. +

+ +

Background

+ +

This code implements a variant of what is commonly known as the "Misra-Gries +algorithm". Variants of it were discovered and rediscovered and redesigned several times +over the years:

+
  • "Finding repeated elements", Misra, Gries, 1982
  • +
  • "Frequency estimation of Internet packet streams with limited space" Demaine, +Lopez-Ortiz, Munro, 2002
  • +
  • "A simple algorithm for finding frequent elements in streams and bags" Karp, Shenker, +Papadimitriou, 2003
  • +
  • "Efficient Computation of Frequent and Top-k Elements in Data Streams" Metwally, +Agrawal, Abbadi, 2006
  • +
+ +1 For speed we do employ some randomization that introduces a small probability that +our proof of the worst-case bound might not apply to a given run. However, we have ensured +that this probability is extremely small. For example, if the stream causes one table purge +(rebuild), our proof of the worst case bound applies with probability at least 1 - 1E-14. +If the stream causes 1E9 purges, our proof applies with probability at least 1 - 1E-5.
+
+
Author:
+
Justin Thaler, Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Nested Class Summary

    +
    Nested Classes
    +
    +
    Modifier and Type
    +
    Class
    +
    Description
    +
    static class 
    + +
    +
    Row class that defines the return values from a getFrequentItems query.
    +
    +
    +
    +
  • + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    +
    FrequentLongsSketch(int maxMapSize)
    +
    +
    Construct this sketch with the parameter maxMapSize and the default initialMapSize (8).
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static double
    +
    getAprioriError(int maxMapSize, + long estimatedTotalStreamWeight)
    +
    +
    Returns the estimated a priori error given the maxMapSize for the sketch and the +estimatedTotalStreamWeight.
    +
    +
    int
    + +
    +
    Returns the current number of counters the sketch is configured to support.
    +
    +
    static double
    +
    getEpsilon(int maxMapSize)
    +
    +
    Returns epsilon used to compute a priori error.
    +
    +
    long
    +
    getEstimate(long item)
    +
    +
    Gets the estimate of the frequency of the given item.
    +
    + +
    getFrequentItems(long threshold, + ErrorType errorType)
    +
    +
    Returns an array of Rows that include frequent items, estimates, upper and lower bounds +given a threshold and an ErrorCondition.
    +
    + + +
    +
    Returns an array of Rows that include frequent items, estimates, upper and lower bounds +given an ErrorCondition and the default threshold.
    +
    + + +
    +
    Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
    +
    + + +
    +
    Returns a sketch instance of this class from the given String, +which must be a String representation of this sketch class.
    +
    +
    long
    +
    getLowerBound(long item)
    +
    +
    Gets the guaranteed lower bound frequency of the given item, which can never be +negative.
    +
    +
    long
    + +
    +
    Returns an upper bound on the maximum error of getEstimate(item) for any item.
    +
    +
    int
    + +
    +
    Returns the maximum number of counters the sketch is configured to support.
    +
    +
    int
    + +
    +
    Returns the number of active items in the sketch.
    +
    +
    int
    + +
    +
    Returns the number of bytes required to store this sketch as an array of bytes.
    +
    +
    long
    + +
    +
    Returns the sum of the frequencies (weights or counts) in the stream seen so far by the sketch
    +
    +
    long
    +
    getUpperBound(long item)
    +
    +
    Gets the guaranteed upper bound frequency of the given item.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch is empty
    +
    + + +
    +
    This function merges the other sketch into this one.
    +
    +
    void
    + +
    +
    Resets this sketch to a virgin state.
    +
    + + +
    +
    Returns a String representation of this sketch
    +
    +
    byte[]
    + +
    +
    Returns a byte array representation of this sketch
    +
    + + +
    +
    Returns a human readable summary of this sketch.
    +
    +
    static String
    +
    toString(byte[] byteArr)
    +
    +
    Returns a human readable string of the preamble of a byte array image of a FrequentLongsSketch.
    +
    +
    static String
    + +
    +
    Returns a human readable string of the preamble of a MemorySegment image of a FrequentLongsSketch.
    +
    +
    void
    +
    update(long item)
    +
    +
    Update this sketch with an item and a frequency count of one.
    +
    +
    void
    +
    update(long item, + long count)
    +
    +
    Update this sketch with a item and a positive frequency count (or weight).
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      FrequentLongsSketch

      +
      +
      public FrequentLongsSketch(int maxMapSize)
      +
      Construct this sketch with the parameter maxMapSize and the default initialMapSize (8).
      +
      +
      Parameters:
      +
      maxMapSize - Determines the physical size of the internal hash map managed by this +sketch and must be a power of 2. The maximum capacity of this internal hash map is +0.75 times * maxMapSize. Both the ultimate accuracy and size of this sketch are a +function of maxMapSize.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getInstance

      +
      +
      public static FrequentLongsSketch getInstance(MemorySegment srcSeg)
      +
      Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment representation of a sketch of this class.
      +
      Returns:
      +
      a sketch instance of this class.
      +
      +
      +
      +
    • +
    • +
      +

      getInstance

      +
      +
      public static FrequentLongsSketch getInstance(String string)
      +
      Returns a sketch instance of this class from the given String, +which must be a String representation of this sketch class.
      +
      +
      Parameters:
      +
      string - a String representation of a sketch of this class.
      +
      Returns:
      +
      a sketch instance of this class.
      +
      +
      +
      +
    • +
    • +
      +

      getAprioriError

      +
      +
      public static double getAprioriError(int maxMapSize, + long estimatedTotalStreamWeight)
      +
      Returns the estimated a priori error given the maxMapSize for the sketch and the +estimatedTotalStreamWeight.
      +
      +
      Parameters:
      +
      maxMapSize - the planned map size to be used when constructing this sketch.
      +
      estimatedTotalStreamWeight - the estimated total stream weight.
      +
      Returns:
      +
      the estimated a priori error.
      +
      +
      +
      +
    • +
    • +
      +

      getCurrentMapCapacity

      +
      +
      public int getCurrentMapCapacity()
      +
      Returns the current number of counters the sketch is configured to support.
      +
      +
      Returns:
      +
      the current number of counters the sketch is configured to support.
      +
      +
      +
      +
    • +
    • +
      +

      getEpsilon

      +
      +
      public static double getEpsilon(int maxMapSize)
      +
      Returns epsilon used to compute a priori error. +This is just the value 3.5 / maxMapSize.
      +
      +
      Parameters:
      +
      maxMapSize - the planned map size to be used when constructing this sketch.
      +
      Returns:
      +
      epsilon used to compute a priori error.
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public long getEstimate(long item)
      +
      Gets the estimate of the frequency of the given item. +Note: The true frequency of a item would be the sum of the counts as a result of the +two update functions.
      +
      +
      Parameters:
      +
      item - the given item
      +
      Returns:
      +
      the estimate of the frequency of the given item
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public long getLowerBound(long item)
      +
      Gets the guaranteed lower bound frequency of the given item, which can never be +negative.
      +
      +
      Parameters:
      +
      item - the given item.
      +
      Returns:
      +
      the guaranteed lower bound frequency of the given item. That is, a number which +is guaranteed to be no larger than the real frequency.
      +
      +
      +
      +
    • +
    • +
      +

      getFrequentItems

      +
      +
      public FrequentLongsSketch.Row[] getFrequentItems(long threshold, + ErrorType errorType)
      +
      Returns an array of Rows that include frequent items, estimates, upper and lower bounds +given a threshold and an ErrorCondition. If the threshold is lower than getMaximumError(), +then getMaximumError() will be used instead. + +

      The method first examines all active items in the sketch (items that have a counter). + +

      If ErrorType = NO_FALSE_NEGATIVES, this will include an item in the result +list if getUpperBound(item) > threshold. +There will be no false negatives, i.e., no Type II error. +There may be items in the set with true frequencies less than the threshold +(false positives).

      + +

      If ErrorType = NO_FALSE_POSITIVES, this will include an item in the result +list if getLowerBound(item) > threshold. +There will be no false positives, i.e., no Type I error. +There may be items omitted from the set with true frequencies greater than the +threshold (false negatives). This is a subset of the NO_FALSE_NEGATIVES case.

      +
      +
      Parameters:
      +
      threshold - to include items in the result list
      +
      errorType - determines whether no false positives or no false negatives are +desired.
      +
      Returns:
      +
      an array of frequent items
      +
      +
      +
      +
    • +
    • +
      +

      getFrequentItems

      +
      +
      public FrequentLongsSketch.Row[] getFrequentItems(ErrorType errorType)
      +
      Returns an array of Rows that include frequent items, estimates, upper and lower bounds +given an ErrorCondition and the default threshold. +This is the same as getFrequentItems(getMaximumError(), errorType)
      +
      +
      Parameters:
      +
      errorType - determines whether no false positives or no false negatives are +desired.
      +
      Returns:
      +
      an array of frequent items
      +
      +
      +
      +
    • +
    • +
      +

      getMaximumError

      +
      +
      public long getMaximumError()
      +
      Returns an upper bound on the maximum error of getEstimate(item) for any item.
      +
      +
      Returns:
      +
      An upper bound on the maximum error of getEstimate(item) for any item. +This is equivalent to the maximum distance between the upper bound and the lower bound +for any item.
      +
      +
      +
      +
    • +
    • +
      +

      getMaximumMapCapacity

      +
      +
      public int getMaximumMapCapacity()
      +
      Returns the maximum number of counters the sketch is configured to support.
      +
      +
      Returns:
      +
      the maximum number of counters the sketch is configured to support.
      +
      +
      +
      +
    • +
    • +
      +

      getNumActiveItems

      +
      +
      public int getNumActiveItems()
      +
      Returns the number of active items in the sketch.
      +
      +
      Returns:
      +
      the number of active items in the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getStorageBytes

      +
      +
      public int getStorageBytes()
      +
      Returns the number of bytes required to store this sketch as an array of bytes.
      +
      +
      Returns:
      +
      the number of bytes required to store this sketch as an array of bytes.
      +
      +
      +
      +
    • +
    • +
      +

      getStreamLength

      +
      +
      public long getStreamLength()
      +
      Returns the sum of the frequencies (weights or counts) in the stream seen so far by the sketch
      +
      +
      Returns:
      +
      the sum of the frequencies in the stream seen so far by the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public long getUpperBound(long item)
      +
      Gets the guaranteed upper bound frequency of the given item.
      +
      +
      Parameters:
      +
      item - the given item
      +
      Returns:
      +
      the guaranteed upper bound frequency of the given item. That is, a number which +is guaranteed to be no smaller than the real frequency.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Returns true if this sketch is empty
      +
      +
      Returns:
      +
      true if this sketch is empty
      +
      +
      +
      +
    • +
    • +
      +

      merge

      +
      + +
      This function merges the other sketch into this one. +The other sketch may be of a different size.
      +
      +
      Parameters:
      +
      other - sketch of this class
      +
      Returns:
      +
      a sketch whose estimates are within the guarantees of the +largest error tolerance of the two merged sketches.
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch to a virgin state.
      +
      +
      +
    • +
    • +
      +

      serializeToString

      +
      +
      public String serializeToString()
      +
      Returns a String representation of this sketch
      +
      +
      Returns:
      +
      a String representation of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Returns a byte array representation of this sketch
      +
      +
      Returns:
      +
      a byte array representation of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns a human readable summary of this sketch.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      a human readable summary of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(byte[] byteArr)
      +
      Returns a human readable string of the preamble of a byte array image of a FrequentLongsSketch.
      +
      +
      Parameters:
      +
      byteArr - the given byte array
      +
      Returns:
      +
      a human readable string of the preamble of a byte array image of a FrequentLongsSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(MemorySegment seg)
      +
      Returns a human readable string of the preamble of a MemorySegment image of a FrequentLongsSketch.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment object
      +
      Returns:
      +
      a human readable string of the preamble of a MemorySegment image of a FrequentLongsSketch.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long item)
      +
      Update this sketch with an item and a frequency count of one.
      +
      +
      Parameters:
      +
      item - for which the frequency should be increased.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long item, + long count)
      +
      Update this sketch with a item and a positive frequency count (or weight).
      +
      +
      Parameters:
      +
      item - for which the frequency should be increased. The item can be any long value +and is only used by the sketch to determine uniqueness.
      +
      count - the amount by which the frequency of the item should be increased. +An count of zero is a no-op, and a negative count will throw an exception.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/class-use/ErrorType.html b/target/site/apidocs/org/apache/datasketches/frequencies/class-use/ErrorType.html new file mode 100644 index 000000000..dd96703b1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/class-use/ErrorType.html @@ -0,0 +1,145 @@ + + + + +Uses of Enum Class org.apache.datasketches.frequencies.ErrorType (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.frequencies.ErrorType

+
+
Packages that use ErrorType
+
+
Package
+
Description
+ +
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/class-use/FrequentItemsSketch.Row.html b/target/site/apidocs/org/apache/datasketches/frequencies/class-use/FrequentItemsSketch.Row.html new file mode 100644 index 000000000..ebec0bf0b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/class-use/FrequentItemsSketch.Row.html @@ -0,0 +1,127 @@ + + + + +Uses of Class org.apache.datasketches.frequencies.FrequentItemsSketch.Row (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.frequencies.FrequentItemsSketch.Row

+
+
Packages that use FrequentItemsSketch.Row
+
+
Package
+
Description
+ +
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/class-use/FrequentItemsSketch.html b/target/site/apidocs/org/apache/datasketches/frequencies/class-use/FrequentItemsSketch.html new file mode 100644 index 000000000..9514e51ae --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/class-use/FrequentItemsSketch.html @@ -0,0 +1,113 @@ + + + + +Uses of Class org.apache.datasketches.frequencies.FrequentItemsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.frequencies.FrequentItemsSketch

+
+
Packages that use FrequentItemsSketch
+
+
Package
+
Description
+ +
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/class-use/FrequentLongsSketch.Row.html b/target/site/apidocs/org/apache/datasketches/frequencies/class-use/FrequentLongsSketch.Row.html new file mode 100644 index 000000000..65d03038e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/class-use/FrequentLongsSketch.Row.html @@ -0,0 +1,127 @@ + + + + +Uses of Class org.apache.datasketches.frequencies.FrequentLongsSketch.Row (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.frequencies.FrequentLongsSketch.Row

+
+
Packages that use FrequentLongsSketch.Row
+
+
Package
+
Description
+ +
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/class-use/FrequentLongsSketch.html b/target/site/apidocs/org/apache/datasketches/frequencies/class-use/FrequentLongsSketch.html new file mode 100644 index 000000000..de0038bef --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/class-use/FrequentLongsSketch.html @@ -0,0 +1,118 @@ + + + + +Uses of Class org.apache.datasketches.frequencies.FrequentLongsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.frequencies.FrequentLongsSketch

+
+
Packages that use FrequentLongsSketch
+
+
Package
+
Description
+ +
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/package-summary.html b/target/site/apidocs/org/apache/datasketches/frequencies/package-summary.html new file mode 100644 index 000000000..b0a85087f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/package-summary.html @@ -0,0 +1,139 @@ + + + + +org.apache.datasketches.frequencies (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.frequencies

+
+
+
+
package org.apache.datasketches.frequencies
+
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+
+
+
    +
  • + +
  • +
  • +
    +
    +
    +
    +
    Class
    +
    Description
    + +
    +
    Specifies one of two types of error regions of the statistical classification Confusion Matrix +that can be excluded from a returned sample of Frequent Items.
    +
    + +
    +
    This sketch is based on the paper https://arxiv.org/abs/1705.07001 +("A High-Performance Algorithm for Identifying Frequent Items in Data Streams" +by Daniel Anderson, Pryce Bevan, Kevin Lang, Edo Liberty, Lee Rhodes, and Justin Thaler) +and is useful for tracking approximate frequencies of items of type <T> +with optional associated counts (<T> item, long count) that are members of a +multiset of such items.
    +
    + +
    +
    Row class that defines the return values from a getFrequentItems query.
    +
    + +
    +
    This sketch is based on the paper https://arxiv.org/abs/1705.07001 +("A High-Performance Algorithm for Identifying Frequent Items in Data Streams" +by Daniel Anderson, Pryce Bevan, Kevin Lang, Edo Liberty, Lee Rhodes, and Justin Thaler) +and is useful for tracking approximate frequencies of long items with optional +associated counts (long item, long count) that are members of a multiset of +such items.
    +
    + +
    +
    Row class that defines the return values from a getFrequentItems query.
    +
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/package-tree.html b/target/site/apidocs/org/apache/datasketches/frequencies/package-tree.html new file mode 100644 index 000000000..f17b01627 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/package-tree.html @@ -0,0 +1,96 @@ + + + + +org.apache.datasketches.frequencies Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.frequencies

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Enum Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/frequencies/package-use.html b/target/site/apidocs/org/apache/datasketches/frequencies/package-use.html new file mode 100644 index 000000000..9009f56f7 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/frequencies/package-use.html @@ -0,0 +1,118 @@ + + + + +Uses of Package org.apache.datasketches.frequencies (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.frequencies

+
+ +
+
Package
+
Description
+ +
+
This package contains the implementations of the paper https://arxiv.org/abs/1705.07001.
+
+
+
+
    +
  • +
    + +
    +
    Class
    +
    Description
    + +
    +
    Specifies one of two types of error regions of the statistical classification Confusion Matrix +that can be excluded from a returned sample of Frequent Items.
    +
    + +
    +
    This sketch is based on the paper https://arxiv.org/abs/1705.07001 +("A High-Performance Algorithm for Identifying Frequent Items in Data Streams" +by Daniel Anderson, Pryce Bevan, Kevin Lang, Edo Liberty, Lee Rhodes, and Justin Thaler) +and is useful for tracking approximate frequencies of items of type <T> +with optional associated counts (<T> item, long count) that are members of a +multiset of such items.
    +
    + +
    +
    Row class that defines the return values from a getFrequentItems query.
    +
    + +
    +
    This sketch is based on the paper https://arxiv.org/abs/1705.07001 +("A High-Performance Algorithm for Identifying Frequent Items in Data Streams" +by Daniel Anderson, Pryce Bevan, Kevin Lang, Edo Liberty, Lee Rhodes, and Justin Thaler) +and is useful for tracking approximate frequencies of long items with optional +associated counts (long item, long count) that are members of a multiset of +such items.
    +
    + +
    +
    Row class that defines the return values from a getFrequentItems query.
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hash/MurmurHash3.html b/target/site/apidocs/org/apache/datasketches/hash/MurmurHash3.html new file mode 100644 index 000000000..b5d56573b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hash/MurmurHash3.html @@ -0,0 +1,461 @@ + + + + +MurmurHash3 (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class MurmurHash3

+
+
java.lang.Object +
org.apache.datasketches.hash.MurmurHash3
+
+
+
+
All Implemented Interfaces:
+
Serializable
+
+
+
+
public final class MurmurHash3 +extends Object +implements Serializable
+
The MurmurHash3 is a fast, non-cryptographic, 128-bit hash function that has +excellent avalanche and 2-way bit independence properties. + +

+Austin Appleby's C++ + +MurmurHash3_x64_128(...), final revision 150, +which is in the Public Domain, was the inspiration for this implementation in Java. +

+ +

+This java implementation pays close attention to the C++ algorithms in order to +maintain bit-wise compatibility, but the design is quite different. This implementation has also +been extended to include processing of arrays of longs, char or ints, which was not part of the +original C++ implementation. This implementation produces the same exact output hash bits as +the above C++ method given the same input.

+ +

In addition, with this implementation, the hash of byte[], char[], int[], or long[] will +produce the same hash result if, and only if, all the arrays have the same exact length in +bytes, and if the contents of the values in the arrays have the same byte endianness and +overall order. There is a unit test for this class that demonstrates this.

+ +

+The structure of this implementation also reflects a separation of code that is dependent on the +input structure (in this case byte[], int[] or long[]) from code that is independent of the input +structure. This also makes the code more readable and suitable for future extensions. +

+ +

Note that even though this hash function produces 128 bits, the entropy of the resulting hash cannot +be greater than the entropy of the input. For example, if the input is only a single long of 64 bits, +the entropy of the resulting 128 bit hash is no greater than 64 bits.

+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static long[]
    +
    hash(byte[] key, + int offsetBytes, + int lengthBytes, + long seed)
    +
    +
    Hash a portion of the given byte[] array.
    +
    +
    static long[]
    +
    hash(byte[] key, + long seed)
    +
    +
    Hash the given byte[] array.
    +
    +
    static long[]
    +
    hash(char[] key, + int offsetChars, + int lengthChars, + long seed)
    +
    +
    Hash a portion of the given char[] array.
    +
    +
    static long[]
    +
    hash(char[] key, + long seed)
    +
    +
    Hash the given char[] array.
    +
    +
    static long[]
    +
    hash(int[] key, + int offsetInts, + int lengthInts, + long seed)
    +
    +
    Hash a portion of the given int[] array.
    +
    +
    static long[]
    +
    hash(int[] key, + long seed)
    +
    +
    Hash the given int[] array.
    +
    +
    static long[]
    +
    hash(long[] key, + int offsetLongs, + int lengthLongs, + long seed)
    +
    +
    Hash a portion of the given long[] array.
    +
    +
    static long[]
    +
    hash(long[] key, + long seed)
    +
    +
    Hash the given long[] array.
    +
    +
    static long[]
    +
    hash(long key, + long seed)
    +
    +
    Hash the given long.
    +
    +
    static long[]
    +
    hash(MemorySegment seg, + long seed)
    +
    +
    Hash the given MemorySegment.
    +
    +
    static long[]
    +
    hash(ByteBuffer buf, + long seed)
    +
    +
    Hash the remaining bytes of the given ByteBuffer starting at position() ending at limit (exclusive).
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      hash

      +
      +
      public static long[] hash(long key, + long seed)
      +
      Hash the given long.
      +
      +
      Parameters:
      +
      key - The input long.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      a 128-bit hash of the input as a long array of size 2.
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(long[] key, + long seed)
      +
      Hash the given long[] array.
      +
      +
      Parameters:
      +
      key - The input long[] array. It must be non-null and non-empty.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      a 128-bit hash of the input as a long array of size 2.
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(long[] key, + int offsetLongs, + int lengthLongs, + long seed)
      +
      Hash a portion of the given long[] array.
      +
      +
      Parameters:
      +
      key - The input long[] array. It must be non-null and non-empty.
      +
      offsetLongs - the starting offset in longs.
      +
      lengthLongs - the length in longs of the portion of the array to be hashed.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      a 128-bit hash of the input as a long array of size 2
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(int[] key, + long seed)
      +
      Hash the given int[] array.
      +
      +
      Parameters:
      +
      key - The input int[] array. It must be non-null and non-empty.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      a 128-bit hash of the input as a long array of size 2.
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(int[] key, + int offsetInts, + int lengthInts, + long seed)
      +
      Hash a portion of the given int[] array.
      +
      +
      Parameters:
      +
      key - The input int[] array. It must be non-null and non-empty.
      +
      offsetInts - the starting offset in ints.
      +
      lengthInts - the length in ints of the portion of the array to be hashed.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      a 128-bit hash of the input as a long array of size 2.
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(char[] key, + long seed)
      +
      Hash the given char[] array.
      +
      +
      Parameters:
      +
      key - The input char[] array. It must be non-null and non-empty.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      a 128-bit hash of the input as a long array of size 2
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(char[] key, + int offsetChars, + int lengthChars, + long seed)
      +
      Hash a portion of the given char[] array.
      +
      +
      Parameters:
      +
      key - The input char[] array. It must be non-null and non-empty.
      +
      offsetChars - the starting offset in chars.
      +
      lengthChars - the length in chars of the portion of the array to be hashed.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      a 128-bit hash of the input as a long array of size 2
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(byte[] key, + long seed)
      +
      Hash the given byte[] array.
      +
      +
      Parameters:
      +
      key - The input byte[] array. It must be non-null and non-empty.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      a 128-bit hash of the input as a long array of size 2.
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(byte[] key, + int offsetBytes, + int lengthBytes, + long seed)
      +
      Hash a portion of the given byte[] array.
      +
      +
      Parameters:
      +
      key - The input byte[] array. It must be non-null and non-empty.
      +
      offsetBytes - the starting offset in bytes.
      +
      lengthBytes - the length in bytes of the portion of the array to be hashed.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      a 128-bit hash of the input as a long array of size 2.
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(ByteBuffer buf, + long seed)
      +
      Hash the remaining bytes of the given ByteBuffer starting at position() ending at limit (exclusive).
      +
      +
      Parameters:
      +
      buf - The input ByteBuffer. It must be non-null and non-empty.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      a 128-bit hash of the input as a long array of size 2.
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(MemorySegment seg, + long seed)
      +
      Hash the given MemorySegment. + +

      Note: if you want to hash only a portion of MemorySegment, convert it to the +appropriate Slice first.

      +
      +
      Parameters:
      +
      seg - The input MemorySegment. It must be non-null and non-empty.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      a 128-bit hash of the input as a long array of size 2.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hash/MurmurHash3FFM.html b/target/site/apidocs/org/apache/datasketches/hash/MurmurHash3FFM.html new file mode 100644 index 000000000..f9b249af7 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hash/MurmurHash3FFM.html @@ -0,0 +1,379 @@ + + + + +MurmurHash3FFM (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class MurmurHash3FFM

+
+
java.lang.Object +
org.apache.datasketches.hash.MurmurHash3FFM
+
+
+
+
+
public final class MurmurHash3FFM +extends Object
+
The MurmurHash3 is a fast, non-cryptographic, 128-bit hash function that has +excellent avalanche and 2-way bit independence properties. + +

Austin Appleby's C++ + +MurmurHash3_x64_128(...), final revision 150, +which is in the Public Domain, was the inspiration for this implementation in Java.

+ +

This implementation of the MurmurHash3 allows hashing of a block of on-heap MemorySegment defined by an offset +and length. The calling API also allows the user to supply the small output array of two longs, +so that the entire hash function is static and free of object allocations.

+ +

This implementation produces exactly the same hash result as the +MurmurHash3 function in datasketches-java given compatible inputs.

+ +

This FFM version of the implementation leverages the java.lang.foreign package (FFM) of JDK-25 in place of +the Unsafe class.

+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static long[]
    +
    hash(byte[] in, + long seed)
    +
    +
    Returns a 128-bit hash of the input.
    +
    +
    static long[]
    +
    hash(char[] in, + long seed)
    +
    +
    Returns a 128-bit hash of the input.
    +
    +
    static long[]
    +
    hash(double in, + long seed, + long[] hashOut)
    +
    +
    Returns a 128-bit hash of the input.
    +
    +
    static long[]
    +
    hash(int[] in, + long seed)
    +
    +
    Returns a 128-bit hash of the input.
    +
    +
    static long[]
    +
    hash(long[] in, + long seed)
    +
    +
    Returns a 128-bit hash of the input.
    +
    +
    static long[]
    +
    hash(long in, + long seed, + long[] hashOut)
    +
    +
    Returns a 128-bit hash of the input.
    +
    +
    static long[]
    +
    hash(MemorySegment seg, + long offsetBytes, + long lengthBytes, + long seed, + long[] hashOut)
    +
    +
    Returns a 128-bit hash of the input as a long array of size 2.
    +
    +
    static long[]
    +
    hash(String in, + long seed, + long[] hashOut)
    +
    +
    Returns a 128-bit hash of the input.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      hash

      +
      +
      public static long[] hash(long[] in, + long seed)
      +
      Returns a 128-bit hash of the input. +Provided for compatibility with older version of MurmurHash3, +but empty or null input now throws IllegalArgumentException.
      +
      +
      Parameters:
      +
      in - long array
      +
      seed - A long valued seed.
      +
      Returns:
      +
      the hash
      +
      Throws:
      +
      IllegalArgumentException - if input is empty or null
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(int[] in, + long seed)
      +
      Returns a 128-bit hash of the input. +Provided for compatibility with older version of MurmurHash3, +but empty or null input now throws IllegalArgumentException.
      +
      +
      Parameters:
      +
      in - int array
      +
      seed - A long valued seed.
      +
      Returns:
      +
      the hash
      +
      Throws:
      +
      IllegalArgumentException - if input is empty or null
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(char[] in, + long seed)
      +
      Returns a 128-bit hash of the input. +Provided for compatibility with older version of MurmurHash3, +but empty or null input now throws IllegalArgumentException.
      +
      +
      Parameters:
      +
      in - char array
      +
      seed - A long valued seed.
      +
      Returns:
      +
      the hash
      +
      Throws:
      +
      IllegalArgumentException - if input is empty or null
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(byte[] in, + long seed)
      +
      Returns a 128-bit hash of the input. +Provided for compatibility with older version of MurmurHash3, +but empty or null input now throws IllegalArgumentException.
      +
      +
      Parameters:
      +
      in - byte array
      +
      seed - A long valued seed.
      +
      Returns:
      +
      the hash
      +
      Throws:
      +
      IllegalArgumentException - if input is empty or null
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(long in, + long seed, + long[] hashOut)
      +
      Returns a 128-bit hash of the input. +Note the entropy of the resulting hash cannot be more than 64 bits.
      +
      +
      Parameters:
      +
      in - a long
      +
      seed - A long valued seed.
      +
      hashOut - A long array of size 2
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(double in, + long seed, + long[] hashOut)
      +
      Returns a 128-bit hash of the input. +Note the entropy of the resulting hash cannot be more than 64 bits.
      +
      +
      Parameters:
      +
      in - a double
      +
      seed - A long valued seed.
      +
      hashOut - A long array of size 2
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(String in, + long seed, + long[] hashOut)
      +
      Returns a 128-bit hash of the input. +An empty or null input throws IllegalArgumentException.
      +
      +
      Parameters:
      +
      in - a String
      +
      seed - A long valued seed.
      +
      hashOut - A long array of size 2
      +
      Returns:
      +
      the hash
      +
      Throws:
      +
      IllegalArgumentException - if input is empty or null
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long[] hash(MemorySegment seg, + long offsetBytes, + long lengthBytes, + long seed, + long[] hashOut)
      +
      Returns a 128-bit hash of the input as a long array of size 2.
      +
      +
      Parameters:
      +
      seg - The input MemorySegment. Must be non-null and non-empty, +otherwise throws IllegalArgumentException.
      +
      offsetBytes - the starting point within MemorySegment.
      +
      lengthBytes - the total number of bytes to be hashed.
      +
      seed - A long valued seed.
      +
      hashOut - the size 2 long array for the resulting 128-bit hash
      +
      Returns:
      +
      the hash.
      +
      Throws:
      +
      IllegalArgumentException - if input MemorySegment is empty
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hash/XxHash.html b/target/site/apidocs/org/apache/datasketches/hash/XxHash.html new file mode 100644 index 000000000..9d84b067b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hash/XxHash.html @@ -0,0 +1,423 @@ + + + + +XxHash (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class XxHash

+
+
java.lang.Object +
org.apache.datasketches.hash.XxHash
+
+
+
+
+
public final class XxHash +extends Object
+
The XxHash is a fast, non-cryptographic, 64-bit hash function that has +excellent avalanche and 2-way bit independence properties. +This java version adapted the C++ version and the OpenHFT/Zero-Allocation-Hashing implementation +referenced below as inspiration. + +

The C++ source repository: + +https://github.com/Cyan4973/xxHash. It has a BSD 2-Clause License: + +http://www.opensource.org/licenses/bsd-license.php. See LICENSE. + +

Portions of this code were adapted from + +OpenHFT/Zero-Allocation-Hashing, which has an Apache 2 license as does this site. See LICENSE.

+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static long
    +
    hashByteArr(byte[] arr, + int offsetBytes, + int lengthBytes, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashCharArr(char[] arr, + int offsetChars, + int lengthChars, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashDoubleArr(double[] arr, + int offsetDoubles, + int lengthDoubles, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashFloatArr(float[] arr, + int offsetFloats, + int lengthFloats, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashIntArr(int[] arr, + int offsetInts, + int lengthInts, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashLong(long in, + long seed)
    +
    +
    Returns a 64-bit hash from a single long.
    +
    +
    static long
    +
    hashLongArr(long[] arr, + int offsetLongs, + int lengthLongs, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashShortArr(short[] arr, + int offsetShorts, + int lengthShorts, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashString(String str, + int offsetChars, + int lengthChars, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      hashByteArr

      +
      +
      public static long hashByteArr(byte[] arr, + int offsetBytes, + int lengthBytes, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetBytes - starting at this offset
      +
      lengthBytes - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashShortArr

      +
      +
      public static long hashShortArr(short[] arr, + int offsetShorts, + int lengthShorts, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetShorts - starting at this offset
      +
      lengthShorts - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashCharArr

      +
      +
      public static long hashCharArr(char[] arr, + int offsetChars, + int lengthChars, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetChars - starting at this offset
      +
      lengthChars - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashIntArr

      +
      +
      public static long hashIntArr(int[] arr, + int offsetInts, + int lengthInts, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetInts - starting at this offset
      +
      lengthInts - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashLongArr

      +
      +
      public static long hashLongArr(long[] arr, + int offsetLongs, + int lengthLongs, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetLongs - starting at this offset
      +
      lengthLongs - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashLong

      +
      +
      public static long hashLong(long in, + long seed)
      +
      Returns a 64-bit hash from a single long. This method has been optimized for speed when only +a single hash of a long is required.
      +
      +
      Parameters:
      +
      in - A long.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      the hash.
      +
      +
      +
      +
    • +
    • +
      +

      hashFloatArr

      +
      +
      public static long hashFloatArr(float[] arr, + int offsetFloats, + int lengthFloats, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetFloats - starting at this offset
      +
      lengthFloats - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashDoubleArr

      +
      +
      public static long hashDoubleArr(double[] arr, + int offsetDoubles, + int lengthDoubles, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetDoubles - starting at this offset
      +
      lengthDoubles - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashString

      +
      +
      public static long hashString(String str, + int offsetChars, + int lengthChars, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      str - the given string
      +
      offsetChars - starting at this offset
      +
      lengthChars - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hash/XxHash64.html b/target/site/apidocs/org/apache/datasketches/hash/XxHash64.html new file mode 100644 index 000000000..5ce6df590 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hash/XxHash64.html @@ -0,0 +1,453 @@ + + + + +XxHash64 (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class XxHash64

+
+
java.lang.Object +
org.apache.datasketches.hash.XxHash64
+
+
+
+
+
public final class XxHash64 +extends Object
+
The XxHash is a fast, non-cryptographic, 64-bit hash function that has +excellent avalanche and 2-way bit independence properties. +This java version adapted from the C++ version and the OpenHFT/Zero-Allocation-Hashing implementation +referenced below as inspiration. + +

The C++ source repository: + +https://github.com/Cyan4973/xxHash. It has a BSD 2-Clause License: + +http://www.opensource.org/licenses/bsd-license.php. See LICENSE. + +

Portions of this code were adapted from + +OpenHFT/Zero-Allocation-Hashing, which has an Apache 2 license as does this site. See LICENSE.

+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static long
    +
    hash(long in, + long seed)
    +
    +
    Returns a 64-bit hash from a single long.
    +
    +
    static long
    +
    hash(MemorySegment seg, + long offsetBytes, + long lengthBytes, + long seed)
    +
    +
    Returns the 64-bit hash of the sequence of bytes in the given MemorySegment
    +
    +
    static long
    +
    hashBytes(byte[] arr, + int offsetBytes, + int lengthBytes, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashChars(char[] arr, + int offsetChars, + int lengthChars, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashDoubles(double[] arr, + int offsetDoubles, + int lengthDoubles, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashFloats(float[] arr, + int offsetFloats, + int lengthFloats, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashInts(int[] arr, + int offsetInts, + int lengthInts, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashLongs(long[] arr, + int offsetLongs, + int lengthLongs, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashShorts(short[] arr, + int offsetShorts, + int lengthShorts, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    static long
    +
    hashString(String str, + int offsetChars, + int lengthChars, + long seed)
    +
    +
    Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      hash

      +
      +
      public static long hash(MemorySegment seg, + long offsetBytes, + long lengthBytes, + long seed)
      +
      Returns the 64-bit hash of the sequence of bytes in the given MemorySegment
      +
      +
      Parameters:
      +
      seg - A reference to the relevant MemorySegment.
      +
      offsetBytes - offset in bytes in the given segment.
      +
      lengthBytes - the length in bytes to be hashed
      +
      seed - a given seed
      +
      Returns:
      +
      the 64-bit hash of the sequence of bytes.
      +
      +
      +
      +
    • +
    • +
      +

      hash

      +
      +
      public static long hash(long in, + long seed)
      +
      Returns a 64-bit hash from a single long. This method has been optimized for speed when only +a single hash of a long is required.
      +
      +
      Parameters:
      +
      in - A long.
      +
      seed - A long valued seed.
      +
      Returns:
      +
      the hash.
      +
      +
      +
      +
    • +
    • +
      +

      hashBytes

      +
      +
      public static long hashBytes(byte[] arr, + int offsetBytes, + int lengthBytes, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetBytes - starting at this offset
      +
      lengthBytes - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashShorts

      +
      +
      public static long hashShorts(short[] arr, + int offsetShorts, + int lengthShorts, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetShorts - starting at this offset
      +
      lengthShorts - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashChars

      +
      +
      public static long hashChars(char[] arr, + int offsetChars, + int lengthChars, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetChars - starting at this offset
      +
      lengthChars - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashInts

      +
      +
      public static long hashInts(int[] arr, + int offsetInts, + int lengthInts, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetInts - starting at this offset
      +
      lengthInts - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashLongs

      +
      +
      public static long hashLongs(long[] arr, + int offsetLongs, + int lengthLongs, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetLongs - starting at this offset
      +
      lengthLongs - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashFloats

      +
      +
      public static long hashFloats(float[] arr, + int offsetFloats, + int lengthFloats, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetFloats - starting at this offset
      +
      lengthFloats - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashDoubles

      +
      +
      public static long hashDoubles(double[] arr, + int offsetDoubles, + int lengthDoubles, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      arr - the given array
      +
      offsetDoubles - starting at this offset
      +
      lengthDoubles - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    • +
      +

      hashString

      +
      +
      public static long hashString(String str, + int offsetChars, + int lengthChars, + long seed)
      +
      Hash the given arr starting at the given offset and continuing for the given length using the +given seed.
      +
      +
      Parameters:
      +
      str - the given string
      +
      offsetChars - starting at this offset
      +
      lengthChars - continuing for this length
      +
      seed - the given seed
      +
      Returns:
      +
      the hash
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hash/class-use/MurmurHash3.html b/target/site/apidocs/org/apache/datasketches/hash/class-use/MurmurHash3.html new file mode 100644 index 000000000..7b6d39939 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hash/class-use/MurmurHash3.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.hash.MurmurHash3 (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.hash.MurmurHash3

+
+No usage of org.apache.datasketches.hash.MurmurHash3 +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hash/class-use/MurmurHash3FFM.html b/target/site/apidocs/org/apache/datasketches/hash/class-use/MurmurHash3FFM.html new file mode 100644 index 000000000..fe3d66620 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hash/class-use/MurmurHash3FFM.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.hash.MurmurHash3FFM (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.hash.MurmurHash3FFM

+
+No usage of org.apache.datasketches.hash.MurmurHash3FFM +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hash/class-use/XxHash.html b/target/site/apidocs/org/apache/datasketches/hash/class-use/XxHash.html new file mode 100644 index 000000000..44d5a83ef --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hash/class-use/XxHash.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.hash.XxHash (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.hash.XxHash

+
+No usage of org.apache.datasketches.hash.XxHash +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hash/class-use/XxHash64.html b/target/site/apidocs/org/apache/datasketches/hash/class-use/XxHash64.html new file mode 100644 index 000000000..1bc667dca --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hash/class-use/XxHash64.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.hash.XxHash64 (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.hash.XxHash64

+
+No usage of org.apache.datasketches.hash.XxHash64 +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hash/package-summary.html b/target/site/apidocs/org/apache/datasketches/hash/package-summary.html new file mode 100644 index 000000000..783cbce6e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hash/package-summary.html @@ -0,0 +1,131 @@ + + + + +org.apache.datasketches.hash (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.hash

+
+
+
+
package org.apache.datasketches.hash
+
+
The hash package contains a high-performing and extended Java implementations +of Austin Appleby's 128-bit MurmurHash3 hash function originally coded in C. +This core MurmurHash3.java class is used throughout many of the sketch classes for consistency +and as long as the user specifies the same seed will result in coordinated hash operations. +This package also contains an adaptor class that extends the basic class with more functions +commonly associated with hashing.
+
+
+
+
    +
  • + +
  • +
  • +
    +
    Classes
    +
    +
    Class
    +
    Description
    + +
    +
    The MurmurHash3 is a fast, non-cryptographic, 128-bit hash function that has +excellent avalanche and 2-way bit independence properties.
    +
    + +
    +
    The MurmurHash3 is a fast, non-cryptographic, 128-bit hash function that has +excellent avalanche and 2-way bit independence properties.
    +
    + +
    +
    The XxHash is a fast, non-cryptographic, 64-bit hash function that has +excellent avalanche and 2-way bit independence properties.
    +
    + +
    +
    The XxHash is a fast, non-cryptographic, 64-bit hash function that has +excellent avalanche and 2-way bit independence properties.
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hash/package-tree.html b/target/site/apidocs/org/apache/datasketches/hash/package-tree.html new file mode 100644 index 000000000..4151bbcd5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hash/package-tree.html @@ -0,0 +1,82 @@ + + + + +org.apache.datasketches.hash Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.hash

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hash/package-use.html b/target/site/apidocs/org/apache/datasketches/hash/package-use.html new file mode 100644 index 000000000..df0d9fe9e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hash/package-use.html @@ -0,0 +1,66 @@ + + + + +Uses of Package org.apache.datasketches.hash (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.hash

+
+No usage of org.apache.datasketches.hash +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hll/HllSketch.html b/target/site/apidocs/org/apache/datasketches/hll/HllSketch.html new file mode 100644 index 000000000..ce9bf9e6d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hll/HllSketch.html @@ -0,0 +1,1294 @@ + + + + +HllSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class HllSketch

+
+
java.lang.Object +
org.apache.datasketches.hll.HllSketch
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus
+
+
+
+
public class HllSketch +extends Object
+
The HllSketch is actually a collection of compact implementations of Phillipe Flajolet’s HyperLogLog (HLL) +sketch but with significantly improved error behavior and excellent speed performance. + +

If the use case for sketching is primarily counting uniques and merging, the HLL sketch is the 2nd highest +performing in terms of accuracy for storage space consumed in the DataSketches library +(the new CPC sketch developed by Kevin J. Lang now beats HLL in terms of accuracy / space). +For large counts, HLL sketches can be 2 to 8 times smaller for the same accuracy than the DataSketches Theta +Sketches when serialized, but the Theta sketches can do set intersections and differences while HLL and CPC cannot. +The CPC sketch and HLL share similar use cases, but the CPC sketch is about 30 to 40% smaller than the HLL sketch +when serialized and larger than the HLL when active in a MemorySegment. Choose your weapons!

+ +

A new HLL sketch is created with a simple constructor:

+
int lgK = 12; //This is log-base2 of k, so k = 4096. lgK can be from 4 to 21
+HllSketch sketch = new HllSketch(lgK); //TgtHllType.HLL_4 is the default
+//OR
+HllSketch sketch = new HllSketch(lgK, TgtHllType.HLL_6);
+//OR
+HllSketch sketch = new HllSketch(lgK, TgtHllType.HLL_8);
+
+ +

All three different sketch types are targets in that the sketches start out in a warm-up mode that is small in +size and gradually grows as needed until the full HLL array is allocated. The HLL_4, HLL_6 and HLL_8 represent +different levels of compression of the final HLL array where the 4, 6 and 8 refer to the number of bits each +bucket of the HLL array is compressed down to. +The HLL_4 is the most compressed but generally slower than the other two, especially during union operations.

+ +

All three types share the same API. Updating the HllSketch is very simple:

+ +
long n = 1000000;
+for (int i = 0; i < n; i++) {
+  sketch.update(i);
+}
+
+ +

Each of the presented integers above are first hashed into 128-bit hash values that are used by the sketch +HLL algorithm, so the above loop is essentially equivalent to using a random number generator initialized with a +seed so that the sequence is deterministic and random.

+ +

Obtaining the cardinality results from the sketch is also simple:

+ +
double estimate = sketch.getEstimate();
+double estUB = sketch.getUpperBound(1.0); //the upper bound at 1 standard deviation.
+double estLB = sketch.getLowerBound(1.0); //the lower bound at 1 standard deviation.
+//OR
+System.out.println(sketch.toString()); //will output a summary of the sketch.
+
+ +

Which produces a console output something like this:

+ +
### HLL SKETCH SUMMARY:
+  Log Config K   : 12
+  Hll Target     : HLL_4
+  Current Mode   : HLL
+  LB             : 977348.7024560181
+  Estimate       : 990116.6007366662
+  UB             : 1003222.5095308956
+  OutOfOrder Flag: false
+  CurMin         : 5
+  NumAtCurMin    : 1
+  HipAccum       : 990116.6007366662
+
+
+
Author:
+
Lee Rhodes, Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    static final TgtHllType
    + +
    +
    The default HLL-TYPE is HLL_4
    +
    +
    static final int
    + +
    +
    The default Log_base2 of K
    +
    +
    +
    +
  • + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    Constructs a new on-heap sketch with the default lgConfigK and tgtHllType.
    +
    +
    HllSketch(int lgConfigK)
    +
    +
    Constructs a new on-heap sketch with the default tgtHllType.
    +
    +
    HllSketch(int lgConfigK, + TgtHllType tgtHllType)
    +
    +
    Constructs a new on-heap sketch with the type of HLL sketch to configure.
    +
    +
    HllSketch(int lgConfigK, + TgtHllType tgtHllType, + MemorySegment dstSeg)
    +
    +
    Constructs a new sketch with the type of HLL sketch to configure and the given +MemorySegment as the destination for the sketch.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Return a copy of this sketch onto the Java heap.
    +
    + +
    copyAs(TgtHllType tgtHllType)
    +
    +
    Return a deep copy of this sketch onto the Java heap with the specified TgtHllType.
    +
    +
    int
    + +
    +
    Gets the size in bytes of the current sketch when serialized using +toCompactByteArray().
    +
    +
    double
    + +
    +
    This is less accurate than the getEstimate() method and is automatically used +when the sketch has gone through union operations where the more accurate HIP estimator +cannot be used.
    +
    +
    double
    + +
    +
    Return the cardinality estimate
    +
    +
    int
    + +
    +
    Gets the lgConfigK.
    +
    +
    double
    +
    getLowerBound(int numStdDev)
    +
    +
    Gets the approximate lower error bound given the specified number of Standard Deviations.
    +
    +
    static final int
    +
    getMaxUpdatableSerializationBytes(int lgConfigK, + TgtHllType tgtHllType)
    +
    +
    Returns the maximum size in bytes that this sketch can grow to given lgConfigK.
    +
    +
    static double
    +
    getRelErr(boolean upperBound, + boolean oooFlag, + int lgConfigK, + int numStdDev)
    +
    +
    Gets the current (approximate) Relative Error (RE) asymptotic values given several +parameters.
    +
    +
    static final int
    + +
    +
    Returns the current serialization version.
    +
    +
    static final int
    + +
    +
    Returns the current serialization version of the given MemorySegment.
    +
    + + +
    +
    Gets the TgtHllType
    +
    +
    int
    + +
    +
    Gets the size in bytes of the current sketch when serialized using +toUpdatableByteArray().
    +
    +
    double
    +
    getUpperBound(int numStdDev)
    +
    +
    Gets the approximate upper error bound given the specified number of Standard Deviations.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch was created using MemorySegment.
    +
    +
    static final HllSketch
    +
    heapify(byte[] byteArray)
    +
    +
    Heapify the given byte array, which must be a valid HllSketch image and may have data.
    +
    +
    static final HllSketch
    + +
    +
    Heapify the given MemorySegment, which must be a valid HllSketch image and may have data.
    +
    +
    boolean
    + +
    +
    Returns true if the backing MemorySegment of this sketch is in compact form.
    +
    +
    boolean
    + +
    +
    Returns true if empty
    +
    +
    boolean
    + +
    +
    This HLL family of sketches and operators is always estimating, even for very small values.
    +
    +
    boolean
    + +
    +
    Returns true if the backing MemorySegment for this sketch is off-heap.
    +
    +
    boolean
    + +
    +
    Returns true if the given MemorySegment refers to the same underlying resource as this sketch.
    +
    +
    void
    + +
    +
    Resets to empty, but does not change the configured values of lgConfigK and tgtHllType.
    +
    +
    byte[]
    + +
    +
    Serializes this sketch as a byte array in compact form.
    +
    + + +
    +
    Human readable summary as a string.
    +
    + +
    toString(boolean summary, + boolean detail, + boolean auxDetail)
    +
    +
    Human readable summary with optional detail.
    +
    + +
    toString(boolean summary, + boolean detail, + boolean auxDetail, + boolean all)
    +
    +
    Human readable summary with optional detail
    +
    +
    static String
    +
    toString(byte[] byteArr)
    +
    +
    Returns a human readable string of the preamble of a byte array image of an HllSketch.
    +
    +
    static String
    + +
    +
    Returns a human readable string of the preamble of a MemorySegment image of an HllSketch.
    +
    +
    byte[]
    + +
    +
    Serializes this sketch as a byte array in an updatable form.
    +
    +
    void
    +
    update(byte[] data)
    +
    +
    Present the given byte array as a potential unique item.
    +
    +
    void
    +
    update(char[] data)
    +
    +
    Present the given char array as a potential unique item.
    +
    +
    void
    +
    update(double datum)
    +
    +
    Present the given double (or float) datum as a potential unique item.
    +
    +
    void
    +
    update(int[] data)
    +
    +
    Present the given integer array as a potential unique item.
    +
    +
    void
    +
    update(long datum)
    +
    +
    Present the given long as a potential unique item.
    +
    +
    void
    +
    update(long[] data)
    +
    +
    Present the given long array as a potential unique item.
    +
    +
    void
    +
    update(String datum)
    +
    +
    Present the given String as a potential unique item.
    +
    +
    void
    + +
    +
    Present the given byte buffer as a potential unique item.
    +
    +
    static final HllSketch
    + +
    +
    Wraps the given read-only MemorySegment that must be a image of a valid sketch, +which may be in compact or updatable form, and should have data.
    +
    +
    static final HllSketch
    + +
    +
    Wraps the given MemorySegment, which must be a image of a valid updatable sketch, +and may have data.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      DEFAULT_LG_K

      +
      +
      public static final int DEFAULT_LG_K
      +
      The default Log_base2 of K
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      DEFAULT_HLL_TYPE

      +
      +
      public static final TgtHllType DEFAULT_HLL_TYPE
      +
      The default HLL-TYPE is HLL_4
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      HllSketch

      +
      +
      public HllSketch()
      +
      Constructs a new on-heap sketch with the default lgConfigK and tgtHllType.
      +
      +
      +
    • +
    • +
      +

      HllSketch

      +
      +
      public HllSketch(int lgConfigK)
      +
      Constructs a new on-heap sketch with the default tgtHllType.
      +
      +
      Parameters:
      +
      lgConfigK - The Log2 of K for the target HLL sketch. This value must be +between 4 and 21 inclusively.
      +
      +
      +
      +
    • +
    • +
      +

      HllSketch

      +
      +
      public HllSketch(int lgConfigK, + TgtHllType tgtHllType)
      +
      Constructs a new on-heap sketch with the type of HLL sketch to configure.
      +
      +
      Parameters:
      +
      lgConfigK - The Log2 of K for the target HLL sketch. This value must be +between 4 and 21 inclusively.
      +
      tgtHllType - the desired HLL type.
      +
      +
      +
      +
    • +
    • +
      +

      HllSketch

      +
      +
      public HllSketch(int lgConfigK, + TgtHllType tgtHllType, + MemorySegment dstSeg)
      +
      Constructs a new sketch with the type of HLL sketch to configure and the given +MemorySegment as the destination for the sketch. This MemorySegment is usually configured +for off-heap MemorySegment. What remains on the java heap is a thin wrapper object that reads and +writes to the given MemorySegment. + +

      The given dstSeg is checked for the required capacity as determined by +getMaxUpdatableSerializationBytes(int, TgtHllType).

      +
      +
      Parameters:
      +
      lgConfigK - The Log2 of K for the target HLL sketch. This value must be +between 4 and 21 inclusively.
      +
      tgtHllType - the desired HLL type.
      +
      dstSeg - the destination MemorySegment for the sketch.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapify

      +
      +
      public static final HllSketch heapify(byte[] byteArray)
      +
      Heapify the given byte array, which must be a valid HllSketch image and may have data.
      +
      +
      Parameters:
      +
      byteArray - the given byte array. This byteArray is not modified and is not retained +by the on-heap sketch.
      +
      Returns:
      +
      an HllSketch on the java heap.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static final HllSketch heapify(MemorySegment srcSeg)
      +
      Heapify the given MemorySegment, which must be a valid HllSketch image and may have data.
      +
      +
      Parameters:
      +
      srcSeg - the given MemorySegment, which is read-only.
      +
      Returns:
      +
      an HllSketch on the java heap.
      +
      +
      +
      +
    • +
    • +
      +

      writableWrap

      +
      +
      public static final HllSketch writableWrap(MemorySegment srcWseg)
      +
      Wraps the given MemorySegment, which must be a image of a valid updatable sketch, +and may have data. What remains on the java heap is a +thin wrapper object that reads and writes to the given MemorySegment, which, depending on +how the user configures the MemorySegment, may actually reside on the Java heap or off-heap. + +

      The given dstSeg is checked for the required capacity as determined by +getMaxUpdatableSerializationBytes(int, TgtHllType).

      +
      +
      Parameters:
      +
      srcWseg - an writable image of a valid source sketch with data.
      +
      Returns:
      +
      an HllSketch where the sketch data is in the given srcWseg.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static final HllSketch wrap(MemorySegment srcSeg)
      +
      Wraps the given read-only MemorySegment that must be a image of a valid sketch, +which may be in compact or updatable form, and should have data. Any attempt to update the +given source MemorySegment will throw an exception.
      +
      +
      Parameters:
      +
      srcSeg - a read-only image of a valid source sketch.
      +
      Returns:
      +
      an HllSketch, where the read-only data of the sketch is in the given srcSeg.
      +
      +
      +
      +
    • +
    • +
      +

      copy

      +
      +
      public HllSketch copy()
      +
      Return a copy of this sketch onto the Java heap.
      +
      +
      Returns:
      +
      a copy of this sketch onto the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      copyAs

      +
      +
      public HllSketch copyAs(TgtHllType tgtHllType)
      +
      Return a deep copy of this sketch onto the Java heap with the specified TgtHllType.
      +
      +
      Parameters:
      +
      tgtHllType - the TgtHllType enum
      +
      Returns:
      +
      a deep copy of this sketch with the specified TgtHllType.
      +
      +
      +
      +
    • +
    • +
      +

      getCompositeEstimate

      +
      +
      public double getCompositeEstimate()
      +
      This is less accurate than the getEstimate() method and is automatically used +when the sketch has gone through union operations where the more accurate HIP estimator +cannot be used. +This is made public only for error characterization software that exists in separate +packages and is not intended for normal use.
      +
      +
      Returns:
      +
      the composite estimate
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public double getEstimate()
      +
      Return the cardinality estimate
      +
      +
      Returns:
      +
      the cardinality estimate
      +
      +
      +
      +
    • +
    • +
      +

      getLgConfigK

      +
      +
      public int getLgConfigK()
      +
      Gets the lgConfigK.
      +
      +
      Returns:
      +
      the lgConfigK.
      +
      +
      +
      +
    • +
    • +
      +

      getCompactSerializationBytes

      +
      +
      public int getCompactSerializationBytes()
      +
      Gets the size in bytes of the current sketch when serialized using +toCompactByteArray().
      +
      +
      Returns:
      +
      the size in bytes of the current sketch when serialized using +toCompactByteArray().
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public double getLowerBound(int numStdDev)
      +
      Gets the approximate lower error bound given the specified number of Standard Deviations.
      +
      +
      Parameters:
      +
      numStdDev - This must be an integer between 1 and 3, inclusive. +See Number of Standard Deviations
      +
      Returns:
      +
      the lower bound.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxUpdatableSerializationBytes

      +
      +
      public static final int getMaxUpdatableSerializationBytes(int lgConfigK, + TgtHllType tgtHllType)
      +
      Returns the maximum size in bytes that this sketch can grow to given lgConfigK. +However, for the HLL_4 sketch type, this value can be exceeded in extremely rare cases. +If exceeded, it will be larger by only a few percent.
      +
      +
      Parameters:
      +
      lgConfigK - The Log2 of K for the target HLL sketch. This value must be +between 4 and 21 inclusively.
      +
      tgtHllType - the desired Hll type
      +
      Returns:
      +
      the maximum size in bytes that this sketch can grow to.
      +
      +
      +
      +
    • +
    • +
      +

      getTgtHllType

      +
      +
      public TgtHllType getTgtHllType()
      +
      Gets the TgtHllType
      +
      +
      Returns:
      +
      the TgtHllType enum value
      +
      +
      +
      +
    • +
    • +
      +

      getUpdatableSerializationBytes

      +
      +
      public int getUpdatableSerializationBytes()
      +
      Gets the size in bytes of the current sketch when serialized using +toUpdatableByteArray().
      +
      +
      Returns:
      +
      the size in bytes of the current sketch when serialized using +toUpdatableByteArray().
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public double getUpperBound(int numStdDev)
      +
      Gets the approximate upper error bound given the specified number of Standard Deviations.
      +
      +
      Parameters:
      +
      numStdDev - This must be an integer between 1 and 3, inclusive. +Number of Standard Deviations
      +
      Returns:
      +
      the upper bound.
      +
      +
      +
      +
    • +
    • +
      +

      isCompact

      +
      +
      public boolean isCompact()
      +
      Returns true if the backing MemorySegment of this sketch is in compact form.
      +
      +
      Returns:
      +
      true if the backing MemorySegment of this sketch is in compact form.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Returns true if empty
      +
      +
      Returns:
      +
      true if empty
      +
      +
      +
      +
    • +
    • +
      +

      hasMemorySegment

      +
      +
      public boolean hasMemorySegment()
      +
      Returns true if this sketch was created using MemorySegment.
      +
      +
      Specified by:
      +
      hasMemorySegment in interface MemorySegmentStatus
      +
      Returns:
      +
      true if this sketch was created using MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isOffHeap

      +
      +
      public boolean isOffHeap()
      +
      Returns true if the backing MemorySegment for this sketch is off-heap.
      +
      +
      Specified by:
      +
      isOffHeap in interface MemorySegmentStatus
      +
      Returns:
      +
      true if the backing MemorySegment for this sketch is off-heap.
      +
      +
      +
      +
    • +
    • +
      +

      isSameResource

      +
      +
      public boolean isSameResource(MemorySegment seg)
      +
      Returns true if the given MemorySegment refers to the same underlying resource as this sketch. +The capacities must be the same. If this is a region, +the region offset must also be the same. + +

      This is only relevant for HLL_4 sketches that have been configured for off-heap +using MemorySegment. For on-heap sketches or unions this will return false. + +

      It is rare, but possible, the the off-heap MemorySegment that has been allocated to an HLL_4 +sketch may not be large enough. If this should happen, the sketch makes a request for more +space from the owner of the resource and then moves itself to this new location. This all +happens transparently to the user. This method provides a means for the user to +inquire of the sketch if it has, in fact, moved itself.

      +
      +
      Specified by:
      +
      isSameResource in interface MemorySegmentStatus
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      true if the given MemorySegment refers to the same underlying resource as this HllSketch or +HllUnion.
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets to empty, but does not change the configured values of lgConfigK and tgtHllType.
      +
      +
      +
    • +
    • +
      +

      toCompactByteArray

      +
      +
      public byte[] toCompactByteArray()
      +
      Serializes this sketch as a byte array in compact form. The compact form is smaller in size +than the updatable form and read-only. It can be used in HllUnion operations as follows: +
          HllUnion union; HllSketch sk, sk2;
      +    int lgK = 12;
      +    sk = new HllSketch(lgK, TgtHllType.HLL_4); //can be 4, 6, or 8
      +    for (int i = 0; i < (2 << lgK); i++) { sk.update(i); }
      +    byte[] arr = HllSketch.toCompactByteArray();
      +    //...
      +    union = HllUnion.heapify(arr); //initializes the HllUnion using data from the array.
      +    //OR, if used in an off-heap environment:
      +    union = HllUnion.heapify(MemorySegment.ofArray(arr)); //same as above, except from MemorySegment object.
      +
      +    //To recover an updatable heap sketch:
      +    sk2 = HllSketch.heapify(arr);
      +    //OR, if used in an off-heap environment:
      +    sk2 = HllSketch.heapify(MemorySegment.ofArray(arr));
      +
      + +

      The sketch "wrapping" operation skips actual deserialization thus is quite fast. However, +any attempt to update the derived HllSketch will result in a Read-only exception.

      + +

      Note that in some cases, based on the state of the sketch, the compact form is +indistiguishable from the updatable form. In these cases the updatable form is returned +and the compact flag bit will not be set.

      +
      +
      Returns:
      +
      this sketch as a compact byte array.
      +
      +
      +
      +
    • +
    • +
      +

      toUpdatableByteArray

      +
      +
      public byte[] toUpdatableByteArray()
      +
      Serializes this sketch as a byte array in an updatable form. The updatable form is larger than +the compact form. The use of this form is primarily in environments that support updating +sketches in off-heap MemorySegment. If the sketch is constructed using HLL_8, HllSketch updating and +HllUnion updating operations can actually occur in MemorySegment, which can be off-heap: +
          HllUnion union; HllSketch sk;
      +    int lgK = 12;
      +    sk = new HllSketch(lgK, TgtHllType.HLL_8) //must be 8
      +    for (int i = 0; i < (2 << lgK); i++) { sk.update(i); }
      +    byte[] arr = sk.toUpdatableByteArray();
      +    MemorySegment wseg = MemorySegment.wrap(arr);
      +    //...
      +    union = HllUnion.writableWrap(wseg); //no deserialization!
      +
      +
      +
      Returns:
      +
      this sketch as an updatable byte array.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean summary, + boolean detail, + boolean auxDetail, + boolean all)
      +
      Human readable summary with optional detail
      +
      +
      Parameters:
      +
      summary - if true, output the sketch summary
      +
      detail - if true, output the internal data array
      +
      auxDetail - if true, output the internal Aux array, if it exists.
      +
      all - if true, outputs all entries including empty ones
      +
      Returns:
      +
      human readable string with optional detail.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(byte[] byteArr)
      +
      Returns a human readable string of the preamble of a byte array image of an HllSketch.
      +
      +
      Parameters:
      +
      byteArr - the given byte array
      +
      Returns:
      +
      a human readable string of the preamble of a byte array image of an HllSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(MemorySegment seg)
      +
      Returns a human readable string of the preamble of a MemorySegment image of an HllSketch.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment object
      +
      Returns:
      +
      a human readable string of the preamble of a MemorySegment image of an HllSketch.
      +
      +
      +
      +
    • +
    • +
      +

      getSerializationVersion

      +
      +
      public static final int getSerializationVersion()
      +
      Returns the current serialization version.
      +
      +
      Returns:
      +
      the current serialization version.
      +
      +
      +
      +
    • +
    • +
      +

      getSerializationVersion

      +
      +
      public static final int getSerializationVersion(MemorySegment seg)
      +
      Returns the current serialization version of the given MemorySegment.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment containing a serialized HllSketch image.
      +
      Returns:
      +
      the current serialization version.
      +
      +
      +
      +
    • +
    • +
      +

      getRelErr

      +
      +
      public static double getRelErr(boolean upperBound, + boolean oooFlag, + int lgConfigK, + int numStdDev)
      +
      Gets the current (approximate) Relative Error (RE) asymptotic values given several +parameters. This is used primarily for testing.
      +
      +
      Parameters:
      +
      upperBound - return the RE for the Upper Bound, otherwise for the Lower Bound.
      +
      oooFlag - set true if the sketch is the result of a non qualifying HllUnion operation.
      +
      lgConfigK - the configured value for the sketch.
      +
      numStdDev - the given number of Standard Deviations. This must be an integer between +1 and 3, inclusive. +Number of Standard Deviations
      +
      Returns:
      +
      the current (approximate) RelativeError
      +
      +
      +
      +
    • +
    • +
      +

      isEstimationMode

      +
      +
      public boolean isEstimationMode()
      +
      This HLL family of sketches and operators is always estimating, even for very small values.
      +
      +
      Returns:
      +
      true
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Human readable summary as a string.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      Human readable summary as a string.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean summary, + boolean detail, + boolean auxDetail)
      +
      Human readable summary with optional detail. Does not list empty entries.
      +
      +
      Parameters:
      +
      summary - if true, output the sketch summary
      +
      detail - if true, output the internal data array
      +
      auxDetail - if true, output the internal Aux array, if it exists.
      +
      Returns:
      +
      human readable string with optional detail.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long datum)
      +
      Present the given long as a potential unique item.
      +
      +
      Parameters:
      +
      datum - The given long datum.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(double datum)
      +
      Present the given double (or float) datum as a potential unique item. +The double will be converted to a long using Double.doubleToLongBits(datum), +which normalizes all NaN values to a single NaN representation. +Plus and minus zero will be normalized to plus zero. +The special floating-point values NaN and +/- Infinity are treated as distinct.
      +
      +
      Parameters:
      +
      datum - The given double datum.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(String datum)
      +
      Present the given String as a potential unique item. +The string is converted to a byte array using UTF8 encoding. +If the string is null or empty no update attempt is made and the method returns. + +

      Note: About 2X faster performance can be obtained by first converting the String to a +char[] and updating the sketch with that. This bypasses the complexity of the Java UTF_8 +encoding. This, of course, will not produce the same internal hash values as updating directly +with a String. So be consistent! Unioning two sketches, one fed with strings and the other +fed with char[] will be meaningless. +

      +
      +
      Parameters:
      +
      datum - The given String.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(ByteBuffer data)
      +
      Present the given byte buffer as a potential unique item. +Bytes are read from the current position of the buffer until its limit. +If the byte buffer is null or has no bytes remaining, no update attempt is made and the method returns. + +

      This method will not modify the position, mark, limit, or byte order of the buffer.

      + +

      Little-endian order is preferred, but not required. This method may perform better if the provided byte +buffer is in little-endian order.

      +
      +
      Parameters:
      +
      data - The given byte buffer.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(byte[] data)
      +
      Present the given byte array as a potential unique item. +If the byte array is null or empty no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      data - The given byte array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(char[] data)
      +
      Present the given char array as a potential unique item. +If the char array is null or empty no update attempt is made and the method returns. + +

      Note: this will not produce the same output hash values as the update(String) +method but will be a little faster as it avoids the complexity of the UTF8 encoding.

      +
      +
      Parameters:
      +
      data - The given char array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(int[] data)
      +
      Present the given integer array as a potential unique item. +If the integer array is null or empty no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      data - The given int array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long[] data)
      +
      Present the given long array as a potential unique item. +If the long array is null or empty no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      data - The given long array.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hll/HllUnion.html b/target/site/apidocs/org/apache/datasketches/hll/HllUnion.html new file mode 100644 index 000000000..d95e64c1f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hll/HllUnion.html @@ -0,0 +1,1106 @@ + + + + +HllUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class HllUnion

+
+
java.lang.Object +
org.apache.datasketches.hll.HllUnion
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus
+
+
+
+
public class HllUnion +extends Object
+
This performs union operations for all HllSketches. This HllUnion operator can be configured to be +on or off heap. The source sketch given to this HllUnion using the update(HllSketch) can +be configured with any precision value lgConfigK (from 4 to 21), any TgtHllType +(HLL_4, HLL_6, HLL_8), and either on or off-heap; and it can be in either of the sparse modes +(LIST or SET), or the dense mode (HLL). + +

Although the API for this HllUnion operator parallels many of the methods of the +HllSketch, the behavior of the HllUnion operator has some fundamental differences.

+ +

First, this HllUnion operator is configured with a lgMaxK instead of the normal +lgConfigK. Generally, this HllUnion operator will inherit the lowest lgConfigK +less than lgMaxK that it has seen. However, the lgConfigK of incoming sketches that +are still in sparse are ignored. The lgMaxK provides the user the ability to specify the +largest maximum size for the HllUnion operation. + +

Second, the user cannot specify the TgtHllType as an input parameter to the HllUnion. +Instead, it is specified for the sketch returned with getResult(TgtHllType). + +

The following graph illustrates the HLL Merge speed.

+ +

HLL_UnionTime4_6_8_Java_CPP.png

+This graph illustrates the relative merging speed of the HLL 4,6,8 Java HLL sketches compared to +the DataSketches C++ implementations of the same sketches. With this particular test (merging 32 relative large +sketches together), the Java HLL 8 is the fastest and the Java HLL 4 the slowest, with a mixed cluster in the middle. +HllUnion / Merging speed is somewhat difficult to measure as the performance is very dependent on the mix of sketch +sizes (and types) you are merging. So your mileage will vary! + +

For a complete example of using the HllUnion operator +see HllUnion Example.

+
+
Author:
+
Lee Rhodes, Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    Construct this HllUnion operator with the default maximum log-base-2 of K.
    +
    +
    HllUnion(int lgMaxK)
    +
    +
    Construct this HllUnion operator with a given maximum log-base-2 of K.
    +
    +
    HllUnion(int lgMaxK, + MemorySegment dstWseg)
    +
    +
    Construct this HllUnion operator with a given maximum log-base-2 of K and the given +MemorySegment as the destination for this HllUnion.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    int
    + +
    +
    Gets the size in bytes of the current sketch when serialized using +toCompactByteArray().
    +
    +
    double
    + +
    +
    This is less accurate than the getEstimate() method and is automatically used +when the sketch has gone through union operations where the more accurate HIP estimator +cannot be used.
    +
    +
    double
    + +
    +
    Return the cardinality estimate
    +
    +
    int
    + +
    +
    Gets the effective lgConfigK for the HllUnion operator, which may be less than +lgMaxK.
    +
    +
    double
    +
    getLowerBound(int numStdDev)
    +
    +
    Gets the approximate lower error bound given the specified number of Standard Deviations.
    +
    +
    static int
    + +
    +
    Returns the maximum size in bytes that this HllUnion operator can grow to given a lgK.
    +
    +
    static double
    +
    getRelErr(boolean upperBound, + boolean oooFlag, + int lgConfigK, + int numStdDev)
    +
    +
    Gets the current (approximate) Relative Error (RE) asymptotic values given several +parameters.
    +
    + + +
    +
    Return the result of this HllUnion operator as an HLL_4 sketch.
    +
    + +
    getResult(TgtHllType tgtHllType)
    +
    +
    Return the result of this HllUnion operator with the specified TgtHllType
    +
    +
    static final int
    + +
    +
    Returns the current serialization version.
    +
    +
    static final int
    + +
    +
    Returns the current serialization version of the given MemorySegment.
    +
    + + +
    +
    Gets the TgtHllType
    +
    +
    int
    + +
    +
    Gets the size in bytes of the current sketch when serialized using +toUpdatableByteArray().
    +
    +
    double
    +
    getUpperBound(int numStdDev)
    +
    +
    Gets the approximate upper error bound given the specified number of Standard Deviations.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch was created using MemorySegment.
    +
    +
    static final HllUnion
    +
    heapify(byte[] byteArray)
    +
    +
    Construct a HllUnion operator populated with the given byte array image of an HllSketch.
    +
    +
    static final HllUnion
    + +
    +
    Construct a HllUnion operator populated with the given MemorySegment image of an HllSketch.
    +
    +
    boolean
    + +
    +
    Returns true if the backing MemorySegment of this sketch is in compact form.
    +
    +
    boolean
    + +
    +
    Returns true if empty
    +
    +
    boolean
    + +
    +
    This HLL family of sketches and operators is always estimating, even for very small values.
    +
    +
    boolean
    + +
    +
    Returns true if the backing MemorySegment for this sketch is off-heap.
    +
    +
    boolean
    + +
    +
    Returns true if the given MemorySegment refers to the same underlying resource as this sketch.
    +
    +
    void
    + +
    +
    Resets to empty and retains the current lgK, but does not change the configured value of +lgMaxK.
    +
    +
    byte[]
    + +
    +
    Gets the serialization of this HllUnion operator as a byte array in compact form, which is +designed to be heapified only.
    +
    + + +
    +
    Human readable summary as a string.
    +
    + +
    toString(boolean summary, + boolean detail, + boolean auxDetail)
    +
    +
    Human readable summary with optional detail.
    +
    + +
    toString(boolean summary, + boolean hllDetail, + boolean auxDetail, + boolean all)
    +
    +
    Human readable summary with optional detail
    +
    +
    byte[]
    + +
    +
    Serializes this sketch as a byte array in an updatable form.
    +
    +
    void
    +
    update(byte[] data)
    +
    +
    Present the given byte array as a potential unique item.
    +
    +
    void
    +
    update(char[] data)
    +
    +
    Present the given char array as a potential unique item.
    +
    +
    void
    +
    update(double datum)
    +
    +
    Present the given double (or float) datum as a potential unique item.
    +
    +
    void
    +
    update(int[] data)
    +
    +
    Present the given integer array as a potential unique item.
    +
    +
    void
    +
    update(long datum)
    +
    +
    Present the given long as a potential unique item.
    +
    +
    void
    +
    update(long[] data)
    +
    +
    Present the given long array as a potential unique item.
    +
    +
    void
    +
    update(String datum)
    +
    +
    Present the given String as a potential unique item.
    +
    +
    void
    + +
    +
    Present the given byte buffer as a potential unique item.
    +
    +
    void
    +
    update(HllSketch sketch)
    +
    +
    Update this HllUnion operator with the given sketch.
    +
    +
    static final HllUnion
    + +
    +
    Wraps the given MemorySegment, which must be a image of a valid updatable HLL_8 sketch, +and may have data.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      HllUnion

      +
      +
      public HllUnion()
      +
      Construct this HllUnion operator with the default maximum log-base-2 of K.
      +
      +
      +
    • +
    • +
      +

      HllUnion

      +
      +
      public HllUnion(int lgMaxK)
      +
      Construct this HllUnion operator with a given maximum log-base-2 of K.
      +
      +
      Parameters:
      +
      lgMaxK - the desired maximum log-base-2 of K. This value must be +between 4 and 21 inclusively.
      +
      +
      +
      +
    • +
    • +
      +

      HllUnion

      +
      +
      public HllUnion(int lgMaxK, + MemorySegment dstWseg)
      +
      Construct this HllUnion operator with a given maximum log-base-2 of K and the given +MemorySegment as the destination for this HllUnion. This MemorySegment is usually configured +for off-heap MemorySegment. What remains on the java heap is a thin wrapper object that reads and +writes to the given MemorySegment. + +

      The given dstSeg is checked for the required capacity as determined by +HllSketch.getMaxUpdatableSerializationBytes(int, TgtHllType).

      +
      +
      Parameters:
      +
      lgMaxK - the desired maximum log-base-2 of K. This value must be +between 4 and 21 inclusively.
      +
      dstWseg - the destination writable MemorySegment for the sketch.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapify

      +
      +
      public static final HllUnion heapify(byte[] byteArray)
      +
      Construct a HllUnion operator populated with the given byte array image of an HllSketch.
      +
      +
      Parameters:
      +
      byteArray - the given byte array
      +
      Returns:
      +
      a HllUnion operator populated with the given byte array image of an HllSketch.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static final HllUnion heapify(MemorySegment seg)
      +
      Construct a HllUnion operator populated with the given MemorySegment image of an HllSketch.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      a HllUnion operator populated with the given MemorySegment image of an HllSketch.
      +
      +
      +
      +
    • +
    • +
      +

      writableWrap

      +
      +
      public static final HllUnion writableWrap(MemorySegment srcWseg)
      +
      Wraps the given MemorySegment, which must be a image of a valid updatable HLL_8 sketch, +and may have data. What remains on the java heap is a +thin wrapper object that reads and writes to the given MemorySegment, which, depending on +how the user configures the MemorySegment, may actually reside on the Java heap or off-heap. + +

      The given dstSeg is checked for the required capacity as determined by +HllSketch.getMaxUpdatableSerializationBytes(int, TgtHllType), and for the correct type.

      +
      +
      Parameters:
      +
      srcWseg - an writable image of a valid sketch with data.
      +
      Returns:
      +
      a HllUnion operator where the sketch data is in the given dstSeg.
      +
      +
      +
      +
    • +
    • +
      +

      getCompositeEstimate

      +
      +
      public double getCompositeEstimate()
      +
      This is less accurate than the getEstimate() method and is automatically used +when the sketch has gone through union operations where the more accurate HIP estimator +cannot be used. +This is made public only for error characterization software that exists in separate +packages and is not intended for normal use.
      +
      +
      Returns:
      +
      the composite estimate
      +
      +
      +
      +
    • +
    • +
      +

      getCompactSerializationBytes

      +
      +
      public int getCompactSerializationBytes()
      +
      Gets the size in bytes of the current sketch when serialized using +toCompactByteArray().
      +
      +
      Returns:
      +
      the size in bytes of the current sketch when serialized using +toCompactByteArray().
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public double getEstimate()
      +
      Return the cardinality estimate
      +
      +
      Returns:
      +
      the cardinality estimate
      +
      +
      +
      +
    • +
    • +
      +

      getLgConfigK

      +
      +
      public int getLgConfigK()
      +
      Gets the effective lgConfigK for the HllUnion operator, which may be less than +lgMaxK.
      +
      +
      Returns:
      +
      the lgConfigK.
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public double getLowerBound(int numStdDev)
      +
      Gets the approximate lower error bound given the specified number of Standard Deviations.
      +
      +
      Parameters:
      +
      numStdDev - This must be an integer between 1 and 3, inclusive. +See Number of Standard Deviations
      +
      Returns:
      +
      the lower bound.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxSerializationBytes

      +
      +
      public static int getMaxSerializationBytes(int lgK)
      +
      Returns the maximum size in bytes that this HllUnion operator can grow to given a lgK.
      +
      +
      Parameters:
      +
      lgK - The maximum Log2 of K for this HllUnion operator. This value must be +between 4 and 21 inclusively.
      +
      Returns:
      +
      the maximum size in bytes that this HllUnion operator can grow to.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public HllSketch getResult()
      +
      Return the result of this HllUnion operator as an HLL_4 sketch.
      +
      +
      Returns:
      +
      the result of this HllUnion operator as an HLL_4 sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public HllSketch getResult(TgtHllType tgtHllType)
      +
      Return the result of this HllUnion operator with the specified TgtHllType
      +
      +
      Parameters:
      +
      tgtHllType - the TgtHllType enum
      +
      Returns:
      +
      the result of this HllUnion operator with the specified TgtHllType
      +
      +
      +
      +
    • +
    • +
      +

      getTgtHllType

      +
      +
      public TgtHllType getTgtHllType()
      +
      Gets the TgtHllType
      +
      +
      Returns:
      +
      the TgtHllType enum value
      +
      +
      +
      +
    • +
    • +
      +

      getUpdatableSerializationBytes

      +
      +
      public int getUpdatableSerializationBytes()
      +
      Gets the size in bytes of the current sketch when serialized using +toUpdatableByteArray().
      +
      +
      Returns:
      +
      the size in bytes of the current sketch when serialized using +toUpdatableByteArray().
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public double getUpperBound(int numStdDev)
      +
      Gets the approximate upper error bound given the specified number of Standard Deviations.
      +
      +
      Parameters:
      +
      numStdDev - This must be an integer between 1 and 3, inclusive. +Number of Standard Deviations
      +
      Returns:
      +
      the upper bound.
      +
      +
      +
      +
    • +
    • +
      +

      isCompact

      +
      +
      public boolean isCompact()
      +
      Returns true if the backing MemorySegment of this sketch is in compact form.
      +
      +
      Returns:
      +
      true if the backing MemorySegment of this sketch is in compact form.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Returns true if empty
      +
      +
      Returns:
      +
      true if empty
      +
      +
      +
      +
    • +
    • +
      +

      hasMemorySegment

      +
      +
      public boolean hasMemorySegment()
      +
      Returns true if this sketch was created using MemorySegment.
      +
      +
      Specified by:
      +
      hasMemorySegment in interface MemorySegmentStatus
      +
      Returns:
      +
      true if this sketch was created using MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isOffHeap

      +
      +
      public boolean isOffHeap()
      +
      Returns true if the backing MemorySegment for this sketch is off-heap.
      +
      +
      Specified by:
      +
      isOffHeap in interface MemorySegmentStatus
      +
      Returns:
      +
      true if the backing MemorySegment for this sketch is off-heap.
      +
      +
      +
      +
    • +
    • +
      +

      isSameResource

      +
      +
      public boolean isSameResource(MemorySegment seg)
      +
      Returns true if the given MemorySegment refers to the same underlying resource as this sketch. +The capacities must be the same. If this is a region, +the region offset must also be the same. + +

      This is only relevant for HLL_4 sketches that have been configured for off-heap +using MemorySegment. For on-heap sketches or unions this will return false. + +

      It is rare, but possible, the the off-heap MemorySegment that has been allocated to an HLL_4 +sketch may not be large enough. If this should happen, the sketch makes a request for more +space from the owner of the resource and then moves itself to this new location. This all +happens transparently to the user. This method provides a means for the user to +inquire of the sketch if it has, in fact, moved itself.

      +
      +
      Specified by:
      +
      isSameResource in interface MemorySegmentStatus
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      true if the given MemorySegment refers to the same underlying resource as this HllSketch or +HllUnion.
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets to empty and retains the current lgK, but does not change the configured value of +lgMaxK.
      +
      +
      +
    • +
    • +
      +

      toCompactByteArray

      +
      +
      public byte[] toCompactByteArray()
      +
      Gets the serialization of this HllUnion operator as a byte array in compact form, which is +designed to be heapified only. It is not directly updatable. +For the HllUnion operator, this is the serialization of the internal state of +the HllUnion operator as a sketch.
      +
      +
      Returns:
      +
      the serialization of this HllUnion operator as a byte array.
      +
      +
      +
      +
    • +
    • +
      +

      toUpdatableByteArray

      +
      +
      public byte[] toUpdatableByteArray()
      +
      Serializes this sketch as a byte array in an updatable form. The updatable form is larger than +the compact form. The use of this form is primarily in environments that support updating +sketches in off-heap MemorySegment. If the sketch is constructed using HLL_8, HllSketch updating and +HllUnion updating operations can actually occur in MemorySegment, which can be off-heap: +
          HllUnion union; HllSketch sk;
      +    int lgK = 12;
      +    sk = new HllSketch(lgK, TgtHllType.HLL_8) //must be 8
      +    for (int i = 0; i < (2 << lgK); i++) { sk.update(i); }
      +    byte[] arr = sk.toUpdatableByteArray();
      +    MemorySegment wseg = MemorySegment.wrap(arr);
      +    //...
      +    union = HllUnion.writableWrap(wseg); //no deserialization!
      +
      +
      +
      Returns:
      +
      this sketch as an updatable byte array.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean summary, + boolean hllDetail, + boolean auxDetail, + boolean all)
      +
      Human readable summary with optional detail
      +
      +
      Parameters:
      +
      summary - if true, output the sketch summary
      +
      hllDetail - if true, output the internal data array
      +
      auxDetail - if true, output the internal Aux array, if it exists.
      +
      all - if true, outputs all entries including empty ones
      +
      Returns:
      +
      human readable string with optional detail.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(HllSketch sketch)
      +
      Update this HllUnion operator with the given sketch.
      +
      +
      Parameters:
      +
      sketch - the given sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getSerializationVersion

      +
      +
      public static final int getSerializationVersion()
      +
      Returns the current serialization version.
      +
      +
      Returns:
      +
      the current serialization version.
      +
      +
      +
      +
    • +
    • +
      +

      getSerializationVersion

      +
      +
      public static final int getSerializationVersion(MemorySegment seg)
      +
      Returns the current serialization version of the given MemorySegment.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment containing a serialized HllSketch image.
      +
      Returns:
      +
      the current serialization version.
      +
      +
      +
      +
    • +
    • +
      +

      getRelErr

      +
      +
      public static double getRelErr(boolean upperBound, + boolean oooFlag, + int lgConfigK, + int numStdDev)
      +
      Gets the current (approximate) Relative Error (RE) asymptotic values given several +parameters. This is used primarily for testing.
      +
      +
      Parameters:
      +
      upperBound - return the RE for the Upper Bound, otherwise for the Lower Bound.
      +
      oooFlag - set true if the sketch is the result of a non qualifying HllUnion operation.
      +
      lgConfigK - the configured value for the sketch.
      +
      numStdDev - the given number of Standard Deviations. This must be an integer between +1 and 3, inclusive. +Number of Standard Deviations
      +
      Returns:
      +
      the current (approximate) RelativeError
      +
      +
      +
      +
    • +
    • +
      +

      isEstimationMode

      +
      +
      public boolean isEstimationMode()
      +
      This HLL family of sketches and operators is always estimating, even for very small values.
      +
      +
      Returns:
      +
      true
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Human readable summary as a string.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      Human readable summary as a string.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean summary, + boolean detail, + boolean auxDetail)
      +
      Human readable summary with optional detail. Does not list empty entries.
      +
      +
      Parameters:
      +
      summary - if true, output the sketch summary
      +
      detail - if true, output the internal data array
      +
      auxDetail - if true, output the internal Aux array, if it exists.
      +
      Returns:
      +
      human readable string with optional detail.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long datum)
      +
      Present the given long as a potential unique item.
      +
      +
      Parameters:
      +
      datum - The given long datum.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(double datum)
      +
      Present the given double (or float) datum as a potential unique item. +The double will be converted to a long using Double.doubleToLongBits(datum), +which normalizes all NaN values to a single NaN representation. +Plus and minus zero will be normalized to plus zero. +The special floating-point values NaN and +/- Infinity are treated as distinct.
      +
      +
      Parameters:
      +
      datum - The given double datum.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(String datum)
      +
      Present the given String as a potential unique item. +The string is converted to a byte array using UTF8 encoding. +If the string is null or empty no update attempt is made and the method returns. + +

      Note: About 2X faster performance can be obtained by first converting the String to a +char[] and updating the sketch with that. This bypasses the complexity of the Java UTF_8 +encoding. This, of course, will not produce the same internal hash values as updating directly +with a String. So be consistent! Unioning two sketches, one fed with strings and the other +fed with char[] will be meaningless. +

      +
      +
      Parameters:
      +
      datum - The given String.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(ByteBuffer data)
      +
      Present the given byte buffer as a potential unique item. +Bytes are read from the current position of the buffer until its limit. +If the byte buffer is null or has no bytes remaining, no update attempt is made and the method returns. + +

      This method will not modify the position, mark, limit, or byte order of the buffer.

      + +

      Little-endian order is preferred, but not required. This method may perform better if the provided byte +buffer is in little-endian order.

      +
      +
      Parameters:
      +
      data - The given byte buffer.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(byte[] data)
      +
      Present the given byte array as a potential unique item. +If the byte array is null or empty no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      data - The given byte array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(char[] data)
      +
      Present the given char array as a potential unique item. +If the char array is null or empty no update attempt is made and the method returns. + +

      Note: this will not produce the same output hash values as the update(String) +method but will be a little faster as it avoids the complexity of the UTF8 encoding.

      +
      +
      Parameters:
      +
      data - The given char array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(int[] data)
      +
      Present the given integer array as a potential unique item. +If the integer array is null or empty no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      data - The given int array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long[] data)
      +
      Present the given long array as a potential unique item. +If the long array is null or empty no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      data - The given long array.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hll/TgtHllType.html b/target/site/apidocs/org/apache/datasketches/hll/TgtHllType.html new file mode 100644 index 000000000..daac2133b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hll/TgtHllType.html @@ -0,0 +1,310 @@ + + + + +TgtHllType (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class TgtHllType

+
+
java.lang.Object +
java.lang.Enum<TgtHllType> +
org.apache.datasketches.hll.TgtHllType
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<TgtHllType>, Constable
+
+
+
+
public enum TgtHllType +extends Enum<TgtHllType>
+
Specifies the target type of HLL sketch to be created. It is a target in that the actual +allocation of the HLL array is deferred until sufficient number of items have been received by +the warm-up phases. + +

These three target types are isomorphic representations of the same underlying HLL algorithm. +Thus, given the same value of lgConfigK and the same input, all three HLL target types +will produce identical estimates and have identical error distributions.

+ +

The memory usage and the serialization size of the sketch during this early warmup phase starts +out very small (8 bytes, when empty) and then grows in increments of 4 bytes as required +until the full HLL array is allocated. This transition point occurs at about 10% of K for +sketches where lgConfigK is > 8.

+ +
    +
  • HLL 8 This uses an 8-bit byte per HLL bucket. It is generally the +fastest in terms of update time, but has the largest storage footprint of about +K bytes.
  • + +
  • HLL 6 This uses a 6-bit field per HLL bucket. It is the generally the next fastest +in terms of update time with a storage footprint of about 3/4 * K bytes.
  • + +
  • HLL 4 This uses a 4-bit field per HLL bucket and for large counts may require +the use of a small internal auxiliary array for storing statistical exceptions, which are rare. +For the values of lgConfigK > 13 (K = 8192), +this additional array adds about 3% to the overall storage. It is generally the slowest in +terms of update time, but has the smallest storage footprint of about +K/2 * 1.03 bytes.
  • +
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Enum Constant Details

    +
      +
    • +
      +

      HLL_4

      +
      +
      public static final TgtHllType HLL_4
      +
      An HLL sketch with a bin size of 4 bits
      +
      +
      +
    • +
    • +
      +

      HLL_6

      +
      +
      public static final TgtHllType HLL_6
      +
      An HLL sketch with a bin size of 6 bits
      +
      +
      +
    • +
    • +
      +

      HLL_8

      +
      +
      public static final TgtHllType HLL_8
      +
      An HLL Sketch with a bin size of 8 bits
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static TgtHllType[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static TgtHllType valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    • +
      +

      fromOrdinal

      +
      +
      public static final TgtHllType fromOrdinal(int typeId)
      +
      Convert the typeId to the enum type
      +
      +
      Parameters:
      +
      typeId - the given typeId
      +
      Returns:
      +
      the enum type
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hll/class-use/HllSketch.html b/target/site/apidocs/org/apache/datasketches/hll/class-use/HllSketch.html new file mode 100644 index 000000000..fbc1eed18 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hll/class-use/HllSketch.html @@ -0,0 +1,143 @@ + + + + +Uses of Class org.apache.datasketches.hll.HllSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.hll.HllSketch

+
+
Packages that use HllSketch
+
+
Package
+
Description
+ +
+
The DataSketches™ HllSketch family package
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hll/class-use/HllUnion.html b/target/site/apidocs/org/apache/datasketches/hll/class-use/HllUnion.html new file mode 100644 index 000000000..420be128c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hll/class-use/HllUnion.html @@ -0,0 +1,106 @@ + + + + +Uses of Class org.apache.datasketches.hll.HllUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.hll.HllUnion

+
+
Packages that use HllUnion
+
+
Package
+
Description
+ +
+
The DataSketches™ HllSketch family package
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hll/class-use/TgtHllType.html b/target/site/apidocs/org/apache/datasketches/hll/class-use/TgtHllType.html new file mode 100644 index 000000000..3855c5392 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hll/class-use/TgtHllType.html @@ -0,0 +1,176 @@ + + + + +Uses of Enum Class org.apache.datasketches.hll.TgtHllType (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.hll.TgtHllType

+
+
Packages that use TgtHllType
+
+
Package
+
Description
+ +
+
The DataSketches™ HllSketch family package
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/src/main/java/org/apache/datasketches/hll/doc-files/HLL_HIP_K12T20U20.png b/target/site/apidocs/org/apache/datasketches/hll/doc-files/HLL_HIP_K12T20U20.png similarity index 100% rename from src/main/java/org/apache/datasketches/hll/doc-files/HLL_HIP_K12T20U20.png rename to target/site/apidocs/org/apache/datasketches/hll/doc-files/HLL_HIP_K12T20U20.png diff --git a/src/main/java/org/apache/datasketches/hll/doc-files/HLL_UnionTime4_6_8_Java_CPP.png b/target/site/apidocs/org/apache/datasketches/hll/doc-files/HLL_UnionTime4_6_8_Java_CPP.png similarity index 100% rename from src/main/java/org/apache/datasketches/hll/doc-files/HLL_UnionTime4_6_8_Java_CPP.png rename to target/site/apidocs/org/apache/datasketches/hll/doc-files/HLL_UnionTime4_6_8_Java_CPP.png diff --git a/target/site/apidocs/org/apache/datasketches/hll/package-summary.html b/target/site/apidocs/org/apache/datasketches/hll/package-summary.html new file mode 100644 index 000000000..dfde8420a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hll/package-summary.html @@ -0,0 +1,275 @@ + + + + +org.apache.datasketches.hll (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.hll

+
+
+
+
package org.apache.datasketches.hll
+
+

The DataSketches™ HllSketch family package

+ HllSketch and HllUnion + are the public facing classes of this high performance implementation of Phillipe Flajolet's + HyperLogLog algorithm[1] but with significantly improved error behavior and important features that can be + essential for large production systems that must handle massive data. + +

Key Features of the DataSketches™ HllSketch and its companion HllUnion

+ +

Advanced Estimation Algorithms for Optimum Accuracy

+ +

Zero error at low cardinalities

+ The HllSketch leverages highly compact arrays and hash tables to keep exact counts until the transition to + dense mode is required for space reasons. The result is perfect accuracy for very low cardinalities. + +

Accuracy for very small streams can be important because Big Data is often fragmented into millions of smaller + streams (or segments) that inevitably are power-law distributed in size. If you are sketching all these fragments, + as a general rule, more than 80% of your sketches will be very small, 20% will be much larger, and only a few will + be very large in cardinality.

+ +

HIP / Martingale Estimator

+ When obtaining a cardinality estimate, the sketch automatically determines if it was the result of the capture of + a single stream, or if was the result of certain qualifying union operations. If this is the case the sketch will + take advantage of Edith Cohen's Historical Inverse Probability (HIP) estimation algorithm[2], which was + also independently developed by Daniel Ting as the Martingale estimation algorithm[3]. + This will result in a 20% improvement in accuracy over the standard Flajolet estimator. + If it is not a single stream or if the specific union operation did not qualify, + the estimator will default to the Composite Estimator. + +

Composite Estimator

+ This advanced estimator is a blend of several algorithms including new algorithms developed by Kevin Lang for his + Compressed Probabilistic Counting (CPC) sketch[4]. These algorithms provide near optimal estimation accuracy + for cases that don't qualify for HIP / Martingale estimation. + +

As a result of all of this work on accuracy, one will get a very smooth curve of the underlying accuracy of the + sketch once the statistical randomness is removed through multiple trials. This can be observed in the + following graph.

+ +

HLL_HIP_K12T20U20.png[6]

+ +

The above graph has 7 curves. At y = 0, is the median line that hugs the x-axis so closely that it can't be seen. + The two curves, just above and just below the x-axis, correspond to +/- 1 standard deviation (SD) of error. + The distance between either one of this pair and the x-axis is also known as the Relative Standard Error (RSE). + This type of graph for illustrating sketch error we call a "pitchfork plot".

+ +

The next two curves above and below correspond to +/- 2 SD, and + the top-most and bottom-most curves correspond to +/- 3 SD. + The chart grid lines are set at +/- multiples of Relative Standard Error (RSE) that correspond to +/- 1,2,3 SD. + Below the cardinality of about 512 there is no error at all. This is the point where this particular + sketch transitions from sparse to dense (or estimation) mode.

+ +

Three HllSketch Types

+ This HLL implementation offers three different types of HllSketch, each with different + trade-offs with accuracy, space and performance. These types are selected with the + TgtHllType parameter. + +

In terms of accuracy, all three types, for the same lgConfigK, have the same error + distribution as a function of cardinality.

+ +

The configuration parameter lgConfigK is the log-base-2 of K, + where K is the number of buckets or slots for the sketch. lgConfigK impacts both accuracy and + the size of the sketch in memory and when stored.

+ +

HLL 8

+ This uses an 8-bit byte per HLL bucket. It is generally the + fastest in terms of update time but has the largest storage footprint of about K bytes. + +

HLL 6

+ This uses a 6-bit field per HLL bucket. It is the generally the next fastest + in terms of update time with a storage footprint of about 3/4 * K bytes. + +

HLL 4

+ This uses a 4-bit field per HLL bucket and for large counts may require + the use of a small internal auxiliary array for storing statistical exceptions, which are rare. + For the values of lgConfigK > 13 (K = 8192), + this additional array adds about 3% to the overall storage. It is generally the slowest in + terms of update time, but has the smallest storage footprint of about K/2 * 1.03 bytes. + +

Off-Heap Operation

+ This HllSketch also offers the capability of operating off-heap. Given a MemorySegment[5] object + created by the user, the sketch will perform all of its updates and internal phase transitions + in that object, which can actually reside either on-heap or off-heap based on how it was + configured. In large systems that must update and union many millions of sketches, having the + sketch operate off-heap avoids the serialization and deserialization costs of moving sketches from heap to + off-heap and back, and reduces the need for garbage collection. + +

Merging sketches with different configured lgConfigK

+ This enables a user to union an HllSketch that was configured with, say, lgConfigK = 12 + with another loaded HllSketch that was configured with, say, lgConfigK = 14. + +

Why is this important? Suppose you have been building a history of sketches of your customer's + data that go back a full year (or 5 or 10!) that were all configured with lgConfigK = 12. Because sketches + are so much smaller than the raw data it is possible that the raw data was discarded keeping only the sketches. + Even if you have the raw data, it might be very expensive and time consuming to reload and rebuild all your + sketches with a larger more accurate size, say, lgConfigK = 14. + This capability enables you to merge last year's data with this year's data built with larger sketches and still + have meaningful results.

+ +

In other words, you can change your mind about what size sketch you need for your application at any time and + will not lose access to the data contained in your older historical sketches.

+ +

This capability does come with a caveat: The resulting accuracy of the merged sketch will be the accuracy of the + smaller of the two sketches. Without this capability, you would either be stuck with the configuration you first + chose forever, or you would have to rebuild all your sketches from scratch, or worse, not be able to recover your + historical data.

+ +

Multi-language, multi-platform.

+ The binary structures for our sketch serializations are language and platform independent. + This means it is possible to generate an HllSketch on a C++ Windows platform and it can be used on a + Java or Python Unix platform. + +

[1] Philippe Flajolet, et al, +HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm. + DMTCS proc. AH, 2007, 127-146. + +

[2] Edith Cohen, +All-Distances Sketches, Revisited: HIP Estimators for Massive Graphs Analysis. + PODS'14, June 22-27, Snowbird, UT, USA. + +

[3] Daniel Ting, + +Streamed Approximate Counting of Distinct Elements, Beating Optimal Batch Methods. + KDD'14 August 24, 2014 New York, New York USA. + +

[4] Kevin Lang, + +Back to the Future: an Even More Nearly Optimal Cardinality Estimation Algorithm. + arXiv 1708.06839, August 22, 2017, Yahoo Research. + +

[5] MemorySegment Component, See + JEP 454: Foreign Function And Memory API + +

[6] MacBook Pro 2.3 GHz 8-Core Intel Core i9

+
+
Author:
+
Lee Rhodes, Kevin Lang
+
See Also:
+
+ +
+
+
+
+
+
    +
  • + +
  • +
  • +
    +
    +
    +
    +
    Class
    +
    Description
    + +
    +
    The HllSketch is actually a collection of compact implementations of Phillipe Flajolet’s HyperLogLog (HLL) +sketch but with significantly improved error behavior and excellent speed performance.
    +
    + +
    +
    This performs union operations for all HllSketches.
    +
    + +
    +
    Specifies the target type of HLL sketch to be created.
    +
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hll/package-tree.html b/target/site/apidocs/org/apache/datasketches/hll/package-tree.html new file mode 100644 index 000000000..fd6ba8150 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hll/package-tree.html @@ -0,0 +1,94 @@ + + + + +org.apache.datasketches.hll Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.hll

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Enum Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hll/package-use.html b/target/site/apidocs/org/apache/datasketches/hll/package-use.html new file mode 100644 index 000000000..47b1cfbc0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hll/package-use.html @@ -0,0 +1,100 @@ + + + + +Uses of Package org.apache.datasketches.hll (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.hll

+
+
Packages that use org.apache.datasketches.hll
+
+
Package
+
Description
+ +
+
The DataSketches™ HllSketch family package
+
+
+
+
    +
  • +
    + +
    +
    Class
    +
    Description
    + +
    +
    The HllSketch is actually a collection of compact implementations of Phillipe Flajolet’s HyperLogLog (HLL) +sketch but with significantly improved error behavior and excellent speed performance.
    +
    + +
    +
    This performs union operations for all HllSketches.
    +
    + +
    +
    Specifies the target type of HLL sketch to be created.
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hllmap/UniqueCountMap.html b/target/site/apidocs/org/apache/datasketches/hllmap/UniqueCountMap.html new file mode 100644 index 000000000..60b408eba --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hllmap/UniqueCountMap.html @@ -0,0 +1,438 @@ + + + + +UniqueCountMap (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class UniqueCountMap

+
+
java.lang.Object +
org.apache.datasketches.hllmap.UniqueCountMap
+
+
+
+
+
public final class UniqueCountMap +extends Object
+
This is a real-time, key-value HLL mapping sketch that tracks approximate unique counts of +identifiers (the values) associated with each key. An example might be tracking the number of +unique user identifiers associated with each IP address. This map has been specifically designed +for the use-case where the number of keys is quite large (many millions) and the distribution of +identifiers per key is very skewed. A typical distribution where this works well is a +power-law distribution of identifiers per key of the form y = Cx, +where α < 0.5, and C is roughly ymax. +For example, with 100M keys, over 75% of the keys would have only +one identifier, 99% of the keys would have less than 20 identifiers, 99.9% would have less than +200 identifiers, and a very tiny fraction might have identifiers in the thousands. + +

The space consumed by this map is quite sensitive to the actual distribution of identifiers +per key, so you should characterize and or experiment with your typical input streams. +Nonetheless, our experiments on live streams of over 100M keys required about 1.4GB of space. +This is about 14 bytes per key for key storage and unique count storage. + +

Given such highly-skewed distributions, using this map is far more efficient space-wise than +the alternative of dedicating an HLL sketch per key. Based on our use cases, after +subtracting the space required for key storage, the average bytes per key required for unique +count estimation (getAverageSketchBytesPerKey()) is about 10. + +

Internally, this map is implemented as a hierarchy of internal hash maps with progressively +increasing storage allocated for unique count estimation. As a key acquires more identifiers it +is "promoted" up to a higher internal map. The final map of keys is a map of compact HLL +sketches. + +

The unique values in all the internal maps, except the final HLL map, are stored in a special +form called a coupon. A coupon is a 16-bit value that fully describes a k=1024 HLL bin. +It contains 10 bits of address and a 6-bit HLL value. + +

All internal maps use a prime number size and Knuth's Open Addressing Double Hash (OADH) +search algorithm. + +

The internal base map holds all the keys and each key is associated with one 16-bit value. +Initially, the value is a single coupon. Once the key is promoted, this 16-bit field contains a +reference to the internal map where the key is still active. + +

The intermediate maps between the base map and the final HLL map are of two types. +The first few of these are called traverse maps where the coupons are +stored as unsorted arrays. After the traverse maps are the coupon hash maps, where the coupons +are stored in small OASH hash tables. + +

All the intermediate maps support deletes and can dynamically grow and shrink as required by +the input stream. + +

The sketch estimator algorithms are unbiased with a Relative Standard Error (RSE) +of about 2.6% with 68% confidence, or equivalently, about 5.2% with a 95% confidence. + +

In a parallel package in the sketches-misc repository, there are 2 classes that can be used +from the command line to feed this mapping sketch piped from standard-in for experimental +evaluation. The first is ProcessIpStream, which processes simple IP/ID pairs and the second, +ProcessDistributionStream, which processes pairs that describe a distribution. +In this same package is the VariousMapRSETest class that was used to generate the error plots +for the web site. Please refer to the javadocs for those classes for more information.

+
+
Author:
+
Lee Rhodes, Alexander Saydakov, Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    +
    UniqueCountMap(int keySizeBytes)
    +
    +
    Constructs a UniqueCountMap with an initial capacity of one million entries.
    +
    +
    UniqueCountMap(int initialNumEntries, + int keySizeBytes)
    +
    +
    Constructs a UniqueCountMap with a given initial number of entries.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    int
    + +
    +
    Returns the number of active, unique keys across all internal maps
    +
    +
    double
    + +
    +
    Returns the average bytes storage per key that is dedicated to sketching the unique counts.
    +
    +
    double
    +
    getEstimate(byte[] key)
    +
    +
    Retrieves the current estimate of unique count for a given key.
    +
    +
    long
    + +
    +
    Returns total bytes used for key storage
    +
    +
    double
    +
    getLowerBound(byte[] key)
    +
    +
    Returns the lower bound cardinality with respect to getEstimate(byte[]) associated +with the given key.
    +
    +
    long
    + +
    +
    Returns total bytes used by all internal maps
    +
    +
    double
    +
    getUpperBound(byte[] key)
    +
    +
    Returns the upper bound cardinality with respect to getEstimate(byte[]) associated +with the given key.
    +
    + + +
    +
    Returns a string with a human-readable summary of the UniqueCountMap and all the internal maps
    +
    +
    double
    +
    update(byte[] key, + byte[] identifier)
    +
    +
    Updates the map with a given key and identifier and returns the estimate of the number of +unique identifiers encountered so far for the given key.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      UniqueCountMap

      +
      +
      public UniqueCountMap(int keySizeBytes)
      +
      Constructs a UniqueCountMap with an initial capacity of one million entries.
      +
      +
      Parameters:
      +
      keySizeBytes - must be at least 4 bytes to have sufficient entropy.
      +
      +
      +
      +
    • +
    • +
      +

      UniqueCountMap

      +
      +
      public UniqueCountMap(int initialNumEntries, + int keySizeBytes)
      +
      Constructs a UniqueCountMap with a given initial number of entries.
      +
      +
      Parameters:
      +
      initialNumEntries - The initial number of entries provides a tradeoff between +wasted space, if too high, and wasted time resizing the table, if too low.
      +
      keySizeBytes - must be at least 4 bytes to have sufficient entropy
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      update

      +
      +
      public double update(byte[] key, + byte[] identifier)
      +
      Updates the map with a given key and identifier and returns the estimate of the number of +unique identifiers encountered so far for the given key.
      +
      +
      Parameters:
      +
      key - the given key
      +
      identifier - the given identifier for unique counting associated with the key
      +
      Returns:
      +
      the estimate of the number of unique identifiers encountered so far for the given key.
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public double getEstimate(byte[] key)
      +
      Retrieves the current estimate of unique count for a given key.
      +
      +
      Parameters:
      +
      key - given key
      +
      Returns:
      +
      estimate of unique count so far
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public double getUpperBound(byte[] key)
      +
      Returns the upper bound cardinality with respect to getEstimate(byte[]) associated +with the given key.
      +
      +
      Parameters:
      +
      key - the given key
      +
      Returns:
      +
      the upper bound cardinality with respect to getEstimate(byte[]) associated +with the given key.
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public double getLowerBound(byte[] key)
      +
      Returns the lower bound cardinality with respect to getEstimate(byte[]) associated +with the given key.
      +
      +
      Parameters:
      +
      key - the given key
      +
      Returns:
      +
      the lower bound cardinality with respect to getEstimate(byte[]) associated +with the given key.
      +
      +
      +
      +
    • +
    • +
      +

      getActiveEntries

      +
      +
      public int getActiveEntries()
      +
      Returns the number of active, unique keys across all internal maps
      +
      +
      Returns:
      +
      the number of active, unique keys across all internal maps
      +
      +
      +
      +
    • +
    • +
      +

      getTotalUsageBytes

      +
      +
      public long getTotalUsageBytes()
      +
      Returns total bytes used by all internal maps
      +
      +
      Returns:
      +
      total bytes used by all internal maps
      +
      +
      +
      +
    • +
    • +
      +

      getKeyUsageBytes

      +
      +
      public long getKeyUsageBytes()
      +
      Returns total bytes used for key storage
      +
      +
      Returns:
      +
      total bytes used for key storage
      +
      +
      +
      +
    • +
    • +
      +

      getAverageSketchBytesPerKey

      +
      +
      public double getAverageSketchBytesPerKey()
      +
      Returns the average bytes storage per key that is dedicated to sketching the unique counts.
      +
      +
      Returns:
      +
      the average bytes storage per key that is dedicated to sketching the unique counts.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns a string with a human-readable summary of the UniqueCountMap and all the internal maps
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      human-readable summary
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hllmap/class-use/UniqueCountMap.html b/target/site/apidocs/org/apache/datasketches/hllmap/class-use/UniqueCountMap.html new file mode 100644 index 000000000..aa2cba59c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hllmap/class-use/UniqueCountMap.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.hllmap.UniqueCountMap (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.hllmap.UniqueCountMap

+
+No usage of org.apache.datasketches.hllmap.UniqueCountMap +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hllmap/package-summary.html b/target/site/apidocs/org/apache/datasketches/hllmap/package-summary.html new file mode 100644 index 000000000..0a995707b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hllmap/package-summary.html @@ -0,0 +1,132 @@ + + + + +org.apache.datasketches.hllmap (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.hllmap

+
+
+
+
package org.apache.datasketches.hllmap
+
+
The hllmap package contains a space efficient HLL mapping sketch of keys to approximate unique +count of identifiers. For example, counting the number of unique users (identifiers) per IP +address. + +

In cases where the number of keys is very large, having an individual HLL sketch per key may +not be practical. If the distribution of values per key is highly skewed where the vast +majority of keys have only a few values then this mapping sketch will make sense as it will be +far more space efficient than dedicating individual HLL sketches per key. + +

From our own testing, sketching 100 million IPv4 addresses with such a +highly skewed distribution of identifiers per IP uses only 1.4GB of memory. This translates to +an average of about 10 bytes per IP allocated to the equivalent of a full k=1024 HLL sketch +and provides an RSE of less than 2.5%. Your results will vary depending on the actual +distribution of identifiers per key.

+
+
See Also:
+
+ +
+
+
+
+
+
    +
  • + +
  • +
  • +
    +
    Classes
    +
    +
    Class
    +
    Description
    + +
    +
    This is a real-time, key-value HLL mapping sketch that tracks approximate unique counts of +identifiers (the values) associated with each key.
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hllmap/package-tree.html b/target/site/apidocs/org/apache/datasketches/hllmap/package-tree.html new file mode 100644 index 000000000..2aa66bbad --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hllmap/package-tree.html @@ -0,0 +1,79 @@ + + + + +org.apache.datasketches.hllmap Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.hllmap

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/hllmap/package-use.html b/target/site/apidocs/org/apache/datasketches/hllmap/package-use.html new file mode 100644 index 000000000..fa86a3391 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/hllmap/package-use.html @@ -0,0 +1,66 @@ + + + + +Uses of Package org.apache.datasketches.hllmap (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.hllmap

+
+No usage of org.apache.datasketches.hllmap +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/KllDoublesSketch.html b/target/site/apidocs/org/apache/datasketches/kll/KllDoublesSketch.html new file mode 100644 index 000000000..51f747b80 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/KllDoublesSketch.html @@ -0,0 +1,943 @@ + + + + +KllDoublesSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class KllDoublesSketch

+
+
java.lang.Object +
org.apache.datasketches.kll.KllSketch +
org.apache.datasketches.kll.KllDoublesSketch
+
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus, QuantilesAPI, QuantilesDoublesAPI
+
+
+
+
public abstract class KllDoublesSketch +extends KllSketch +implements QuantilesDoublesAPI
+
This variation of the KllSketch implements primitive doubles.
+
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      newHeapInstance

      +
      +
      public static KllDoublesSketch newHeapInstance()
      +
      Create a new heap instance of this sketch with the default k = 200. +The default k = 200 results in a normalized rank error of about +1.65%. Larger K will have smaller error but the sketch will be larger (and slower).
      +
      +
      Returns:
      +
      new KllDoublesSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      newHeapInstance

      +
      +
      public static KllDoublesSketch newHeapInstance(int k)
      +
      Create a new heap instance of this sketch with a given parameter k. +k can be between 8, inclusive, and 65535, inclusive. +The default k = 200 results in a normalized rank error of about +1.65%. Larger K will have smaller error but the sketch will be larger (and slower).
      +
      +
      Parameters:
      +
      k - parameter that controls size of the sketch and accuracy of estimates.
      +
      Returns:
      +
      new KllDoublesSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      newDirectInstance

      +
      +
      public static KllDoublesSketch newDirectInstance(MemorySegment dstSeg)
      +
      Create a new direct updatable instance of this sketch with the default k. +The default k = 200 results in a normalized rank error of about +1.65%. Larger k will have smaller error but the sketch will be larger (and slower).
      +
      +
      Parameters:
      +
      dstSeg - the given destination MemorySegment object for use by the sketch
      +
      Returns:
      +
      a new direct instance of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      newDirectInstance

      +
      +
      public static KllDoublesSketch newDirectInstance(int k, + MemorySegment dstSeg, + MemorySegmentRequest mSegReq)
      +
      Create a new direct updatable instance of this sketch with a given k.
      +
      +
      Parameters:
      +
      k - parameter that controls size of the sketch and accuracy of estimates.
      +
      dstSeg - the given destination MemorySegment object for use by the sketch
      +
      mSegReq - the callback for the sketch to request a larger MemorySegment. It may be null.
      +
      Returns:
      +
      a new direct instance of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static KllDoublesSketch heapify(MemorySegment srcSeg)
      +
      Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch. +The resulting sketch will not retain any link to the source MemorySegment.
      +
      +
      Parameters:
      +
      srcSeg - a compact MemorySegment image of a sketch serialized by this sketch.
      +
      Returns:
      +
      a heap-based sketch based on the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static KllDoublesSketch wrap(MemorySegment srcSeg)
      +
      Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch. + +

      The given MemorySegment must be writable and it must contain a KllDoublesSketch in updatable form. +The sketch will be updated and managed totally within the MemorySegment. If the given source +MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

      + +

      NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch +will request more capacity using the MemorySegmentRequest interface. The default of this interface will +return a new MemorySegment on the heap.

      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment that contains sketch data.
      +
      Returns:
      +
      an instance of this sketch that wraps the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static KllDoublesSketch wrap(MemorySegment srcSeg, + MemorySegmentRequest mSegReq)
      +
      Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch and including an +optional, user defined MemorySegmentRequest. + +

      The given MemorySegment must be writable and it must contain a KllDoublesSketch in updatable form. +The sketch will be updated and managed totally within the MemorySegment. If the given source +MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

      + +

      NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch +will request more capacity using the MemorySegmentRequest interface. The default of this interface will +return a new MemorySegment on the heap. It is up to the user to optionally extend this interface if more flexible +handling of requests for more capacity is required.

      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment that contains sketch data.
      +
      mSegReq - the MemorySegmentRequest used if the given MemorySegment needs to expand. +Otherwise, it can be null and the default MemorySegmentRequest will be used.
      +
      Returns:
      +
      an instance of this sketch that wraps the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      getCDF

      +
      +
      public double[] getCDF(double[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Specified by:
      +
      getCDF in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      public double[] getPMF(double[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Specified by:
      +
      getPMF in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public double getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      public double[] getQuantiles(double[] ranks, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Gets an array of quantiles from the given array of normalized ranks.
      +
      +
      Specified by:
      +
      getQuantiles in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      searchCrit - if INCLUSIVE, the given ranks include all quantiles ≤ +the quantile directly corresponding to each rank.
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileLowerBound

      +
      +
      public double getQuantileLowerBound(double rank)
      +
      Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile confidence interval +as an additive or multiplicative percent of the true quantile.

      +The approximate probability that the true quantile is within the confidence interval +specified by the upper and lower quantile bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getQuantileLowerBound in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileUpperBound

      +
      +
      public double getQuantileUpperBound(double rank)
      +
      Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile interval +as an additive or multiplicative percent of the true quantile.

      +The approximate probability that the true quantile is within the confidence interval +specified by the upper and lower quantile bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getQuantileUpperBound in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      public double getRank(double quantile, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Specified by:
      +
      getRank in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRankLowerBound

      +
      +
      public double getRankLowerBound(double rank)
      +
      Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists. +The approximate probability that the true rank is within the confidence interval +specified by the upper and lower rank bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getRankLowerBound in interface QuantilesAPI
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRankUpperBound

      +
      +
      public double getRankUpperBound(double rank)
      +
      Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists. +The approximate probability that the true rank is within the confidence interval +specified by the upper and lower rank bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getRankUpperBound in interface QuantilesAPI
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      public double[] getRanks(double[] quantiles, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
      +
      +
      Specified by:
      +
      getRanks in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      searchCrit - if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile.
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Description copied from interface: QuantilesDoublesAPI
      +
      Gets the iterator for this sketch, which is not sorted.
      +
      +
      Specified by:
      +
      iterator in interface QuantilesDoublesAPI
      +
      Returns:
      +
      the iterator for this sketch
      +
      +
      +
      +
    • +
    • +
      +

      merge

      +
      +
      public final void merge(KllSketch other)
      +
      Description copied from class: KllSketch
      +
      Merges another sketch into this one. +Attempting to merge a sketch of the wrong type will throw an exception.
      +
      +
      Specified by:
      +
      merge in class KllSketch
      +
      Parameters:
      +
      other - sketch to merge into this one
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public final void reset()
      +
      Resets this sketch to the empty state. +If the sketch is read only this does nothing. + +

      The parameter k will not change.

      + +

      The parameter k will not change.

      +
      +
      Specified by:
      +
      reset in interface QuantilesAPI
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Returns a byte array representation of this sketch.
      +
      +
      Specified by:
      +
      toByteArray in interface QuantilesDoublesAPI
      +
      Returns:
      +
      a byte array representation of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean withLevels, + boolean withLevelsAndItems)
      +
      Description copied from class: KllSketch
      +
      Returns human readable summary information about this sketch. +Used for debugging.
      +
      +
      Specified by:
      +
      toString in class KllSketch
      +
      Parameters:
      +
      withLevels - if true includes sketch levels array summary information
      +
      withLevelsAndItems - if true include detail of levels array and items array together
      +
      Returns:
      +
      human readable summary information about this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(double item)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Updates this sketch with the given item.
      +
      +
      Specified by:
      +
      update in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      item - from a stream of items. NaNs are ignored.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(double item, + long weight)
      +
      Weighted update. Updates this sketch with the given item the number of times specified by the given integer weight.
      +
      +
      Parameters:
      +
      item - the item to be repeated. NaNs are ignored.
      +
      weight - the number of times the update of item is to be repeated. It must be ≥ one.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(double[] items, + int offset, + int length)
      +
      Vector update. Updates this sketch with the given array (vector) of items, starting at the items +offset for a length number of items. This is not supported for direct sketches. +

      Note: a single occurrence of a NaN in the array will force this method to use the conventional update path +rather than the fast update path.

      +
      +
      Parameters:
      +
      items - the vector of items
      +
      offset - the starting index of the items[] array
      +
      length - the number of items
      +
      +
      +
      +
    • +
    • +
      +

      getSortedView

      +
      +
      public DoublesSketchSortedView getSortedView()
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Gets the sorted view of this sketch
      +
      +
      Specified by:
      +
      getSortedView in interface QuantilesDoublesAPI
      +
      Returns:
      +
      the sorted view of this sketch
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/KllDoublesSketchIterator.html b/target/site/apidocs/org/apache/datasketches/kll/KllDoublesSketchIterator.html new file mode 100644 index 000000000..f5014e53a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/KllDoublesSketchIterator.html @@ -0,0 +1,163 @@ + + + + +KllDoublesSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class KllDoublesSketchIterator

+
+
java.lang.Object +
org.apache.datasketches.kll.KllSketchIterator +
org.apache.datasketches.kll.KllDoublesSketchIterator
+
+
+
+
+
All Implemented Interfaces:
+
QuantilesDoublesSketchIteratorAPI, QuantilesSketchIteratorAPI
+
+
+
+
public final class KllDoublesSketchIterator +extends KllSketchIterator +implements QuantilesDoublesSketchIteratorAPI
+
Iterator over KllDoublesSketch. The order is not defined.
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      public double getQuantile()
      +
      Description copied from interface: QuantilesDoublesSketchIteratorAPI
      +
      Gets the double quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesDoublesSketchIteratorAPI
      +
      Returns:
      +
      the double quantile at the current index.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/KllFloatsSketch.html b/target/site/apidocs/org/apache/datasketches/kll/KllFloatsSketch.html new file mode 100644 index 000000000..310e1bda3 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/KllFloatsSketch.html @@ -0,0 +1,943 @@ + + + + +KllFloatsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class KllFloatsSketch

+
+
java.lang.Object +
org.apache.datasketches.kll.KllSketch +
org.apache.datasketches.kll.KllFloatsSketch
+
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus, QuantilesAPI, QuantilesFloatsAPI
+
+
+
+
public abstract class KllFloatsSketch +extends KllSketch +implements QuantilesFloatsAPI
+
This variation of the KllSketch implements primitive floats.
+
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      newHeapInstance

      +
      +
      public static KllFloatsSketch newHeapInstance()
      +
      Create a new heap instance of this sketch with the default k = 200. +The default k = 200 results in a normalized rank error of about +1.65%. Larger K will have smaller error but the sketch will be larger (and slower).
      +
      +
      Returns:
      +
      new KllFloatsSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      newHeapInstance

      +
      +
      public static KllFloatsSketch newHeapInstance(int k)
      +
      Create a new heap instance of this sketch with a given parameter k. +k can be between 8, inclusive, and 65535, inclusive. +The default k = 200 results in a normalized rank error of about +1.65%. Larger K will have smaller error but the sketch will be larger (and slower).
      +
      +
      Parameters:
      +
      k - parameter that controls size of the sketch and accuracy of estimates.
      +
      Returns:
      +
      new KllFloatsSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      newDirectInstance

      +
      +
      public static KllFloatsSketch newDirectInstance(MemorySegment dstSeg)
      +
      Create a new direct updatable instance of this sketch with the default k. +The default k = 200 results in a normalized rank error of about +1.65%. Larger k will have smaller error but the sketch will be larger (and slower).
      +
      +
      Parameters:
      +
      dstSeg - the given destination MemorySegment object for use by the sketch
      +
      Returns:
      +
      a new direct instance of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      newDirectInstance

      +
      +
      public static KllFloatsSketch newDirectInstance(int k, + MemorySegment dstSeg, + MemorySegmentRequest mSegReq)
      +
      Create a new direct updatable instance of this sketch with a given k.
      +
      +
      Parameters:
      +
      k - parameter that controls size of the sketch and accuracy of estimates.
      +
      dstSeg - the given destination MemorySegment object for use by the sketch
      +
      mSegReq - the callback for the sketch to request a larger MemorySegment. It may be null.
      +
      Returns:
      +
      a new direct instance of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static KllFloatsSketch heapify(MemorySegment srcSeg)
      +
      Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch. +The resulting sketch will not retain any link to the source MemorySegment.
      +
      +
      Parameters:
      +
      srcSeg - a compact MemorySegment image of a sketch serialized by this sketch.
      +
      Returns:
      +
      a heap-based sketch based on the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static KllFloatsSketch wrap(MemorySegment srcSeg)
      +
      Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch. + +

      The given MemorySegment must be writable and it must contain a KllFloatsSketch in updatable form. +The sketch will be updated and managed totally within the MemorySegment. If the given source +MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

      + +

      NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch +will request more capacity using the MemorySegmentRequest interface. The default of this interface will +return a new MemorySegment on the heap.

      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment that contains sketch data.
      +
      Returns:
      +
      an instance of this sketch that wraps the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static KllFloatsSketch wrap(MemorySegment srcSeg, + MemorySegmentRequest mSegReq)
      +
      Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch and including an +optional, user defined MemorySegmentRequest. + +

      The given MemorySegment must be writable and it must contain a KllFloatsSketch in updatable form. +The sketch will be updated and managed totally within the MemorySegment. If the given source +MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

      + +

      NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch +will request more capacity using the MemorySegmentRequest interface. The default of this interface will +return a new MemorySegment on the heap. It is up to the user to optionally extend this interface if more flexible +handling of requests for more capacity is required.

      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment that contains sketch data.
      +
      mSegReq - the MemorySegmentRequest used if the given MemorySegment needs to expand. +Otherwise, it can be null and the default MemorySegmentRequest will be used.
      +
      Returns:
      +
      an instance of this sketch that wraps the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      getCDF

      +
      +
      public double[] getCDF(float[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Specified by:
      +
      getCDF in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      public double[] getPMF(float[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Specified by:
      +
      getPMF in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public float getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      public float[] getQuantiles(double[] ranks, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Gets an array of quantiles from the given array of normalized ranks.
      +
      +
      Specified by:
      +
      getQuantiles in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      searchCrit - if INCLUSIVE, the given ranks include all quantiles ≤ +the quantile directly corresponding to each rank.
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileLowerBound

      +
      +
      public float getQuantileLowerBound(double rank)
      +
      Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile confidence interval +as an additive or multiplicative percent of the true quantile.

      +The approximate probability that the true quantile is within the confidence interval +specified by the upper and lower quantile bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getQuantileLowerBound in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileUpperBound

      +
      +
      public float getQuantileUpperBound(double rank)
      +
      Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile interval +as an additive or multiplicative percent of the true quantile.

      +The approximate probability that the true quantile is within the confidence interval +specified by the upper and lower quantile bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getQuantileUpperBound in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      public double getRank(float quantile, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Specified by:
      +
      getRank in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRankLowerBound

      +
      +
      public double getRankLowerBound(double rank)
      +
      Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists. +The approximate probability that the true rank is within the confidence interval +specified by the upper and lower rank bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getRankLowerBound in interface QuantilesAPI
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRankUpperBound

      +
      +
      public double getRankUpperBound(double rank)
      +
      Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists. +The approximate probability that the true rank is within the confidence interval +specified by the upper and lower rank bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getRankUpperBound in interface QuantilesAPI
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      public double[] getRanks(float[] quantiles, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
      +
      +
      Specified by:
      +
      getRanks in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      searchCrit - if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile.
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public QuantilesFloatsSketchIterator iterator()
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Gets the iterator for this sketch, which is not sorted.
      +
      +
      Specified by:
      +
      iterator in interface QuantilesFloatsAPI
      +
      Returns:
      +
      the iterator for this sketch
      +
      +
      +
      +
    • +
    • +
      +

      merge

      +
      +
      public final void merge(KllSketch other)
      +
      Description copied from class: KllSketch
      +
      Merges another sketch into this one. +Attempting to merge a sketch of the wrong type will throw an exception.
      +
      +
      Specified by:
      +
      merge in class KllSketch
      +
      Parameters:
      +
      other - sketch to merge into this one
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public final void reset()
      +
      Resets this sketch to the empty state. +If the sketch is read only this does nothing. + +

      The parameter k will not change.

      + +

      The parameter k will not change.

      +
      +
      Specified by:
      +
      reset in interface QuantilesAPI
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Returns a byte array representation of this sketch.
      +
      +
      Specified by:
      +
      toByteArray in interface QuantilesFloatsAPI
      +
      Returns:
      +
      a byte array representation of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean withLevels, + boolean withLevelsAndItems)
      +
      Description copied from class: KllSketch
      +
      Returns human readable summary information about this sketch. +Used for debugging.
      +
      +
      Specified by:
      +
      toString in class KllSketch
      +
      Parameters:
      +
      withLevels - if true includes sketch levels array summary information
      +
      withLevelsAndItems - if true include detail of levels array and items array together
      +
      Returns:
      +
      human readable summary information about this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(float item)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Updates this sketch with the given item.
      +
      +
      Specified by:
      +
      update in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      item - from a stream of quantiles. NaNs are ignored.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(float item, + long weight)
      +
      Weighted update. Updates this sketch with the given item the number of times specified by the given integer weight.
      +
      +
      Parameters:
      +
      item - the item to be repeated. NaNs are ignored.
      +
      weight - the number of times the update of item is to be repeated. It must be ≥ one.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(float[] items, + int offset, + int length)
      +
      Vector update. Updates this sketch with the given array (vector) of items, starting at the items +offset for a length number of items. This is not supported for direct sketches. +

      Note: a single occurrence of a NaN in the array will force this method to use the conventional update path +rather than the fast update path.

      +
      +
      Parameters:
      +
      items - the vector of items
      +
      offset - the starting index of the items[] array
      +
      length - the number of items
      +
      +
      +
      +
    • +
    • +
      +

      getSortedView

      +
      +
      public FloatsSketchSortedView getSortedView()
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Gets the sorted view of this sketch
      +
      +
      Specified by:
      +
      getSortedView in interface QuantilesFloatsAPI
      +
      Returns:
      +
      the sorted view of this sketch
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/KllFloatsSketchIterator.html b/target/site/apidocs/org/apache/datasketches/kll/KllFloatsSketchIterator.html new file mode 100644 index 000000000..5ad06faad --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/KllFloatsSketchIterator.html @@ -0,0 +1,163 @@ + + + + +KllFloatsSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class KllFloatsSketchIterator

+
+
java.lang.Object +
org.apache.datasketches.kll.KllSketchIterator +
org.apache.datasketches.kll.KllFloatsSketchIterator
+
+
+
+
+
All Implemented Interfaces:
+
QuantilesFloatsSketchIterator, QuantilesSketchIteratorAPI
+
+
+
+
public final class KllFloatsSketchIterator +extends KllSketchIterator +implements QuantilesFloatsSketchIterator
+
Iterator over KllFloatsSketch. The order is not defined.
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      public float getQuantile()
      +
      Description copied from interface: QuantilesFloatsSketchIterator
      +
      Gets the float quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesFloatsSketchIterator
      +
      Returns:
      +
      the float quantile at the current index.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/KllItemsSketch.html b/target/site/apidocs/org/apache/datasketches/kll/KllItemsSketch.html new file mode 100644 index 000000000..d9d9910ab --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/KllItemsSketch.html @@ -0,0 +1,995 @@ + + + + +KllItemsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class KllItemsSketch<T>

+
+
java.lang.Object +
org.apache.datasketches.kll.KllSketch +
org.apache.datasketches.kll.KllItemsSketch<T>
+
+
+
+
+
Type Parameters:
+
T - The sketch data type.
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus, PartitioningFeature<T>, QuantilesAPI, QuantilesGenericAPI<T>, SketchPartitionLimits
+
+
+
+
public abstract class KllItemsSketch<T> +extends KllSketch +implements QuantilesGenericAPI<T>
+
This variation of the KllSketch implements generic data types. The user must provide +a suitable implementation of the java.lang.Comparator as well as an implementation of +the serializer / deserializer, org.apache.datasketches.common.ArrayOfItemsSerDe.
+
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      newHeapInstance

      +
      +
      public static <T> KllItemsSketch<T> newHeapInstance(Comparator<? super T> comparator, + ArrayOfItemsSerDe<T> serDe)
      +
      Create a new heap instance of this sketch with the default k = 200. +The default k = 200 results in a normalized rank error of about +1.65%. Larger K will have smaller error but the sketch will be larger (and slower).
      +
      +
      Type Parameters:
      +
      T - The sketch data type.
      +
      Parameters:
      +
      comparator - to compare items
      +
      serDe - Serializer / deserializer for an array of items, T[].
      +
      Returns:
      +
      new KllItemsSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      newHeapInstance

      +
      +
      public static <T> KllItemsSketch<T> newHeapInstance(int k, + Comparator<? super T> comparator, + ArrayOfItemsSerDe<T> serDe)
      +
      Create a new heap instance of this sketch with a given parameter k. +k can be between DEFAULT_M and 65535, inclusive. +The default k = 200 results in a normalized rank error of about +1.65%. Larger K will have smaller error but the sketch will be larger (and slower).
      +
      +
      Type Parameters:
      +
      T - The sketch data type
      +
      Parameters:
      +
      k - parameter that controls size of the sketch and accuracy of estimates.
      +
      comparator - to compare items
      +
      serDe - Serializer / deserializer for items of type T and T[].
      +
      Returns:
      +
      new KllItemsSketch on the heap.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static <T> KllItemsSketch<T> heapify(MemorySegment srcSeg, + Comparator<? super T> comparator, + ArrayOfItemsSerDe<T> serDe)
      +
      Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch. +The resulting sketch will not retain any link to the source MemorySegment.
      +
      +
      Type Parameters:
      +
      T - The sketch data type
      +
      Parameters:
      +
      srcSeg - a compact MemorySegment image of a sketch serialized by this sketch and of the same type of T.
      +
      comparator - to compare items
      +
      serDe - Serializer / deserializer for items of type T and T[].
      +
      Returns:
      +
      a heap-based sketch based on the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static <T> KllItemsSketch<T> wrap(MemorySegment srcSeg, + Comparator<? super T> comparator, + ArrayOfItemsSerDe<T> serDe)
      +
      Constructs a thin wrapper on the heap around a MemorySegment (or MemorySegment) already initialized with a +validated sketch image of a type T consistent with the given comparator and serDe. +A reference to the MemorySegment is kept in the sketch and must remain in scope consistent +with the temporal scope of this sketch. The amount of data kept on the heap is very small. +All of the item data originally collected by the given MemorySegment sketch object remains in the +MemorySegment object.
      +
      +
      Type Parameters:
      +
      T - The sketch data type
      +
      Parameters:
      +
      srcSeg - the MemorySegment object that this sketch will wrap. It will not be modified.
      +
      comparator - to compare items
      +
      serDe - Serializer / deserializer for items of type T and T[].
      +
      Returns:
      +
      a heap-base sketch that is a thin wrapper around the given srcSeg.
      +
      +
      +
      +
    • +
    • +
      +

      getCDF

      +
      +
      public double[] getCDF(T[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Specified by:
      +
      getCDF in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getClassOfT

      +
      +
      public Class<T> getClassOfT()
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Returns the sketch item class
      +
      +
      Specified by:
      +
      getClassOfT in interface QuantilesGenericAPI<T>
      +
      Returns:
      +
      the sketch item class
      +
      +
      +
      +
    • +
    • +
      +

      getComparator

      +
      +
      public Comparator<? super T> getComparator()
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Returns the Comparator of T
      +
      +
      Specified by:
      +
      getComparator in interface QuantilesGenericAPI<T>
      +
      Returns:
      +
      Comparator of the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getPartitionBoundariesFromNumParts

      +
      +
      public GenericPartitionBoundaries<T> getPartitionBoundariesFromNumParts(int numEquallySizedParts, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: PartitioningFeature
      +
      This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition. + +

      The sketch must not be empty.

      +
      +
      Specified by:
      +
      getPartitionBoundariesFromNumParts in interface PartitioningFeature<T>
      +
      Parameters:
      +
      numEquallySizedParts - an integer that specifies the number of equally sized partitions between +getMinItem() and +getMaxItem(). +This must be a positive integer less than +getMaxPartitions() +
        +
      • A 1 will return: minItem, maxItem.
      • +
      • A 2 will return: minItem, median quantile, maxItem.
      • +
      • Etc.
      • +
      +
      searchCrit - If INCLUSIVE, all the returned quantiles are the upper boundaries of the equally sized partitions +with the exception of the lowest returned quantile, which is the lowest boundary of the lowest ranked partition. +If EXCLUSIVE, all the returned quantiles are the lower boundaries of the equally sized partitions +with the exception of the highest returned quantile, which is the upper boundary of the highest ranked partition.
      +
      Returns:
      +
      an instance of GenericPartitionBoundaries.
      +
      +
      +
      +
    • +
    • +
      +

      getPartitionBoundariesFromPartSize

      +
      +
      public GenericPartitionBoundaries<T> getPartitionBoundariesFromPartSize(long nominalPartSizeItems, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: PartitioningFeature
      +
      This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition. + +

      The sketch must not be empty.

      +
      +
      Specified by:
      +
      getPartitionBoundariesFromPartSize in interface PartitioningFeature<T>
      +
      Parameters:
      +
      nominalPartSizeItems - an integer that specifies the nominal size, in items, of each target partition. +This must be a positive integer greater than +getMinPartitionSizeItems().
      +
      searchCrit - If INCLUSIVE, all the returned quantiles are the upper boundaries of the equally sized partitions +with the exception of the lowest returned quantile, which is the lowest boundary of the lowest ranked partition. +If EXCLUSIVE, all the returned quantiles are the lower boundaries of the equally sized partitions +with the exception of the highest returned quantile, which is the upper boundary of the highest ranked partition.
      +
      Returns:
      +
      an instance of GenericPartitionBoundaries.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      public double[] getPMF(T[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Specified by:
      +
      getPMF in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public T getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      public T[] getQuantiles(double[] ranks, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets an array of quantiles from the given array of normalized ranks.
      +
      +
      Specified by:
      +
      getQuantiles in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      searchCrit - if INCLUSIVE, the given ranks include all quantiles ≤ +the quantile directly corresponding to each rank.
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileLowerBound

      +
      +
      public T getQuantileLowerBound(double rank)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile confidence interval +as an additive or multiplicative percent of the true quantile.

      +
      +
      Specified by:
      +
      getQuantileLowerBound in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileUpperBound

      +
      +
      public T getQuantileUpperBound(double rank)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile interval +as an additive or multiplicative percent of the true quantile.

      +
      +
      Specified by:
      +
      getQuantileUpperBound in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      public double getRank(T quantile, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Specified by:
      +
      getRank in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRankLowerBound

      +
      +
      public double getRankLowerBound(double rank)
      +
      Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists. +The approximate probability that the true rank is within the confidence interval +specified by the upper and lower rank bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getRankLowerBound in interface QuantilesAPI
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRankUpperBound

      +
      +
      public double getRankUpperBound(double rank)
      +
      Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists. +The approximate probability that the true rank is within the confidence interval +specified by the upper and lower rank bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getRankUpperBound in interface QuantilesAPI
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      public double[] getRanks(T[] quantiles, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
      +
      +
      Specified by:
      +
      getRanks in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      searchCrit - if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile.
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getSortedView

      +
      +
      public final ItemsSketchSortedView<T> getSortedView()
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets the sorted view of this sketch
      +
      +
      Specified by:
      +
      getSortedView in interface QuantilesGenericAPI<T>
      +
      Returns:
      +
      the sorted view of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets the iterator for this sketch, which is not sorted.
      +
      +
      Specified by:
      +
      iterator in interface QuantilesGenericAPI<T>
      +
      Returns:
      +
      the iterator for this sketch
      +
      +
      +
      +
    • +
    • +
      +

      merge

      +
      +
      public final void merge(KllSketch other)
      +
      Description copied from class: KllSketch
      +
      Merges another sketch into this one. +Attempting to merge a sketch of the wrong type will throw an exception.
      +
      +
      Specified by:
      +
      merge in class KllSketch
      +
      Parameters:
      +
      other - sketch to merge into this one
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Description copied from interface: QuantilesAPI
      +
      Resets this sketch to the empty state. +If the sketch is read only this does nothing. + +

      The parameter k will not change.

      +
      +
      Specified by:
      +
      reset in interface QuantilesAPI
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Export the current sketch as a compact byte array.
      +
      +
      Returns:
      +
      the current sketch as a compact byte array.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean withLevels, + boolean withLevelsAndItems)
      +
      Description copied from class: KllSketch
      +
      Returns human readable summary information about this sketch. +Used for debugging.
      +
      +
      Specified by:
      +
      toString in class KllSketch
      +
      Parameters:
      +
      withLevels - if true includes sketch levels array summary information
      +
      withLevelsAndItems - if true include detail of levels array and items array together
      +
      Returns:
      +
      human readable summary information about this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(T item)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Updates this sketch with the given item.
      +
      +
      Specified by:
      +
      update in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      item - from a stream of items. Nulls are ignored.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(T item, + long weight)
      +
      Weighted update. Updates this sketch with the given item the number of times specified by the given integer weight.
      +
      +
      Parameters:
      +
      item - the item to be repeated. NaNs are ignored.
      +
      weight - the number of times the update of item is to be repeated. It must be ≥ one.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/KllItemsSketchIterator.html b/target/site/apidocs/org/apache/datasketches/kll/KllItemsSketchIterator.html new file mode 100644 index 000000000..b8b1a1d65 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/KllItemsSketchIterator.html @@ -0,0 +1,167 @@ + + + + +KllItemsSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class KllItemsSketchIterator<T>

+
+
java.lang.Object +
org.apache.datasketches.kll.KllSketchIterator +
org.apache.datasketches.kll.KllItemsSketchIterator<T>
+
+
+
+
+
Type Parameters:
+
T - the item class type
+
+
+
All Implemented Interfaces:
+
QuantilesGenericSketchIteratorAPI<T>, QuantilesSketchIteratorAPI
+
+
+
+
public final class KllItemsSketchIterator<T> +extends KllSketchIterator +implements QuantilesGenericSketchIteratorAPI<T>
+
Iterator over KllItemsSketch. The order is not defined.
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      public T getQuantile()
      +
      Description copied from interface: QuantilesGenericSketchIteratorAPI
      +
      Gets the generic quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesGenericSketchIteratorAPI<T>
      +
      Returns:
      +
      the generic quantile at the current index.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/KllLongsSketch.html b/target/site/apidocs/org/apache/datasketches/kll/KllLongsSketch.html new file mode 100644 index 000000000..f74c65ce7 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/KllLongsSketch.html @@ -0,0 +1,941 @@ + + + + +KllLongsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class KllLongsSketch

+
+
java.lang.Object +
org.apache.datasketches.kll.KllSketch +
org.apache.datasketches.kll.KllLongsSketch
+
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus, QuantilesAPI, QuantilesLongsAPI
+
+
+
+
public abstract class KllLongsSketch +extends KllSketch +implements QuantilesLongsAPI
+
This variation of the KllSketch implements primitive longs.
+
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      newHeapInstance

      +
      +
      public static KllLongsSketch newHeapInstance()
      +
      Create a new heap instance of this sketch with the default k = 200. +The default k = 200 results in a normalized rank error of about +1.65%. Larger K will have smaller error but the sketch will be larger (and slower).
      +
      +
      Returns:
      +
      new KllLongsSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      newHeapInstance

      +
      +
      public static KllLongsSketch newHeapInstance(int k)
      +
      Create a new heap instance of this sketch with a given parameter k. +k can be between 8, inclusive, and 65535, inclusive. +The default k = 200 results in a normalized rank error of about +1.65%. Larger K will have smaller error but the sketch will be larger (and slower).
      +
      +
      Parameters:
      +
      k - parameter that controls size of the sketch and accuracy of estimates.
      +
      Returns:
      +
      new KllLongsSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      newDirectInstance

      +
      +
      public static KllLongsSketch newDirectInstance(MemorySegment dstSeg)
      +
      Create a new direct updatable instance of this sketch with the default k. +The default k = 200 results in a normalized rank error of about +1.65%. Larger k will have smaller error but the sketch will be larger (and slower).
      +
      +
      Parameters:
      +
      dstSeg - the given destination MemorySegment object for use by the sketch
      +
      Returns:
      +
      a new direct instance of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      newDirectInstance

      +
      +
      public static KllLongsSketch newDirectInstance(int k, + MemorySegment dstSeg, + MemorySegmentRequest mSegReq)
      +
      Create a new direct updatable instance of this sketch with a given k.
      +
      +
      Parameters:
      +
      k - parameter that controls size of the sketch and accuracy of estimates.
      +
      dstSeg - the given destination MemorySegment object for use by the sketch
      +
      mSegReq - the callback for the sketch to request a larger MemorySegment. It may be null.
      +
      Returns:
      +
      a new direct instance of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static KllLongsSketch heapify(MemorySegment srcSeg)
      +
      Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch. +The resulting sketch will not retain any link to the source MemorySegment.
      +
      +
      Parameters:
      +
      srcSeg - a compact MemorySegment image of a sketch serialized by this sketch.
      +
      Returns:
      +
      a heap-based sketch based on the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static KllLongsSketch wrap(MemorySegment srcSeg)
      +
      Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch. + +

      The given MemorySegment must be writable and it must contain a KllLongsSketch in updatable form. +The sketch will be updated and managed totally within the MemorySegment. If the given source +MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

      + +

      NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch +will request more capacity using the MemorySegmentRequest interface. The default of this interface will +return a new MemorySegment on the heap.

      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment that contains sketch data.
      +
      Returns:
      +
      an instance of this sketch that wraps the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static KllLongsSketch wrap(MemorySegment srcSeg, + MemorySegmentRequest mSegReq)
      +
      Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch and including an +optional, user defined MemorySegmentRequest. + +

      The given MemorySegment must be writable and it must contain a KllLongsSketch in updatable form. +The sketch will be updated and managed totally within the MemorySegment. If the given source +MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

      + +

      NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch +will request more capacity using the MemorySegmentRequest interface. The default of this interface will +return a new MemorySegment on the heap. It is up to the user to optionally extend this interface if more flexible +handling of requests for more capacity is required.

      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment that contains sketch data.
      +
      mSegReq - the MemorySegmentRequest used if the given MemorySegment needs to expand. +Otherwise, it can be null and the default MemorySegmentRequest will be used.
      +
      Returns:
      +
      an instance of this sketch that wraps the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      getCDF

      +
      +
      public double[] getCDF(long[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesLongsAPI
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Specified by:
      +
      getCDF in interface QuantilesLongsAPI
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      public double[] getPMF(long[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesLongsAPI
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Specified by:
      +
      getPMF in interface QuantilesLongsAPI
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public long getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesLongsAPI
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesLongsAPI
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      public long[] getQuantiles(double[] ranks, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesLongsAPI
      +
      Gets an array of quantiles from the given array of normalized ranks.
      +
      +
      Specified by:
      +
      getQuantiles in interface QuantilesLongsAPI
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      searchCrit - if INCLUSIVE, the given ranks include all quantiles ≤ +the quantile directly corresponding to each rank.
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileLowerBound

      +
      +
      public long getQuantileLowerBound(double rank)
      +
      Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile confidence interval +as an additive or multiplicative percent of the true quantile.

      +The approximate probability that the true quantile is within the confidence interval +specified by the upper and lower quantile bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getQuantileLowerBound in interface QuantilesLongsAPI
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileUpperBound

      +
      +
      public long getQuantileUpperBound(double rank)
      +
      Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile interval +as an additive or multiplicative percent of the true quantile.

      +The approximate probability that the true quantile is within the confidence interval +specified by the upper and lower quantile bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getQuantileUpperBound in interface QuantilesLongsAPI
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      public double getRank(long quantile, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesLongsAPI
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Specified by:
      +
      getRank in interface QuantilesLongsAPI
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRankLowerBound

      +
      +
      public double getRankLowerBound(double rank)
      +
      Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists. +The approximate probability that the true rank is within the confidence interval +specified by the upper and lower rank bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getRankLowerBound in interface QuantilesAPI
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRankUpperBound

      +
      +
      public double getRankUpperBound(double rank)
      +
      Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists. +The approximate probability that the true rank is within the confidence interval +specified by the upper and lower rank bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getRankUpperBound in interface QuantilesAPI
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      public double[] getRanks(long[] quantiles, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesLongsAPI
      +
      Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
      +
      +
      Specified by:
      +
      getRanks in interface QuantilesLongsAPI
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      searchCrit - if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile.
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public QuantilesLongsSketchIterator iterator()
      +
      Description copied from interface: QuantilesLongsAPI
      +
      Gets the iterator for this sketch, which is not sorted.
      +
      +
      Specified by:
      +
      iterator in interface QuantilesLongsAPI
      +
      Returns:
      +
      the iterator for this sketch
      +
      +
      +
      +
    • +
    • +
      +

      merge

      +
      +
      public final void merge(KllSketch other)
      +
      Description copied from class: KllSketch
      +
      Merges another sketch into this one. +Attempting to merge a sketch of the wrong type will throw an exception.
      +
      +
      Specified by:
      +
      merge in class KllSketch
      +
      Parameters:
      +
      other - sketch to merge into this one
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public final void reset()
      +
      Resets this sketch to the empty state. +If the sketch is read only this does nothing. + +

      The parameter k will not change.

      + +

      The parameter k will not change.

      +
      +
      Specified by:
      +
      reset in interface QuantilesAPI
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Description copied from interface: QuantilesLongsAPI
      +
      Returns a byte array representation of this sketch.
      +
      +
      Specified by:
      +
      toByteArray in interface QuantilesLongsAPI
      +
      Returns:
      +
      a byte array representation of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean withLevels, + boolean withLevelsAndItems)
      +
      Description copied from class: KllSketch
      +
      Returns human readable summary information about this sketch. +Used for debugging.
      +
      +
      Specified by:
      +
      toString in class KllSketch
      +
      Parameters:
      +
      withLevels - if true includes sketch levels array summary information
      +
      withLevelsAndItems - if true include detail of levels array and items array together
      +
      Returns:
      +
      human readable summary information about this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long item)
      +
      Description copied from interface: QuantilesLongsAPI
      +
      Updates this sketch with the given item.
      +
      +
      Specified by:
      +
      update in interface QuantilesLongsAPI
      +
      Parameters:
      +
      item - from a stream of items. NaNs are ignored.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long item, + long weight)
      +
      Weighted update. Updates this sketch with the given item the number of times specified by the given integer weight.
      +
      +
      Parameters:
      +
      item - the item to be repeated.
      +
      weight - the number of times the update of item is to be repeated. It must be ≥ one.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long[] items, + int offset, + int length)
      +
      Vector update. Updates this sketch with the given array (vector) of items, starting at the items +offset for a length number of items. This is not supported for direct sketches.
      +
      +
      Parameters:
      +
      items - the vector of items
      +
      offset - the starting index of the items[] array
      +
      length - the number of items
      +
      +
      +
      +
    • +
    • +
      +

      getSortedView

      +
      +
      public LongsSketchSortedView getSortedView()
      +
      Description copied from interface: QuantilesLongsAPI
      +
      Gets the sorted view of this sketch
      +
      +
      Specified by:
      +
      getSortedView in interface QuantilesLongsAPI
      +
      Returns:
      +
      the sorted view of this sketch
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/KllLongsSketchIterator.html b/target/site/apidocs/org/apache/datasketches/kll/KllLongsSketchIterator.html new file mode 100644 index 000000000..0c6c1a21c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/KllLongsSketchIterator.html @@ -0,0 +1,163 @@ + + + + +KllLongsSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class KllLongsSketchIterator

+
+
java.lang.Object +
org.apache.datasketches.kll.KllSketchIterator +
org.apache.datasketches.kll.KllLongsSketchIterator
+
+
+
+
+
All Implemented Interfaces:
+
QuantilesLongsSketchIterator, QuantilesSketchIteratorAPI
+
+
+
+
public final class KllLongsSketchIterator +extends KllSketchIterator +implements QuantilesLongsSketchIterator
+
Iterator over KllLongsSketch. The order is not defined.
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      public long getQuantile()
      +
      Description copied from interface: QuantilesLongsSketchIterator
      +
      Gets the long quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesLongsSketchIterator
      +
      Returns:
      +
      the long quantile at the current index.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/KllSketch.SketchStructure.html b/target/site/apidocs/org/apache/datasketches/kll/KllSketch.SketchStructure.html new file mode 100644 index 000000000..a01f87598 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/KllSketch.SketchStructure.html @@ -0,0 +1,343 @@ + + + + +KllSketch.SketchStructure (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class KllSketch.SketchStructure

+
+
java.lang.Object +
java.lang.Enum<KllSketch.SketchStructure> +
org.apache.datasketches.kll.KllSketch.SketchStructure
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<KllSketch.SketchStructure>, Constable
+
+
+
Enclosing class:
+
KllSketch
+
+
+
+
public static enum KllSketch.SketchStructure +extends Enum<KllSketch.SketchStructure>
+
Used primarily to define the structure of the serialized sketch. Also used by the Heap Sketch.
+
+
Author:
+
Lee Rhodes, Kevin Lang, Alexander Saydakov
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Enum Constant Details

    + +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static KllSketch.SketchStructure[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static KllSketch.SketchStructure valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    • +
      +

      getPreInts

      +
      +
      public int getPreInts()
      +
      gets the Preamble Integers for this Structure.
      +
      +
      Returns:
      +
      the Preamble Integers for this Structure
      +
      +
      +
      +
    • +
    • +
      +

      getSerVer

      +
      +
      public int getSerVer()
      +
      gets the Serialization Version for this Structure.
      +
      +
      Returns:
      +
      the Serialization Version for this Structure.
      +
      +
      +
      +
    • +
    • +
      +

      getSketchStructure

      +
      +
      public static KllSketch.SketchStructure getSketchStructure(int preInts, + int serVer)
      +
      gets the SketchStructure given preInts and serVer.
      +
      +
      Parameters:
      +
      preInts - the given preamble size in integers
      +
      serVer - the given Serialization Version
      +
      Returns:
      +
      the SketchStructure given preInts and serVer.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/KllSketch.SketchType.html b/target/site/apidocs/org/apache/datasketches/kll/KllSketch.SketchType.html new file mode 100644 index 000000000..db06d29be --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/KllSketch.SketchType.html @@ -0,0 +1,319 @@ + + + + +KllSketch.SketchType (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class KllSketch.SketchType

+
+
java.lang.Object +
java.lang.Enum<KllSketch.SketchType> +
org.apache.datasketches.kll.KllSketch.SketchType
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<KllSketch.SketchType>, Constable
+
+
+
Enclosing class:
+
KllSketch
+
+
+
+
public static enum KllSketch.SketchType +extends Enum<KllSketch.SketchType>
+
Used to define the variable type of the current instance of this class.
+
+
Author:
+
Lee Rhodes, Kevin Lang, Alexander Saydakov
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Enum Constant Details

    +
      +
    • +
      +

      KLL_DOUBLES_SKETCH

      +
      +
      public static final KllSketch.SketchType KLL_DOUBLES_SKETCH
      +
      KllDoublesSketch
      +
      +
      +
    • +
    • +
      +

      KLL_FLOATS_SKETCH

      +
      +
      public static final KllSketch.SketchType KLL_FLOATS_SKETCH
      +
      KllFloatsSketch
      +
      +
      +
    • +
    • +
      +

      KLL_ITEMS_SKETCH

      +
      +
      public static final KllSketch.SketchType KLL_ITEMS_SKETCH
      +
      KllItemsSketch
      +
      +
      +
    • +
    • +
      +

      KLL_LONGS_SKETCH

      +
      +
      public static final KllSketch.SketchType KLL_LONGS_SKETCH
      +
      KllDoublesSketch
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static KllSketch.SketchType[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static KllSketch.SketchType valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    • +
      +

      getBytes

      +
      +
      public int getBytes()
      +
      Gets the item size in bytes. If the item is generic, this returns zero.
      +
      +
      Returns:
      +
      the item size in bytes
      +
      +
      +
      +
    • +
    • +
      +

      getName

      +
      +
      public String getName()
      +
      Get the name of the associated sketch
      +
      +
      Returns:
      +
      the name of the associated sketch
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/KllSketch.html b/target/site/apidocs/org/apache/datasketches/kll/KllSketch.html new file mode 100644 index 000000000..73624ce31 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/KllSketch.html @@ -0,0 +1,659 @@ + + + + +KllSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class KllSketch

+
+
java.lang.Object +
org.apache.datasketches.kll.KllSketch
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus, QuantilesAPI
+
+
+
Direct Known Subclasses:
+
KllDoublesSketch, KllFloatsSketch, KllItemsSketch, KllLongsSketch
+
+
+
+
public abstract class KllSketch +extends Object +implements QuantilesAPI, MemorySegmentStatus
+
This class is the root of the KLL sketch class hierarchy. It includes the public API that is independent +of either sketch type (e.g., float, double, long or generic item) and independent of whether the sketch is targeted +for use on the Java heap or off-heap. + +

KLL is an implementation of a very compact quantiles sketch with lazy compaction scheme +and nearly optimal accuracy per retained quantile.

+ +

Reference Optimal Quantile Approximation in Streams.

+ +

The default k of 200 yields a "single-sided" epsilon of about 1.33% and a +"double-sided" (PMF) epsilon of about 1.65%, with a confidence of 99%.

+
+
Author:
+
Lee Rhodes, Kevin Lang, Alexander Saydakov
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Nested Class Summary

    +
    Nested Classes
    +
    +
    Modifier and Type
    +
    Class
    +
    Description
    +
    static enum 
    + +
    +
    Used primarily to define the structure of the serialized sketch.
    +
    +
    static enum 
    + +
    +
    Used to define the variable type of the current instance of this class.
    +
    +
    +
    +
  • + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    static final int
    + +
    +
    The default K
    +
    +
    static final int
    + +
    +
    The maximum K
    +
    +
    + +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static int
    +
    getKFromEpsilon(double epsilon, + boolean pmf)
    +
    +
    Gets the approximate k to use given epsilon, the normalized rank error.
    +
    +
    static int
    +
    getMaxSerializedSizeBytes(int k, + long n, + KllSketch.SketchType sketchType, + boolean updatableFormat)
    +
    +
    Returns upper bound on the serialized size of a KllSketch given the following parameters.
    +
    +
    final double
    + +
    +
    Gets the approximate rank error of this sketch normalized as a fraction between zero and one.
    +
    +
    static double
    +
    getNormalizedRankError(int k, + boolean pmf)
    +
    +
    Gets the normalized rank error given k and pmf.
    +
    +
    final int
    + +
    +
    Gets the number of quantiles retained by the sketch.
    +
    +
    int
    + +
    +
    Returns the current number of bytes this Sketch would require if serialized in compact form.
    +
    +
    abstract boolean
    + +
    +
    Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch is in a Compact MemorySegment Format.
    +
    +
    final boolean
    + +
    +
    Returns true if this sketch is empty.
    +
    +
    final boolean
    + +
    +
    Returns true if this sketch is in estimation mode.
    +
    +
    final boolean
    + +
    +
    Returns true if the backing MemorySegment is in updatable format.
    +
    +
    abstract boolean
    + +
    +
    Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
    +
    +
    final boolean
    + +
    +
    Returns true if this sketch is read only.
    +
    +
    abstract boolean
    + +
    +
    Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap.
    +
    +
    abstract void
    + +
    +
    Merges another sketch into this one.
    +
    +
    final String
    + +
    +
    Returns a summary of the key parameters of the sketch.
    +
    +
    abstract String
    +
    toString(boolean withLevels, + boolean withLevelsAndItems)
    +
    +
    Returns human readable summary information about this sketch.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +

    Methods inherited from interface QuantilesAPI

    +getK, getN, getRankLowerBound, getRankUpperBound, reset
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      DEFAULT_K

      +
      +
      public static final int DEFAULT_K
      +
      The default K
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      MAX_K

      +
      +
      public static final int MAX_K
      +
      The maximum K
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getKFromEpsilon

      +
      +
      public static int getKFromEpsilon(double epsilon, + boolean pmf)
      +
      Gets the approximate k to use given epsilon, the normalized rank error.
      +
      +
      Parameters:
      +
      epsilon - the normalized rank error between zero and one.
      +
      pmf - if true, this function returns the k assuming the input epsilon +is the desired "double-sided" epsilon for the getPMF() function. Otherwise, this function +returns k assuming the input epsilon is the desired "single-sided" +epsilon for all the other queries.
      +
      Returns:
      +
      k given epsilon.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxSerializedSizeBytes

      +
      +
      public static int getMaxSerializedSizeBytes(int k, + long n, + KllSketch.SketchType sketchType, + boolean updatableFormat)
      +
      Returns upper bound on the serialized size of a KllSketch given the following parameters.
      +
      +
      Parameters:
      +
      k - parameter that controls size of the sketch and accuracy of estimates
      +
      n - stream length
      +
      sketchType - Only DOUBLES_SKETCH, LONGS_SKETCH and FLOATS_SKETCH are supported for this operation.
      +
      updatableFormat - true if updatable MemorySegment format, otherwise the standard compact format.
      +
      Returns:
      +
      upper bound on the serialized size of a KllSketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNormalizedRankError

      +
      +
      public static double getNormalizedRankError(int k, + boolean pmf)
      +
      Gets the normalized rank error given k and pmf. +Static method version of the getNormalizedRankError(boolean). +The epsilon returned is a best fit to 99 percent confidence empirically measured max error +in thousands of trials.
      +
      +
      Parameters:
      +
      k - the configuration parameter
      +
      pmf - if true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      Returns:
      +
      if pmf is true, the normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      +
      +
      +
    • +
    • +
      +

      getNormalizedRankError

      +
      +
      public final double getNormalizedRankError(boolean pmf)
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the approximate rank error of this sketch normalized as a fraction between zero and one. +The epsilon returned is a best fit to 99 percent confidence empirically measured max error +in thousands of trials.
      +
      +
      Specified by:
      +
      getNormalizedRankError in interface QuantilesAPI
      +
      Parameters:
      +
      pmf - if true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      Returns:
      +
      if pmf is true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      +
      +
      +
    • +
    • +
      +

      getNumRetained

      +
      +
      public final int getNumRetained()
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the number of quantiles retained by the sketch.
      +
      +
      Specified by:
      +
      getNumRetained in interface QuantilesAPI
      +
      Returns:
      +
      the number of quantiles retained by the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getSerializedSizeBytes

      +
      +
      public int getSerializedSizeBytes()
      +
      Returns the current number of bytes this Sketch would require if serialized in compact form.
      +
      +
      Returns:
      +
      the number of bytes this sketch would require if serialized.
      +
      +
      +
      +
    • +
    • +
      +

      hasMemorySegment

      +
      +
      public abstract boolean hasMemorySegment()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
      +
      +
      Specified by:
      +
      hasMemorySegment in interface MemorySegmentStatus
      +
      Returns:
      +
      true if this object's internal data is backed by a MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isCompactMemorySegmentFormat

      +
      +
      public boolean isCompactMemorySegmentFormat()
      +
      Returns true if this sketch is in a Compact MemorySegment Format.
      +
      +
      Returns:
      +
      true if this sketch is in a Compact MemorySegment Format.
      +
      +
      +
      +
    • +
    • +
      +

      isOffHeap

      +
      +
      public abstract boolean isOffHeap()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      Specified by:
      +
      isOffHeap in interface MemorySegmentStatus
      +
      Returns:
      +
      true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public final boolean isEmpty()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is empty.
      +
      +
      Specified by:
      +
      isEmpty in interface QuantilesAPI
      +
      Returns:
      +
      true if this sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      isEstimationMode

      +
      +
      public final boolean isEstimationMode()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is in estimation mode.
      +
      +
      Specified by:
      +
      isEstimationMode in interface QuantilesAPI
      +
      Returns:
      +
      true if this sketch is in estimation mode.
      +
      +
      +
      +
    • +
    • +
      +

      isMemorySegmentUpdatableFormat

      +
      +
      public final boolean isMemorySegmentUpdatableFormat()
      +
      Returns true if the backing MemorySegment is in updatable format.
      +
      +
      Returns:
      +
      true if the backing MemorySegment is in updatable format.
      +
      +
      +
      +
    • +
    • +
      +

      isReadOnly

      +
      +
      public final boolean isReadOnly()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is read only.
      +
      +
      Specified by:
      +
      isReadOnly in interface QuantilesAPI
      +
      Returns:
      +
      true if this sketch is read only.
      +
      +
      +
      +
    • +
    • +
      +

      isSameResource

      +
      +
      public abstract boolean isSameResource(MemorySegment that)
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap. This applies to both on-heap and off-heap MemorySegments. + +

      Note: If both segments are on-heap and not read-only, it can be determined if they were derived from +the same backing memory (array). However, this is not always possible off-heap. Because of this asymmetry, this definition +of "isSameResource" is confined to the existence of an overlap.

      +
      +
      Specified by:
      +
      isSameResource in interface MemorySegmentStatus
      +
      Parameters:
      +
      that - The given MemorySegment.
      +
      Returns:
      +
      true if an internally referenced MemorySegment has the same backing resource as that.
      +
      +
      +
      +
    • +
    • +
      +

      merge

      +
      +
      public abstract void merge(KllSketch other)
      +
      Merges another sketch into this one. +Attempting to merge a sketch of the wrong type will throw an exception.
      +
      +
      Parameters:
      +
      other - sketch to merge into this one
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public final String toString()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns a summary of the key parameters of the sketch.
      +
      +
      Specified by:
      +
      toString in interface QuantilesAPI
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      a summary of the key parameters of the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public abstract String toString(boolean withLevels, + boolean withLevelsAndItems)
      +
      Returns human readable summary information about this sketch. +Used for debugging.
      +
      +
      Parameters:
      +
      withLevels - if true includes sketch levels array summary information
      +
      withLevelsAndItems - if true include detail of levels array and items array together
      +
      Returns:
      +
      human readable summary information about this sketch.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/KllSketchIterator.html b/target/site/apidocs/org/apache/datasketches/kll/KllSketchIterator.html new file mode 100644 index 000000000..0dfd36a19 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/KllSketchIterator.html @@ -0,0 +1,194 @@ + + + + +KllSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class KllSketchIterator

+
+
java.lang.Object +
org.apache.datasketches.kll.KllSketchIterator
+
+
+
+
All Implemented Interfaces:
+
QuantilesSketchIteratorAPI
+
+
+
Direct Known Subclasses:
+
KllDoublesSketchIterator, KllFloatsSketchIterator, KllItemsSketchIterator, KllLongsSketchIterator
+
+
+
+
public class KllSketchIterator +extends Object +implements QuantilesSketchIteratorAPI
+
The base implementation for the KLL sketch iterator hierarchy used for viewing the +non-ordered quantiles retained by a sketch. + +

Prototype example of the recommended iteration loop:

+
  SketchIterator itr = sketch.iterator();
+  while (itr.next()) {
+    ...get*();
+  }
+
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getWeight

      +
      +
      public long getWeight()
      +
      Description copied from interface: QuantilesSketchIteratorAPI
      +
      Gets the natural weight at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Specified by:
      +
      getWeight in interface QuantilesSketchIteratorAPI
      +
      Returns:
      +
      the natural weight at the current index.
      +
      +
      +
      +
    • +
    • +
      +

      next

      +
      +
      public boolean next()
      +
      Description copied from interface: QuantilesSketchIteratorAPI
      +
      Advances the index and checks if it is valid. +The state of this iterator is undefined before the first call of this method.
      +
      +
      Specified by:
      +
      next in interface QuantilesSketchIteratorAPI
      +
      Returns:
      +
      true if the next index is valid.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/class-use/KllDoublesSketch.html b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllDoublesSketch.html new file mode 100644 index 000000000..4f9d4abf3 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllDoublesSketch.html @@ -0,0 +1,130 @@ + + + + +Uses of Class org.apache.datasketches.kll.KllDoublesSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.kll.KllDoublesSketch

+
+
Packages that use KllDoublesSketch
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/class-use/KllDoublesSketchIterator.html b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllDoublesSketchIterator.html new file mode 100644 index 000000000..1284ab6f1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllDoublesSketchIterator.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.kll.KllDoublesSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.kll.KllDoublesSketchIterator

+
+No usage of org.apache.datasketches.kll.KllDoublesSketchIterator +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/class-use/KllFloatsSketch.html b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllFloatsSketch.html new file mode 100644 index 000000000..ed70a66ee --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllFloatsSketch.html @@ -0,0 +1,130 @@ + + + + +Uses of Class org.apache.datasketches.kll.KllFloatsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.kll.KllFloatsSketch

+
+
Packages that use KllFloatsSketch
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/class-use/KllFloatsSketchIterator.html b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllFloatsSketchIterator.html new file mode 100644 index 000000000..51015448b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllFloatsSketchIterator.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.kll.KllFloatsSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.kll.KllFloatsSketchIterator

+
+No usage of org.apache.datasketches.kll.KllFloatsSketchIterator +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/class-use/KllItemsSketch.html b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllItemsSketch.html new file mode 100644 index 000000000..b64f5a782 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllItemsSketch.html @@ -0,0 +1,119 @@ + + + + +Uses of Class org.apache.datasketches.kll.KllItemsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.kll.KllItemsSketch

+
+
Packages that use KllItemsSketch
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/class-use/KllItemsSketchIterator.html b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllItemsSketchIterator.html new file mode 100644 index 000000000..9c2bf5468 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllItemsSketchIterator.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.kll.KllItemsSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.kll.KllItemsSketchIterator

+
+No usage of org.apache.datasketches.kll.KllItemsSketchIterator +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/class-use/KllLongsSketch.html b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllLongsSketch.html new file mode 100644 index 000000000..f7e0f2736 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllLongsSketch.html @@ -0,0 +1,130 @@ + + + + +Uses of Class org.apache.datasketches.kll.KllLongsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.kll.KllLongsSketch

+
+
Packages that use KllLongsSketch
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/class-use/KllLongsSketchIterator.html b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllLongsSketchIterator.html new file mode 100644 index 000000000..ac1c0fb2f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllLongsSketchIterator.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.kll.KllLongsSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.kll.KllLongsSketchIterator

+
+No usage of org.apache.datasketches.kll.KllLongsSketchIterator +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/class-use/KllSketch.SketchStructure.html b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllSketch.SketchStructure.html new file mode 100644 index 000000000..4e339c36b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllSketch.SketchStructure.html @@ -0,0 +1,120 @@ + + + + +Uses of Enum Class org.apache.datasketches.kll.KllSketch.SketchStructure (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.kll.KllSketch.SketchStructure

+
+
Packages that use KllSketch.SketchStructure
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/class-use/KllSketch.SketchType.html b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllSketch.SketchType.html new file mode 100644 index 000000000..809491bd3 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllSketch.SketchType.html @@ -0,0 +1,128 @@ + + + + +Uses of Enum Class org.apache.datasketches.kll.KllSketch.SketchType (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.kll.KllSketch.SketchType

+
+
Packages that use KllSketch.SketchType
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/class-use/KllSketch.html b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllSketch.html new file mode 100644 index 000000000..3f83d3bbb --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllSketch.html @@ -0,0 +1,134 @@ + + + + +Uses of Class org.apache.datasketches.kll.KllSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.kll.KllSketch

+
+
Packages that use KllSketch
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/class-use/KllSketchIterator.html b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllSketchIterator.html new file mode 100644 index 000000000..2b6767ca8 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/class-use/KllSketchIterator.html @@ -0,0 +1,111 @@ + + + + +Uses of Class org.apache.datasketches.kll.KllSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.kll.KllSketchIterator

+
+
Packages that use KllSketchIterator
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/package-summary.html b/target/site/apidocs/org/apache/datasketches/kll/package-summary.html new file mode 100644 index 000000000..9db532db0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/package-summary.html @@ -0,0 +1,158 @@ + + + + +org.apache.datasketches.kll (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.kll

+
+
+
+
package org.apache.datasketches.kll
+
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+
+
+
    +
  • + +
  • +
  • +
    +
    +
    +
    +
    Class
    +
    Description
    + +
    +
    This variation of the KllSketch implements primitive doubles.
    +
    + +
    +
    Iterator over KllDoublesSketch.
    +
    + +
    +
    This variation of the KllSketch implements primitive floats.
    +
    + +
    +
    Iterator over KllFloatsSketch.
    +
    + +
    +
    This variation of the KllSketch implements generic data types.
    +
    + +
    +
    Iterator over KllItemsSketch.
    +
    + +
    +
    This variation of the KllSketch implements primitive longs.
    +
    + +
    +
    Iterator over KllLongsSketch.
    +
    + +
    +
    This class is the root of the KLL sketch class hierarchy.
    +
    + +
    +
    Used primarily to define the structure of the serialized sketch.
    +
    + +
    +
    Used to define the variable type of the current instance of this class.
    +
    + +
    +
    The base implementation for the KLL sketch iterator hierarchy used for viewing the +non-ordered quantiles retained by a sketch.
    +
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/package-tree.html b/target/site/apidocs/org/apache/datasketches/kll/package-tree.html new file mode 100644 index 000000000..f6a2c6f34 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/package-tree.html @@ -0,0 +1,109 @@ + + + + +org.apache.datasketches.kll Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.kll

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Enum Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/kll/package-use.html b/target/site/apidocs/org/apache/datasketches/kll/package-use.html new file mode 100644 index 000000000..f00c4db53 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/kll/package-use.html @@ -0,0 +1,121 @@ + + + + +Uses of Package org.apache.datasketches.kll (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.kll

+
+
Packages that use org.apache.datasketches.kll
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/package-summary.html b/target/site/apidocs/org/apache/datasketches/package-summary.html new file mode 100644 index 000000000..2246d15f8 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/package-summary.html @@ -0,0 +1,185 @@ + + + + +org.apache.datasketches (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches

+
+
+
+
package org.apache.datasketches
+
+
This package is the parent package for all sketch families and common code areas.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/package-tree.html b/target/site/apidocs/org/apache/datasketches/package-tree.html new file mode 100644 index 000000000..ec20b7b8f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/package-tree.html @@ -0,0 +1,69 @@ + + + + +org.apache.datasketches Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches

+
+Package Hierarchies: + +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/package-use.html b/target/site/apidocs/org/apache/datasketches/package-use.html new file mode 100644 index 000000000..c02357c13 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/package-use.html @@ -0,0 +1,66 @@ + + + + +Uses of Package org.apache.datasketches (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches

+
+No usage of org.apache.datasketches +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/BoundsRule.html b/target/site/apidocs/org/apache/datasketches/partitions/BoundsRule.html new file mode 100644 index 000000000..bdd65cc06 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/BoundsRule.html @@ -0,0 +1,273 @@ + + + + +BoundsRule (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class BoundsRule

+
+
java.lang.Object +
java.lang.Enum<BoundsRule> +
org.apache.datasketches.partitions.BoundsRule
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<BoundsRule>, Constable
+
+
+
+
public enum BoundsRule +extends Enum<BoundsRule>
+
This instructs the user about which of the upper and lower bounds of a partition definition row +should be included with the returned data.
+
+
+
+ +
+
+
    + +
  • +
    +

    Enum Constant Details

    +
      +
    • +
      +

      INCLUDE_BOTH

      +
      +
      public static final BoundsRule INCLUDE_BOTH
      +
      Include both the upper and lower bounds
      +
      +
      +
    • +
    • +
      +

      INCLUDE_UPPER

      +
      +
      public static final BoundsRule INCLUDE_UPPER
      +
      Include only the upper bound but not the lower bound
      +
      +
      +
    • +
    • +
      +

      INCLUDE_LOWER

      +
      +
      public static final BoundsRule INCLUDE_LOWER
      +
      Include only the lower bound but not the upper bound
      +
      +
      +
    • +
    • +
      +

      INCLUDE_NEITHER

      +
      +
      public static final BoundsRule INCLUDE_NEITHER
      +
      Include none
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static BoundsRule[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static BoundsRule valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/Partitioner.PartitionBoundsRow.html b/target/site/apidocs/org/apache/datasketches/partitions/Partitioner.PartitionBoundsRow.html new file mode 100644 index 000000000..3cebe2270 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/Partitioner.PartitionBoundsRow.html @@ -0,0 +1,269 @@ + + + + +Partitioner.PartitionBoundsRow (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class Partitioner.PartitionBoundsRow<T>

+
+
java.lang.Object +
org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow<T>
+
+
+
+
Type Parameters:
+
T - the item class type
+
+
+
Enclosing class:
+
Partitioner<T, S extends QuantilesGenericAPI<T> & PartitioningFeature<T>>
+
+
+
+
public static class Partitioner.PartitionBoundsRow<T> +extends Object
+
Defines a row for List of PartitionBounds.
+
+
+
+ +
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      part

      +
      +
      public int part
      +
      The partition index
      +
      +
      +
    • +
    • +
      +

      levelPartId

      +
      +
      public String levelPartId
      +
      A brief string description of the partition and its hierarchy
      +
      +
      +
    • +
    • +
      +

      approxNumDeltaItems

      +
      +
      public long approxNumDeltaItems
      +
      The approximate number of items represented by this partition description row.
      +
      +
      +
    • +
    • +
      +

      rule

      +
      +
      public BoundsRule rule
      +
      The BoundsRule for this partition description row.
      +
      +
      +
    • +
    • +
      +

      lowerBound

      +
      +
      public T lowerBound
      +
      The lower bound value
      +
      +
      +
    • +
    • +
      +

      upperBound

      +
      +
      public T upperBound
      +
      The upper bound value
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      PartitionBoundsRow

      +
      +
      public PartitionBoundsRow(Partitioner.StackElement<T> se)
      +
      The constructor for the StackElement class.
      +
      +
      Parameters:
      +
      se - the given stack element.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/Partitioner.StackElement.html b/target/site/apidocs/org/apache/datasketches/partitions/Partitioner.StackElement.html new file mode 100644 index 000000000..87139cce2 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/Partitioner.StackElement.html @@ -0,0 +1,230 @@ + + + + +Partitioner.StackElement (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class Partitioner.StackElement<T>

+
+
java.lang.Object +
org.apache.datasketches.partitions.Partitioner.StackElement<T>
+
+
+
+
Type Parameters:
+
T - the item class type
+
+
+
Enclosing class:
+
Partitioner<T, S extends QuantilesGenericAPI<T> & PartitioningFeature<T>>
+
+
+
+
public static class Partitioner.StackElement<T> +extends Object
+
Holds data for a Stack element
+
+
+
+ +
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      gpb

      +
      +
      public final GenericPartitionBoundaries<T> gpb
      +
      A reference to the relevant GenericPartitionBoundaries class
      +
      +
      +
    • +
    • +
      +

      part

      +
      +
      public int part
      +
      The partition index
      +
      +
      +
    • +
    • +
      +

      levelPartId

      +
      +
      public String levelPartId
      +
      A brief string description of the partition and its hierarchy
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      StackElement

      +
      +
      public StackElement(GenericPartitionBoundaries<T> gpb, + int part, + String levelPartId)
      +
      Constructs this StackElement
      +
      +
      Parameters:
      +
      gpb - the given GenericPartitionBoundarie reference
      +
      part - The partition index
      +
      levelPartId - A brief string description of the partition and its hierarchy
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/Partitioner.html b/target/site/apidocs/org/apache/datasketches/partitions/Partitioner.html new file mode 100644 index 000000000..b3b04d288 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/Partitioner.html @@ -0,0 +1,261 @@ + + + + +Partitioner (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class Partitioner<T, S extends QuantilesGenericAPI<T> & PartitioningFeature<T>>

+
+
java.lang.Object +
org.apache.datasketches.partitions.Partitioner<T,S>
+
+
+
+
Type Parameters:
+
T - the data type
+
S - the quantiles sketch that implements both QuantilesGenericAPI and PartitioningFeature.
+
+
+
+
public class Partitioner<T, S extends QuantilesGenericAPI<T> & PartitioningFeature<T>> +extends Object
+
A partitioning process that can partition very large data sets into thousands +of partitions of approximately the same size. + +

The code included here does work fine for moderate sized partitioning tasks. +As an example, using the test code in the test branch with the partitioning task of splitting +a data set of 1 billion items into 324 partitions of size 3M items completed in under 3 minutes, which was +performed on a single CPU. For much larger partitioning tasks, it is recommended that this code be leveraged into a +parallelized systems environment.

+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      Partitioner

      +
      +
      public Partitioner(long tgtPartitionSize, + int maxPartsPerPass, + SketchFillRequest<T,S> fillReq)
      +
      This constructor assumes a QuantileSearchCriteria of INCLUSIVE.
      +
      +
      Parameters:
      +
      tgtPartitionSize - the target size of the resulting partitions in number of items.
      +
      maxPartsPerPass - The maximum number of partitions to request from the sketch. The smaller this number is +the smaller the variance will be of the resulting partitions, but this will increase the number of passes of the +source data set.
      +
      fillReq - The is an implementation of the SketchFillRequest call-back supplied by the user and implements +the SketchFillRequest interface.
      +
      +
      +
      +
    • +
    • +
      +

      Partitioner

      +
      +
      public Partitioner(long tgtPartitionSize, + int maxPartsPerSk, + SketchFillRequest<T,S> fillReq, + QuantileSearchCriteria criteria)
      +
      This constructor includes the QuantileSearchCriteria criteria as a parameter.
      +
      +
      Parameters:
      +
      tgtPartitionSize - the target size of the resulting partitions in number of items.
      +
      maxPartsPerSk - The maximum number of partitions to request from the sketch. The smaller this number is +the smaller the variance will be of the resulting partitions, but this will increase the number of passes of the +source data set.
      +
      fillReq - The is an implementation of the SketchFillRequest call-back supplied by the user.
      +
      criteria - This is the desired QuantileSearchCriteria to be used.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      partition

      +
      +
      public List<Partitioner.PartitionBoundsRow<T>> partition(S sk)
      +
      This initiates the partitioning process
      +
      +
      Parameters:
      +
      sk - A sketch of the entire data set.
      +
      Returns:
      +
      the final partitioning list
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/SketchFillRequest.html b/target/site/apidocs/org/apache/datasketches/partitions/SketchFillRequest.html new file mode 100644 index 000000000..cdc2344f0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/SketchFillRequest.html @@ -0,0 +1,160 @@ + + + + +SketchFillRequest (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface SketchFillRequest<T, S extends QuantilesGenericAPI<T> & PartitioningFeature<T>>

+
+
+
+
Type Parameters:
+
T - the item class type
+
S - the sketch type
+
+
+
+
public interface SketchFillRequest<T, S extends QuantilesGenericAPI<T> & PartitioningFeature<T>>
+
This is a callback request to the data source to fill a quantiles sketch, +which is returned to the caller.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + +
    getRange(T lowerQuantile, + T upperQuantile, + BoundsRule boundsRule)
    +
    +
    This is a callback request to the data source to fill a quantiles sketch +with a range of data between upper and lower bounds.
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getRange

      +
      +
      S getRange(T lowerQuantile, + T upperQuantile, + BoundsRule boundsRule)
      +
      This is a callback request to the data source to fill a quantiles sketch +with a range of data between upper and lower bounds. Which of these bounds are to be included is determined by +the BoundsRule. + +

      This range of data may or may not be subsequently further partitioned.

      +
      +
      Parameters:
      +
      lowerQuantile - the lowest quantile of a range
      +
      upperQuantile - the highest quantile of a range
      +
      boundsRule - determines which quantile bounds to include
      +
      Returns:
      +
      a quantiles sketch filled from the given upper and lower bounds.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/class-use/BoundsRule.html b/target/site/apidocs/org/apache/datasketches/partitions/class-use/BoundsRule.html new file mode 100644 index 000000000..c2cd79525 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/class-use/BoundsRule.html @@ -0,0 +1,139 @@ + + + + +Uses of Enum Class org.apache.datasketches.partitions.BoundsRule (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.partitions.BoundsRule

+
+
Packages that use BoundsRule
+
+
Package
+
Description
+ +
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/class-use/Partitioner.PartitionBoundsRow.html b/target/site/apidocs/org/apache/datasketches/partitions/class-use/Partitioner.PartitionBoundsRow.html new file mode 100644 index 000000000..a64557012 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/class-use/Partitioner.PartitionBoundsRow.html @@ -0,0 +1,97 @@ + + + + +Uses of Class org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.partitions.Partitioner.PartitionBoundsRow

+
+ +
+
Package
+
Description
+ +
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/class-use/Partitioner.StackElement.html b/target/site/apidocs/org/apache/datasketches/partitions/class-use/Partitioner.StackElement.html new file mode 100644 index 000000000..07d7e95b7 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/class-use/Partitioner.StackElement.html @@ -0,0 +1,97 @@ + + + + +Uses of Class org.apache.datasketches.partitions.Partitioner.StackElement (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.partitions.Partitioner.StackElement

+
+
Packages that use Partitioner.StackElement
+
+
Package
+
Description
+ +
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/class-use/Partitioner.html b/target/site/apidocs/org/apache/datasketches/partitions/class-use/Partitioner.html new file mode 100644 index 000000000..5038624ae --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/class-use/Partitioner.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.partitions.Partitioner (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.partitions.Partitioner

+
+No usage of org.apache.datasketches.partitions.Partitioner +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/class-use/SketchFillRequest.html b/target/site/apidocs/org/apache/datasketches/partitions/class-use/SketchFillRequest.html new file mode 100644 index 000000000..bfc7e5688 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/class-use/SketchFillRequest.html @@ -0,0 +1,106 @@ + + + + +Uses of Interface org.apache.datasketches.partitions.SketchFillRequest (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.partitions.SketchFillRequest

+
+
Packages that use SketchFillRequest
+
+
Package
+
Description
+ +
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/package-summary.html b/target/site/apidocs/org/apache/datasketches/partitions/package-summary.html new file mode 100644 index 000000000..ee27f51a6 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/package-summary.html @@ -0,0 +1,132 @@ + + + + +org.apache.datasketches.partitions (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.partitions

+
+
+
+
package org.apache.datasketches.partitions
+
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+
+
+
    +
  • + +
  • +
  • +
    +
    +
    +
    +
    Class
    +
    Description
    + +
    +
    This instructs the user about which of the upper and lower bounds of a partition definition row +should be included with the returned data.
    +
    + +
    +
    A partitioning process that can partition very large data sets into thousands +of partitions of approximately the same size.
    +
    + +
    +
    Defines a row for List of PartitionBounds.
    +
    + +
    +
    Holds data for a Stack element
    +
    + +
    +
    This is a callback request to the data source to fill a quantiles sketch, +which is returned to the caller.
    +
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/package-tree.html b/target/site/apidocs/org/apache/datasketches/partitions/package-tree.html new file mode 100644 index 000000000..d22d13239 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/package-tree.html @@ -0,0 +1,101 @@ + + + + +org.apache.datasketches.partitions Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.partitions

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Interface Hierarchy

+ +
+
+

Enum Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/partitions/package-use.html b/target/site/apidocs/org/apache/datasketches/partitions/package-use.html new file mode 100644 index 000000000..d629980e5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/partitions/package-use.html @@ -0,0 +1,106 @@ + + + + +Uses of Package org.apache.datasketches.partitions (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.partitions

+
+ +
+
Package
+
Description
+ +
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/ClassicUtil.html b/target/site/apidocs/org/apache/datasketches/quantiles/ClassicUtil.html new file mode 100644 index 000000000..ba1b132be --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/ClassicUtil.html @@ -0,0 +1,185 @@ + + + + +ClassicUtil (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ClassicUtil

+
+
java.lang.Object +
org.apache.datasketches.quantiles.ClassicUtil
+
+
+
+
+
public final class ClassicUtil +extends Object
+
Utilities for the classic quantiles sketches and independent of the type.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getNormalizedRankError

      +
      +
      public static double getNormalizedRankError(int k, + boolean pmf)
      +
      Used by Classic Quantiles. +Gets the normalized rank error given k and pmf for the QuantilesDoubleSketch and QuantilesItemsSketch.
      +
      +
      Parameters:
      +
      k - the configuration parameter
      +
      pmf - if true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      Returns:
      +
      if pmf is true, the normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      +
      +
      +
    • +
    • +
      +

      getKFromEpsilon

      +
      +
      public static int getKFromEpsilon(double epsilon, + boolean pmf)
      +
      Used by Classic Quantiles. +Gets the approximate k to use given epsilon, the normalized rank error +for the QuantilesDoubleSketch and QuantilesItemsSketch.
      +
      +
      Parameters:
      +
      epsilon - the normalized rank error between zero and one.
      +
      pmf - if true, this function returns k assuming the input epsilon +is the desired "double-sided" epsilon for the getPMF() function. Otherwise, this function +returns k assuming the input epsilon is the desired "single-sided" +epsilon for all the other queries.
      +
      Returns:
      +
      k given epsilon.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/CompactQuantilesDoublesSketch.html b/target/site/apidocs/org/apache/datasketches/quantiles/CompactQuantilesDoublesSketch.html new file mode 100644 index 000000000..d20b651dd --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/CompactQuantilesDoublesSketch.html @@ -0,0 +1,220 @@ + + + + +CompactQuantilesDoublesSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class CompactQuantilesDoublesSketch

+
+
java.lang.Object +
org.apache.datasketches.quantiles.QuantilesDoublesSketch +
org.apache.datasketches.quantiles.CompactQuantilesDoublesSketch
+
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus, QuantilesAPI, QuantilesDoublesAPI
+
+
+
+
public abstract class CompactQuantilesDoublesSketch +extends QuantilesDoublesSketch
+
Compact sketches are inherently read only.
+
+
Author:
+
Jon Malkin
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      isReadOnly

      +
      +
      public boolean isReadOnly()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is read only.
      +
      +
      Specified by:
      +
      isReadOnly in interface QuantilesAPI
      +
      Specified by:
      +
      isReadOnly in class QuantilesDoublesSketch
      +
      Returns:
      +
      true if this sketch is read only.
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Description copied from interface: QuantilesAPI
      +
      Resets this sketch to the empty state. +If the sketch is read only this does nothing. + +

      The parameter k will not change.

      +
      +
      Specified by:
      +
      reset in interface QuantilesAPI
      +
      Specified by:
      +
      reset in class QuantilesDoublesSketch
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(double quantile)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Updates this sketch with the given item.
      +
      +
      Parameters:
      +
      quantile - from a stream of items. NaNs are ignored.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesSketch.html b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesSketch.html new file mode 100644 index 000000000..013e5e33b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesSketch.html @@ -0,0 +1,1444 @@ + + + + +QuantilesDoublesSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class QuantilesDoublesSketch

+
+
java.lang.Object +
org.apache.datasketches.quantiles.QuantilesDoublesSketch
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus, QuantilesAPI, QuantilesDoublesAPI
+
+
+
Direct Known Subclasses:
+
CompactQuantilesDoublesSketch, UpdatableQuantilesDoublesSketch
+
+
+
+
public abstract class QuantilesDoublesSketch +extends Object +implements QuantilesDoublesAPI, MemorySegmentStatus
+
This is an implementation of the Low Discrepancy Mergeable Quantiles Sketch, using doubles, + described in section 3.2 of the journal version of the paper "Mergeable Summaries" + by Agarwal, Cormode, Huang, Phillips, Wei, and Yi: + +

Reference:

+ +

A k of 128 produces a normalized, rank error of about 1.7%. + For example, the median returned from getQuantile(0.5) will be between the actual quantiles + from the hypothetically sorted array of input quantiles at normalized ranks of 0.483 and 0.517, with + a confidence of about 99%.

+ +
+Table Guide for QuantilesDoublesSketch Size in Bytes and Approximate Error:
+          K => |      16      32      64     128     256     512   1,024
+    ~ Error => | 12.145%  6.359%  3.317%  1.725%  0.894%  0.463%  0.239%
+             N | Size in Bytes ->
+------------------------------------------------------------------------
+             0 |       8       8       8       8       8       8       8
+             1 |      72      72      72      72      72      72      72
+             3 |      72      72      72      72      72      72      72
+             7 |     104     104     104     104     104     104     104
+            15 |     168     168     168     168     168     168     168
+            31 |     296     296     296     296     296     296     296
+            63 |     424     552     552     552     552     552     552
+           127 |     552     808   1,064   1,064   1,064   1,064   1,064
+           255 |     680   1,064   1,576   2,088   2,088   2,088   2,088
+           511 |     808   1,320   2,088   3,112   4,136   4,136   4,136
+         1,023 |     936   1,576   2,600   4,136   6,184   8,232   8,232
+         2,047 |   1,064   1,832   3,112   5,160   8,232  12,328  16,424
+         4,095 |   1,192   2,088   3,624   6,184  10,280  16,424  24,616
+         8,191 |   1,320   2,344   4,136   7,208  12,328  20,520  32,808
+        16,383 |   1,448   2,600   4,648   8,232  14,376  24,616  41,000
+        32,767 |   1,576   2,856   5,160   9,256  16,424  28,712  49,192
+        65,535 |   1,704   3,112   5,672  10,280  18,472  32,808  57,384
+       131,071 |   1,832   3,368   6,184  11,304  20,520  36,904  65,576
+       262,143 |   1,960   3,624   6,696  12,328  22,568  41,000  73,768
+       524,287 |   2,088   3,880   7,208  13,352  24,616  45,096  81,960
+     1,048,575 |   2,216   4,136   7,720  14,376  26,664  49,192  90,152
+     2,097,151 |   2,344   4,392   8,232  15,400  28,712  53,288  98,344
+     4,194,303 |   2,472   4,648   8,744  16,424  30,760  57,384 106,536
+     8,388,607 |   2,600   4,904   9,256  17,448  32,808  61,480 114,728
+    16,777,215 |   2,728   5,160   9,768  18,472  34,856  65,576 122,920
+    33,554,431 |   2,856   5,416  10,280  19,496  36,904  69,672 131,112
+    67,108,863 |   2,984   5,672  10,792  20,520  38,952  73,768 139,304
+   134,217,727 |   3,112   5,928  11,304  21,544  41,000  77,864 147,496
+   268,435,455 |   3,240   6,184  11,816  22,568  43,048  81,960 155,688
+   536,870,911 |   3,368   6,440  12,328  23,592  45,096  86,056 163,880
+ 1,073,741,823 |   3,496   6,696  12,840  24,616  47,144  90,152 172,072
+ 2,147,483,647 |   3,624   6,952  13,352  25,640  49,192  94,248 180,264
+ 4,294,967,295 |   3,752   7,208  13,864  26,664  51,240  98,344 188,456
+ 
+
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Field Summary

    + +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Returns a new builder
    +
    + +
    downSample(QuantilesDoublesSketch srcSketch, + int smallerK, + MemorySegment dstSeg, + MemorySegmentRequest mSegReq)
    +
    +
    From an source sketch, create a new sketch that must have a smaller K.
    +
    +
    double[]
    +
    getCDF(double[] splitPoints, + QuantileSearchCriteria searchCrit)
    +
    +
    Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
    +
    +
    static int
    +
    getCompactSerialiedSizeBytes(int k, + long n)
    +
    +
    Returns the number of bytes a QuantilesDoublesSketch would require to store in compact form +given k and n.
    +
    +
    int
    + +
    +
    Returns the current number of bytes this sketch would require to store in the compact MemorySegment Format.
    +
    +
    int
    + +
    +
    Returns the current number of bytes this sketch would require to store in the updatable MemorySegment Format.
    +
    +
    int
    + +
    +
    Gets the user configured parameter k, which controls the accuracy of the sketch +and its memory space usage.
    +
    +
    static int
    +
    getKFromEpsilon(double epsilon, + boolean pmf)
    +
    +
    Gets the approximate k to use given epsilon, the normalized rank error.
    +
    +
    abstract double
    + +
    +
    Returns the maximum item of the stream.
    +
    +
    abstract double
    + +
    +
    Returns the minimum item of the stream.
    +
    +
    abstract long
    + +
    +
    Gets the length of the input stream offered to the sketch..
    +
    +
    double
    + +
    +
    Gets the approximate rank error of this sketch normalized as a fraction between zero and one.
    +
    +
    static double
    +
    getNormalizedRankError(int k, + boolean pmf)
    +
    +
    Gets the normalized rank error given k and pmf.
    +
    +
    int
    + +
    +
    Gets the number of quantiles retained by the sketch.
    +
    +
    double[]
    +
    getPMF(double[] splitPoints, + QuantileSearchCriteria searchCrit)
    +
    +
    Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
    +
    +
    double
    +
    getQuantile(double rank, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets the approximate quantile of the given normalized rank and the given search criterion.
    +
    +
    double
    +
    getQuantileLowerBound(double rank)
    +
    +
    Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
    +
    +
    double[]
    +
    getQuantiles(double[] ranks, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets an array of quantiles from the given array of normalized ranks.
    +
    +
    double
    +
    getQuantileUpperBound(double rank)
    +
    +
    Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
    +
    +
    double
    +
    getRank(double quantile, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets the normalized rank corresponding to the given a quantile.
    +
    +
    double
    +
    getRankLowerBound(double rank)
    +
    +
    Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
    +
    +
    double[]
    +
    getRanks(double[] quantiles, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
    +
    +
    double
    +
    getRankUpperBound(double rank)
    +
    +
    Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
    +
    +
    int
    + +
    +
    Returns the current number of bytes this Sketch would require if serialized.
    +
    + + +
    +
    Gets the sorted view of this sketch
    +
    +
    static int
    +
    getUpdatableStorageBytes(int k, + long n)
    +
    +
    Returns the number of bytes a sketch would require to store in updatable form.
    +
    +
    abstract boolean
    + +
    +
    Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
    +
    + + +
    +
    Heapify takes the sketch image in MemorySegment and instantiates an on-heap Sketch.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch is empty.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch is in estimation mode.
    +
    +
    abstract boolean
    + +
    +
    Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
    +
    +
    abstract boolean
    + +
    +
    Returns true if this sketch is read only.
    +
    +
    abstract boolean
    + +
    +
    Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap.
    +
    + + +
    +
    Gets the iterator for this sketch, which is not sorted.
    +
    +
    void
    + +
    +
    Puts the current sketch into the given MemorySegment in compact form if there is sufficient space, +otherwise, it throws an error.
    +
    +
    void
    +
    putIntoMemorySegment(MemorySegment dstSeg, + boolean compact)
    +
    +
    Puts the current sketch into the given MemorySegment if there is sufficient space, otherwise, +throws an error.
    +
    +
    abstract void
    + +
    +
    Resets this sketch to the empty state.
    +
    +
    byte[]
    + +
    +
    Returns a byte array representation of this sketch.
    +
    +
    byte[]
    +
    toByteArray(boolean compact)
    +
    +
    Serialize this sketch in a byte array form.
    +
    + + +
    +
    Returns human readable summary information about this sketch.
    +
    + +
    toString(boolean withLevels, + boolean withLevelsAndItems)
    +
    +
    Returns human readable summary information about this sketch.
    +
    +
    static String
    +
    toString(byte[] byteArr)
    +
    +
    Returns a human readable string of the preamble of a byte array image of a QuantilesDoublesSketch.
    +
    +
    static String
    + +
    +
    Returns a human readable string of the preamble of a MemorySegment image of a QuantilesDoublesSketch.
    +
    + + +
    +
    Wrap this sketch around the given MemorySegment image of a compact, read-only QuantilesDoublesSketch.
    +
    + + +
    +
    Wrap this sketch around the given MemorySegment image of an updatable QuantilesDoublesSketch.
    +
    + + +
    +
    Wrap this sketch around the given MemorySegment image of an updatable QuantilesDoublesSketch.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +

    Methods inherited from interface QuantilesDoublesAPI

    +getCDF, getPMF, getQuantile, getQuantiles, getRank, getRanks, update
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      builder

      +
      +
      public static final QuantilesDoublesSketchBuilder builder()
      +
      Returns a new builder
      +
      +
      Returns:
      +
      a new builder
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static QuantilesDoublesSketch heapify(MemorySegment srcSeg)
      +
      Heapify takes the sketch image in MemorySegment and instantiates an on-heap Sketch. +The resulting sketch will not retain any link to the source MemorySegment.
      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment image of a Sketch.
      +
      Returns:
      +
      a heap-based Sketch based on the given MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static QuantilesDoublesSketch wrap(MemorySegment srcSeg)
      +
      Wrap this sketch around the given MemorySegment image of a compact, read-only QuantilesDoublesSketch.
      +
      +
      Parameters:
      +
      srcSeg - the given MemorySegment image of a compact, read-only QuantilesDoublesSketch.
      +
      Returns:
      +
      a compact, read-only sketch that wraps the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      writableWrap

      +
      +
      public static QuantilesDoublesSketch writableWrap(MemorySegment srcSeg)
      +
      Wrap this sketch around the given MemorySegment image of an updatable QuantilesDoublesSketch. + +

      The given MemorySegment must be writable and it must contain a UpdatableQuantilesDoublesSketch. +The sketch will be updated and managed totally within the MemorySegment. If the given source +MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

      + +

      NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch +will request more capacity using the MemorySegmentRequest interface. The default of this interface will +return a new MemorySegment on the heap.

      +
      +
      Parameters:
      +
      srcSeg - the given MemorySegment image of an UpdatableQuantilesDoublesSketch.
      +
      Returns:
      +
      an updatable sketch that wraps the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      writableWrap

      +
      +
      public static QuantilesDoublesSketch writableWrap(MemorySegment srcSeg, + MemorySegmentRequest mSegReq)
      +
      Wrap this sketch around the given MemorySegment image of an updatable QuantilesDoublesSketch. + +

      The given MemorySegment must be writable and it must contain a UpdatableQuantilesDoublesSketch. +The sketch will be updated and managed totally within the MemorySegment. If the given source +MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

      + +

      NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch +will request more capacity using the MemorySegmentRequest interface. The default of this interface will +return a new MemorySegment on the heap. It is up to the user to optionally extend this interface if more flexible +handling of requests for more capacity is required.

      +
      +
      Parameters:
      +
      srcSeg - the given MemorySegment image of a QuantilesDoublesSketch.
      +
      mSegReq - the MemorySegmentRequest used if the given MemorySegment needs to expand. +Otherwise, it can be null and the default MemorySegmentRequest will be used.
      +
      Returns:
      +
      a sketch that wraps the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      getCDF

      +
      +
      public double[] getCDF(double[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Specified by:
      +
      getCDF in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      public abstract double getMaxItem()
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Returns the maximum item of the stream. This is provided for convenience and may be different from the +item returned by getQuantile(1.0).
      +
      +
      Specified by:
      +
      getMaxItem in interface QuantilesDoublesAPI
      +
      Returns:
      +
      the maximum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      public abstract double getMinItem()
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Returns the minimum item of the stream. This is provided for convenience and may be different from the +item returned by getQuantile(0.0).
      +
      +
      Specified by:
      +
      getMinItem in interface QuantilesDoublesAPI
      +
      Returns:
      +
      the minimum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      public double[] getPMF(double[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Specified by:
      +
      getPMF in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public double getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      public double[] getQuantiles(double[] ranks, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Gets an array of quantiles from the given array of normalized ranks.
      +
      +
      Specified by:
      +
      getQuantiles in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      searchCrit - if INCLUSIVE, the given ranks include all quantiles ≤ +the quantile directly corresponding to each rank.
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileLowerBound

      +
      +
      public double getQuantileLowerBound(double rank)
      +
      Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile confidence interval +as an additive or multiplicative percent of the true quantile.

      +The approximate probability that the true quantile is within the confidence interval +specified by the upper and lower quantile bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getQuantileLowerBound in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileUpperBound

      +
      +
      public double getQuantileUpperBound(double rank)
      +
      Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile interval +as an additive or multiplicative percent of the true quantile.

      +The approximate probability that the true quantile is within the confidence interval +specified by the upper and lower quantile bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getQuantileUpperBound in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      public double getRank(double quantile, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Specified by:
      +
      getRank in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRankLowerBound

      +
      +
      public double getRankLowerBound(double rank)
      +
      Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists. +The approximate probability that the true rank is within the confidence interval +specified by the upper and lower rank bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getRankLowerBound in interface QuantilesAPI
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRankUpperBound

      +
      +
      public double getRankUpperBound(double rank)
      +
      Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists. +The approximate probability that the true rank is within the confidence interval +specified by the upper and lower rank bounds for this sketch is 0.99.
      +
      +
      Specified by:
      +
      getRankUpperBound in interface QuantilesAPI
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      public double[] getRanks(double[] quantiles, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
      +
      +
      Specified by:
      +
      getRanks in interface QuantilesDoublesAPI
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      searchCrit - if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile.
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getK

      +
      +
      public int getK()
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the user configured parameter k, which controls the accuracy of the sketch +and its memory space usage.
      +
      +
      Specified by:
      +
      getK in interface QuantilesAPI
      +
      Returns:
      +
      the user configured parameter k, which controls the accuracy of the sketch +and its memory space usage.
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      public abstract long getN()
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the length of the input stream offered to the sketch..
      +
      +
      Specified by:
      +
      getN in interface QuantilesAPI
      +
      Returns:
      +
      the length of the input stream offered to the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNormalizedRankError

      +
      +
      public double getNormalizedRankError(boolean pmf)
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the approximate rank error of this sketch normalized as a fraction between zero and one. +The epsilon returned is a best fit to 99 percent confidence empirically measured max error +in thousands of trials.
      +
      +
      Specified by:
      +
      getNormalizedRankError in interface QuantilesAPI
      +
      Parameters:
      +
      pmf - if true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      Returns:
      +
      if pmf is true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      +
      +
      +
    • +
    • +
      +

      getNormalizedRankError

      +
      +
      public static double getNormalizedRankError(int k, + boolean pmf)
      +
      Gets the normalized rank error given k and pmf. +Static method version of the getNormalizedRankError(boolean). +The epsilon returned is a best fit to 99 percent confidence empirically measured max error +in thousands of trials.
      +
      +
      Parameters:
      +
      k - the configuration parameter
      +
      pmf - if true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      Returns:
      +
      if pmf is true, the normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      +
      +
      +
    • +
    • +
      +

      getKFromEpsilon

      +
      +
      public static int getKFromEpsilon(double epsilon, + boolean pmf)
      +
      Gets the approximate k to use given epsilon, the normalized rank error.
      +
      +
      Parameters:
      +
      epsilon - the normalized rank error between zero and one.
      +
      pmf - if true, this function returns k assuming the input epsilon +is the desired "double-sided" epsilon for the getPMF() function. Otherwise, this function +returns k assuming the input epsilon is the desired "single-sided" +epsilon for all the other queries.
      +
      Returns:
      +
      k given epsilon.
      +
      +
      +
      +
    • +
    • +
      +

      hasMemorySegment

      +
      +
      public abstract boolean hasMemorySegment()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
      +
      +
      Specified by:
      +
      hasMemorySegment in interface MemorySegmentStatus
      +
      Returns:
      +
      true if this object's internal data is backed by a MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isOffHeap

      +
      +
      public abstract boolean isOffHeap()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      Specified by:
      +
      isOffHeap in interface MemorySegmentStatus
      +
      Returns:
      +
      true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is empty.
      +
      +
      Specified by:
      +
      isEmpty in interface QuantilesAPI
      +
      Returns:
      +
      true if this sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      isEstimationMode

      +
      +
      public boolean isEstimationMode()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is in estimation mode.
      +
      +
      Specified by:
      +
      isEstimationMode in interface QuantilesAPI
      +
      Returns:
      +
      true if this sketch is in estimation mode.
      +
      +
      +
      +
    • +
    • +
      +

      isReadOnly

      +
      +
      public abstract boolean isReadOnly()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is read only.
      +
      +
      Specified by:
      +
      isReadOnly in interface QuantilesAPI
      +
      Returns:
      +
      true if this sketch is read only.
      +
      +
      +
      +
    • +
    • +
      +

      isSameResource

      +
      +
      public abstract boolean isSameResource(MemorySegment that)
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap. This applies to both on-heap and off-heap MemorySegments. + +

      Note: If both segments are on-heap and not read-only, it can be determined if they were derived from +the same backing memory (array). However, this is not always possible off-heap. Because of this asymmetry, this definition +of "isSameResource" is confined to the existence of an overlap.

      +
      +
      Specified by:
      +
      isSameResource in interface MemorySegmentStatus
      +
      Parameters:
      +
      that - The given MemorySegment.
      +
      Returns:
      +
      true if an internally referenced MemorySegment has the same backing resource as that.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Returns a byte array representation of this sketch.
      +
      +
      Specified by:
      +
      toByteArray in interface QuantilesDoublesAPI
      +
      Returns:
      +
      a byte array representation of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(boolean compact)
      +
      Serialize this sketch in a byte array form.
      +
      +
      Parameters:
      +
      compact - if true the sketch will be serialized in compact form. +DirectCompactDoublesSketch can wrap() only a compact byte array; +DirectUpdateDoublesSketch can wrap() only a updatable byte array.
      +
      Returns:
      +
      this sketch in a byte array form.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns human readable summary information about this sketch. +Used for debugging.
      +
      +
      Specified by:
      +
      toString in interface QuantilesAPI
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      a summary of the key parameters of the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean withLevels, + boolean withLevelsAndItems)
      +
      Returns human readable summary information about this sketch. +Used for debugging.
      +
      +
      Parameters:
      +
      withLevels - if true includes sketch levels array summary information
      +
      withLevelsAndItems - if true include detail of levels array and items array together
      +
      Returns:
      +
      human readable summary information about this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(byte[] byteArr)
      +
      Returns a human readable string of the preamble of a byte array image of a QuantilesDoublesSketch. +Used for debugging.
      +
      +
      Parameters:
      +
      byteArr - the given byte array
      +
      Returns:
      +
      a human readable string of the preamble of a byte array image of a QuantilesDoublesSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(MemorySegment seg)
      +
      Returns a human readable string of the preamble of a MemorySegment image of a QuantilesDoublesSketch. +Used for debugging.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      a human readable string of the preamble of a MemorySegment image of a QuantilesDoublesSketch.
      +
      +
      +
      +
    • +
    • +
      +

      downSample

      +
      +
      public QuantilesDoublesSketch downSample(QuantilesDoublesSketch srcSketch, + int smallerK, + MemorySegment dstSeg, + MemorySegmentRequest mSegReq)
      +
      From an source sketch, create a new sketch that must have a smaller K. +The original sketch is not modified.
      +
      +
      Parameters:
      +
      srcSketch - the sourcing sketch
      +
      smallerK - the new sketch's K that must be smaller than this K. +It is required that this.getK() = smallerK * 2^(nonnegative integer).
      +
      dstSeg - the destination MemorySegment. It must not overlap the MemorySegment of this sketch. +If null, a heap sketch will be returned, otherwise it will be MemorySegment based.
      +
      mSegReq - the MemorySegmentRequest used if the given MemorySegment needs to expand. +Otherwise, it can be null and the default MemorySegmentRequest will be used.
      +
      Returns:
      +
      the new sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNumRetained

      +
      +
      public int getNumRetained()
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the number of quantiles retained by the sketch.
      +
      +
      Specified by:
      +
      getNumRetained in interface QuantilesAPI
      +
      Returns:
      +
      the number of quantiles retained by the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getCurrentCompactSerializedSizeBytes

      +
      +
      public int getCurrentCompactSerializedSizeBytes()
      +
      Returns the current number of bytes this sketch would require to store in the compact MemorySegment Format.
      +
      +
      Returns:
      +
      the current number of bytes this sketch would require to store in the compact MemorySegment Format.
      +
      +
      +
      +
    • +
    • +
      +

      getCompactSerialiedSizeBytes

      +
      +
      public static int getCompactSerialiedSizeBytes(int k, + long n)
      +
      Returns the number of bytes a QuantilesDoublesSketch would require to store in compact form +given k and n. The compact form is not updatable.
      +
      +
      Parameters:
      +
      k - the size configuration parameter for the sketch
      +
      n - the number of quantiles input into the sketch
      +
      Returns:
      +
      the number of bytes required to store this sketch in compact form.
      +
      +
      +
      +
    • +
    • +
      +

      getSerializedSizeBytes

      +
      +
      public int getSerializedSizeBytes()
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Returns the current number of bytes this Sketch would require if serialized.
      +
      +
      Specified by:
      +
      getSerializedSizeBytes in interface QuantilesDoublesAPI
      +
      Returns:
      +
      the number of bytes this sketch would require if serialized.
      +
      +
      +
      +
    • +
    • +
      +

      getCurrentUpdatableSerializedSizeBytes

      +
      +
      public int getCurrentUpdatableSerializedSizeBytes()
      +
      Returns the current number of bytes this sketch would require to store in the updatable MemorySegment Format.
      +
      +
      Returns:
      +
      the current number of bytes this sketch would require to store in the updatable MemorySegment Format.
      +
      +
      +
      +
    • +
    • +
      +

      getUpdatableStorageBytes

      +
      +
      public static int getUpdatableStorageBytes(int k, + long n)
      +
      Returns the number of bytes a sketch would require to store in updatable form. +This uses roughly 2X the storage of the compact form +given k and n.
      +
      +
      Parameters:
      +
      k - the size configuration parameter for the sketch
      +
      n - the number of quantiles input into the sketch
      +
      Returns:
      +
      the number of bytes this sketch would require to store in updatable form.
      +
      +
      +
      +
    • +
    • +
      +

      putIntoMemorySegment

      +
      +
      public void putIntoMemorySegment(MemorySegment dstSeg)
      +
      Puts the current sketch into the given MemorySegment in compact form if there is sufficient space, +otherwise, it throws an error.
      +
      +
      Parameters:
      +
      dstSeg - the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      putIntoMemorySegment

      +
      +
      public void putIntoMemorySegment(MemorySegment dstSeg, + boolean compact)
      +
      Puts the current sketch into the given MemorySegment if there is sufficient space, otherwise, +throws an error.
      +
      +
      Parameters:
      +
      dstSeg - the given MemorySegment.
      +
      compact - if true, compacts and sorts the base buffer, which optimizes merge + performance at the cost of slightly increased serialization time.
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Description copied from interface: QuantilesDoublesAPI
      +
      Gets the iterator for this sketch, which is not sorted.
      +
      +
      Specified by:
      +
      iterator in interface QuantilesDoublesAPI
      +
      Returns:
      +
      the iterator for this sketch
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public abstract void reset()
      +
      Description copied from interface: QuantilesAPI
      +
      Resets this sketch to the empty state. +If the sketch is read only this does nothing. + +

      The parameter k will not change.

      +
      +
      Specified by:
      +
      reset in interface QuantilesAPI
      +
      +
      +
      +
    • +
    • +
      +

      getSortedView

      +
      +
      public final DoublesSketchSortedView getSortedView()
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Gets the sorted view of this sketch
      +
      +
      Specified by:
      +
      getSortedView in interface QuantilesDoublesAPI
      +
      Returns:
      +
      the sorted view of this sketch
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesSketchBuilder.html b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesSketchBuilder.html new file mode 100644 index 000000000..d8ddf3b17 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesSketchBuilder.html @@ -0,0 +1,302 @@ + + + + +QuantilesDoublesSketchBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class QuantilesDoublesSketchBuilder

+
+
java.lang.Object +
org.apache.datasketches.quantiles.QuantilesDoublesSketchBuilder
+
+
+
+
+
public class QuantilesDoublesSketchBuilder +extends Object
+
For building a new quantiles QuantilesDoublesSketch.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      QuantilesDoublesSketchBuilder

      +
      +
      public QuantilesDoublesSketchBuilder()
      +
      Constructor for a new QuantilesDoublesSketchBuilder. The default configuration is +
        +
      • k: 128. This produces a normalized rank error of about 1.7%
      • +
      • MemorySegment: null
      • +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      setK

      +
      +
      public QuantilesDoublesSketchBuilder setK(int k)
      +
      Sets the parameter k that determines the accuracy and size of the sketch.
      +
      +
      Parameters:
      +
      k - determines the accuracy and size of the sketch. +It is recommended that k be a power of 2 to enable unioning of sketches with +different k. It is only possible to union from +larger k to smaller k.
      +
      Returns:
      +
      this builder
      +
      +
      +
      +
    • +
    • +
      +

      getK

      +
      +
      public int getK()
      +
      Gets the current configured k
      +
      +
      Returns:
      +
      the current configured k
      +
      +
      +
      +
    • +
    • +
      +

      build

      +
      + +
      Returns an UpdatableQuantilesDoublesSketch with the current configuration of this Builder.
      +
      +
      Returns:
      +
      a UpdatableQuantilesDoublesSketch
      +
      +
      +
      +
    • +
    • +
      +

      build

      +
      + +
      Returns a UpdatableQuantilesDoublesSketch with the current configuration of this builder +and the specified backing destination MemorySegment store that can grow.
      +
      +
      Parameters:
      +
      dstSeg - destination MemorySegment for use by the sketch
      +
      Returns:
      +
      an UpdatableQuantilesDoublesSketch
      +
      +
      +
      +
    • +
    • +
      +

      build

      +
      + +
      Returns a UpdatableQuantilesDoublesSketch with the current configuration of this builder +and the specified backing destination MemorySegment store that can grow.
      +
      +
      Parameters:
      +
      dstSeg - destination MemorySegment for use by the sketch
      +
      mSegReq - the MemorySegmentRequest used if the given MemorySegment needs to expand. +Otherwise, it can be null and the default MemorySegmentRequest will be used.
      +
      Returns:
      +
      an UpdatableQuantilesDoublesSketch
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Creates a human readable string that describes the current configuration of this builder.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesSketchIterator.html b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesSketchIterator.html new file mode 100644 index 000000000..fd7a06627 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesSketchIterator.html @@ -0,0 +1,203 @@ + + + + +QuantilesDoublesSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class QuantilesDoublesSketchIterator

+
+
java.lang.Object +
org.apache.datasketches.quantiles.QuantilesDoublesSketchIterator
+
+
+
+
All Implemented Interfaces:
+
QuantilesDoublesSketchIteratorAPI, QuantilesSketchIteratorAPI
+
+
+
+
public final class QuantilesDoublesSketchIterator +extends Object +implements QuantilesDoublesSketchIteratorAPI
+
Iterator over QuantilesDoublesSketch. The order is not defined.
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    double
    + +
    +
    Gets the double quantile at the current index.
    +
    +
    long
    + +
    +
    Gets the natural weight at the current index.
    +
    +
    boolean
    + +
    +
    Advances the index and checks if it is valid.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      public double getQuantile()
      +
      Description copied from interface: QuantilesDoublesSketchIteratorAPI
      +
      Gets the double quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesDoublesSketchIteratorAPI
      +
      Returns:
      +
      the double quantile at the current index.
      +
      +
      +
      +
    • +
    • +
      +

      getWeight

      +
      +
      public long getWeight()
      +
      Description copied from interface: QuantilesSketchIteratorAPI
      +
      Gets the natural weight at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Specified by:
      +
      getWeight in interface QuantilesSketchIteratorAPI
      +
      Returns:
      +
      the natural weight at the current index.
      +
      +
      +
      +
    • +
    • +
      +

      next

      +
      +
      public boolean next()
      +
      Description copied from interface: QuantilesSketchIteratorAPI
      +
      Advances the index and checks if it is valid. +The state of this iterator is undefined before the first call of this method.
      +
      +
      Specified by:
      +
      next in interface QuantilesSketchIteratorAPI
      +
      Returns:
      +
      true if the next index is valid.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesUnion.html b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesUnion.html new file mode 100644 index 000000000..627e572ec --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesUnion.html @@ -0,0 +1,638 @@ + + + + +QuantilesDoublesUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class QuantilesDoublesUnion

+
+
java.lang.Object +
org.apache.datasketches.quantiles.QuantilesDoublesUnion
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus
+
+
+
+
public abstract class QuantilesDoublesUnion +extends Object +implements MemorySegmentStatus
+
The API for Union operations for QuantilesDoublesSketches
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    No argument constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Returns a new UnionBuilder
    +
    +
    abstract int
    + +
    +
    Returns the effective k of this Union.
    +
    +
    abstract int
    + +
    +
    Returns the configured maxK of this Union.
    +
    + + +
    +
    Gets the result of this Union as an UpdatableQuantilesDoublesSketch, which enables further update +operations on the resulting sketch.
    +
    + + +
    +
    Places the result of this Union into the provided MemorySegment as an UpdatableQuantilesDoublesSketch, +which enables further update operations on the resulting sketch.
    +
    + + +
    +
    Gets the result of this Union as an UpdatableQuantilesDoublesSketch, which enables further update +operations on the resulting sketch.
    +
    +
    abstract boolean
    + +
    +
    Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
    +
    + + +
    +
    Returns a Heap Union object that has been initialized with the data from the given MemorySegment that contains an +image of a sketch.
    +
    + + +
    +
    Returns a Heap Union object that has been initialized with the data from the given sketch.
    +
    +
    abstract boolean
    + +
    +
    Returns true if this union is empty
    +
    +
    abstract boolean
    + +
    +
    Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
    +
    +
    abstract boolean
    + +
    +
    Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap.
    +
    +
    abstract void
    + +
    +
    Resets this Union to a virgin state.
    +
    +
    abstract byte[]
    + +
    +
    Serialize this union to a byte array.
    +
    +
    abstract String
    + +
    +
    Returns summary information about the backing sketch.
    +
    +
    abstract String
    +
    toString(boolean sketchSummary, + boolean dataDetail)
    +
    +
    Returns summary information about the backing sketch.
    +
    +
    abstract void
    + +
    +
    Iterative union operation, which means this method can be repeatedly called.
    +
    +
    abstract void
    + +
    +
    Iterative union operation, which means this method can be repeatedly called.
    +
    +
    abstract void
    +
    update(double dataItem)
    +
    +
    Update this union with the given double (or float) data Item.
    +
    + + +
    +
    Returns an updatable Union object that wraps the given MemorySegment that contains an image of a QuantilesDoublesSketch.
    +
    + + +
    +
    Returns an updatable Union object that wraps the given MemorySegment that contains an image of a QuantilesDoublesSketch.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      QuantilesDoublesUnion

      +
      +
      public QuantilesDoublesUnion()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      builder

      +
      +
      public static QuantilesDoublesUnionBuilder builder()
      +
      Returns a new UnionBuilder
      +
      +
      Returns:
      +
      a new UnionBuilder
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static QuantilesDoublesUnion heapify(QuantilesDoublesSketch sketch)
      +
      Returns a Heap Union object that has been initialized with the data from the given sketch.
      +
      +
      Parameters:
      +
      sketch - A QuantilesDoublesSketch to be used as a source of data only and will not be modified.
      +
      Returns:
      +
      a QuantilesDoublesUnion object
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static QuantilesDoublesUnion heapify(MemorySegment srcSeg)
      +
      Returns a Heap Union object that has been initialized with the data from the given MemorySegment that contains an +image of a sketch.
      +
      +
      Parameters:
      +
      srcSeg - A MemorySegment image of a QuantilesDoublesSketch to be used as a source of data and will not be modified.
      +
      Returns:
      +
      a Union object
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static QuantilesDoublesUnion wrap(MemorySegment srcSeg)
      +
      Returns an updatable Union object that wraps the given MemorySegment that contains an image of a QuantilesDoublesSketch.
      +
      +
      Parameters:
      +
      srcSeg - A MemorySegment image of an updatable QuantilesDoublesSketch to be used as the data structure for the union +and will be modified.
      +
      Returns:
      +
      a Union object
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static QuantilesDoublesUnion wrap(MemorySegment srcSeg, + MemorySegmentRequest mSegReq)
      +
      Returns an updatable Union object that wraps the given MemorySegment that contains an image of a QuantilesDoublesSketch.
      +
      +
      Parameters:
      +
      srcSeg - A MemorySegment sketch to be used as the data structure for the union and will be modified.
      +
      mSegReq - the MemorySegmentRequest used if the given MemorySegment needs to expand. +Otherwise, it can be null and the default MemorySegmentRequest will be used.
      +
      Returns:
      +
      a Union object
      +
      +
      +
      +
    • +
    • +
      +

      hasMemorySegment

      +
      +
      public abstract boolean hasMemorySegment()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
      +
      +
      Specified by:
      +
      hasMemorySegment in interface MemorySegmentStatus
      +
      Returns:
      +
      true if this object's internal data is backed by a MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isOffHeap

      +
      +
      public abstract boolean isOffHeap()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      Specified by:
      +
      isOffHeap in interface MemorySegmentStatus
      +
      Returns:
      +
      true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isSameResource

      +
      +
      public abstract boolean isSameResource(MemorySegment that)
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap. This applies to both on-heap and off-heap MemorySegments. + +

      Note: If both segments are on-heap and not read-only, it can be determined if they were derived from +the same backing memory (array). However, this is not always possible off-heap. Because of this asymmetry, this definition +of "isSameResource" is confined to the existence of an overlap.

      +
      +
      Specified by:
      +
      isSameResource in interface MemorySegmentStatus
      +
      Parameters:
      +
      that - The given MemorySegment.
      +
      Returns:
      +
      true if an internally referenced MemorySegment has the same backing resource as that.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public abstract boolean isEmpty()
      +
      Returns true if this union is empty
      +
      +
      Returns:
      +
      true if this union is empty
      +
      +
      +
      +
    • +
    • +
      +

      getMaxK

      +
      +
      public abstract int getMaxK()
      +
      Returns the configured maxK of this Union.
      +
      +
      Returns:
      +
      the configured maxK of this Union.
      +
      +
      +
      +
    • +
    • +
      +

      getEffectiveK

      +
      +
      public abstract int getEffectiveK()
      +
      Returns the effective k of this Union.
      +
      +
      Returns:
      +
      the effective k of this Union.
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public abstract void union(QuantilesDoublesSketch sketchIn)
      +
      Iterative union operation, which means this method can be repeatedly called. +Merges the given sketch into this union object. +The given sketch is not modified. +It is required that the ratio of the two K's be a power of 2. +This is easily satisfied if each of the K's are already a power of 2. +If the given sketch is null or empty it is ignored. + +

      It is required that the results of the union operation, which can be obtained at any time, +is obtained from getResult().

      +
      +
      Parameters:
      +
      sketchIn - the sketch to be merged into this one.
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public abstract void union(MemorySegment seg)
      +
      Iterative union operation, which means this method can be repeatedly called. +Merges the given MemorySegment image of a QuantilesDoublesSketch into this union object. +The given MemorySegment object is not modified and a link to it is not retained. +It is required that the ratio of the two K's be a power of 2. +This is easily satisfied if each of the K's are already a power of 2. +If the given sketch is null or empty it is ignored. + +

      It is required that the results of the union operation, which can be obtained at any time, +is obtained from getResult().

      +
      +
      Parameters:
      +
      seg - MemorySegment image of sketch to be merged
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public abstract void update(double dataItem)
      +
      Update this union with the given double (or float) data Item.
      +
      +
      Parameters:
      +
      dataItem - The given double datum.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public abstract UpdatableQuantilesDoublesSketch getResult()
      +
      Gets the result of this Union as an UpdatableQuantilesDoublesSketch, which enables further update +operations on the resulting sketch. The Union state has not been changed, which allows +further union operations.
      +
      +
      Returns:
      +
      the result of this Union operation
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public abstract UpdatableQuantilesDoublesSketch getResult(MemorySegment dstSeg, + MemorySegmentRequest mSegReq)
      +
      Places the result of this Union into the provided MemorySegment as an UpdatableQuantilesDoublesSketch, +which enables further update operations on the resulting sketch. The Union state has not +been changed, which allows further union operations.
      +
      +
      Parameters:
      +
      dstSeg - the destination MemorySegment for the result
      +
      mSegReq - the MemorySegmentRequest used if the given MemorySegment needs to expand. +Otherwise, it can be null and the default MemorySegmentRequest will be used.
      +
      Returns:
      +
      the result of this Union operation
      +
      +
      +
      +
    • +
    • +
      +

      getResultAndReset

      +
      +
      public abstract UpdatableQuantilesDoublesSketch getResultAndReset()
      +
      Gets the result of this Union as an UpdatableQuantilesDoublesSketch, which enables further update +operations on the resulting sketch. The Union is reset to the virgin state.
      +
      +
      Returns:
      +
      the result of this Union operation and reset.
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public abstract void reset()
      +
      Resets this Union to a virgin state.
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public abstract byte[] toByteArray()
      +
      Serialize this union to a byte array. Result is an UpdatableQuantilesDoublesSketch, serialized in an +unordered, non-compact form. The resulting byte[] can be heapified or wrapped as either a +sketch or a union.
      +
      +
      Returns:
      +
      byte array of this union
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public abstract String toString()
      +
      Returns summary information about the backing sketch.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public abstract String toString(boolean sketchSummary, + boolean dataDetail)
      +
      Returns summary information about the backing sketch. Used for debugging.
      +
      +
      Parameters:
      +
      sketchSummary - if true includes sketch summary
      +
      dataDetail - if true includes data detail
      +
      Returns:
      +
      summary information about the sketch.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesUnionBuilder.html b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesUnionBuilder.html new file mode 100644 index 000000000..2f4c3761e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesDoublesUnionBuilder.html @@ -0,0 +1,261 @@ + + + + +QuantilesDoublesUnionBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class QuantilesDoublesUnionBuilder

+
+
java.lang.Object +
org.apache.datasketches.quantiles.QuantilesDoublesUnionBuilder
+
+
+
+
+
public class QuantilesDoublesUnionBuilder +extends Object
+
For building a new QuantilesDoublesSketch Union operation.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      QuantilesDoublesUnionBuilder

      +
      +
      public QuantilesDoublesUnionBuilder()
      +
      Constructor for a new QuantilesDoublesUnionBuilder. The default configuration is +
        +
      • k: 128. This produces a normalized rank error of about 1.7%
      • +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      setMaxK

      +
      +
      public QuantilesDoublesUnionBuilder setMaxK(int maxK)
      +
      Sets the parameter masK that determines the maximum size of the sketch that +results from a union and its accuracy.
      +
      +
      Parameters:
      +
      maxK - determines the accuracy and size of the union and is a maximum. +The effective k can be smaller due to unions with smaller k sketches. +It is recommended that maxK be a power of 2 to enable unioning of sketches with +different k.
      +
      Returns:
      +
      this builder
      +
      +
      +
      +
    • +
    • +
      +

      getMaxK

      +
      +
      public int getMaxK()
      +
      Gets the current configured maxK
      +
      +
      Returns:
      +
      the current configured maxK
      +
      +
      +
      +
    • +
    • +
      +

      build

      +
      +
      public QuantilesDoublesUnion build()
      +
      Returns a new empty Union object with the current configuration of this Builder.
      +
      +
      Returns:
      +
      a Union object
      +
      +
      +
      +
    • +
    • +
      +

      build

      +
      +
      public QuantilesDoublesUnion build(MemorySegment dstSeg, + MemorySegmentRequest mSegReq)
      +
      Returns a new empty Union object with the current configuration of this Builder +and the specified backing destination MemorySegment store.
      +
      +
      Parameters:
      +
      dstSeg - the destination MemorySegment
      +
      mSegReq - the MemorySegmentRequest used if the given MemorySegment needs to expand. +Otherwise, it can be null and the default MemorySegmentRequest will be used.
      +
      Returns:
      +
      a Union object
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesItemsSketch.html b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesItemsSketch.html new file mode 100644 index 000000000..9ad82c659 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesItemsSketch.html @@ -0,0 +1,1338 @@ + + + + +QuantilesItemsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class QuantilesItemsSketch<T>

+
+
java.lang.Object +
org.apache.datasketches.quantiles.QuantilesItemsSketch<T>
+
+
+
+
Type Parameters:
+
T - The sketch item data type.
+
+
+
All Implemented Interfaces:
+
PartitioningFeature<T>, QuantilesAPI, QuantilesGenericAPI<T>, SketchPartitionLimits
+
+
+
+
public final class QuantilesItemsSketch<T> +extends Object +implements QuantilesGenericAPI<T>
+
This is an implementation of the Low Discrepancy Mergeable Quantiles Sketch, using generic items, +described in section 3.2 of the journal version of the paper "Mergeable Summaries" +by Agarwal, Cormode, Huang, Phillips, Wei, and Yi: + +

Reference:

+ +

A k of 128 produces a normalized, rank error of about 1.7%. +For example, the median returned from getQuantile(0.5) will be between the actual quantiles +from the hypothetically sorted array of input quantiles at normalized ranks of 0.483 and 0.517, with +a confidence of about 99%.

+ +

The size of an QuantilesItemsSketch is very dependent on the size of the generic Items input into the sketch, +so there is no comparable size table as there is for the QuantilesDoublesSketch.

+
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      rand

      +
      +
      public static final Random rand
      +
      Setting the seed makes the results of the sketch deterministic if the input items are +received in exactly the same order. This is only useful when performing test comparisons, +otherwise, it is not recommended.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getInstance

      +
      +
      public static <T> QuantilesItemsSketch<T> getInstance(Class<T> clazz, + Comparator<? super T> comparator)
      +
      Obtains a new instance of an QuantilesItemsSketch using the DEFAULT_K.
      +
      +
      Type Parameters:
      +
      T - The sketch item data type.
      +
      Parameters:
      +
      clazz - the given class of T.
      +
      comparator - to compare items.
      +
      Returns:
      +
      an ItemSketch<T>.
      +
      +
      +
      +
    • +
    • +
      +

      getInstance

      +
      +
      public static <T> QuantilesItemsSketch<T> getInstance(Class<T> clazz, + int k, + Comparator<? super T> comparator)
      +
      Obtains a new instance of an QuantilesItemsSketch using the given k.
      +
      +
      Type Parameters:
      +
      T - The sketch item data type.
      +
      Parameters:
      +
      clazz - the given class of T.
      +
      k - Parameter that controls space usage of sketch and accuracy of estimates. +Must be greater than 2 and less than 65536 and a power of 2.
      +
      comparator - to compare items.
      +
      Returns:
      +
      an ItemSketch<T>.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static <T> QuantilesItemsSketch<T> heapify(Class<T> clazz, + MemorySegment srcSeg, + Comparator<? super T> comparator, + ArrayOfItemsSerDe<T> serDe)
      +
      Heapifies the given srcSeg, which must be a MemorySegment image of a QuantilesItemsSketch.
      +
      +
      Type Parameters:
      +
      T - The sketch item data type.
      +
      Parameters:
      +
      clazz - the given class of T.
      +
      srcSeg - a MemorySegment image of a sketch generated from this class.
      +
      comparator - to compare items.
      +
      serDe - an instance of ArrayOfItemsSerDe.
      +
      Returns:
      +
      a QuantilesItemsSketch<T> on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      getCDF

      +
      +
      public double[] getCDF(T[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Specified by:
      +
      getCDF in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getClassOfT

      +
      +
      public Class<T> getClassOfT()
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Returns the sketch item class
      +
      +
      Specified by:
      +
      getClassOfT in interface QuantilesGenericAPI<T>
      +
      Returns:
      +
      the sketch item class
      +
      +
      +
      +
    • +
    • +
      +

      getComparator

      +
      +
      public Comparator<? super T> getComparator()
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Returns the Comparator of T
      +
      +
      Specified by:
      +
      getComparator in interface QuantilesGenericAPI<T>
      +
      Returns:
      +
      Comparator of the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      public T getMaxItem()
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Returns the maximum item of the stream. This may be distinct from the largest item retained by the +sketch algorithm.
      +
      +
      Specified by:
      +
      getMaxItem in interface QuantilesGenericAPI<T>
      +
      Returns:
      +
      the maximum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      public T getMinItem()
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Returns the minimum item of the stream. This may be distinct from the smallest item retained by the +sketch algorithm.
      +
      +
      Specified by:
      +
      getMinItem in interface QuantilesGenericAPI<T>
      +
      Returns:
      +
      the minimum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getPartitionBoundariesFromNumParts

      +
      +
      public GenericPartitionBoundaries<T> getPartitionBoundariesFromNumParts(int numEquallySizedParts, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: PartitioningFeature
      +
      This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition. + +

      The sketch must not be empty.

      +
      +
      Specified by:
      +
      getPartitionBoundariesFromNumParts in interface PartitioningFeature<T>
      +
      Parameters:
      +
      numEquallySizedParts - an integer that specifies the number of equally sized partitions between +getMinItem() and +getMaxItem(). +This must be a positive integer less than +getMaxPartitions() +
        +
      • A 1 will return: minItem, maxItem.
      • +
      • A 2 will return: minItem, median quantile, maxItem.
      • +
      • Etc.
      • +
      +
      searchCrit - If INCLUSIVE, all the returned quantiles are the upper boundaries of the equally sized partitions +with the exception of the lowest returned quantile, which is the lowest boundary of the lowest ranked partition. +If EXCLUSIVE, all the returned quantiles are the lower boundaries of the equally sized partitions +with the exception of the highest returned quantile, which is the upper boundary of the highest ranked partition.
      +
      Returns:
      +
      an instance of GenericPartitionBoundaries.
      +
      +
      +
      +
    • +
    • +
      +

      getPartitionBoundariesFromPartSize

      +
      +
      public GenericPartitionBoundaries<T> getPartitionBoundariesFromPartSize(long nominalPartSizeItems, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: PartitioningFeature
      +
      This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition. + +

      The sketch must not be empty.

      +
      +
      Specified by:
      +
      getPartitionBoundariesFromPartSize in interface PartitioningFeature<T>
      +
      Parameters:
      +
      nominalPartSizeItems - an integer that specifies the nominal size, in items, of each target partition. +This must be a positive integer greater than +getMinPartitionSizeItems().
      +
      searchCrit - If INCLUSIVE, all the returned quantiles are the upper boundaries of the equally sized partitions +with the exception of the lowest returned quantile, which is the lowest boundary of the lowest ranked partition. +If EXCLUSIVE, all the returned quantiles are the lower boundaries of the equally sized partitions +with the exception of the highest returned quantile, which is the upper boundary of the highest ranked partition.
      +
      Returns:
      +
      an instance of GenericPartitionBoundaries.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      public double[] getPMF(T[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Specified by:
      +
      getPMF in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public T getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileLowerBound

      +
      +
      public T getQuantileLowerBound(double rank)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile confidence interval +as an additive or multiplicative percent of the true quantile.

      +
      +
      Specified by:
      +
      getQuantileLowerBound in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileUpperBound

      +
      +
      public T getQuantileUpperBound(double rank)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile interval +as an additive or multiplicative percent of the true quantile.

      +
      +
      Specified by:
      +
      getQuantileUpperBound in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      public T[] getQuantiles(double[] ranks, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets an array of quantiles from the given array of normalized ranks.
      +
      +
      Specified by:
      +
      getQuantiles in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      searchCrit - if INCLUSIVE, the given ranks include all quantiles ≤ +the quantile directly corresponding to each rank.
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      public double getRank(T quantile, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Specified by:
      +
      getRank in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRankLowerBound

      +
      +
      public double getRankLowerBound(double rank)
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      Specified by:
      +
      getRankLowerBound in interface QuantilesAPI
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRankUpperBound

      +
      +
      public double getRankUpperBound(double rank)
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      Specified by:
      +
      getRankUpperBound in interface QuantilesAPI
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      public double[] getRanks(T[] quantiles, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
      +
      +
      Specified by:
      +
      getRanks in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      searchCrit - if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile.
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets the iterator for this sketch, which is not sorted.
      +
      +
      Specified by:
      +
      iterator in interface QuantilesGenericAPI<T>
      +
      Returns:
      +
      the iterator for this sketch
      +
      +
      +
      +
    • +
    • +
      +

      getK

      +
      +
      public int getK()
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the user configured parameter k, which controls the accuracy of the sketch +and its memory space usage.
      +
      +
      Specified by:
      +
      getK in interface QuantilesAPI
      +
      Returns:
      +
      the user configured parameter k, which controls the accuracy of the sketch +and its memory space usage.
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      public long getN()
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the length of the input stream offered to the sketch..
      +
      +
      Specified by:
      +
      getN in interface QuantilesAPI
      +
      Specified by:
      +
      getN in interface SketchPartitionLimits
      +
      Returns:
      +
      the length of the input stream offered to the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNormalizedRankError

      +
      +
      public double getNormalizedRankError(boolean pmf)
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the approximate rank error of this sketch normalized as a fraction between zero and one. +The epsilon returned is a best fit to 99 percent confidence empirically measured max error +in thousands of trials.
      +
      +
      Specified by:
      +
      getNormalizedRankError in interface QuantilesAPI
      +
      Parameters:
      +
      pmf - if true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      Returns:
      +
      if pmf is true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      +
      +
      +
    • +
    • +
      +

      getNormalizedRankError

      +
      +
      public static double getNormalizedRankError(int k, + boolean pmf)
      +
      Gets the normalized rank error given k and pmf. +Static method version of the getNormalizedRankError(boolean).
      +
      +
      Parameters:
      +
      k - the configuration parameter
      +
      pmf - if true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      Returns:
      +
      if pmf is true, the normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      +
      +
      +
    • +
    • +
      +

      getKFromEpsilon

      +
      +
      public static int getKFromEpsilon(double epsilon, + boolean pmf)
      +
      Gets the approximate k to use given epsilon, the normalized rank error.
      +
      +
      Parameters:
      +
      epsilon - the normalized rank error between zero and one.
      +
      pmf - if true, this function returns k assuming the input epsilon +is the desired "double-sided" epsilon for the getPMF() function. Otherwise, this function +returns k assuming the input epsilon is the desired "single-sided" +epsilon for all the other queries.
      +
      Returns:
      +
      k given epsilon.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is empty.
      +
      +
      Specified by:
      +
      isEmpty in interface QuantilesAPI
      +
      Returns:
      +
      true if this sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      isEstimationMode

      +
      +
      public boolean isEstimationMode()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is in estimation mode.
      +
      +
      Specified by:
      +
      isEstimationMode in interface QuantilesAPI
      +
      Returns:
      +
      true if this sketch is in estimation mode.
      +
      +
      +
      +
    • +
    • +
      +

      isReadOnly

      +
      +
      public boolean isReadOnly()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is read only.
      +
      +
      Specified by:
      +
      isReadOnly in interface QuantilesAPI
      +
      Returns:
      +
      true if this sketch is read only.
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Description copied from interface: QuantilesAPI
      +
      Resets this sketch to the empty state. +If the sketch is read only this does nothing. + +

      The parameter k will not change.

      +
      +
      Specified by:
      +
      reset in interface QuantilesAPI
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<T> serDe)
      +
      Serialize this sketch to a byte array form.
      +
      +
      Parameters:
      +
      serDe - an instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      byte array of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(boolean ordered, + ArrayOfItemsSerDe<T> serDe)
      +
      Serialize this sketch to a byte array form.
      +
      +
      Parameters:
      +
      ordered - if true the base buffer will be ordered (default == false).
      +
      serDe - an instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      this sketch in a byte array form.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns human readable summary information about this sketch. +Used for debugging.
      +
      +
      Specified by:
      +
      toString in interface QuantilesAPI
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      a summary of the key parameters of the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean withLevels, + boolean withLevelsAndItems)
      +
      Returns human readable summary information about this sketch. +Used for debugging.
      +
      +
      Parameters:
      +
      withLevels - if true includes sketch levels array summary information
      +
      withLevelsAndItems - if true include detail of levels array and items array together
      +
      Returns:
      +
      human readable summary information about this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(byte[] byteArr)
      +
      Returns a human readable string of the preamble of a byte array image of an QuantilesItemsSketch. +Used for debugging.
      +
      +
      Parameters:
      +
      byteArr - the given byte array
      +
      Returns:
      +
      a human readable string of the preamble of a byte array image of an QuantilesItemsSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(MemorySegment seg)
      +
      Returns a human readable string of the preamble of a MemorySegment image of an QuantilesItemsSketch. +Used for debugging.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      a human readable string of the preamble of a MemorySegment image of an QuantilesItemsSketch.
      +
      +
      +
      +
    • +
    • +
      +

      downSample

      +
      +
      public QuantilesItemsSketch<T> downSample(int newK)
      +
      From an existing sketch, this creates a new sketch that can have a smaller K. +The original sketch is not modified.
      +
      +
      Parameters:
      +
      newK - the new K that must be smaller than current K. +It is required that this.getK() = newK * 2^(nonnegative integer).
      +
      Returns:
      +
      the new sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNumRetained

      +
      +
      public int getNumRetained()
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the number of quantiles retained by the sketch.
      +
      +
      Specified by:
      +
      getNumRetained in interface QuantilesAPI
      +
      Returns:
      +
      the number of quantiles retained by the sketch
      +
      +
      +
      +
    • +
    • +
      +

      putIntoMemorySegment

      +
      +
      public void putIntoMemorySegment(MemorySegment dstSeg, + ArrayOfItemsSerDe<T> serDe)
      +
      Puts the current sketch into the given MemorySegment if there is sufficient space. +Otherwise, throws an error.
      +
      +
      Parameters:
      +
      dstSeg - the given MemorySegment.
      +
      serDe - an instance of ArrayOfItemsSerDe
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(T item)
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Updates this sketch with the given item.
      +
      +
      Specified by:
      +
      update in interface QuantilesGenericAPI<T>
      +
      Parameters:
      +
      item - from a stream of items. Nulls are ignored.
      +
      +
      +
      +
    • +
    • +
      +

      getSortedView

      +
      +
      public ItemsSketchSortedView<T> getSortedView()
      +
      Description copied from interface: QuantilesGenericAPI
      +
      Gets the sorted view of this sketch
      +
      +
      Specified by:
      +
      getSortedView in interface QuantilesGenericAPI<T>
      +
      Returns:
      +
      the sorted view of this sketch
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesItemsSketchIterator.html b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesItemsSketchIterator.html new file mode 100644 index 000000000..75a7c8471 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesItemsSketchIterator.html @@ -0,0 +1,207 @@ + + + + +QuantilesItemsSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class QuantilesItemsSketchIterator<T>

+
+
java.lang.Object +
org.apache.datasketches.quantiles.QuantilesItemsSketchIterator<T>
+
+
+
+
Type Parameters:
+
T - type of item
+
+
+
All Implemented Interfaces:
+
QuantilesGenericSketchIteratorAPI<T>, QuantilesSketchIteratorAPI
+
+
+
+
public final class QuantilesItemsSketchIterator<T> +extends Object +implements QuantilesGenericSketchIteratorAPI<T>
+
Iterator over QuantilesItemsSketch. The order is not defined.
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Gets the generic quantile at the current index.
    +
    +
    long
    + +
    +
    Gets the natural weight at the current index.
    +
    +
    boolean
    + +
    +
    Advances the index and checks if it is valid.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      public T getQuantile()
      +
      Description copied from interface: QuantilesGenericSketchIteratorAPI
      +
      Gets the generic quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesGenericSketchIteratorAPI<T>
      +
      Returns:
      +
      the generic quantile at the current index.
      +
      +
      +
      +
    • +
    • +
      +

      getWeight

      +
      +
      public long getWeight()
      +
      Description copied from interface: QuantilesSketchIteratorAPI
      +
      Gets the natural weight at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Specified by:
      +
      getWeight in interface QuantilesSketchIteratorAPI
      +
      Returns:
      +
      the natural weight at the current index.
      +
      +
      +
      +
    • +
    • +
      +

      next

      +
      +
      public boolean next()
      +
      Description copied from interface: QuantilesSketchIteratorAPI
      +
      Advances the index and checks if it is valid. +The state of this iterator is undefined before the first call of this method.
      +
      +
      Specified by:
      +
      next in interface QuantilesSketchIteratorAPI
      +
      Returns:
      +
      true if the next index is valid.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesItemsUnion.html b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesItemsUnion.html new file mode 100644 index 000000000..762556350 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/QuantilesItemsUnion.html @@ -0,0 +1,499 @@ + + + + +QuantilesItemsUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class QuantilesItemsUnion<T>

+
+
java.lang.Object +
org.apache.datasketches.quantiles.QuantilesItemsUnion<T>
+
+
+
+
Type Parameters:
+
T - The sketch item data type.
+
+
+
+
public final class QuantilesItemsUnion<T> +extends Object
+
The API for Union operations for generic QuantilesItemsSketches
+
+
Author:
+
Lee Rhodes, Alexander Saydakov
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getInstance

      +
      +
      public static <T> QuantilesItemsUnion<T> getInstance(Class<T> clazz, + Comparator<? super T> comparator)
      +
      Create an instance of QuantilesItemsUnion with the default k.
      +
      +
      Type Parameters:
      +
      T - The sketch item data type.
      +
      Parameters:
      +
      clazz - The sketch class type.
      +
      comparator - to compare items.
      +
      Returns:
      +
      a new instance of QuantilesItemsUnion
      +
      +
      +
      +
    • +
    • +
      +

      getInstance

      +
      +
      public static <T> QuantilesItemsUnion<T> getInstance(Class<T> clazz, + int maxK, + Comparator<? super T> comparator)
      +
      Create an instance of QuantilesItemsUnion
      +
      +
      Type Parameters:
      +
      T - The sketch item data type.
      +
      Parameters:
      +
      clazz - The sketch class type.
      +
      maxK - determines the accuracy and size of the union and is a maximum. +The effective k can be smaller due to unions with smaller k sketches. +maxK must be a power of 2 to enable unioning of sketches with a different k.
      +
      comparator - to compare items.
      +
      Returns:
      +
      an new instance of QuantilesItemsUnion
      +
      +
      +
      +
    • +
    • +
      +

      initializeWithMemorySegment

      +
      +
      public static <T> QuantilesItemsUnion<T> initializeWithMemorySegment(Class<T> clazz, + MemorySegment srcSeg, + Comparator<? super T> comparator, + ArrayOfItemsSerDe<T> serDe)
      +
      Initialize a new QuantilesItemsUnion with a heapified instance of an QuantilesItemsSketch from a MemorySegment.
      +
      +
      Type Parameters:
      +
      T - The sketch data type.
      +
      Parameters:
      +
      clazz - The sketch class type.
      +
      srcSeg - the given srcSeg, an image of an QuantilesItemsSketch. A reference to srcSeg will not be maintained internally.
      +
      comparator - to compare items.
      +
      serDe - an instance of ArrayOfItemsSerDe.
      +
      Returns:
      +
      an QuantilesItemsUnion initialized with a heapified QuantilesItemsSketch from a MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      initialize

      +
      +
      public static <T> QuantilesItemsUnion<T> initialize(QuantilesItemsSketch<T> sketch)
      +
      Initialize a new QuantilesItemsUnion with an instance of QuantilesItemsSketch
      +
      +
      Type Parameters:
      +
      T - The sketch data type
      +
      Parameters:
      +
      sketch - an instance of QuantilesItemsSketch to initialize this union
      +
      Returns:
      +
      an initialized instance of QuantilesItemsUnion
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public void union(QuantilesItemsSketch<T> sketchIn)
      +
      Iterative union operation, which means this method can be repeatedly called. +Merges the given sketch into this union object. +The given sketch is not modified. +It is required that the ratio of the two K's be a power of 2. +This is easily satisfied if each of the K's are already a power of 2. +If the given sketch is null or empty it is ignored. + +

      It is required that the results of the union operation, which can be obtained at any time, +is obtained from getResult().

      +
      +
      Parameters:
      +
      sketchIn - the sketch to be merged into this one.
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public void union(MemorySegment srcSeg, + ArrayOfItemsSerDe<T> serDe)
      +
      Iterative union operation, which means this method can be repeatedly called. +Merges the given MemorySegment image of a QuantilesItemsSketch into this union object. +The given MemorySegment object is not modified and a link to it is not retained. +It is required that the ratio of the two K's be a power of 2. +This is easily satisfied if each of the K's are already a power of 2. +If the given sketch is null or empty it is ignored. + +

      It is required that the results of the union operation, which can be obtained at any time, +is obtained from getResult().

      +
      +
      Parameters:
      +
      srcSeg - MemorySegment image of sketch to be merged
      +
      serDe - an instance of ArrayOfItemsSerDe
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(T dataItem)
      +
      Update this union with the given dataItem.
      +
      +
      Parameters:
      +
      dataItem - The given datum.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public QuantilesItemsSketch<T> getResult()
      +
      Gets the result of this Union operation as a copy of the internal state. +This enables further union update operations on this state.
      +
      +
      Returns:
      +
      the result of this Union operation
      +
      +
      +
      +
    • +
    • +
      +

      getResultAndReset

      +
      +
      public QuantilesItemsSketch<T> getResultAndReset()
      +
      Gets the sketch result of this Union operation and resets this Union to the virgin state.
      +
      +
      Returns:
      +
      the result of this Union operation and reset.
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this Union to a virgin state. +Keeps maxK, comparator and clazz
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Returns true if this union is empty
      +
      +
      Returns:
      +
      true if this union is empty
      +
      +
      +
      +
    • +
    • +
      +

      getMaxK

      +
      +
      public int getMaxK()
      +
      Returns the configured maxK of this Union.
      +
      +
      Returns:
      +
      the configured maxK of this Union.
      +
      +
      +
      +
    • +
    • +
      +

      getEffectiveK

      +
      +
      public int getEffectiveK()
      +
      Returns the effective k of this Union.
      +
      +
      Returns:
      +
      the effective k of this Union.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns summary information about the backing sketch.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean sketchSummary, + boolean dataDetail)
      +
      Returns summary information about the backing sketch. Used for debugging.
      +
      +
      Parameters:
      +
      sketchSummary - if true includes sketch summary
      +
      dataDetail - if true includes data detail
      +
      Returns:
      +
      summary information about the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<T> serDe)
      +
      Serialize this union to a byte array. Result is an QuantilesItemsSketch, serialized in an +unordered, non-compact form. The resulting byte[] can be passed to getInstance for either a +sketch or union.
      +
      +
      Parameters:
      +
      serDe - an instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      byte array of this union
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/UpdatableQuantilesDoublesSketch.html b/target/site/apidocs/org/apache/datasketches/quantiles/UpdatableQuantilesDoublesSketch.html new file mode 100644 index 000000000..deae676e4 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/UpdatableQuantilesDoublesSketch.html @@ -0,0 +1,299 @@ + + + + +UpdatableQuantilesDoublesSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class UpdatableQuantilesDoublesSketch

+
+
java.lang.Object +
org.apache.datasketches.quantiles.QuantilesDoublesSketch +
org.apache.datasketches.quantiles.UpdatableQuantilesDoublesSketch
+
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus, QuantilesAPI, QuantilesDoublesAPI
+
+
+
+
public abstract class UpdatableQuantilesDoublesSketch +extends QuantilesDoublesSketch
+
Extends QuantilesDoubleSketch
+
+
Author:
+
Jon Malkin
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      wrap

      +
      +
      public static UpdatableQuantilesDoublesSketch wrap(MemorySegment srcSeg)
      +
      Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch. + +

      The given MemorySegment must be writable and it must contain a UpdatableQuantilesDoublesSketch. +The sketch will be updated and managed totally within the MemorySegment. If the given source +MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

      + +

      NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch +will request more capacity using the MemorySegmentRequest interface. The default of this interface will +return a new MemorySegment on the heap.

      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment that contains sketch data.
      +
      Returns:
      +
      an instance of this sketch that wraps the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static UpdatableQuantilesDoublesSketch wrap(MemorySegment srcSeg, + MemorySegmentRequest mSegReq)
      +
      Wrap a sketch around the given source MemorySegment containing sketch data that originated from this sketch and including an +optional, user defined MemorySegmentRequest. + +

      The given MemorySegment must be writable and it must contain a UpdatableQuantilesDoublesSketch. +The sketch will be updated and managed totally within the MemorySegment. If the given source +MemorySegment is created off-heap, then all the management of the sketch's internal data will be off-heap as well.

      + +

      NOTE:If during updating of the sketch the sketch requires more capacity than the given size of the MemorySegment, the sketch +will request more capacity using the MemorySegmentRequest interface. The default of this interface will +return a new MemorySegment on the heap. It is up to the user to optionally extend this interface if more flexible +handling of requests for more capacity is required.

      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment that contains sketch data.
      +
      mSegReq - the MemorySegmentRequest used if the given MemorySegment needs to expand. +Otherwise, it can be null and the default MemorySegmentRequest will be used.
      +
      Returns:
      +
      an instance of this sketch that wraps the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static UpdatableQuantilesDoublesSketch heapify(MemorySegment srcSeg)
      +
      Factory heapify takes a compact sketch image in MemorySegment and instantiates an on-heap sketch. +The resulting sketch will not retain any link to the source MemorySegment.
      +
      +
      Parameters:
      +
      srcSeg - compact MemorySegment image of a sketch serialized by this sketch.
      +
      Returns:
      +
      a heap-based sketch based on the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      compact

      +
      + +
      Returns a CompactQuantilesDoublesSketch of this class
      +
      +
      Returns:
      +
      a CompactQuantilesDoublesSketch of this class
      +
      +
      +
      +
    • +
    • +
      +

      compact

      +
      + +
      Returns a compact version of this sketch. If passing in a MemorySegment object, the compact sketch +will use and load that MemorySegment; otherwise, an on-heap sketch will be returned.
      +
      +
      Parameters:
      +
      dstSeg - An optional target MemorySegment to hold the sketch.
      +
      Returns:
      +
      A compact version of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public abstract void update(double item)
      +
      Description copied from interface: QuantilesDoublesAPI
      +
      Updates this sketch with the given item.
      +
      +
      Parameters:
      +
      item - from a stream of items. NaNs are ignored.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/class-use/ClassicUtil.html b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/ClassicUtil.html new file mode 100644 index 000000000..51e6f2ec1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/ClassicUtil.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.quantiles.ClassicUtil (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantiles.ClassicUtil

+
+No usage of org.apache.datasketches.quantiles.ClassicUtil +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/class-use/CompactQuantilesDoublesSketch.html b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/CompactQuantilesDoublesSketch.html new file mode 100644 index 000000000..2f01de8c2 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/CompactQuantilesDoublesSketch.html @@ -0,0 +1,101 @@ + + + + +Uses of Class org.apache.datasketches.quantiles.CompactQuantilesDoublesSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantiles.CompactQuantilesDoublesSketch

+
+ +
+
Package
+
Description
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesSketch.html b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesSketch.html new file mode 100644 index 000000000..ab36eaa73 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesSketch.html @@ -0,0 +1,160 @@ + + + + +Uses of Class org.apache.datasketches.quantiles.QuantilesDoublesSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantiles.QuantilesDoublesSketch

+
+
Packages that use QuantilesDoublesSketch
+
+
Package
+
Description
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesSketchBuilder.html b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesSketchBuilder.html new file mode 100644 index 000000000..af9476648 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesSketchBuilder.html @@ -0,0 +1,101 @@ + + + + +Uses of Class org.apache.datasketches.quantiles.QuantilesDoublesSketchBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantiles.QuantilesDoublesSketchBuilder

+
+ +
+
Package
+
Description
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesSketchIterator.html b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesSketchIterator.html new file mode 100644 index 000000000..c6a794a2b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesSketchIterator.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.quantiles.QuantilesDoublesSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantiles.QuantilesDoublesSketchIterator

+
+No usage of org.apache.datasketches.quantiles.QuantilesDoublesSketchIterator +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesUnion.html b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesUnion.html new file mode 100644 index 000000000..ca5779a8f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesUnion.html @@ -0,0 +1,125 @@ + + + + +Uses of Class org.apache.datasketches.quantiles.QuantilesDoublesUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantiles.QuantilesDoublesUnion

+
+
Packages that use QuantilesDoublesUnion
+
+
Package
+
Description
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesUnionBuilder.html b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesUnionBuilder.html new file mode 100644 index 000000000..a088db089 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesDoublesUnionBuilder.html @@ -0,0 +1,102 @@ + + + + +Uses of Class org.apache.datasketches.quantiles.QuantilesDoublesUnionBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantiles.QuantilesDoublesUnionBuilder

+
+ +
+
Package
+
Description
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesItemsSketch.html b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesItemsSketch.html new file mode 100644 index 000000000..2f4775832 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesItemsSketch.html @@ -0,0 +1,143 @@ + + + + +Uses of Class org.apache.datasketches.quantiles.QuantilesItemsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantiles.QuantilesItemsSketch

+
+
Packages that use QuantilesItemsSketch
+
+
Package
+
Description
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesItemsSketchIterator.html b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesItemsSketchIterator.html new file mode 100644 index 000000000..ba540df96 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesItemsSketchIterator.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.quantiles.QuantilesItemsSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantiles.QuantilesItemsSketchIterator

+
+No usage of org.apache.datasketches.quantiles.QuantilesItemsSketchIterator +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesItemsUnion.html b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesItemsUnion.html new file mode 100644 index 000000000..772006c04 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/QuantilesItemsUnion.html @@ -0,0 +1,117 @@ + + + + +Uses of Class org.apache.datasketches.quantiles.QuantilesItemsUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantiles.QuantilesItemsUnion

+
+
Packages that use QuantilesItemsUnion
+
+
Package
+
Description
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/class-use/UpdatableQuantilesDoublesSketch.html b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/UpdatableQuantilesDoublesSketch.html new file mode 100644 index 000000000..81bf0f976 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/class-use/UpdatableQuantilesDoublesSketch.html @@ -0,0 +1,145 @@ + + + + +Uses of Class org.apache.datasketches.quantiles.UpdatableQuantilesDoublesSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantiles.UpdatableQuantilesDoublesSketch

+
+ +
+
Package
+
Description
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/package-summary.html b/target/site/apidocs/org/apache/datasketches/quantiles/package-summary.html new file mode 100644 index 000000000..beca93690 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/package-summary.html @@ -0,0 +1,164 @@ + + + + +org.apache.datasketches.quantiles (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.quantiles

+
+
+
+
package org.apache.datasketches.quantiles
+
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
See Also:
+
+ +
+
+
+
+
+
    +
  • + +
  • +
  • +
    +
    Classes
    +
    +
    Class
    +
    Description
    + +
    +
    Utilities for the classic quantiles sketches and independent of the type.
    +
    + +
    +
    Compact sketches are inherently read only.
    +
    + +
    +
    This is an implementation of the Low Discrepancy Mergeable Quantiles Sketch, using doubles, + described in section 3.2 of the journal version of the paper "Mergeable Summaries" + by Agarwal, Cormode, Huang, Phillips, Wei, and Yi:
    +
    + +
    +
    For building a new quantiles QuantilesDoublesSketch.
    +
    + +
    +
    Iterator over QuantilesDoublesSketch.
    +
    + +
    +
    The API for Union operations for QuantilesDoublesSketches
    +
    + +
    +
    For building a new QuantilesDoublesSketch Union operation.
    +
    + +
    +
    This is an implementation of the Low Discrepancy Mergeable Quantiles Sketch, using generic items, +described in section 3.2 of the journal version of the paper "Mergeable Summaries" +by Agarwal, Cormode, Huang, Phillips, Wei, and Yi:
    +
    + +
    +
    Iterator over QuantilesItemsSketch.
    +
    + +
    +
    The API for Union operations for generic QuantilesItemsSketches
    +
    + +
    +
    Extends QuantilesDoubleSketch
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/package-tree.html b/target/site/apidocs/org/apache/datasketches/quantiles/package-tree.html new file mode 100644 index 000000000..1687288d7 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/package-tree.html @@ -0,0 +1,92 @@ + + + + +org.apache.datasketches.quantiles Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.quantiles

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantiles/package-use.html b/target/site/apidocs/org/apache/datasketches/quantiles/package-use.html new file mode 100644 index 000000000..1e5ed19d0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantiles/package-use.html @@ -0,0 +1,124 @@ + + + + +Uses of Package org.apache.datasketches.quantiles (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.quantiles

+
+ +
+
Package
+
Description
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/BinarySearch.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/BinarySearch.html new file mode 100644 index 000000000..170d15fec --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/BinarySearch.html @@ -0,0 +1,260 @@ + + + + +BinarySearch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class BinarySearch

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.BinarySearch
+
+
+
+
+
public final class BinarySearch +extends Object
+
Contains common equality binary search algorithms.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    No argument constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static int
    +
    find(double[] arr, + int low, + int high, + double v)
    +
    +
    Binary Search for the index of the exact double value in the given search range.
    +
    +
    static int
    +
    find(float[] arr, + int low, + int high, + float v)
    +
    +
    Binary Search for the index of the exact float value in the given search range.
    +
    +
    static int
    +
    find(long[] arr, + int low, + int high, + long v)
    +
    +
    Binary Search for the index of the exact long value in the given search range.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      BinarySearch

      +
      +
      public BinarySearch()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      find

      +
      +
      public static int find(float[] arr, + int low, + int high, + float v)
      +
      Binary Search for the index of the exact float value in the given search range. +If -1 is returned there are no values in the search range that equals the given value.
      +
      +
      Parameters:
      +
      arr - The given ordered array to search.
      +
      low - the index of the lowest value of the search range
      +
      high - the index of the highest value of the search range
      +
      v - the value to search for
      +
      Returns:
      +
      return the index of the value, if found, otherwise, return -1;
      +
      +
      +
      +
    • +
    • +
      +

      find

      +
      +
      public static int find(double[] arr, + int low, + int high, + double v)
      +
      Binary Search for the index of the exact double value in the given search range. +If -1 is returned there are no values in the search range that equals the given value.
      +
      +
      Parameters:
      +
      arr - The given ordered array to search.
      +
      low - the index of the lowest value of the search range
      +
      high - the index of the highest value of the search range
      +
      v - the value to search for
      +
      Returns:
      +
      return the index of the value, if found, otherwise, return -1;
      +
      +
      +
      +
    • +
    • +
      +

      find

      +
      +
      public static int find(long[] arr, + int low, + int high, + long v)
      +
      Binary Search for the index of the exact long value in the given search range. +If -1 is returned there are no values in the search range that equals the given value.
      +
      +
      Parameters:
      +
      arr - The given ordered array to search.
      +
      low - the index of the lowest value of the search range
      +
      high - the index of the highest value of the search range
      +
      v - the value to search for
      +
      Returns:
      +
      return the index of the value, if found, otherwise, return -1;
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/DoublesSketchSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/DoublesSketchSortedView.html new file mode 100644 index 000000000..a340b004a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/DoublesSketchSortedView.html @@ -0,0 +1,436 @@ + + + + +DoublesSketchSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class DoublesSketchSortedView

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.DoublesSketchSortedView
+
+
+
+
All Implemented Interfaces:
+
DoublesSortedView, SortedView
+
+
+
+
public final class DoublesSketchSortedView +extends Object +implements DoublesSortedView
+
The SortedView of the Quantiles Classic QuantilesDoublesSketch and the KllDoublesSketch.
+
+
Author:
+
Alexander Saydakov, Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      DoublesSketchSortedView

      +
      +
      public DoublesSketchSortedView(double[] quantiles, + long[] cumWeights, + QuantilesDoublesAPI sk)
      +
      Construct from elements, also used in testing.
      +
      +
      Parameters:
      +
      quantiles - sorted array of quantiles
      +
      cumWeights - sorted, monotonically increasing cumulative weights.
      +
      sk - the underlying quantile sketch.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCumulativeWeights

      +
      +
      public long[] getCumulativeWeights()
      +
      Description copied from interface: SortedView
      +
      Returns the array of cumulative weights from the sketch. +Also known as the natural ranks, which are the Natural Numbers on the interval [1, N].
      +
      +
      Specified by:
      +
      getCumulativeWeights in interface SortedView
      +
      Returns:
      +
      the array of cumulative weights (or natural ranks).
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      public double getMaxItem()
      +
      Description copied from interface: DoublesSortedView
      +
      Returns the maximum item of the stream. This may be distinct from the largest item retained by the +sketch algorithm.
      +
      +
      Specified by:
      +
      getMaxItem in interface DoublesSortedView
      +
      Returns:
      +
      the maximum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      public double getMinItem()
      +
      Description copied from interface: DoublesSortedView
      +
      Returns the minimum item of the stream. This may be distinct from the smallest item retained by the +sketch algorithm.
      +
      +
      Specified by:
      +
      getMinItem in interface DoublesSortedView
      +
      Returns:
      +
      the minimum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      public long getN()
      +
      Description copied from interface: SortedView
      +
      Returns the total number of items presented to the sourcing sketch.
      +
      +
      Specified by:
      +
      getN in interface SortedView
      +
      Returns:
      +
      the total number of items presented to the sourcing sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNumRetained

      +
      +
      public int getNumRetained()
      +
      Description copied from interface: SortedView
      +
      Gets the number of quantiles retained by this sorted view. +This may be slightly different from the function with the same name when called from the originating sketch.
      +
      +
      Specified by:
      +
      getNumRetained in interface SortedView
      +
      Returns:
      +
      the number of quantiles retained by this sorted view
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public double getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: DoublesSortedView
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Specified by:
      +
      getQuantile in interface DoublesSortedView
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      public double[] getQuantiles()
      +
      Description copied from interface: DoublesSortedView
      +
      Returns an array of all retained quantiles by the sketch.
      +
      +
      Specified by:
      +
      getQuantiles in interface DoublesSortedView
      +
      Returns:
      +
      an array of all retained quantiles by the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      public double getRank(double quantile, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: DoublesSortedView
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Specified by:
      +
      getRank in interface DoublesSortedView
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Description copied from interface: SortedView
      +
      Returns true if this sorted view is empty.
      +
      +
      Specified by:
      +
      isEmpty in interface SortedView
      +
      Returns:
      +
      true if this sorted view is empty.
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public DoublesSortedViewIterator iterator()
      +
      Description copied from interface: SortedView
      +
      Returns an iterator for this Sorted View.
      +
      +
      Specified by:
      +
      iterator in interface DoublesSortedView
      +
      Specified by:
      +
      iterator in interface SortedView
      +
      Returns:
      +
      an iterator for this Sorted View.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/DoublesSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/DoublesSortedView.html new file mode 100644 index 000000000..44919dbef --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/DoublesSortedView.html @@ -0,0 +1,405 @@ + + + + +DoublesSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface DoublesSortedView

+
+
+
+
All Superinterfaces:
+
SortedView
+
+
+
All Known Implementing Classes:
+
DoublesSketchSortedView
+
+
+
+
public interface DoublesSortedView +extends SortedView
+
The Sorted View for quantile sketches of primitive type double.
+
+
Author:
+
Alexander Saydakov, Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    default double[]
    +
    getCDF(double[] splitPoints, + QuantileSearchCriteria searchCrit)
    +
    +
    Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
    +
    +
    double
    + +
    +
    Returns the maximum item of the stream.
    +
    +
    double
    + +
    +
    Returns the minimum item of the stream.
    +
    +
    default double[]
    +
    getPMF(double[] splitPoints, + QuantileSearchCriteria searchCrit)
    +
    +
    Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
    +
    +
    double
    +
    getQuantile(double rank, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets the approximate quantile of the given normalized rank and the given search criterion.
    +
    +
    double[]
    + +
    +
    Returns an array of all retained quantiles by the sketch.
    +
    +
    double
    +
    getRank(double quantile, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets the normalized rank corresponding to the given a quantile.
    +
    + + +
    +
    Returns an iterator for this Sorted View.
    +
    +
    +
    +
    +
    +

    Methods inherited from interface SortedView

    +getCumulativeWeights, getN, getNumRetained, isEmpty
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCDF

      +
      +
      default double[] getCDF(double[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      double getMaxItem()
      +
      Returns the maximum item of the stream. This may be distinct from the largest item retained by the +sketch algorithm.
      +
      +
      Returns:
      +
      the maximum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      double getMinItem()
      +
      Returns the minimum item of the stream. This may be distinct from the smallest item retained by the +sketch algorithm.
      +
      +
      Returns:
      +
      the minimum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      default double[] getPMF(double[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      double getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      double[] getQuantiles()
      +
      Returns an array of all retained quantiles by the sketch.
      +
      +
      Returns:
      +
      an array of all retained quantiles by the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      double getRank(double quantile, + QuantileSearchCriteria searchCrit)
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Description copied from interface: SortedView
      +
      Returns an iterator for this Sorted View.
      +
      +
      Specified by:
      +
      iterator in interface SortedView
      +
      Returns:
      +
      an iterator for this Sorted View.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/DoublesSortedViewIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/DoublesSortedViewIterator.html new file mode 100644 index 000000000..8c9a5e321 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/DoublesSortedViewIterator.html @@ -0,0 +1,198 @@ + + + + +DoublesSortedViewIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class DoublesSortedViewIterator

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.SortedViewIterator +
org.apache.datasketches.quantilescommon.DoublesSortedViewIterator
+
+
+
+
+
+
public final class DoublesSortedViewIterator +extends SortedViewIterator
+
Iterator over quantile sketches of primitive type double.
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      DoublesSortedViewIterator

      +
      +
      public DoublesSortedViewIterator(double[] quantiles, + long[] cumWeights)
      +
      Constructor.
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles, which must be ordered.
      +
      cumWeights - the given array of cumulative weights, which must be ordered, start with the value one, and +the last value must be equal to N, the total number of items updated to the sketch.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      public double getQuantile()
      +
      Gets the quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Returns:
      +
      the quantile at the current index.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/FloatsSketchSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/FloatsSketchSortedView.html new file mode 100644 index 000000000..83ad4d30d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/FloatsSketchSortedView.html @@ -0,0 +1,436 @@ + + + + +FloatsSketchSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class FloatsSketchSortedView

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.FloatsSketchSortedView
+
+
+
+
All Implemented Interfaces:
+
FloatsSortedView, SortedView
+
+
+
+
public class FloatsSketchSortedView +extends Object +implements FloatsSortedView
+
The SortedView for the KllFloatsSketch and the ReqSketch.
+
+
Author:
+
Alexander Saydakov, Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      FloatsSketchSortedView

      +
      +
      public FloatsSketchSortedView(float[] quantiles, + long[] cumWeights, + QuantilesFloatsAPI sk)
      +
      Construct Sorted View.
      +
      +
      Parameters:
      +
      quantiles - sorted array of quantiles
      +
      cumWeights - sorted, monotonically increasing cumulative weights.
      +
      sk - the underlying quantile sketch.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCumulativeWeights

      +
      +
      public long[] getCumulativeWeights()
      +
      Description copied from interface: SortedView
      +
      Returns the array of cumulative weights from the sketch. +Also known as the natural ranks, which are the Natural Numbers on the interval [1, N].
      +
      +
      Specified by:
      +
      getCumulativeWeights in interface SortedView
      +
      Returns:
      +
      the array of cumulative weights (or natural ranks).
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      public float getMaxItem()
      +
      Description copied from interface: FloatsSortedView
      +
      Returns the maximum item of the stream. This may be distinct from the largest item retained by the +sketch algorithm.
      +
      +
      Specified by:
      +
      getMaxItem in interface FloatsSortedView
      +
      Returns:
      +
      the maximum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      public float getMinItem()
      +
      Description copied from interface: FloatsSortedView
      +
      Returns the minimum item of the stream. This may be distinct from the smallest item retained by the +sketch algorithm.
      +
      +
      Specified by:
      +
      getMinItem in interface FloatsSortedView
      +
      Returns:
      +
      the minimum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      public long getN()
      +
      Description copied from interface: SortedView
      +
      Returns the total number of items presented to the sourcing sketch.
      +
      +
      Specified by:
      +
      getN in interface SortedView
      +
      Returns:
      +
      the total number of items presented to the sourcing sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNumRetained

      +
      +
      public int getNumRetained()
      +
      Description copied from interface: SortedView
      +
      Gets the number of quantiles retained by this sorted view. +This may be slightly different from the function with the same name when called from the originating sketch.
      +
      +
      Specified by:
      +
      getNumRetained in interface SortedView
      +
      Returns:
      +
      the number of quantiles retained by this sorted view
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public float getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: FloatsSortedView
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Specified by:
      +
      getQuantile in interface FloatsSortedView
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      public float[] getQuantiles()
      +
      Description copied from interface: FloatsSortedView
      +
      Returns an array of all retained quantiles by the sketch.
      +
      +
      Specified by:
      +
      getQuantiles in interface FloatsSortedView
      +
      Returns:
      +
      an array of all retained quantiles by the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      public double getRank(float quantile, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: FloatsSortedView
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Specified by:
      +
      getRank in interface FloatsSortedView
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Description copied from interface: SortedView
      +
      Returns true if this sorted view is empty.
      +
      +
      Specified by:
      +
      isEmpty in interface SortedView
      +
      Returns:
      +
      true if this sorted view is empty.
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public FloatsSortedViewIterator iterator()
      +
      Description copied from interface: SortedView
      +
      Returns an iterator for this Sorted View.
      +
      +
      Specified by:
      +
      iterator in interface FloatsSortedView
      +
      Specified by:
      +
      iterator in interface SortedView
      +
      Returns:
      +
      an iterator for this Sorted View.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/FloatsSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/FloatsSortedView.html new file mode 100644 index 000000000..11e6359c8 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/FloatsSortedView.html @@ -0,0 +1,405 @@ + + + + +FloatsSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface FloatsSortedView

+
+
+
+
All Superinterfaces:
+
SortedView
+
+
+
All Known Implementing Classes:
+
FloatsSketchSortedView
+
+
+
+
public interface FloatsSortedView +extends SortedView
+
The Sorted View for quantiles of primitive type float.
+
+
Author:
+
Alexander Saydakov, Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    default double[]
    +
    getCDF(float[] splitPoints, + QuantileSearchCriteria searchCrit)
    +
    +
    Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
    +
    +
    float
    + +
    +
    Returns the maximum item of the stream.
    +
    +
    float
    + +
    +
    Returns the minimum item of the stream.
    +
    +
    default double[]
    +
    getPMF(float[] splitPoints, + QuantileSearchCriteria searchCrit)
    +
    +
    Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
    +
    +
    float
    +
    getQuantile(double rank, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets the approximate quantile of the given normalized rank and the given search criterion.
    +
    +
    float[]
    + +
    +
    Returns an array of all retained quantiles by the sketch.
    +
    +
    double
    +
    getRank(float quantile, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets the normalized rank corresponding to the given a quantile.
    +
    + + +
    +
    Returns an iterator for this Sorted View.
    +
    +
    +
    +
    +
    +

    Methods inherited from interface SortedView

    +getCumulativeWeights, getN, getNumRetained, isEmpty
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCDF

      +
      +
      default double[] getCDF(float[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      float getMaxItem()
      +
      Returns the maximum item of the stream. This may be distinct from the largest item retained by the +sketch algorithm.
      +
      +
      Returns:
      +
      the maximum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      float getMinItem()
      +
      Returns the minimum item of the stream. This may be distinct from the smallest item retained by the +sketch algorithm.
      +
      +
      Returns:
      +
      the minimum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      default double[] getPMF(float[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      float getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      float[] getQuantiles()
      +
      Returns an array of all retained quantiles by the sketch.
      +
      +
      Returns:
      +
      an array of all retained quantiles by the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      double getRank(float quantile, + QuantileSearchCriteria searchCrit)
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Description copied from interface: SortedView
      +
      Returns an iterator for this Sorted View.
      +
      +
      Specified by:
      +
      iterator in interface SortedView
      +
      Returns:
      +
      an iterator for this Sorted View.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/FloatsSortedViewIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/FloatsSortedViewIterator.html new file mode 100644 index 000000000..68d4eaf5d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/FloatsSortedViewIterator.html @@ -0,0 +1,198 @@ + + + + +FloatsSortedViewIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class FloatsSortedViewIterator

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.SortedViewIterator +
org.apache.datasketches.quantilescommon.FloatsSortedViewIterator
+
+
+
+
+
+
public final class FloatsSortedViewIterator +extends SortedViewIterator
+
Iterator over quantile sketches of primitive type float.
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      FloatsSortedViewIterator

      +
      +
      public FloatsSortedViewIterator(float[] quantiles, + long[] cumWeights)
      +
      Constructor.
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles, which must be ordered.
      +
      cumWeights - the given array of cumulative weights, which must be ordered, start with the value one, and +the last value must be equal to N, the total number of items updated to the sketch.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      public float getQuantile()
      +
      Gets the quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Returns:
      +
      the quantile at the current index.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericInequalitySearch.Inequality.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericInequalitySearch.Inequality.html new file mode 100644 index 000000000..c64a434ed --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericInequalitySearch.Inequality.html @@ -0,0 +1,349 @@ + + + + +GenericInequalitySearch.Inequality (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class GenericInequalitySearch.Inequality

+
+
java.lang.Object +
java.lang.Enum<GenericInequalitySearch.Inequality> +
org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<GenericInequalitySearch.Inequality>, Constable
+
+
+
Enclosing class:
+
GenericInequalitySearch
+
+
+
+
public static enum GenericInequalitySearch.Inequality +extends Enum<GenericInequalitySearch.Inequality>
+
The enumerator of inequalities
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Nested Class Summary

    +
    +

    Nested classes/interfaces inherited from class Enum

    +Enum.EnumDesc<E>
    +
    +
  • + +
  • +
    +

    Enum Constant Summary

    +
    Enum Constants
    +
    +
    Enum Constant
    +
    Description
    + +
    +
    Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the adjacent pair of +values {A,B} such that A ≤ V ≤ B.
    +
    + +
    +
    Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the lowest adjacent pair of +values {A,B} such that A < V ≤ B.
    +Let low = index of the lowest value in the range.
    +Let high = index of the highest value in the range.
    +
    + +
    +
    Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the lowest adjacent pair of +values {A,B} such that A ≤ V < B.
    +Let low = index of the lowest value in the range.
    +Let high = index of the highest value in the range.
    +
    + +
    +
    Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the highest adjacent pair of +values {A,B} such that A ≤ V < B.
    +Let low = index of the lowest value in the range.
    +Let high = index of the highest value in the range.
    +
    + +
    +
    Given a sorted array of increasing values arr[] and a key value v, +this criterion instructs the binary search algorithm to find the highest adjacent pair of +values {A,B} such that A < v ≤ B.
    +Let low = index of the lowest value in the range.
    +Let high = index of the highest value in the range.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Returns the enum constant of this class with the specified name.
    +
    + + +
    +
    Returns an array containing the constants of this enum class, in +the order they are declared.
    +
    +
    +
    +
    + +
    +

    Methods inherited from class Object

    +getClass, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Enum Constant Details

    +
      +
    • +
      +

      LT

      +
      +
      public static final GenericInequalitySearch.Inequality LT
      +
      Given a sorted array of increasing values arr[] and a key value v, +this criterion instructs the binary search algorithm to find the highest adjacent pair of +values {A,B} such that A < v ≤ B.
      +Let low = index of the lowest value in the range.
      +Let high = index of the highest value in the range. + +

      If v > arr[high], return arr[high].
      +If v ≤ arr[low], return -1.
      +Else return index of A.

      +
      +
      +
    • +
    • +
      +

      LE

      +
      +
      public static final GenericInequalitySearch.Inequality LE
      +
      Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the highest adjacent pair of +values {A,B} such that A ≤ V < B.
      +Let low = index of the lowest value in the range.
      +Let high = index of the highest value in the range. + +

      If v ≥ arr[high], return arr[high].
      +If v < arr[low], return -1.
      +Else return index of A.

      +
      +
      +
    • +
    • +
      +

      EQ

      +
      +
      public static final GenericInequalitySearch.Inequality EQ
      +
      Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the adjacent pair of +values {A,B} such that A ≤ V ≤ B. +The returned value from the binary search algorithm will be the index of A or B, +if one of them is equal to V, or -1 if V is not equal to either one.
      +
      +
      +
    • +
    • +
      +

      GE

      +
      +
      public static final GenericInequalitySearch.Inequality GE
      +
      Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the lowest adjacent pair of +values {A,B} such that A < V ≤ B.
      +Let low = index of the lowest value in the range.
      +Let high = index of the highest value in the range. + +

      If v ≤ arr[low], return arr[low].
      +If v > arr[high], return -1.
      +Else return index of B.

      +
      +
      +
    • +
    • +
      +

      GT

      +
      +
      public static final GenericInequalitySearch.Inequality GT
      +
      Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the lowest adjacent pair of +values {A,B} such that A ≤ V < B.
      +Let low = index of the lowest value in the range.
      +Let high = index of the highest value in the range. + +

      If v < arr[low], return arr[low].
      +If v ≥ arr[high], return -1.
      +Else return index of B.

      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static GenericInequalitySearch.Inequality[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static GenericInequalitySearch.Inequality valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericInequalitySearch.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericInequalitySearch.html new file mode 100644 index 000000000..c97bf035b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericInequalitySearch.html @@ -0,0 +1,250 @@ + + + + +GenericInequalitySearch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class GenericInequalitySearch

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.GenericInequalitySearch
+
+
+
+
+
public final class GenericInequalitySearch +extends Object
+
This provides efficient, unique and unambiguous binary searching for inequality comparison criteria +for ordered arrays of values that may include duplicate values. The inequality criteria include +<, ≤, ==, ≥, >. All the inequality criteria use the same search algorithm. +(Although == is not an inequality, it is included for convenience.) + +

In order to make the searching unique and unambiguous, we modified the traditional binary +search algorithm to search for adjacent pairs of values {A, B} in the values array +instead of just a single value, where a and b are the array indices of two +adjacent values in the array. For all the search criteria, when the algorithm has narrowed the +search down to a single value or adjacent pair of values, the resolve() method provides the +final result of the search. If there is no valid value in the array that satisfies the search +criterion, the algorithm will return -1 to the caller.

+ +

Given a sorted array of values arr[] and a search key value v, the algorithms for +the searching criteria are given with each enum criterion.

+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      GenericInequalitySearch

      +
      +
      public GenericInequalitySearch()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      find

      +
      +
      public static <T> int find(T[] arr, + int low, + int high, + T v, + GenericInequalitySearch.Inequality crit, + Comparator<T> comparator)
      +
      Binary Search for the index of the generic value in the given search range that satisfies +the given Inequality criterion. +If -1 is returned there are no values in the search range that satisfy the inequality.
      +
      +
      Type Parameters:
      +
      T - The generic type of value to be used in the search process.
      +
      Parameters:
      +
      arr - the given array of comparable values that must be sorted. +The array must not be null or empty and the values of the array must not be null (or NaN) +in the range [low, high].
      +
      low - the lowest index of the lowest value in the search range, inclusive.
      +
      high - the highest index of the highest value in the search range, inclusive.
      +
      v - the value to search for. It must not be null (or NaN).
      +
      crit - one of the Inequality criteria: LT, LE, EQ, GE, GT. It must not be null.
      +
      comparator - for the type T. +It must not be null. It must return: -1 if A < B, 0 if A == B, and +1 if A > B.
      +
      Returns:
      +
      the index of the value in the given search range that satisfies the Inequality criterion.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericPartitionBoundaries.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericPartitionBoundaries.html new file mode 100644 index 000000000..d6aaf32d1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericPartitionBoundaries.html @@ -0,0 +1,396 @@ + + + + +GenericPartitionBoundaries (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class GenericPartitionBoundaries<T>

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.GenericPartitionBoundaries<T>
+
+
+
+
Type Parameters:
+
T - the item class type
+
+
+
+
public final class GenericPartitionBoundaries<T> +extends Object
+
This defines the returned results of the getParitionBoundaries() function and +includes the basic methods needed to construct actual partitions.
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    +
    GenericPartitionBoundaries(long totalN, + T[] boundaries, + long[] natRanks, + double[] normRanks, + T maxItem, + T minItem, + QuantileSearchCriteria searchCrit)
    +
    +
    Constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    T[]
    + +
    +
    Gets an ordered array of boundaries that sequentially define the upper and lower boundaries of partitions.
    +
    + + +
    +
    Returns the maximum item of the stream.
    +
    + + +
    +
    Returns the minimum item of the stream.
    +
    +
    long
    + +
    +
    Gets the length of the input stream offered to the underlying sketch.
    +
    +
    long[]
    + +
    +
    Gets an ordered array of natural ranks of the associated array of partition boundaries utilizing +a specified search criterion.
    +
    +
    double[]
    + +
    +
    Gets an ordered array of normalized ranks of the associated array of partition boundaries utilizing +a specified search criterion.
    +
    +
    long[]
    + +
    +
    Gets the number of items to be included for each partition as an array.
    +
    +
    int
    + +
    +
    Gets the number of partitions
    +
    + + +
    +
    Gets the search criteria specified for the source sketch
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      GenericPartitionBoundaries

      +
      +
      public GenericPartitionBoundaries(long totalN, + T[] boundaries, + long[] natRanks, + double[] normRanks, + T maxItem, + T minItem, + QuantileSearchCriteria searchCrit)
      +
      Constructor.
      +
      +
      Parameters:
      +
      totalN - the total number of items input to the sketch.
      +
      boundaries - The quantile boundaries between partitions
      +
      natRanks - The array of natural Ranks corresponding to the array of boundaries.
      +
      normRanks - The normalized Ranks corresponding to the array of boundaries.
      +
      maxItem - the maximum item of the stream.
      +
      minItem - the minimum item of the stream.
      +
      searchCrit - the user defined search criteria
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getN

      +
      +
      public long getN()
      +
      Gets the length of the input stream offered to the underlying sketch.
      +
      +
      Returns:
      +
      the length of the input stream offered to the underlying sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getBoundaries

      +
      +
      public T[] getBoundaries()
      +
      Gets an ordered array of boundaries that sequentially define the upper and lower boundaries of partitions. +These partitions are to be constructed by an external process. Each boundary is essentially a reference and +should uniquely identify an item or a set of identical items from the original stream of data fed to the +originating sketch. + +

      Assume boundaries array has size N + 1. Let the indicies be sequentially numbered from 0 to N. +The number of partitions is always one less than the size of the boundaries array. +Let the the partitions be sequentially numbered from 1 to N. + +

      If these results were computed using QuantileSearchCriteria.INCLUSIVE then these sequential boundaries +are to be interpreted as follows: +

        +
      • Partition 1: include all items ≥ index 0 and ≤ index 1.
      • +
      • Partition 2: include all items > index 1 and ≤ index 2.
      • +
      • Partition N: include all items > index N-1 and ≤ index N.
      • +
      + +

      If these results were computed using QuantileSearchCriteria.EXCLUSIVE then these sequential boundaries +are to be interpreted as follows: +

        +
      • Partition 1: include all items ≥ index 0 and < index 1.
      • +
      • Partition 2: include all items ≥ index 1 and < index 2.
      • +
      • Partition N: include all items ≥ index N-1 and ≤ index N.
      • +
      +
      +
      Returns:
      +
      an array of boundaries that sequentially define the upper and lower boundaries of partitions.
      +
      +
      +
      +
    • +
    • +
      +

      getNaturalRanks

      +
      +
      public long[] getNaturalRanks()
      +
      Gets an ordered array of natural ranks of the associated array of partition boundaries utilizing +a specified search criterion. Natural ranks are integral values on the interval [1, N]
      +
      +
      Returns:
      +
      an array of natural ranks.
      +
      +
      +
      +
    • +
    • +
      +

      getNormalizedRanks

      +
      +
      public double[] getNormalizedRanks()
      +
      Gets an ordered array of normalized ranks of the associated array of partition boundaries utilizing +a specified search criterion. Normalized ranks are double values on the interval [0.0, 1.0].
      +
      +
      Returns:
      +
      an array of normalized ranks.
      +
      +
      +
      +
    • +
    • +
      +

      getNumDeltaItems

      +
      +
      public long[] getNumDeltaItems()
      +
      Gets the number of items to be included for each partition as an array. +The count at index 0 is 0. The number of items included in the first partition, defined by the boundaries at +index 0 and index 1, is at index 1 in this array, etc.
      +
      +
      Returns:
      +
      the number of items to be included for each partition as an array.
      +
      +
      +
      +
    • +
    • +
      +

      getNumPartitions

      +
      +
      public int getNumPartitions()
      +
      Gets the number of partitions
      +
      +
      Returns:
      +
      the number of partitions
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      public T getMaxItem()
      +
      Returns the maximum item of the stream. This may be distinct from the largest item retained by the +sketch algorithm.
      +
      +
      Returns:
      +
      the maximum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      public T getMinItem()
      +
      Returns the minimum item of the stream. This may be distinct from the smallest item retained by the +sketch algorithm.
      +
      +
      Returns:
      +
      the minimum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getSearchCriteria

      +
      +
      public QuantileSearchCriteria getSearchCriteria()
      +
      Gets the search criteria specified for the source sketch
      +
      +
      Returns:
      +
      The search criteria specified for the source sketch
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericSortedView.html new file mode 100644 index 000000000..8f08a64f2 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericSortedView.html @@ -0,0 +1,461 @@ + + + + +GenericSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface GenericSortedView<T>

+
+
+
+
Type Parameters:
+
T - The generic quantile type.
+
+
+
All Superinterfaces:
+
PartitioningFeature<T>, SketchPartitionLimits, SortedView
+
+
+
All Known Implementing Classes:
+
ItemsSketchSortedView
+
+
+
+
public interface GenericSortedView<T> +extends PartitioningFeature<T>, SketchPartitionLimits, SortedView
+
The Sorted View for quantiles of generic type.
+
+
Author:
+
Alexander Saydakov, Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCDF

      +
      +
      default double[] getCDF(T[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      If the sketch is empty this returns null.

      + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getComparator

      +
      +
      Comparator<? super T> getComparator()
      +
      Gets the Comparator for this generic type.
      +
      +
      Returns:
      +
      the Comparator for this generic type.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      T getMaxItem()
      +
      Returns the maximum item of the stream. This may be distinct from the largest item retained by the +sketch algorithm.
      +
      +
      Returns:
      +
      the maximum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      T getMinItem()
      +
      Returns the minimum item of the stream. This may be distinct from the smallest item retained by the +sketch algorithm.
      +
      +
      Returns:
      +
      the minimum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      default double[] getPMF(T[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      T getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      T[] getQuantiles()
      +
      Returns the full array of quantiles.
      +
      +
      Returns:
      +
      the full array of quantiles.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      double getRank(T quantile, + QuantileSearchCriteria searchCrit)
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Description copied from interface: SortedView
      +
      Returns an iterator for this Sorted View.
      +
      +
      Specified by:
      +
      iterator in interface SortedView
      +
      Returns:
      +
      an iterator for this Sorted View.
      +
      +
      +
      +
    • +
    • +
      +

      validateItems

      +
      +
      static <T> void validateItems(T[] items, + Comparator<? super T> comparator)
      +
      Checks the sequential validity of the given array of generic items. +They must be unique, monotonically increasing and not null.
      +
      +
      Type Parameters:
      +
      T - the data type
      +
      Parameters:
      +
      items - given array of generic items
      +
      comparator - the comparator for generic item data type T
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericSortedViewIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericSortedViewIterator.html new file mode 100644 index 000000000..620c1285e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/GenericSortedViewIterator.html @@ -0,0 +1,231 @@ + + + + +GenericSortedViewIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class GenericSortedViewIterator<T>

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.SortedViewIterator +
org.apache.datasketches.quantilescommon.GenericSortedViewIterator<T>
+
+
+
+
+
Type Parameters:
+
T - The generic item class type
+
+
+
+
public class GenericSortedViewIterator<T> +extends SortedViewIterator
+
Iterator over quantile sketches of generic type.
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      GenericSortedViewIterator

      +
      +
      public GenericSortedViewIterator(T[] quantiles, + long[] cumWeights)
      +
      Constructor
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      cumWeights - the array of cumulative weights, corresponding to the array of quantiles, +starting with the value one and the end value must equal N, the total number of items input to the sketch.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      public T getQuantile()
      +
      Gets the quantile at the current index +This is equivalent to getQuantile(INCLUSIVE). + +

      Don't call this before calling next() for the first time or after getting false from next().

      +
      +
      Returns:
      +
      the quantile at the current index.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public T getQuantile(QuantileSearchCriteria searchCrit)
      +
      Gets the quantile at the current index (or previous index) +based on the chosen search criterion. + +

      Don't call this before calling next() for the first time or after getting false from next().

      +
      +
      Parameters:
      +
      searchCrit - if INCLUSIVE, includes the quantile at the current index. +Otherwise, returns the quantile of the previous index.
      +
      Returns:
      +
      the quantile at the current index (or previous index) +based on the chosen search criterion. If the chosen search criterion is EXCLUSIVE and +the current index is at zero, this will return null.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.DoublesPair.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.DoublesPair.html new file mode 100644 index 000000000..bc6f0b898 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.DoublesPair.html @@ -0,0 +1,208 @@ + + + + +IncludeMinMax.DoublesPair (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class IncludeMinMax.DoublesPair

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.IncludeMinMax.DoublesPair
+
+
+
+
Enclosing class:
+
IncludeMinMax
+
+
+
+
public static class IncludeMinMax.DoublesPair +extends Object
+
A simple structure to hold a pair of arrays
+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    long[]
    + +
    +
    the array of associated cumulative weights
    +
    +
    double[]
    + +
    +
    the array of quantiles
    +
    +
    +
    +
  • + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    +
    DoublesPair(double[] quantiles, + long[] cumWeights)
    +
    +
    Constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      quantiles

      +
      +
      public double[] quantiles
      +
      the array of quantiles
      +
      +
      +
    • +
    • +
      +

      cumWeights

      +
      +
      public long[] cumWeights
      +
      the array of associated cumulative weights
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      DoublesPair

      +
      +
      public DoublesPair(double[] quantiles, + long[] cumWeights)
      +
      Constructor.
      +
      +
      Parameters:
      +
      quantiles - the array of quantiles
      +
      cumWeights - the array of associated cumulative weights
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.FloatsPair.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.FloatsPair.html new file mode 100644 index 000000000..137b1ea35 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.FloatsPair.html @@ -0,0 +1,208 @@ + + + + +IncludeMinMax.FloatsPair (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class IncludeMinMax.FloatsPair

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.IncludeMinMax.FloatsPair
+
+
+
+
Enclosing class:
+
IncludeMinMax
+
+
+
+
public static class IncludeMinMax.FloatsPair +extends Object
+
A simple structure to hold a pair of arrays
+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    long[]
    + +
    +
    The array of associated cumulative weights
    +
    +
    float[]
    + +
    +
    The array of quantiles
    +
    +
    +
    +
  • + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    +
    FloatsPair(float[] quantiles, + long[] cumWeights)
    +
    +
    Constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      quantiles

      +
      +
      public float[] quantiles
      +
      The array of quantiles
      +
      +
      +
    • +
    • +
      +

      cumWeights

      +
      +
      public long[] cumWeights
      +
      The array of associated cumulative weights
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      FloatsPair

      +
      +
      public FloatsPair(float[] quantiles, + long[] cumWeights)
      +
      Constructor.
      +
      +
      Parameters:
      +
      quantiles - the array of quantiles
      +
      cumWeights - the array of associated cumulative weights
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.ItemsPair.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.ItemsPair.html new file mode 100644 index 000000000..cf03f3bc0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.ItemsPair.html @@ -0,0 +1,212 @@ + + + + +IncludeMinMax.ItemsPair (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class IncludeMinMax.ItemsPair<T>

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.IncludeMinMax.ItemsPair<T>
+
+
+
+
Type Parameters:
+
T - the item class type
+
+
+
Enclosing class:
+
IncludeMinMax
+
+
+
+
public static class IncludeMinMax.ItemsPair<T> +extends Object
+
A simple structure to hold a pair of arrays
+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    long[]
    + +
    +
    The array of associated cumulative weights
    +
    +
    T[]
    + +
    +
    The array of quantiles
    +
    +
    +
    +
  • + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    +
    ItemsPair(T[] quantiles, + long[] cumWeights)
    +
    +
    Constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      quantiles

      +
      +
      public T[] quantiles
      +
      The array of quantiles
      +
      +
      +
    • +
    • +
      +

      cumWeights

      +
      +
      public long[] cumWeights
      +
      The array of associated cumulative weights
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ItemsPair

      +
      +
      public ItemsPair(T[] quantiles, + long[] cumWeights)
      +
      Constructor.
      +
      +
      Parameters:
      +
      quantiles - the array of quantiles
      +
      cumWeights - the array of associated cumulative weights
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.LongsPair.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.LongsPair.html new file mode 100644 index 000000000..33dec11e8 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.LongsPair.html @@ -0,0 +1,208 @@ + + + + +IncludeMinMax.LongsPair (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class IncludeMinMax.LongsPair

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.IncludeMinMax.LongsPair
+
+
+
+
Enclosing class:
+
IncludeMinMax
+
+
+
+
public static class IncludeMinMax.LongsPair +extends Object
+
A simple structure to hold a pair of arrays
+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    long[]
    + +
    +
    the array of associated cumulative weights
    +
    +
    long[]
    + +
    +
    the array of quantiles
    +
    +
    +
    +
  • + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    +
    LongsPair(long[] quantiles, + long[] cumWeights)
    +
    +
    Constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      quantiles

      +
      +
      public long[] quantiles
      +
      the array of quantiles
      +
      +
      +
    • +
    • +
      +

      cumWeights

      +
      +
      public long[] cumWeights
      +
      the array of associated cumulative weights
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      LongsPair

      +
      +
      public LongsPair(long[] quantiles, + long[] cumWeights)
      +
      Constructor.
      +
      +
      Parameters:
      +
      quantiles - the array of quantiles
      +
      cumWeights - the array of associated cumulative weights
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.html new file mode 100644 index 000000000..67ee18191 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/IncludeMinMax.html @@ -0,0 +1,321 @@ + + + + +IncludeMinMax (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class IncludeMinMax

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.IncludeMinMax
+
+
+
+
+
public class IncludeMinMax +extends Object
+
This class reinserts the min and max values into the sorted view arrays as required.
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      IncludeMinMax

      +
      +
      public IncludeMinMax()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      includeDoublesMinMax

      +
      +
      public static IncludeMinMax.DoublesPair includeDoublesMinMax(double[] quantilesIn, + long[] cumWeightsIn, + double maxItem, + double minItem)
      +
      The logic to include the min and max of type double.
      +
      +
      Parameters:
      +
      quantilesIn - The array of quantiles
      +
      cumWeightsIn - The array of associated cumulative weights
      +
      maxItem - the maximum item of the stream
      +
      minItem - the minimum item of the stream
      +
      Returns:
      +
      a DoublesPair
      +
      +
      +
      +
    • +
    • +
      +

      includeLongsMinMax

      +
      +
      public static IncludeMinMax.LongsPair includeLongsMinMax(long[] quantilesIn, + long[] cumWeightsIn, + long maxItem, + long minItem)
      +
      The logic to include the min and max of type double.
      +
      +
      Parameters:
      +
      quantilesIn - The array of quantiles
      +
      cumWeightsIn - The array of associated cumulative weights
      +
      maxItem - the maximum item of the stream
      +
      minItem - the minimum item of the stream
      +
      Returns:
      +
      a DoublesPair
      +
      +
      +
      +
    • +
    • +
      +

      includeFloatsMinMax

      +
      +
      public static IncludeMinMax.FloatsPair includeFloatsMinMax(float[] quantilesIn, + long[] cumWeightsIn, + float maxItem, + float minItem)
      +
      The logic to include the min and max of type float.
      +
      +
      Parameters:
      +
      quantilesIn - The array of quantiles
      +
      cumWeightsIn - The array of associated cumulative weights
      +
      maxItem - the maximum item of the stream
      +
      minItem - the minimum item of the stream
      +
      Returns:
      +
      a FloatsPair
      +
      +
      +
      +
    • +
    • +
      +

      includeItemsMinMax

      +
      +
      public static <T> IncludeMinMax.ItemsPair<T> includeItemsMinMax(T[] quantilesIn, + long[] cumWeightsIn, + T maxItem, + T minItem, + Comparator<? super T> comparator)
      +
      The logic to include the min and max of type T.
      +
      +
      Type Parameters:
      +
      T - the item class type
      +
      Parameters:
      +
      quantilesIn - The array of quantiles
      +
      cumWeightsIn - The array of associated cumulative weights
      +
      maxItem - the maximum item of the stream
      +
      minItem - the minimum item of the stream
      +
      comparator - a comparator for type T
      +
      Returns:
      +
      an ItemsPair
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/InequalitySearch.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/InequalitySearch.html new file mode 100644 index 000000000..3b5450eda --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/InequalitySearch.html @@ -0,0 +1,647 @@ + + + + +InequalitySearch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class InequalitySearch

+
+
java.lang.Object +
java.lang.Enum<InequalitySearch> +
org.apache.datasketches.quantilescommon.InequalitySearch
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<InequalitySearch>, Constable
+
+
+
+
public enum InequalitySearch +extends Enum<InequalitySearch>
+
This provides efficient, unique and unambiguous binary searching for inequality comparison criteria +for ordered arrays of values that may include duplicate values. The inequality criteria include +<, ≤, ==, ≥, >. All the inequality criteria use the same search algorithm. +(Although == is not an inequality, it is included for convenience.) + +

In order to make the searching unique and unambiguous, we modified the traditional binary +search algorithm to search for adjacent pairs of values {A, B} in the values array +instead of just a single value, where a and b are the array indices of two +adjacent values in the array. For all the search criteria, when the algorithm has narrowed the +search down to a single value or adjacent pair of values, the resolve() method provides the +final result of the search. If there is no valid value in the array that satisfies the search +criterion, the algorithm will return -1 to the caller.

+ +

Given a sorted array of values arr[] and a search key value v, the algorithms for +the searching criteria are given with each enum criterion.

+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Nested Class Summary

    +
    +

    Nested classes/interfaces inherited from class Enum

    +Enum.EnumDesc<E>
    +
    +
  • + +
  • +
    +

    Enum Constant Summary

    +
    Enum Constants
    +
    +
    Enum Constant
    +
    Description
    + +
    +
    Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the adjacent pair of +values {A,B} such that A ≤ V ≤ B.
    +
    + +
    +
    Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the lowest adjacent pair of +values {A,B} such that A < V ≤ B.
    +Let low = index of the lowest value in the range.
    +Let high = index of the highest value in the range.
    +
    + +
    +
    Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the lowest adjacent pair of +values {A,B} such that A ≤ V < B.
    +Let low = index of the lowest value in the range.
    +Let high = index of the highest value in the range.
    +
    + +
    +
    Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the highest adjacent pair of +values {A,B} such that A ≤ V < B.
    +Let low = index of the lowest value in the range.
    +Let high = index of the highest value in the range.
    +
    + +
    +
    Given a sorted array of increasing values arr[] and a key value v, +this criterion instructs the binary search algorithm to find the highest adjacent pair of +values {A,B} such that A < v ≤ B.
    +Let low = index of the lowest value in the range.
    +Let high = index of the highest value in the range.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    abstract String
    +
    desc(double[] arr, + int low, + int high, + double v, + int idx)
    +
    +
    Optional call that describes the details of the results of the search.
    +
    +
    abstract String
    +
    desc(float[] arr, + int low, + int high, + float v, + int idx)
    +
    +
    Optional call that describes the details of the results of the search.
    +
    +
    abstract String
    +
    desc(long[] arr, + int low, + int high, + double v, + int idx)
    +
    +
    Optional call that describes the details of the results of the search.
    +
    +
    abstract String
    +
    desc(long[] arr, + int low, + int high, + long v, + int idx)
    +
    +
    Optional call that describes the details of the results of the search.
    +
    +
    static int
    +
    find(double[] arr, + int low, + int high, + double v, + InequalitySearch crit)
    +
    +
    Binary Search for the index of the double value in the given search range that satisfies +the given InequalitySearch criterion.
    +
    +
    static int
    +
    find(float[] arr, + int low, + int high, + float v, + InequalitySearch crit)
    +
    +
    Binary Search for the index of the float value in the given search range that satisfies +the given InequalitySearch criterion.
    +
    +
    static int
    +
    find(long[] arr, + int low, + int high, + double v, + InequalitySearch crit)
    +
    +
    Binary Search for the index of the double value in the given search range that satisfies +the given InequalitySearch criterion.
    +
    +
    static int
    +
    find(long[] arr, + int low, + int high, + long v, + InequalitySearch crit)
    +
    +
    Binary Search for the index of the long value in the given search range that satisfies +the given InequalitySearch criterion.
    +
    + + +
    +
    Returns the enum constant of this class with the specified name.
    +
    + + +
    +
    Returns an array containing the constants of this enum class, in +the order they are declared.
    +
    +
    +
    +
    + +
    +

    Methods inherited from class Object

    +getClass, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Enum Constant Details

    +
      +
    • +
      +

      LT

      +
      +
      public static final InequalitySearch LT
      +
      Given a sorted array of increasing values arr[] and a key value v, +this criterion instructs the binary search algorithm to find the highest adjacent pair of +values {A,B} such that A < v ≤ B.
      +Let low = index of the lowest value in the range.
      +Let high = index of the highest value in the range. + +

      If v > arr[high], return arr[high].
      +If v ≤ arr[low], return -1.
      +Else return index of A.

      +
      +
      +
    • +
    • +
      +

      LE

      +
      +
      public static final InequalitySearch LE
      +
      Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the highest adjacent pair of +values {A,B} such that A ≤ V < B.
      +Let low = index of the lowest value in the range.
      +Let high = index of the highest value in the range. + +

      If v ≥ arr[high], return arr[high].
      +If v < arr[low], return -1.
      +Else return index of A.

      +
      +
      +
    • +
    • +
      +

      EQ

      +
      +
      public static final InequalitySearch EQ
      +
      Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the adjacent pair of +values {A,B} such that A ≤ V ≤ B. +The returned value from the binary search algorithm will be the index of A or B, +if one of them is equal to V, or -1 if V is not equal to either one.
      +
      +
      +
    • +
    • +
      +

      GE

      +
      +
      public static final InequalitySearch GE
      +
      Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the lowest adjacent pair of +values {A,B} such that A < V ≤ B.
      +Let low = index of the lowest value in the range.
      +Let high = index of the highest value in the range. + +

      If v ≤ arr[low], return arr[low].
      +If v > arr[high], return -1.
      +Else return index of B.

      +
      +
      +
    • +
    • +
      +

      GT

      +
      +
      public static final InequalitySearch GT
      +
      Given a sorted array of increasing values arr[] and a key value V, +this criterion instructs the binary search algorithm to find the lowest adjacent pair of +values {A,B} such that A ≤ V < B.
      +Let low = index of the lowest value in the range.
      +Let high = index of the highest value in the range. + +

      If v < arr[low], return arr[low].
      +If v ≥ arr[high], return -1.
      +Else return index of B.

      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static InequalitySearch[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static InequalitySearch valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    • +
      +

      desc

      +
      +
      public abstract String desc(double[] arr, + int low, + int high, + double v, + int idx)
      +
      Optional call that describes the details of the results of the search. +Used primarily for debugging.
      +
      +
      Parameters:
      +
      arr - The underlying sorted array of values
      +
      low - the low index of the range
      +
      high - the high index of the range
      +
      v - the value to search for
      +
      idx - the resolved index from the search
      +
      Returns:
      +
      the descriptive string.
      +
      +
      +
      +
    • +
    • +
      +

      desc

      +
      +
      public abstract String desc(float[] arr, + int low, + int high, + float v, + int idx)
      +
      Optional call that describes the details of the results of the search. +Used primarily for debugging.
      +
      +
      Parameters:
      +
      arr - The underlying sorted array of values
      +
      low - the low index of the range
      +
      high - the high index of the range
      +
      v - the value to search for
      +
      idx - the resolved index from the search
      +
      Returns:
      +
      the descriptive string.
      +
      +
      +
      +
    • +
    • +
      +

      desc

      +
      +
      public abstract String desc(long[] arr, + int low, + int high, + long v, + int idx)
      +
      Optional call that describes the details of the results of the search. +Used primarily for debugging.
      +
      +
      Parameters:
      +
      arr - The underlying sorted array of values
      +
      low - the low index of the range
      +
      high - the high index of the range
      +
      v - the value to search for
      +
      idx - the resolved index from the search
      +
      Returns:
      +
      the descriptive string.
      +
      +
      +
      +
    • +
    • +
      +

      desc

      +
      +
      public abstract String desc(long[] arr, + int low, + int high, + double v, + int idx)
      +
      Optional call that describes the details of the results of the search. +Used primarily for debugging.
      +
      +
      Parameters:
      +
      arr - The underlying sorted array of values
      +
      low - the low index of the range
      +
      high - the high index of the range
      +
      v - the value to search for
      +
      idx - the resolved index from the search
      +
      Returns:
      +
      the descriptive string.
      +
      +
      +
      +
    • +
    • +
      +

      find

      +
      +
      public static int find(double[] arr, + int low, + int high, + double v, + InequalitySearch crit)
      +
      Binary Search for the index of the double value in the given search range that satisfies +the given InequalitySearch criterion. +If -1 is returned there are no values in the search range that satisfy the criterion.
      +
      +
      Parameters:
      +
      arr - the given array of comparable values that must be sorted with increasing values. +The array must not be null and the values of the array must not be NaN in the range [low, high].
      +
      low - the lowest index of the lowest value in the search range, inclusive.
      +
      high - the highest index of the highest value in the search range, inclusive.
      +
      v - the value to search for. It must not be NaN.
      +
      crit - one of the InequalitySearch criteria: LT, LE, EQ, GT, GE. It must not be null.
      +
      Returns:
      +
      the index of the value in the given search range that satisfies the InequalitySearch criterion
      +
      +
      +
      +
    • +
    • +
      +

      find

      +
      +
      public static int find(float[] arr, + int low, + int high, + float v, + InequalitySearch crit)
      +
      Binary Search for the index of the float value in the given search range that satisfies +the given InequalitySearch criterion. +If -1 is returned there are no values in the search range that satisfy the criterion.
      +
      +
      Parameters:
      +
      arr - the given array that must be sorted. +It must not be null and must not contain any NaN values in the range {low, high} inclusive.
      +
      low - the lowest index of the lowest value in the search range, inclusive.
      +
      high - the highest index of the highest value in the search range, inclusive.
      +
      v - the value to search for. It must not be NaN.
      +
      crit - one of LT, LE, EQ, GT, GE
      +
      Returns:
      +
      the index of the value in the given search range that satisfies the criterion
      +
      +
      +
      +
    • +
    • +
      +

      find

      +
      +
      public static int find(long[] arr, + int low, + int high, + long v, + InequalitySearch crit)
      +
      Binary Search for the index of the long value in the given search range that satisfies +the given InequalitySearch criterion. +If -1 is returned there are no values in the search range that satisfy the criterion.
      +
      +
      Parameters:
      +
      arr - the given array that must be sorted.
      +
      low - the lowest index of the lowest value in the search range, inclusive.
      +
      high - the highest index of the highest value in the search range, inclusive.
      +
      v - the value to search for.
      +
      crit - one of LT, LE, EQ, GT, GE
      +
      Returns:
      +
      the index of the value in the given search range that satisfies the criterion
      +
      +
      +
      +
    • +
    • +
      +

      find

      +
      +
      public static int find(long[] arr, + int low, + int high, + double v, + InequalitySearch crit)
      +
      Binary Search for the index of the double value in the given search range that satisfies +the given InequalitySearch criterion. +If -1 is returned there are no values in the search range that satisfy the criterion.
      +
      +
      Parameters:
      +
      arr - the given array that must be sorted.
      +
      low - the lowest index of the lowest value in the search range, inclusive.
      +
      high - the highest index of the highest value in the search range, inclusive.
      +
      v - the value to search for.
      +
      crit - one of LT, LE, EQ, GT, GE
      +
      Returns:
      +
      the index of the value in the given search range that satisfies the criterion
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/ItemsSketchSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/ItemsSketchSortedView.html new file mode 100644 index 000000000..a6462d03f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/ItemsSketchSortedView.html @@ -0,0 +1,606 @@ + + + + +ItemsSketchSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ItemsSketchSortedView<T>

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.ItemsSketchSortedView<T>
+
+
+
+
Type Parameters:
+
T - The sketch data type
+
+
+
All Implemented Interfaces:
+
GenericSortedView<T>, PartitioningFeature<T>, SketchPartitionLimits, SortedView
+
+
+
+
public class ItemsSketchSortedView<T> +extends Object +implements GenericSortedView<T>
+
The SortedView for the KllItemsSketch and the classic QuantilesItemsSketch.
+
+
Author:
+
Alexander Saydakov, Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ItemsSketchSortedView

      +
      +
      public ItemsSketchSortedView(T[] quantiles, + long[] cumWeights, + QuantilesGenericAPI<T> sk)
      +
      Constructor.
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles, which must be ordered.
      +
      cumWeights - the given array of cumulative weights, which must be ordered, start with the value one, and +the last value must be equal to N, the total number of items updated to the sketch.
      +
      sk - the underlying quantile sketch.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getComparator

      +
      +
      public Comparator<? super T> getComparator()
      +
      Description copied from interface: GenericSortedView
      +
      Gets the Comparator for this generic type.
      +
      +
      Specified by:
      +
      getComparator in interface GenericSortedView<T>
      +
      Returns:
      +
      the Comparator for this generic type.
      +
      +
      +
      +
    • +
    • +
      +

      getCumulativeWeights

      +
      +
      public long[] getCumulativeWeights()
      +
      Description copied from interface: SortedView
      +
      Returns the array of cumulative weights from the sketch. +Also known as the natural ranks, which are the Natural Numbers on the interval [1, N].
      +
      +
      Specified by:
      +
      getCumulativeWeights in interface SortedView
      +
      Returns:
      +
      the array of cumulative weights (or natural ranks).
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      public T getMaxItem()
      +
      Description copied from interface: GenericSortedView
      +
      Returns the maximum item of the stream. This may be distinct from the largest item retained by the +sketch algorithm.
      +
      +
      Specified by:
      +
      getMaxItem in interface GenericSortedView<T>
      +
      Returns:
      +
      the maximum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      public T getMinItem()
      +
      Description copied from interface: GenericSortedView
      +
      Returns the minimum item of the stream. This may be distinct from the smallest item retained by the +sketch algorithm.
      +
      +
      Specified by:
      +
      getMinItem in interface GenericSortedView<T>
      +
      Returns:
      +
      the minimum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      public long getN()
      +
      Description copied from interface: SketchPartitionLimits
      +
      Gets the length of the input stream offered to the sketch..
      +
      +
      Specified by:
      +
      getN in interface SketchPartitionLimits
      +
      Specified by:
      +
      getN in interface SortedView
      +
      Returns:
      +
      the length of the input stream offered to the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNumRetained

      +
      +
      public int getNumRetained()
      +
      Description copied from interface: SortedView
      +
      Gets the number of quantiles retained by this sorted view. +This may be slightly different from the function with the same name when called from the originating sketch.
      +
      +
      Specified by:
      +
      getNumRetained in interface SortedView
      +
      Returns:
      +
      the number of quantiles retained by this sorted view
      +
      +
      +
      +
    • +
    • +
      +

      getMaxPartitions

      +
      +
      public int getMaxPartitions()
      +
      Description copied from interface: SketchPartitionLimits
      +
      Gets the maximum number of partitions this sketch will support based on the configured size K +and the number of retained values of this sketch.
      +
      +
      Specified by:
      +
      getMaxPartitions in interface SketchPartitionLimits
      +
      Returns:
      +
      the maximum number of partitions this sketch will support.
      +
      +
      +
      +
    • +
    • +
      +

      getPartitionBoundariesFromPartSize

      +
      +
      public GenericPartitionBoundaries<T> getPartitionBoundariesFromPartSize(long nominalPartitionSize, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: PartitioningFeature
      +
      This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition. + +

      The sketch must not be empty.

      +
      +
      Specified by:
      +
      getPartitionBoundariesFromPartSize in interface PartitioningFeature<T>
      +
      Parameters:
      +
      nominalPartitionSize - an integer that specifies the nominal size, in items, of each target partition. +This must be a positive integer greater than +getMinPartitionSizeItems().
      +
      searchCrit - If INCLUSIVE, all the returned quantiles are the upper boundaries of the equally sized partitions +with the exception of the lowest returned quantile, which is the lowest boundary of the lowest ranked partition. +If EXCLUSIVE, all the returned quantiles are the lower boundaries of the equally sized partitions +with the exception of the highest returned quantile, which is the upper boundary of the highest ranked partition.
      +
      Returns:
      +
      an instance of GenericPartitionBoundaries.
      +
      +
      +
      +
    • +
    • +
      +

      getPartitionBoundariesFromNumParts

      +
      +
      public GenericPartitionBoundaries<T> getPartitionBoundariesFromNumParts(int numEquallySizedParts, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: PartitioningFeature
      +
      This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition. + +

      The sketch must not be empty.

      +
      +
      Specified by:
      +
      getPartitionBoundariesFromNumParts in interface PartitioningFeature<T>
      +
      Parameters:
      +
      numEquallySizedParts - an integer that specifies the number of equally sized partitions between +getMinItem() and +getMaxItem(). +This must be a positive integer less than +getMaxPartitions() +
        +
      • A 1 will return: minItem, maxItem.
      • +
      • A 2 will return: minItem, median quantile, maxItem.
      • +
      • Etc.
      • +
      +
      searchCrit - If INCLUSIVE, all the returned quantiles are the upper boundaries of the equally sized partitions +with the exception of the lowest returned quantile, which is the lowest boundary of the lowest ranked partition. +If EXCLUSIVE, all the returned quantiles are the lower boundaries of the equally sized partitions +with the exception of the highest returned quantile, which is the upper boundary of the highest ranked partition.
      +
      Returns:
      +
      an instance of GenericPartitionBoundaries.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public T getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: GenericSortedView
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Specified by:
      +
      getQuantile in interface GenericSortedView<T>
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      public T[] getQuantiles(double[] ranks, + QuantileSearchCriteria searchCrit)
      +
      Gets an array of quantiles corresponding to the given array of ranks.
      +
      +
      Parameters:
      +
      ranks - the given array of normalized ranks
      +
      searchCrit - The search criterion: either INCLUSIVE or EXCLUSIVE.
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of ranks.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      public T[] getQuantiles()
      +
      Description copied from interface: GenericSortedView
      +
      Returns the full array of quantiles.
      +
      +
      Specified by:
      +
      getQuantiles in interface GenericSortedView<T>
      +
      Returns:
      +
      the full array of quantiles.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      public double getRank(T quantile, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: GenericSortedView
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Specified by:
      +
      getRank in interface GenericSortedView<T>
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Description copied from interface: SortedView
      +
      Returns true if this sorted view is empty.
      +
      +
      Specified by:
      +
      isEmpty in interface SortedView
      +
      Returns:
      +
      true if this sorted view is empty.
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public GenericSortedViewIterator<T> iterator()
      +
      Description copied from interface: SortedView
      +
      Returns an iterator for this Sorted View.
      +
      +
      Specified by:
      +
      iterator in interface GenericSortedView<T>
      +
      Specified by:
      +
      iterator in interface SortedView
      +
      Returns:
      +
      an iterator for this Sorted View.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/KolmogorovSmirnov.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/KolmogorovSmirnov.html new file mode 100644 index 000000000..dfa24a228 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/KolmogorovSmirnov.html @@ -0,0 +1,274 @@ + + + + +KolmogorovSmirnov (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class KolmogorovSmirnov

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.KolmogorovSmirnov
+
+
+
+
+
public final class KolmogorovSmirnov +extends Object
+
Kolmogorov-Smirnov Test +See Kolmogorov–Smirnov Test
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      KolmogorovSmirnov

      +
      +
      public KolmogorovSmirnov()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      computeKSDelta

      +
      +
      public static double computeKSDelta(QuantilesDoublesAPI sketch1, + QuantilesDoublesAPI sketch2)
      +
      Computes the raw delta between two QuantilesDoublesAPI sketches for the kolmogorovSmirnovTest(...) method.
      +
      +
      Parameters:
      +
      sketch1 - first Input QuantilesDoublesAPI
      +
      sketch2 - second Input QuantilesDoublesAPI
      +
      Returns:
      +
      the raw delta area between two QuantilesDoublesAPI sketches
      +
      +
      +
      +
    • +
    • +
      +

      computeKSDelta

      +
      +
      public static double computeKSDelta(QuantilesFloatsAPI sketch1, + QuantilesFloatsAPI sketch2)
      +
      Computes the raw delta between two QuantilesFloatsAPI sketches for the kolmogorovSmirnovTest(...) method. +method.
      +
      +
      Parameters:
      +
      sketch1 - first Input QuantilesFloatsAPI sketch
      +
      sketch2 - second Input QuantilesFloatsAPI sketch
      +
      Returns:
      +
      the raw delta area between two QuantilesFloatsAPI sketches
      +
      +
      +
      +
    • +
    • +
      +

      computeKSThreshold

      +
      +
      public static double computeKSThreshold(QuantilesAPI sketch1, + QuantilesAPI sketch2, + double tgtPvalue)
      +
      Computes the adjusted delta height threshold for the kolmogorovSmirnovTest(...) method. +This adjusts the computed threshold by the error epsilons of the two given sketches. +The two sketches must be of the same primitive type, double or float. +This will not work with the REQ sketch.
      +
      +
      Parameters:
      +
      sketch1 - first Input QuantilesAPI sketch
      +
      sketch2 - second Input QuantilesAPI sketch
      +
      tgtPvalue - Target p-value. Typically .001 to .1, e.g., .05.
      +
      Returns:
      +
      the adjusted threshold to be compared with the raw delta area.
      +
      +
      +
      +
    • +
    • +
      +

      kolmogorovSmirnovTest

      +
      +
      public static boolean kolmogorovSmirnovTest(QuantilesAPI sketch1, + QuantilesAPI sketch2, + double tgtPvalue)
      +
      Performs the Kolmogorov-Smirnov Test between two QuantilesAPI sketches. +Note: if the given sketches have insufficient data or if the sketch sizes are too small, +this will return false. The two sketches must be of the same primitive type, double or float. +This will not work with the REQ sketch.
      +
      +
      Parameters:
      +
      sketch1 - first Input QuantilesAPI
      +
      sketch2 - second Input QuantilesAPI
      +
      tgtPvalue - Target p-value. Typically .001 to .1, e.g., .05.
      +
      Returns:
      +
      Boolean indicating whether we can reject the null hypothesis (that the sketches +reflect the same underlying distribution) using the provided tgtPValue.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/LongsSketchSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/LongsSketchSortedView.html new file mode 100644 index 000000000..c0284356f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/LongsSketchSortedView.html @@ -0,0 +1,436 @@ + + + + +LongsSketchSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class LongsSketchSortedView

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.LongsSketchSortedView
+
+
+
+
All Implemented Interfaces:
+
LongsSortedView, SortedView
+
+
+
+
public final class LongsSketchSortedView +extends Object +implements LongsSortedView
+
The SortedView of the KllLongsSketch.
+
+
Author:
+
Lee Rhodes, Zac Blanco
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      LongsSketchSortedView

      +
      +
      public LongsSketchSortedView(long[] quantiles, + long[] cumWeights, + QuantilesLongsAPI sk)
      +
      Construct from elements, also used in testing.
      +
      +
      Parameters:
      +
      quantiles - sorted array of quantiles
      +
      cumWeights - sorted, monotonically increasing cumulative weights.
      +
      sk - the underlying quantile sketch.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCumulativeWeights

      +
      +
      public long[] getCumulativeWeights()
      +
      Description copied from interface: SortedView
      +
      Returns the array of cumulative weights from the sketch. +Also known as the natural ranks, which are the Natural Numbers on the interval [1, N].
      +
      +
      Specified by:
      +
      getCumulativeWeights in interface SortedView
      +
      Returns:
      +
      the array of cumulative weights (or natural ranks).
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      public long getMaxItem()
      +
      Description copied from interface: LongsSortedView
      +
      Returns the maximum item of the stream. This may be distinct from the largest item retained by the +sketch algorithm.
      +
      +
      Specified by:
      +
      getMaxItem in interface LongsSortedView
      +
      Returns:
      +
      the maximum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      public long getMinItem()
      +
      Description copied from interface: LongsSortedView
      +
      Returns the minimum item of the stream. This may be distinct from the smallest item retained by the +sketch algorithm.
      +
      +
      Specified by:
      +
      getMinItem in interface LongsSortedView
      +
      Returns:
      +
      the minimum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      public long getN()
      +
      Description copied from interface: SortedView
      +
      Returns the total number of items presented to the sourcing sketch.
      +
      +
      Specified by:
      +
      getN in interface SortedView
      +
      Returns:
      +
      the total number of items presented to the sourcing sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNumRetained

      +
      +
      public int getNumRetained()
      +
      Description copied from interface: SortedView
      +
      Gets the number of quantiles retained by this sorted view. +This may be slightly different from the function with the same name when called from the originating sketch.
      +
      +
      Specified by:
      +
      getNumRetained in interface SortedView
      +
      Returns:
      +
      the number of quantiles retained by this sorted view
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public long getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: LongsSortedView
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Specified by:
      +
      getQuantile in interface LongsSortedView
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      public long[] getQuantiles()
      +
      Description copied from interface: LongsSortedView
      +
      Returns an array of all retained quantiles by the sketch.
      +
      +
      Specified by:
      +
      getQuantiles in interface LongsSortedView
      +
      Returns:
      +
      an array of all retained quantiles by the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      public double getRank(long quantile, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: LongsSortedView
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Specified by:
      +
      getRank in interface LongsSortedView
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Description copied from interface: SortedView
      +
      Returns true if this sorted view is empty.
      +
      +
      Specified by:
      +
      isEmpty in interface SortedView
      +
      Returns:
      +
      true if this sorted view is empty.
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public LongsSortedViewIterator iterator()
      +
      Description copied from interface: SortedView
      +
      Returns an iterator for this Sorted View.
      +
      +
      Specified by:
      +
      iterator in interface LongsSortedView
      +
      Specified by:
      +
      iterator in interface SortedView
      +
      Returns:
      +
      an iterator for this Sorted View.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/LongsSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/LongsSortedView.html new file mode 100644 index 000000000..8931c8d38 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/LongsSortedView.html @@ -0,0 +1,405 @@ + + + + +LongsSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface LongsSortedView

+
+
+
+
All Superinterfaces:
+
SortedView
+
+
+
All Known Implementing Classes:
+
LongsSketchSortedView
+
+
+
+
public interface LongsSortedView +extends SortedView
+
The Sorted View for quantile sketches of primitive type long.
+
+
Author:
+
Lee Rhodes, Zac Blanco
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    default double[]
    +
    getCDF(long[] splitPoints, + QuantileSearchCriteria searchCrit)
    +
    +
    Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
    +
    +
    long
    + +
    +
    Returns the maximum item of the stream.
    +
    +
    long
    + +
    +
    Returns the minimum item of the stream.
    +
    +
    default double[]
    +
    getPMF(long[] splitPoints, + QuantileSearchCriteria searchCrit)
    +
    +
    Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
    +
    +
    long
    +
    getQuantile(double rank, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets the approximate quantile of the given normalized rank and the given search criterion.
    +
    +
    long[]
    + +
    +
    Returns an array of all retained quantiles by the sketch.
    +
    +
    double
    +
    getRank(long quantile, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets the normalized rank corresponding to the given a quantile.
    +
    + + +
    +
    Returns an iterator for this Sorted View.
    +
    +
    +
    +
    +
    +

    Methods inherited from interface SortedView

    +getCumulativeWeights, getN, getNumRetained, isEmpty
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCDF

      +
      +
      default double[] getCDF(long[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      long getMaxItem()
      +
      Returns the maximum item of the stream. This may be distinct from the largest item retained by the +sketch algorithm.
      +
      +
      Returns:
      +
      the maximum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      long getMinItem()
      +
      Returns the minimum item of the stream. This may be distinct from the smallest item retained by the +sketch algorithm.
      +
      +
      Returns:
      +
      the minimum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      default double[] getPMF(long[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      long getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      long[] getQuantiles()
      +
      Returns an array of all retained quantiles by the sketch.
      +
      +
      Returns:
      +
      an array of all retained quantiles by the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      double getRank(long quantile, + QuantileSearchCriteria searchCrit)
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Description copied from interface: SortedView
      +
      Returns an iterator for this Sorted View.
      +
      +
      Specified by:
      +
      iterator in interface SortedView
      +
      Returns:
      +
      an iterator for this Sorted View.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/LongsSortedViewIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/LongsSortedViewIterator.html new file mode 100644 index 000000000..c7fcf79bb --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/LongsSortedViewIterator.html @@ -0,0 +1,198 @@ + + + + +LongsSortedViewIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class LongsSortedViewIterator

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.SortedViewIterator +
org.apache.datasketches.quantilescommon.LongsSortedViewIterator
+
+
+
+
+
+
public final class LongsSortedViewIterator +extends SortedViewIterator
+
Iterator over quantile sketches of primitive type long.
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      LongsSortedViewIterator

      +
      +
      public LongsSortedViewIterator(long[] quantiles, + long[] cumWeights)
      +
      Constructor.
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles, which must be ordered.
      +
      cumWeights - the given array of cumulative weights, which must be ordered, start with the value one, and +the last value must be equal to N, the total number of items updated to the sketch.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      public long getQuantile()
      +
      Gets the quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Returns:
      +
      the quantile at the current index.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/PartitioningFeature.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/PartitioningFeature.html new file mode 100644 index 000000000..1b6fde7d0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/PartitioningFeature.html @@ -0,0 +1,288 @@ + + + + +PartitioningFeature (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface PartitioningFeature<T>

+
+
+
+
Type Parameters:
+
T - the item class type
+
+
+
All Known Subinterfaces:
+
GenericSortedView<T>, QuantilesGenericAPI<T>
+
+
+
All Known Implementing Classes:
+
ItemsSketchSortedView, KllItemsSketch, QuantilesItemsSketch
+
+
+
+
public interface PartitioningFeature<T>
+
This enables the special functions for performing efficient partitioning of massive data.
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getPartitionBoundariesFromNumParts

      +
      +
      default GenericPartitionBoundaries<T> getPartitionBoundariesFromNumParts(int numEquallySizedParts)
      +
      This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition. + +

      This method is equivalent to +getPartitionBoundariesFromNumParts(numEquallySizedParts, INCLUSIVE). +

      + +

      The sketch must not be empty.

      +
      +
      Parameters:
      +
      numEquallySizedParts - an integer that specifies the number of equally sized partitions between +getMinItem() and +getMaxItem(). +This must be a positive integer less than +getMaxPartitions() +
        +
      • A 1 will return: minItem, maxItem.
      • +
      • A 2 will return: minItem, median quantile, maxItem.
      • +
      • Etc.
      • +
      +
      Returns:
      +
      an instance of GenericPartitionBoundaries.
      +
      +
      +
      +
    • +
    • +
      +

      getPartitionBoundariesFromNumParts

      +
      +
      GenericPartitionBoundaries<T> getPartitionBoundariesFromNumParts(int numEquallySizedParts, + QuantileSearchCriteria searchCrit)
      +
      This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition. + +

      The sketch must not be empty.

      +
      +
      Parameters:
      +
      numEquallySizedParts - an integer that specifies the number of equally sized partitions between +getMinItem() and +getMaxItem(). +This must be a positive integer less than +getMaxPartitions() +
        +
      • A 1 will return: minItem, maxItem.
      • +
      • A 2 will return: minItem, median quantile, maxItem.
      • +
      • Etc.
      • +
      +
      searchCrit - If INCLUSIVE, all the returned quantiles are the upper boundaries of the equally sized partitions +with the exception of the lowest returned quantile, which is the lowest boundary of the lowest ranked partition. +If EXCLUSIVE, all the returned quantiles are the lower boundaries of the equally sized partitions +with the exception of the highest returned quantile, which is the upper boundary of the highest ranked partition.
      +
      Returns:
      +
      an instance of GenericPartitionBoundaries.
      +
      +
      +
      +
    • +
    • +
      +

      getPartitionBoundariesFromPartSize

      +
      +
      default GenericPartitionBoundaries<T> getPartitionBoundariesFromPartSize(long nominalPartSizeItems)
      +
      This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition. + +

      This method is equivalent to +getPartitionBoundariesFromPartSize(nominalPartSizeItems, INCLUSIVE). +

      + +

      The sketch must not be empty.

      +
      +
      Parameters:
      +
      nominalPartSizeItems - an integer that specifies the nominal size, in items, of each target partition. +This must be a positive integer greater than +getMinPartitionSizeItems()
      +
      Returns:
      +
      an instance of GenericPartitionBoundaries.
      +
      +
      +
      +
    • +
    • +
      +

      getPartitionBoundariesFromPartSize

      +
      +
      GenericPartitionBoundaries<T> getPartitionBoundariesFromPartSize(long nominalPartSizeItems, + QuantileSearchCriteria searchCrit)
      +
      This method returns an instance of +GenericPartitionBoundaries which provides +sufficient information for the user to create the given number of equally sized partitions, where "equally sized" +refers to an approximately equal number of items per partition. + +

      The sketch must not be empty.

      +
      +
      Parameters:
      +
      nominalPartSizeItems - an integer that specifies the nominal size, in items, of each target partition. +This must be a positive integer greater than +getMinPartitionSizeItems().
      +
      searchCrit - If INCLUSIVE, all the returned quantiles are the upper boundaries of the equally sized partitions +with the exception of the lowest returned quantile, which is the lowest boundary of the lowest ranked partition. +If EXCLUSIVE, all the returned quantiles are the lower boundaries of the equally sized partitions +with the exception of the highest returned quantile, which is the upper boundary of the highest ranked partition.
      +
      Returns:
      +
      an instance of GenericPartitionBoundaries.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantileSearchCriteria.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantileSearchCriteria.html new file mode 100644 index 000000000..1baea5629 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantileSearchCriteria.html @@ -0,0 +1,277 @@ + + + + +QuantileSearchCriteria (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class QuantileSearchCriteria

+
+
java.lang.Object +
java.lang.Enum<QuantileSearchCriteria> +
org.apache.datasketches.quantilescommon.QuantileSearchCriteria
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<QuantileSearchCriteria>, Constable
+
+
+
+
public enum QuantileSearchCriteria +extends Enum<QuantileSearchCriteria>
+
These search criteria are used by the KLL, REQ and Classic Quantiles sketches in the DataSketches library.
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Enum Constant Details

    +
      +
    • +
      +

      INCLUSIVE

      +
      +
      public static final QuantileSearchCriteria INCLUSIVE
      +
      Definition of INCLUSIVE getQuantile(r) search:
      +Given rank r, return the quantile of the smallest rank that is +strictly greater than or equal to r. + +

      Definition of INCLUSIVE getRank(q) search:
      +Given quantile q, return the rank, r, of the largest quantile that is +less than or equal to q.

      +
      +
      +
    • +
    • +
      +

      EXCLUSIVE

      +
      +
      public static final QuantileSearchCriteria EXCLUSIVE
      +
      Definition of EXCLUSIVE getQuantile(r) search:
      +Given rank r, return the quantile of the smallest rank that is +strictly greater than r. + +

      However, if the given rank is is equal to 1.0, or there is no quantile that satisfies this criterion +the method will return a NaN or null.

      + +

      Definition of EXCLUSIVE getRank(q) search:
      +Given quantile q, return the rank, r, of the largest quantile that is +strictly less than q.

      + +

      If there is no quantile value that is strictly less than q, +the method will return a rank of zero.

      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static QuantileSearchCriteria[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static QuantileSearchCriteria valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesAPI.html new file mode 100644 index 000000000..023d53574 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesAPI.html @@ -0,0 +1,702 @@ + + + + +QuantilesAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface QuantilesAPI

+
+
+
+
All Known Subinterfaces:
+
QuantilesDoublesAPI, QuantilesFloatsAPI, QuantilesGenericAPI<T>, QuantilesLongsAPI
+
+
+
All Known Implementing Classes:
+
CompactQuantilesDoublesSketch, KllDoublesSketch, KllFloatsSketch, KllItemsSketch, KllLongsSketch, KllSketch, QuantilesDoublesSketch, QuantilesItemsSketch, ReqSketch, UpdatableQuantilesDoublesSketch
+
+
+
+
public interface QuantilesAPI
+
This is a stochastic streaming sketch that enables near-real time analysis of the +approximate distribution of items from a very large stream in a single pass, requiring only +that the items are comparable. +The analysis is obtained using the getQuantile() function or the +inverse functions getRank(), getPMF() (the Probability Mass Function), and getCDF() +(the Cumulative Distribution Function). + +

Given an input stream of N items, the natural rank of any specific +item is defined as its index (1 to N) in the hypothetical sorted stream of all +N input items.

+ +

The normalized rank (rank) of any specific item is defined as its +natural rank divided by N, which is a number in the interval [0.0, 1.0]. +In the Javadocs for all the quantile sketches natural rank is seldom used +so any reference to just rank should be interpreted as normalized rank.

+ +

Inputs into a quantile sketch are called "items" that can be either generic or specific +primitives, like float or double depending on the sketch implementation. +In order to keep its size small, sketches don't retain all the items offered and retain only +a small fraction of all the items, thus purging most of the items. The items retained are +then sorted and associated with a rank. At this point we call the retained items quantiles. +Thus, all quantiles are items, but only a few items become quantiles. Depending on the context +the two terms can be interchangeable.

+ +

All quantile sketches are configured with a parameter k, which affects the size of +the sketch and its estimation error.

+ +

In the research literature, the estimation error is commonly called epsilon +(or eps) and is a fraction between zero and one. +Larger sizes of k result in a smaller epsilon, but also a larger sketch. +The epsilon error is always with respect to the rank domain. Estimating the confidence interval +in the quantile domain can be done by first computing the error in the rank domain and then +translating that to the quantile domain. The sketch provides methods to assist with that.

+ +

The relationship between the normalized rank and the corresponding quantiles can be viewed +as a two dimensional monotonic plot with the normalized rank on one axis and the +corresponding quantiles on the other axis. Let q := quantile and r := rank then both +q = getQuantile(r) and r = getRank(q) are monotonically increasing functions. +If the y-axis is used for the rank domain and the x-axis for the quantile domain, +then y = getRank(x) is also the single point Cumulative Distribution Function (CDF).

+ +

The functions getQuantile() translate ranks into corresponding quantiles. +The functions getRank(), getCDF(), and getPMF() (Probability Mass Function) +perform the opposite operation and translate quantiles into ranks (or cumulative probabilities, +or probability masses, depending on the context).

+ +

As an example, consider a large stream of one million items such as packet sizes coming into a network node. +The absolute rank of any specific item size is simply its index in the hypothetical sorted +array of such items. +The normalized rank is the natural rank divided by the stream size, or N, +in this case one million. +The quantile corresponding to the normalized rank of 0.5 represents the 50th percentile or median +of the distribution, obtained from getQuantile(0.5). Similarly, the 95th percentile is obtained from +getQuantile(0.95).

+ +

From the min and max quantiles, for example, say 1 and 1000 bytes, +you can obtain the PMF from getPMF(100, 500, 900) that will result in an array of +4 probability masses such as {.4, .3, .2, .1}, which means that +

    +
  • 40% of the mass was < 100,
  • +
  • 30% of the mass was ≥ 100 and < 500,
  • +
  • 20% of the mass was ≥ 500 and < 900, and
  • +
  • 10% of the mass was ≥ 900.
  • +
+A frequency histogram can be obtained by simply multiplying these probability masses by getN(), +which is the total count of items received. +The getCDF() works similarly, but produces the cumulative distribution instead. + +

The accuracy of this sketch is a function of the configured k, which also affects +the overall size of the sketch. Accuracy of this quantile sketch is always with respect to +the normalized rank. + +

The getPMF() function has about 13 to 47% worse rank error (depending +on k) than the other queries because the mass of each "bin" of the PMF has +"double-sided" error from the upper and lower edges of the bin as a result of a subtraction +of random variables where the errors from the two edges can sometimes add.

+ +

A getQuantile(rank) query has the following probabilistic guarantees:

+
    +
  • Let q = getQuantile(r) where r is the rank between zero and one.
  • +
  • The quantile q will be a quantile from the input stream.
  • +
  • Let trueRank be the true rank of q derived from the hypothetical sorted +stream of all N quantiles.
  • +
  • Let eps = getNormalizedRankError(false)[*].
  • +
  • Then r - eps ≤ trueRank ≤ r + eps. +Note that the error is on the rank, not the quantile.
  • +
+ +

A getRank(quantile) query has the following probabilistic guarantees:

+
    +
  • Let r = getRank(q) where q is a quantile between the min and max quantiles of +the input stream.
  • +
  • Let trueRank be the true rank of q derived from the hypothetical sorted +stream of all N quantiles.
  • +
  • Let eps = getNormalizedRankError(false)[*].
  • +
  • Then r - eps ≤ trueRank ≤ r + eps.
  • +
+ +

A getPMF() query has the following probabilistic guarantees:

+
    +
  • Let {r1, r2, ..., rm+1} += getPMF(v1, v2, ..., vm) where +q1, q2, ..., qm are monotonically increasing quantiles +supplied by the user that are part of the monotonic sequence +q0 = min, q1, q2, ..., qm, qm+1 = max, +and where min and max are the actual minimum and maximum quantiles of the input +stream automatically included in the sequence by the getPMF(...) function. + +
  • Let ri = massi = estimated mass between +vi-1 and qi where q0 = min +and qm+1 = max.
  • + +
  • Let trueMass be the true mass between the quantiles of qi, +qi+1 derived from the hypothetical sorted stream of all N quantiles.
  • +
  • Let eps = getNormalizedRankError(true)[*].
  • +
  • Then mass - eps ≤ trueMass ≤ mass + eps.
  • +
  • r1 includes the mass of all points between min = q0 and +q1.
  • +
  • rm+1 includes the mass of all points between qm and +max = qm+1.
  • +
+ +

A getCDF(...) query has the following probabilistic guarantees:

+
    +
  • Let {r1, r2, ..., rm+1} += getCDF(q1, q2, ..., qm) where +q1, q2, ..., qm) are monotonically increasing quantiles +supplied by the user that are part of the monotonic sequence +{q0 = min, q1, q2, ..., qm, qm+1 = max}, +and where min and max are the actual minimum and maximum quantiles of the input +stream automatically included in the sequence by the getCDF(...) function. + +
  • Let ri = massi = estimated mass between +q0 = min and qi.
  • + +
  • Let trueMass be the true mass between the true ranks of qi, +qi+1 derived from the hypothetical sorted stream of all N quantiles.
  • +
  • Let eps = getNormalizedRankError(true)[*].
  • +
  • then mass - eps ≤ trueMass ≤ mass + eps.
  • +
  • r1 includes the mass of all points between min = q0 and +q1.
  • +
  • rm+1 includes the mass of all points between min = q0 and +max = qm+1.
  • +
+ +

Because errors are independent, we can make some estimates of the size of the confidence bounds +for the quantile returned from a call to getQuantile(), but not error bounds. +These confidence bounds may be quite large for certain distributions.

+ +
    +
  • Let q = getQuantile(r), the estimated quantile of rank r.
  • +
  • Let eps = getNormalizedRankError(false)[*].
  • +
  • Let qlo = estimated quantile of rank (r - eps).
  • +
  • Let qhi = estimated quantile of rank (r + eps).
  • +
  • Then qlo ≤ q ≤ qhi.
  • +
+ +

This sketch is order and distribution insensitive

+ +

This algorithm intentionally inserts randomness into the sampling process for items that +ultimately get retained in the sketch. Thus, the results produced by this algorithm are not +deterministic. For example, if the same stream is inserted into two different instances of this +sketch, the answers obtained from the two sketches should be close, but may not be be identical.

+ +

Similarly, there may be directional inconsistencies. For example, if a quantile obtained +from getQuantile(rank) is input into the reverse query +getRank(quantile), the resulting rank should be close, but may not exactly equal the original rank.

+ +

Please visit our website: DataSketches Home Page +and specific Javadocs for more information.

+ +

[*] Note that obtaining epsilon may require using a similar function but with more parameters +based on the specific sketch implementation.

+
+
Author:
+
Lee Rhodes, Kevin Lang, Alexander Saydakov
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    static final String
    + +
    +
    The sketch must not be empty for this operation.
    +
    +
    static final String
    + +
    +
    MemoryRequestServer must not be null.
    +
    +
    static final String
    + +
    +
    Sketch does not have just one item.
    +
    +
    static final String
    + +
    +
    A sketch cannot merge with itself.
    +
    +
    static final String
    + +
    +
    Target sketch is Read Only, cannot write.
    +
    +
    static final String
    + +
    +
    Unsupported operation for this Sketch Type.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    int
    + +
    +
    Gets the user configured parameter k, which controls the accuracy of the sketch +and its memory space usage.
    +
    +
    long
    + +
    +
    Gets the length of the input stream offered to the sketch..
    +
    +
    double
    + +
    +
    Gets the approximate rank error of this sketch normalized as a fraction between zero and one.
    +
    +
    int
    + +
    +
    Gets the number of quantiles retained by the sketch.
    +
    +
    double
    +
    getRankLowerBound(double rank)
    +
    +
    Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
    +
    +
    double
    +
    getRankUpperBound(double rank)
    +
    +
    Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch is empty.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch is in estimation mode.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch is read only.
    +
    +
    void
    + +
    +
    Resets this sketch to the empty state.
    +
    + + +
    +
    Returns a summary of the key parameters of the sketch.
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      EMPTY_MSG

      +
      +
      static final String EMPTY_MSG
      +
      The sketch must not be empty for this operation.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      UNSUPPORTED_MSG

      +
      +
      static final String UNSUPPORTED_MSG
      +
      Unsupported operation for this Sketch Type.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      NOT_SINGLE_ITEM_MSG

      +
      +
      static final String NOT_SINGLE_ITEM_MSG
      +
      Sketch does not have just one item.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      MEM_REQ_SVR_NULL_MSG

      +
      +
      static final String MEM_REQ_SVR_NULL_MSG
      +
      MemoryRequestServer must not be null.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      TGT_IS_READ_ONLY_MSG

      +
      +
      static final String TGT_IS_READ_ONLY_MSG
      +
      Target sketch is Read Only, cannot write.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      SELF_MERGE_MSG

      +
      +
      static final String SELF_MERGE_MSG
      +
      A sketch cannot merge with itself.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getK

      +
      +
      int getK()
      +
      Gets the user configured parameter k, which controls the accuracy of the sketch +and its memory space usage.
      +
      +
      Returns:
      +
      the user configured parameter k, which controls the accuracy of the sketch +and its memory space usage.
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      long getN()
      +
      Gets the length of the input stream offered to the sketch..
      +
      +
      Returns:
      +
      the length of the input stream offered to the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNormalizedRankError

      +
      +
      double getNormalizedRankError(boolean pmf)
      +
      Gets the approximate rank error of this sketch normalized as a fraction between zero and one. +The epsilon returned is a best fit to 99 percent confidence empirically measured max error +in thousands of trials.
      +
      +
      Parameters:
      +
      pmf - if true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      Returns:
      +
      if pmf is true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      +
      +
      +
    • +
    • +
      +

      getNumRetained

      +
      +
      int getNumRetained()
      +
      Gets the number of quantiles retained by the sketch.
      +
      +
      Returns:
      +
      the number of quantiles retained by the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getRankLowerBound

      +
      +
      double getRankLowerBound(double rank)
      +
      Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRankUpperBound

      +
      +
      double getRankUpperBound(double rank)
      +
      Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      boolean isEmpty()
      +
      Returns true if this sketch is empty.
      +
      +
      Returns:
      +
      true if this sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      isEstimationMode

      +
      +
      boolean isEstimationMode()
      +
      Returns true if this sketch is in estimation mode.
      +
      +
      Returns:
      +
      true if this sketch is in estimation mode.
      +
      +
      +
      +
    • +
    • +
      +

      isReadOnly

      +
      +
      boolean isReadOnly()
      +
      Returns true if this sketch is read only.
      +
      +
      Returns:
      +
      true if this sketch is read only.
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      void reset()
      +
      Resets this sketch to the empty state. +If the sketch is read only this does nothing. + +

      The parameter k will not change.

      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      String toString()
      +
      Returns a summary of the key parameters of the sketch.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      a summary of the key parameters of the sketch.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesDoublesAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesDoublesAPI.html new file mode 100644 index 000000000..a8cbbe8e9 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesDoublesAPI.html @@ -0,0 +1,738 @@ + + + + +QuantilesDoublesAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface QuantilesDoublesAPI

+
+
+
+
All Superinterfaces:
+
QuantilesAPI
+
+
+
All Known Implementing Classes:
+
CompactQuantilesDoublesSketch, KllDoublesSketch, QuantilesDoublesSketch, UpdatableQuantilesDoublesSketch
+
+
+
+
public interface QuantilesDoublesAPI +extends QuantilesAPI
+
The Quantiles API for item type double.
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCDF

      +
      +
      default double[] getCDF(double[] splitPoints)
      +
      This is equivalent to getCDF(splitPoints, INCLUSIVE)
      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getCDF

      +
      +
      double[] getCDF(double[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      double getMaxItem()
      +
      Returns the maximum item of the stream. This is provided for convenience and may be different from the +item returned by getQuantile(1.0).
      +
      +
      Returns:
      +
      the maximum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      double getMinItem()
      +
      Returns the minimum item of the stream. This is provided for convenience and may be different from the +item returned by getQuantile(0.0).
      +
      +
      Returns:
      +
      the minimum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      default double[] getPMF(double[] splitPoints)
      +
      This is equivalent to getPMF(splitPoints, INCLUSIVE)
      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      double[] getPMF(double[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      default double getQuantile(double rank)
      +
      This is equivalent to getQuantile(rank, INCLUSIVE)
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      double getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileLowerBound

      +
      +
      double getQuantileLowerBound(double rank)
      +
      Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile confidence interval +as an additive or multiplicative percent of the true quantile.

      +
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileUpperBound

      +
      +
      double getQuantileUpperBound(double rank)
      +
      Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile interval +as an additive or multiplicative percent of the true quantile.

      +
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      default double[] getQuantiles(double[] ranks)
      +
      This is equivalent to getQuantiles(ranks, INCLUSIVE)
      +
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      double[] getQuantiles(double[] ranks, + QuantileSearchCriteria searchCrit)
      +
      Gets an array of quantiles from the given array of normalized ranks.
      +
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      searchCrit - if INCLUSIVE, the given ranks include all quantiles ≤ +the quantile directly corresponding to each rank.
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      default double getRank(double quantile)
      +
      This is equivalent to getRank(quantile, INCLUSIVE)
      +
      +
      Parameters:
      +
      quantile - the given quantile
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      double getRank(double quantile, + QuantileSearchCriteria searchCrit)
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      default double[] getRanks(double[] quantiles)
      +
      This is equivalent to getRanks(quantiles, INCLUSIVE)
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      double[] getRanks(double[] quantiles, + QuantileSearchCriteria searchCrit)
      +
      Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      searchCrit - if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile.
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getSerializedSizeBytes

      +
      +
      int getSerializedSizeBytes()
      +
      Returns the current number of bytes this Sketch would require if serialized.
      +
      +
      Returns:
      +
      the number of bytes this sketch would require if serialized.
      +
      +
      +
      +
    • +
    • +
      +

      getSortedView

      +
      +
      DoublesSortedView getSortedView()
      +
      Gets the sorted view of this sketch
      +
      +
      Returns:
      +
      the sorted view of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Gets the iterator for this sketch, which is not sorted.
      +
      +
      Returns:
      +
      the iterator for this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      byte[] toByteArray()
      +
      Returns a byte array representation of this sketch.
      +
      +
      Returns:
      +
      a byte array representation of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      void update(double item)
      +
      Updates this sketch with the given item.
      +
      +
      Parameters:
      +
      item - from a stream of items. NaNs are ignored.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesDoublesSketchIteratorAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesDoublesSketchIteratorAPI.html new file mode 100644 index 000000000..020b81182 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesDoublesSketchIteratorAPI.html @@ -0,0 +1,162 @@ + + + + +QuantilesDoublesSketchIteratorAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface QuantilesDoublesSketchIteratorAPI

+
+
+
+
All Superinterfaces:
+
QuantilesSketchIteratorAPI
+
+
+
All Known Implementing Classes:
+
KllDoublesSketchIterator, QuantilesDoublesSketchIterator
+
+
+
+
public interface QuantilesDoublesSketchIteratorAPI +extends QuantilesSketchIteratorAPI
+
The quantiles sketch iterator for primitive type double.
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    double
    + +
    +
    Gets the double quantile at the current index.
    +
    +
    +
    +
    +
    +

    Methods inherited from interface QuantilesSketchIteratorAPI

    +getWeight, next
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      double getQuantile()
      +
      Gets the double quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Returns:
      +
      the double quantile at the current index.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesFloatsAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesFloatsAPI.html new file mode 100644 index 000000000..09a7d909f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesFloatsAPI.html @@ -0,0 +1,738 @@ + + + + +QuantilesFloatsAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface QuantilesFloatsAPI

+
+
+
+
All Superinterfaces:
+
QuantilesAPI
+
+
+
All Known Implementing Classes:
+
KllFloatsSketch, ReqSketch
+
+
+
+
public interface QuantilesFloatsAPI +extends QuantilesAPI
+
The Quantiles API for item type float.
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCDF

      +
      +
      default double[] getCDF(float[] splitPoints)
      +
      This is equivalent to getCDF(splitPoints, INCLUSIVE)
      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getCDF

      +
      +
      double[] getCDF(float[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      float getMaxItem()
      +
      Returns the maximum item of the stream. This is provided for convenience, but may be different from the largest +item retained by the sketch algorithm.
      +
      +
      Returns:
      +
      the maximum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      float getMinItem()
      +
      Returns the minimum item of the stream. This is provided for convenience, but is distinct from the smallest +item retained by the sketch algorithm.
      +
      +
      Returns:
      +
      the minimum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      default double[] getPMF(float[] splitPoints)
      +
      This is equivalent to getPMF(splitPoints, INCLUSIVE)
      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      double[] getPMF(float[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      default float getQuantile(double rank)
      +
      This is equivalent to getQuantile(rank, INCLUSIVE)
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      float getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileLowerBound

      +
      +
      float getQuantileLowerBound(double rank)
      +
      Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile confidence interval +as an additive or multiplicative percent of the true quantile.

      +
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileUpperBound

      +
      +
      float getQuantileUpperBound(double rank)
      +
      Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile interval +as an additive or multiplicative percent of the true quantile.

      +
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      default float[] getQuantiles(double[] ranks)
      +
      This is equivalent to getQuantiles(ranks, INCLUSIVE)
      +
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      float[] getQuantiles(double[] ranks, + QuantileSearchCriteria searchCrit)
      +
      Gets an array of quantiles from the given array of normalized ranks.
      +
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      searchCrit - if INCLUSIVE, the given ranks include all quantiles ≤ +the quantile directly corresponding to each rank.
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      default double getRank(float quantile)
      +
      This is equivalent to getRank(quantile, INCLUSIVE)
      +
      +
      Parameters:
      +
      quantile - the given quantile
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      double getRank(float quantile, + QuantileSearchCriteria searchCrit)
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      default double[] getRanks(float[] quantiles)
      +
      This is equivalent to getRanks(quantiles, INCLUSIVE)
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      double[] getRanks(float[] quantiles, + QuantileSearchCriteria searchCrit)
      +
      Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      searchCrit - if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile.
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getSerializedSizeBytes

      +
      +
      int getSerializedSizeBytes()
      +
      Returns the current number of bytes this Sketch would require if serialized.
      +
      +
      Returns:
      +
      the number of bytes this sketch would require if serialized.
      +
      +
      +
      +
    • +
    • +
      +

      getSortedView

      +
      +
      FloatsSortedView getSortedView()
      +
      Gets the sorted view of this sketch
      +
      +
      Returns:
      +
      the sorted view of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Gets the iterator for this sketch, which is not sorted.
      +
      +
      Returns:
      +
      the iterator for this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      byte[] toByteArray()
      +
      Returns a byte array representation of this sketch.
      +
      +
      Returns:
      +
      a byte array representation of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      void update(float item)
      +
      Updates this sketch with the given item.
      +
      +
      Parameters:
      +
      item - from a stream of quantiles. NaNs are ignored.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesFloatsSketchIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesFloatsSketchIterator.html new file mode 100644 index 000000000..a8d6eaf4f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesFloatsSketchIterator.html @@ -0,0 +1,162 @@ + + + + +QuantilesFloatsSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface QuantilesFloatsSketchIterator

+
+
+
+
All Superinterfaces:
+
QuantilesSketchIteratorAPI
+
+
+
All Known Implementing Classes:
+
KllFloatsSketchIterator, ReqSketchIterator
+
+
+
+
public interface QuantilesFloatsSketchIterator +extends QuantilesSketchIteratorAPI
+
The quantiles sketch iterator for primitive type float.
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    float
    + +
    +
    Gets the float quantile at the current index.
    +
    +
    +
    +
    +
    +

    Methods inherited from interface QuantilesSketchIteratorAPI

    +getWeight, next
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      float getQuantile()
      +
      Gets the float quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Returns:
      +
      the float quantile at the current index.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesGenericAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesGenericAPI.html new file mode 100644 index 000000000..3c60440db --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesGenericAPI.html @@ -0,0 +1,772 @@ + + + + +QuantilesGenericAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface QuantilesGenericAPI<T>

+
+
+
+
Type Parameters:
+
T - The given item type
+
+
+
All Superinterfaces:
+
PartitioningFeature<T>, QuantilesAPI, SketchPartitionLimits
+
+
+
All Known Implementing Classes:
+
KllItemsSketch, QuantilesItemsSketch
+
+
+
+
public interface QuantilesGenericAPI<T> +extends QuantilesAPI, PartitioningFeature<T>, SketchPartitionLimits
+
The Quantiles API for item type generic.
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCDF

      +
      +
      default double[] getCDF(T[] splitPoints)
      +
      This is equivalent to getCDF(splitPoints, INCLUSIVE)
      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getCDF

      +
      +
      double[] getCDF(T[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getClassOfT

      +
      +
      Class<T> getClassOfT()
      +
      Returns the sketch item class
      +
      +
      Returns:
      +
      the sketch item class
      +
      +
      +
      +
    • +
    • +
      +

      getComparator

      +
      +
      Comparator<? super T> getComparator()
      +
      Returns the Comparator of T
      +
      +
      Returns:
      +
      Comparator of the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      T getMaxItem()
      +
      Returns the maximum item of the stream. This may be distinct from the largest item retained by the +sketch algorithm.
      +
      +
      Returns:
      +
      the maximum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxPartitions

      +
      +
      default int getMaxPartitions()
      +
      Description copied from interface: SketchPartitionLimits
      +
      Gets the maximum number of partitions this sketch will support based on the configured size K +and the number of retained values of this sketch.
      +
      +
      Specified by:
      +
      getMaxPartitions in interface SketchPartitionLimits
      +
      Returns:
      +
      the maximum number of partitions this sketch will support.
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      T getMinItem()
      +
      Returns the minimum item of the stream. This may be distinct from the smallest item retained by the +sketch algorithm.
      +
      +
      Returns:
      +
      the minimum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      default double[] getPMF(T[] splitPoints)
      +
      This is equivalent to getPMF(splitPoints, INCLUSIVE)
      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      double[] getPMF(T[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      default T getQuantile(double rank)
      +
      This is equivalent to getQuantile(rank, INCLUSIVE)
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      T getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileLowerBound

      +
      +
      T getQuantileLowerBound(double rank)
      +
      Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile confidence interval +as an additive or multiplicative percent of the true quantile.

      +
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileUpperBound

      +
      +
      T getQuantileUpperBound(double rank)
      +
      Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile interval +as an additive or multiplicative percent of the true quantile.

      +
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      default T[] getQuantiles(double[] ranks)
      +
      This is equivalent to getQuantiles(ranks, INCLUSIVE)
      +
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      T[] getQuantiles(double[] ranks, + QuantileSearchCriteria searchCrit)
      +
      Gets an array of quantiles from the given array of normalized ranks.
      +
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      searchCrit - if INCLUSIVE, the given ranks include all quantiles ≤ +the quantile directly corresponding to each rank.
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      default double getRank(T quantile)
      +
      This is equivalent to getRank(T quantile, INCLUSIVE)
      +
      +
      Parameters:
      +
      quantile - the given quantile
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      double getRank(T quantile, + QuantileSearchCriteria searchCrit)
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      default double[] getRanks(T[] quantiles)
      +
      This is equivalent to getRanks(quantiles, INCLUSIVE)
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      double[] getRanks(T[] quantiles, + QuantileSearchCriteria searchCrit)
      +
      Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      searchCrit - if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile.
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getSortedView

      +
      +
      GenericSortedView<T> getSortedView()
      +
      Gets the sorted view of this sketch
      +
      +
      Returns:
      +
      the sorted view of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Gets the iterator for this sketch, which is not sorted.
      +
      +
      Returns:
      +
      the iterator for this sketch
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      void update(T item)
      +
      Updates this sketch with the given item.
      +
      +
      Parameters:
      +
      item - from a stream of items. Nulls are ignored.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesGenericSketchIteratorAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesGenericSketchIteratorAPI.html new file mode 100644 index 000000000..a7902a6c7 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesGenericSketchIteratorAPI.html @@ -0,0 +1,166 @@ + + + + +QuantilesGenericSketchIteratorAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface QuantilesGenericSketchIteratorAPI<T>

+
+
+
+
Type Parameters:
+
T - The generic quantile type
+
+
+
All Superinterfaces:
+
QuantilesSketchIteratorAPI
+
+
+
All Known Implementing Classes:
+
KllItemsSketchIterator, QuantilesItemsSketchIterator
+
+
+
+
public interface QuantilesGenericSketchIteratorAPI<T> +extends QuantilesSketchIteratorAPI
+
The quantiles sketch iterator for generic types.
+
+
Author:
+
Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Gets the generic quantile at the current index.
    +
    +
    +
    +
    +
    +

    Methods inherited from interface QuantilesSketchIteratorAPI

    +getWeight, next
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      T getQuantile()
      +
      Gets the generic quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Returns:
      +
      the generic quantile at the current index.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesLongsAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesLongsAPI.html new file mode 100644 index 000000000..126c7c461 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesLongsAPI.html @@ -0,0 +1,738 @@ + + + + +QuantilesLongsAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface QuantilesLongsAPI

+
+
+
+
All Superinterfaces:
+
QuantilesAPI
+
+
+
All Known Implementing Classes:
+
KllLongsSketch
+
+
+
+
public interface QuantilesLongsAPI +extends QuantilesAPI
+
The Quantiles API for item type long.
+
+
Author:
+
Lee Rhodes, Zac Blanco
+
See Also:
+
+ +
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCDF

      +
      +
      default double[] getCDF(long[] splitPoints)
      +
      This is equivalent to getCDF(splitPoints, INCLUSIVE)
      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getCDF

      +
      +
      double[] getCDF(long[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      long getMaxItem()
      +
      Returns the maximum item of the stream. This is provided for convenience and may be different from the +item returned by getQuantile(1.0).
      +
      +
      Returns:
      +
      the maximum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      long getMinItem()
      +
      Returns the minimum item of the stream. This is provided for convenience and may be different from the +item returned by getQuantile(0.0).
      +
      +
      Returns:
      +
      the minimum item of the stream
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      default double[] getPMF(long[] splitPoints)
      +
      This is equivalent to getPMF(splitPoints, INCLUSIVE)
      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      double[] getPMF(long[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      default long getQuantile(double rank)
      +
      This is equivalent to getQuantile(rank, INCLUSIVE)
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      long getQuantile(double rank, + QuantileSearchCriteria searchCrit)
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileLowerBound

      +
      +
      long getQuantileLowerBound(double rank)
      +
      Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile confidence interval +as an additive or multiplicative percent of the true quantile.

      +
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileUpperBound

      +
      +
      long getQuantileUpperBound(double rank)
      +
      Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile interval +as an additive or multiplicative percent of the true quantile.

      +
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      default long[] getQuantiles(double[] ranks)
      +
      This is equivalent to getQuantiles(ranks, INCLUSIVE)
      +
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      long[] getQuantiles(double[] ranks, + QuantileSearchCriteria searchCrit)
      +
      Gets an array of quantiles from the given array of normalized ranks.
      +
      +
      Parameters:
      +
      ranks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      searchCrit - if INCLUSIVE, the given ranks include all quantiles ≤ +the quantile directly corresponding to each rank.
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      default double getRank(long quantile)
      +
      This is equivalent to getRank(quantile, INCLUSIVE)
      +
      +
      Parameters:
      +
      quantile - the given quantile
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      double getRank(long quantile, + QuantileSearchCriteria searchCrit)
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      default double[] getRanks(long[] quantiles)
      +
      This is equivalent to getRanks(quantiles, INCLUSIVE)
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      double[] getRanks(long[] quantiles, + QuantileSearchCriteria searchCrit)
      +
      Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
      +
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      searchCrit - if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile.
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      Throws:
      +
      IllegalArgumentException - if sketch is empty.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getSerializedSizeBytes

      +
      +
      int getSerializedSizeBytes()
      +
      Returns the current number of bytes this Sketch would require if serialized.
      +
      +
      Returns:
      +
      the number of bytes this sketch would require if serialized.
      +
      +
      +
      +
    • +
    • +
      +

      getSortedView

      +
      +
      LongsSortedView getSortedView()
      +
      Gets the sorted view of this sketch
      +
      +
      Returns:
      +
      the sorted view of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Gets the iterator for this sketch, which is not sorted.
      +
      +
      Returns:
      +
      the iterator for this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      byte[] toByteArray()
      +
      Returns a byte array representation of this sketch.
      +
      +
      Returns:
      +
      a byte array representation of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      void update(long item)
      +
      Updates this sketch with the given item.
      +
      +
      Parameters:
      +
      item - from a stream of items. NaNs are ignored.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesLongsSketchIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesLongsSketchIterator.html new file mode 100644 index 000000000..230137e8c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesLongsSketchIterator.html @@ -0,0 +1,162 @@ + + + + +QuantilesLongsSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface QuantilesLongsSketchIterator

+
+
+
+
All Superinterfaces:
+
QuantilesSketchIteratorAPI
+
+
+
All Known Implementing Classes:
+
KllLongsSketchIterator
+
+
+
+
public interface QuantilesLongsSketchIterator +extends QuantilesSketchIteratorAPI
+
The quantiles sketch iterator for primitive type long.
+
+
Author:
+
Zac Blanco
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    long
    + +
    +
    Gets the long quantile at the current index.
    +
    +
    +
    +
    +
    +

    Methods inherited from interface QuantilesSketchIteratorAPI

    +getWeight, next
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      long getQuantile()
      +
      Gets the long quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Returns:
      +
      the long quantile at the current index.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesSketchIteratorAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesSketchIteratorAPI.html new file mode 100644 index 000000000..243e0483e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesSketchIteratorAPI.html @@ -0,0 +1,180 @@ + + + + +QuantilesSketchIteratorAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface QuantilesSketchIteratorAPI

+
+
+
+
All Known Subinterfaces:
+
QuantilesDoublesSketchIteratorAPI, QuantilesFloatsSketchIterator, QuantilesGenericSketchIteratorAPI<T>, QuantilesLongsSketchIterator
+
+
+
All Known Implementing Classes:
+
KllDoublesSketchIterator, KllFloatsSketchIterator, KllItemsSketchIterator, KllLongsSketchIterator, KllSketchIterator, QuantilesDoublesSketchIterator, QuantilesItemsSketchIterator, ReqSketchIterator
+
+
+
+
public interface QuantilesSketchIteratorAPI
+
This is the base API for the iterator hierarchy used for viewing the +non-ordered quantiles retained by the classic Quantiles* sketches and KLL sketches, for example. + +

Prototype example of the recommended iteration loop:

+
  SketchIterator itr = sketch.iterator();
+  while (itr.next()) {
+    ...get*();
+  }
+
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    long
    + +
    +
    Gets the natural weight at the current index.
    +
    +
    boolean
    + +
    +
    Advances the index and checks if it is valid.
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getWeight

      +
      +
      long getWeight()
      +
      Gets the natural weight at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Returns:
      +
      the natural weight at the current index.
      +
      +
      +
      +
    • +
    • +
      +

      next

      +
      +
      boolean next()
      +
      Advances the index and checks if it is valid. +The state of this iterator is undefined before the first call of this method.
      +
      +
      Returns:
      +
      true if the next index is valid.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesUtil.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesUtil.html new file mode 100644 index 000000000..f8f34274f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/QuantilesUtil.html @@ -0,0 +1,434 @@ + + + + +QuantilesUtil (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class QuantilesUtil

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.QuantilesUtil
+
+
+
+
+
public final class QuantilesUtil +extends Object
+
Utilities for the quantiles sketches.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    static final double
    + +
    +
    used in search to improve rounding over a wide dynamic range
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static final void
    + +
    +
    Checks the sequential validity of the given array of double values.
    +
    +
    static final void
    + +
    +
    Checks the sequential validity of the given array of float values.
    +
    +
    static void
    + +
    +
    Checks the sequential validity of the given array of double values.
    +
    +
    static final void
    + +
    +
    Checks that the given normalized rank: 0 ≤ nRank ≤ 1.0.
    +
    +
    static double[]
    + +
    +
    Returns an array of (num + 1) values that define equally sized intervals between 0.0, inclusive, and 1.0, +inclusive.
    +
    +
    static long[]
    +
    equallySpacedLongs(long min, + long max, + int num)
    +
    +
    Returns an array of (num + 1) longs that define, approximately, equally spaced intervals between the given +max, inclusive, and min, inclusive.
    +
    +
    static double[]
    +
    evenlyLogSpaced(double value1, + double value2, + int num)
    +
    +
    Returns a double array of values between min and max inclusive where the log of the +returned values are evenly spaced.
    +
    +
    static double[]
    +
    evenlySpacedDoubles(double value1, + double value2, + int num)
    +
    +
    Returns a double array of evenly spaced values between value1, inclusive, and value2 inclusive.
    +
    +
    static float[]
    +
    evenlySpacedFloats(float value1, + float value2, + int num)
    +
    +
    Returns a float array of evenly spaced values between value1, inclusive, and value2 inclusive.
    +
    +
    static double
    +
    getNaturalRank(double normalizedRank, + long totalN, + QuantileSearchCriteria searchCrit)
    +
    +
    Computes the closest Natural Rank from a given Normalized Rank
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      tailRoundingFactor

      +
      +
      public static final double tailRoundingFactor
      +
      used in search to improve rounding over a wide dynamic range
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      checkNormalizedRankBounds

      +
      +
      public static final void checkNormalizedRankBounds(double nRank)
      +
      Checks that the given normalized rank: 0 ≤ nRank ≤ 1.0.
      +
      +
      Parameters:
      +
      nRank - the given normalized rank.
      +
      +
      +
      +
    • +
    • +
      +

      checkDoublesSplitPointsOrder

      +
      +
      public static final void checkDoublesSplitPointsOrder(double[] values)
      +
      Checks the sequential validity of the given array of double values. +They must be unique, monotonically increasing and not NaN.
      +
      +
      Parameters:
      +
      values - the given array of double values
      +
      +
      +
      +
    • +
    • +
      +

      checkLongsSplitPointsOrder

      +
      +
      public static void checkLongsSplitPointsOrder(long[] values)
      +
      Checks the sequential validity of the given array of double values. +They must be unique and monotonically increasing.
      +
      +
      Parameters:
      +
      values - the given array of double values
      +
      +
      +
      +
    • +
    • +
      +

      checkFloatsSplitPointsOrder

      +
      +
      public static final void checkFloatsSplitPointsOrder(float[] values)
      +
      Checks the sequential validity of the given array of float values. +They must be unique, monotonically increasing and not NaN.
      +
      +
      Parameters:
      +
      values - the given array of double values
      +
      +
      +
      +
    • +
    • +
      +

      equallySpacedDoubles

      +
      +
      public static double[] equallySpacedDoubles(int num)
      +
      Returns an array of (num + 1) values that define equally sized intervals between 0.0, inclusive, and 1.0, +inclusive. The end points 0.0 and 1.0 are part of the returned array. + +

      For example, if num == 2, three values will be returned: 0.0, .5, and 1, where the two equally sized regions +are {0.0,0.5}, and {0.5, 1.0}.

      +
      +
      Parameters:
      +
      num - the total number of equally sized intervals between 0.0, inclusive and 1.0, inclusive. +Must be 1 or greater.
      +
      Returns:
      +
      a double array of values that define (num + 1) equally sized intervals between 0.0, inclusive and 1.0, +inclusive.
      +
      Throws:
      +
      IllegalArgumentException - if num is less than 1.
      +
      +
      +
      +
    • +
    • +
      +

      equallySpacedLongs

      +
      +
      public static long[] equallySpacedLongs(long min, + long max, + int num)
      +
      Returns an array of (num + 1) longs that define, approximately, equally spaced intervals between the given +max, inclusive, and min, inclusive. The end points max and min are part of the +returned array. Because the range of the values may not exactly divide into num intervals, +the size of these intervals may vary by plus or minus one.
      +
      +
      Parameters:
      +
      min - the lowest positive valued (or zero) number of the range
      +
      max - the highest positive valued number of the range. max must be greater than min
      +
      num - Number of requested intervals. Must be greater or equal to one, and less than or equal to +max - min.
      +
      Returns:
      +
      an array of (num + 1) longs that are approximately equally spaced between the given min and max.
      +
      +
      +
      +
    • +
    • +
      +

      evenlySpacedFloats

      +
      +
      public static float[] evenlySpacedFloats(float value1, + float value2, + int num)
      +
      Returns a float array of evenly spaced values between value1, inclusive, and value2 inclusive. +If value2 > value1, the resulting sequence will be increasing. +If value2 < value1, the resulting sequence will be decreasing.
      +
      +
      Parameters:
      +
      value1 - will be in index 0 of the returned array
      +
      value2 - will be in the highest index of the returned array
      +
      num - the total number of values including value1 and value2. Must be 2 or greater.
      +
      Returns:
      +
      a float array of evenly spaced values between value1, inclusive, and value2 inclusive.
      +
      +
      +
      +
    • +
    • +
      +

      evenlySpacedDoubles

      +
      +
      public static double[] evenlySpacedDoubles(double value1, + double value2, + int num)
      +
      Returns a double array of evenly spaced values between value1, inclusive, and value2 inclusive. +If value2 > value1, the resulting sequence will be increasing. +If value2 < value1, the resulting sequence will be decreasing.
      +
      +
      Parameters:
      +
      value1 - will be in index 0 of the returned array
      +
      value2 - will be in the highest index of the returned array
      +
      num - the total number of values including value1 and value2. Must be 2 or greater.
      +
      Returns:
      +
      a float array of evenly spaced values between value1, inclusive, and value2 inclusive.
      +
      +
      +
      +
    • +
    • +
      +

      evenlyLogSpaced

      +
      +
      public static double[] evenlyLogSpaced(double value1, + double value2, + int num)
      +
      Returns a double array of values between min and max inclusive where the log of the +returned values are evenly spaced. +If value2 > value1, the resulting sequence will be increasing. +If value2 < value1, the resulting sequence will be decreasing.
      +
      +
      Parameters:
      +
      value1 - will be in index 0 of the returned array, and must be greater than zero.
      +
      value2 - will be in the highest index of the returned array, and must be greater than zero.
      +
      num - the total number of values including value1 and value2. Must be 2 or greater
      +
      Returns:
      +
      a double array of exponentially spaced values between value1 and value2 inclusive.
      +
      +
      +
      +
    • +
    • +
      +

      getNaturalRank

      +
      +
      public static double getNaturalRank(double normalizedRank, + long totalN, + QuantileSearchCriteria searchCrit)
      +
      Computes the closest Natural Rank from a given Normalized Rank
      +
      +
      Parameters:
      +
      normalizedRank - the given normalized rank
      +
      totalN - the total N
      +
      searchCrit - the search criterion.
      +
      Returns:
      +
      the closest Natural Rank from a given Normalized Rank
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/SketchPartitionLimits.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/SketchPartitionLimits.html new file mode 100644 index 000000000..beb6a761f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/SketchPartitionLimits.html @@ -0,0 +1,187 @@ + + + + +SketchPartitionLimits (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface SketchPartitionLimits

+
+
+
+
All Known Subinterfaces:
+
GenericSortedView<T>, QuantilesGenericAPI<T>
+
+
+
All Known Implementing Classes:
+
ItemsSketchSortedView, KllItemsSketch, QuantilesItemsSketch
+
+
+
+
public interface SketchPartitionLimits
+
This defines the methods required to compute the partition limits.
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    int
    + +
    +
    Gets the maximum number of partitions this sketch will support based on the configured size K +and the number of retained values of this sketch.
    +
    +
    default long
    + +
    +
    Gets the minimum partition size in items this sketch will support based on the configured size K of this +sketch and the number of retained values of this sketch.
    +
    +
    long
    + +
    +
    Gets the length of the input stream offered to the sketch..
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getMaxPartitions

      +
      +
      int getMaxPartitions()
      +
      Gets the maximum number of partitions this sketch will support based on the configured size K +and the number of retained values of this sketch.
      +
      +
      Returns:
      +
      the maximum number of partitions this sketch will support.
      +
      +
      +
      +
    • +
    • +
      +

      getMinPartitionSizeItems

      +
      +
      default long getMinPartitionSizeItems()
      +
      Gets the minimum partition size in items this sketch will support based on the configured size K of this +sketch and the number of retained values of this sketch.
      +
      +
      Returns:
      +
      the minimum partition size in items this sketch will support.
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      long getN()
      +
      Gets the length of the input stream offered to the sketch..
      +
      +
      Returns:
      +
      the length of the input stream offered to the sketch.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/SortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/SortedView.html new file mode 100644 index 000000000..244b58f62 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/SortedView.html @@ -0,0 +1,235 @@ + + + + +SortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface SortedView

+
+
+
+
All Known Subinterfaces:
+
DoublesSortedView, FloatsSortedView, GenericSortedView<T>, LongsSortedView
+
+
+
All Known Implementing Classes:
+
DoublesSketchSortedView, FloatsSketchSortedView, ItemsSketchSortedView, LongsSketchSortedView
+
+
+
+
public interface SortedView
+
This is the base interface for the Sorted View interface hierarchy and defines the methods that are type independent. + +

The SortedView interface hierarchy provides a sorted view of the data retained by a quantiles-type sketch that +would be cumbersome to get any other way. +One could use the sketch's iterator to iterate over the contents of the sketch, +but the result would not be sorted.

+ +

The data from a Sorted view is an unbiased random sample of the input stream that can be used for other kinds of +analysis not directly provided by the sketch.

+
+
Author:
+
Alexander Saydakov, Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    long[]
    + +
    +
    Returns the array of cumulative weights from the sketch.
    +
    +
    long
    + +
    +
    Returns the total number of items presented to the sourcing sketch.
    +
    +
    int
    + +
    +
    Gets the number of quantiles retained by this sorted view.
    +
    +
    boolean
    + +
    +
    Returns true if this sorted view is empty.
    +
    + + +
    +
    Returns an iterator for this Sorted View.
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCumulativeWeights

      +
      +
      long[] getCumulativeWeights()
      +
      Returns the array of cumulative weights from the sketch. +Also known as the natural ranks, which are the Natural Numbers on the interval [1, N].
      +
      +
      Returns:
      +
      the array of cumulative weights (or natural ranks).
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      long getN()
      +
      Returns the total number of items presented to the sourcing sketch.
      +
      +
      Returns:
      +
      the total number of items presented to the sourcing sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNumRetained

      +
      +
      int getNumRetained()
      +
      Gets the number of quantiles retained by this sorted view. +This may be slightly different from the function with the same name when called from the originating sketch.
      +
      +
      Returns:
      +
      the number of quantiles retained by this sorted view
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      boolean isEmpty()
      +
      Returns true if this sorted view is empty.
      +
      +
      Returns:
      +
      true if this sorted view is empty.
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      SortedViewIterator iterator()
      +
      Returns an iterator for this Sorted View.
      +
      +
      Returns:
      +
      an iterator for this Sorted View.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/SortedViewIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/SortedViewIterator.html new file mode 100644 index 000000000..274a69729 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/SortedViewIterator.html @@ -0,0 +1,302 @@ + + + + +SortedViewIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class SortedViewIterator

+
+
java.lang.Object +
org.apache.datasketches.quantilescommon.SortedViewIterator
+
+
+
+
Direct Known Subclasses:
+
DoublesSortedViewIterator, FloatsSortedViewIterator, GenericSortedViewIterator, LongsSortedViewIterator
+
+
+
+
public class SortedViewIterator +extends Object
+
This is the base interface for the SortedViewIterator hierarchy used with a SortedView obtained +from a quantile-type sketch. This provides an ordered iterator over the retained quantiles of +the associated quantile-type sketch. + +

Prototype example of the recommended iteration loop:

+
  SortedViewIterator itr = sketch.getSortedView().iterator();
+  while (itr.next()) {
+    long weight = itr.getWeight();
+    ...
+  }
+
+
+
Author:
+
Alexander Saydakov, Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    long
    + +
    +
    Gets the total count of all items presented to the sketch.
    +
    +
    long
    + +
    +
    Gets the natural rank at the current index.
    +
    +
    long
    + +
    +
    Gets the natural rank at the current index (or previous index) based on the chosen search criterion.
    +
    +
    double
    + +
    +
    Gets the normalized rank at the current index.
    +
    +
    double
    + +
    +
    Gets the normalized rank at the current index (or previous index) +based on the chosen search criterion.
    +
    +
    long
    + +
    +
    Gets the weight contribution of the item at the current index.
    +
    +
    boolean
    + +
    +
    Advances the index and checks if it is valid.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getNaturalRank

      +
      +
      public long getNaturalRank()
      +
      Gets the natural rank at the current index. +This is equivalent to getNaturalRank(INCLUSIVE). + +

      Don't call this before calling next() for the first time or after getting false from next().

      +
      +
      Returns:
      +
      the natural rank at the current index.
      +
      +
      +
      +
    • +
    • +
      +

      getNaturalRank

      +
      +
      public long getNaturalRank(QuantileSearchCriteria searchCrit)
      +
      Gets the natural rank at the current index (or previous index) based on the chosen search criterion. +This is also referred to as the "cumulative weight". The natural rank is a number in the range [1, N], +where N (getN()) is the total number of items fed to the sketch. + +

      Don't call this before calling next() for the first time or after getting false from next().

      +
      +
      Parameters:
      +
      searchCrit - if INCLUSIVE, includes the weight of the item at the current index in the computation of +the natural rank. +Otherwise, it will return the natural rank of the previous index.
      +
      Returns:
      +
      the natural rank at the current index (or previous index) based on the chosen search criterion.
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      public long getN()
      +
      Gets the total count of all items presented to the sketch.
      +
      +
      Returns:
      +
      the total count of all items presented to the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNormalizedRank

      +
      +
      public double getNormalizedRank()
      +
      Gets the normalized rank at the current index. +This is equivalent to getNormalizedRank(INCLUSIVE). + +

      Don't call this before calling next() for the first time or after getting false from next().

      +
      +
      Returns:
      +
      the normalized rank at the current index
      +
      +
      +
      +
    • +
    • +
      +

      getNormalizedRank

      +
      +
      public double getNormalizedRank(QuantileSearchCriteria searchCrit)
      +
      Gets the normalized rank at the current index (or previous index) +based on the chosen search criterion. Where normalized rank = natural rank / N (getN()) +and is a fraction in the range (0,1.0]. + +

      Don't call this before calling next() for the first time or after getting false from next().

      +
      +
      Parameters:
      +
      searchCrit - if INCLUSIVE, includes the normalized rank at the current index. +Otherwise, returns the normalized rank of the previous index.
      +
      Returns:
      +
      the normalized rank at the current index (or previous index) +based on the chosen search criterion.
      +
      +
      +
      +
    • +
    • +
      +

      getWeight

      +
      +
      public long getWeight()
      +
      Gets the weight contribution of the item at the current index. + +

      Don't call this before calling next() for the first time or after getting false from next().

      +
      +
      Returns:
      +
      the weight contribution of the item at the current index.
      +
      +
      +
      +
    • +
    • +
      +

      next

      +
      +
      public boolean next()
      +
      Advances the index and checks if it is valid. +The state of this iterator is undefined before the first call of this method.
      +
      +
      Returns:
      +
      true if the next index is valid.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/BinarySearch.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/BinarySearch.html new file mode 100644 index 000000000..e2731247b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/BinarySearch.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.BinarySearch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.BinarySearch

+
+No usage of org.apache.datasketches.quantilescommon.BinarySearch +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/DoublesSketchSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/DoublesSketchSortedView.html new file mode 100644 index 000000000..474da3159 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/DoublesSketchSortedView.html @@ -0,0 +1,113 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.DoublesSketchSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.DoublesSketchSortedView

+
+
Packages that use DoublesSketchSortedView
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/DoublesSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/DoublesSortedView.html new file mode 100644 index 000000000..8ae663e80 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/DoublesSortedView.html @@ -0,0 +1,107 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.DoublesSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.DoublesSortedView

+
+
Packages that use DoublesSortedView
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/DoublesSortedViewIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/DoublesSortedViewIterator.html new file mode 100644 index 000000000..2986ea3c2 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/DoublesSortedViewIterator.html @@ -0,0 +1,97 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.DoublesSortedViewIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.DoublesSortedViewIterator

+
+
Packages that use DoublesSortedViewIterator
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/FloatsSketchSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/FloatsSketchSortedView.html new file mode 100644 index 000000000..4e0b61480 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/FloatsSketchSortedView.html @@ -0,0 +1,112 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.FloatsSketchSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.FloatsSketchSortedView

+
+
Packages that use FloatsSketchSortedView
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/FloatsSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/FloatsSortedView.html new file mode 100644 index 000000000..a87ceb9e0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/FloatsSortedView.html @@ -0,0 +1,107 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.FloatsSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.FloatsSortedView

+
+
Packages that use FloatsSortedView
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/FloatsSortedViewIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/FloatsSortedViewIterator.html new file mode 100644 index 000000000..57d6251c1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/FloatsSortedViewIterator.html @@ -0,0 +1,97 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.FloatsSortedViewIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.FloatsSortedViewIterator

+
+
Packages that use FloatsSortedViewIterator
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericInequalitySearch.Inequality.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericInequalitySearch.Inequality.html new file mode 100644 index 000000000..905ef399d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericInequalitySearch.Inequality.html @@ -0,0 +1,131 @@ + + + + +Uses of Enum Class org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.quantilescommon.GenericInequalitySearch.Inequality

+
+ +
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericInequalitySearch.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericInequalitySearch.html new file mode 100644 index 000000000..6c55a81fe --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericInequalitySearch.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.GenericInequalitySearch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.GenericInequalitySearch

+
+No usage of org.apache.datasketches.quantilescommon.GenericInequalitySearch +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericPartitionBoundaries.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericPartitionBoundaries.html new file mode 100644 index 000000000..80c31e0bd --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericPartitionBoundaries.html @@ -0,0 +1,215 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.GenericPartitionBoundaries (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.GenericPartitionBoundaries

+
+
Packages that use GenericPartitionBoundaries
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericSortedView.html new file mode 100644 index 000000000..1685bb8df --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericSortedView.html @@ -0,0 +1,107 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.GenericSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.GenericSortedView

+
+
Packages that use GenericSortedView
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericSortedViewIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericSortedViewIterator.html new file mode 100644 index 000000000..1c642a65a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/GenericSortedViewIterator.html @@ -0,0 +1,97 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.GenericSortedViewIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.GenericSortedViewIterator

+
+
Packages that use GenericSortedViewIterator
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.DoublesPair.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.DoublesPair.html new file mode 100644 index 000000000..f03cf807f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.DoublesPair.html @@ -0,0 +1,100 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.IncludeMinMax.DoublesPair (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.IncludeMinMax.DoublesPair

+
+
Packages that use IncludeMinMax.DoublesPair
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.FloatsPair.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.FloatsPair.html new file mode 100644 index 000000000..07c515a3f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.FloatsPair.html @@ -0,0 +1,100 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.IncludeMinMax.FloatsPair (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.IncludeMinMax.FloatsPair

+
+
Packages that use IncludeMinMax.FloatsPair
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.ItemsPair.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.ItemsPair.html new file mode 100644 index 000000000..bd79aed64 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.ItemsPair.html @@ -0,0 +1,101 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.IncludeMinMax.ItemsPair (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.IncludeMinMax.ItemsPair

+
+
Packages that use IncludeMinMax.ItemsPair
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.LongsPair.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.LongsPair.html new file mode 100644 index 000000000..c6a89ce1e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.LongsPair.html @@ -0,0 +1,100 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.IncludeMinMax.LongsPair (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.IncludeMinMax.LongsPair

+
+
Packages that use IncludeMinMax.LongsPair
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.html new file mode 100644 index 000000000..b2f232d79 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/IncludeMinMax.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.IncludeMinMax (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.IncludeMinMax

+
+No usage of org.apache.datasketches.quantilescommon.IncludeMinMax +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/InequalitySearch.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/InequalitySearch.html new file mode 100644 index 000000000..54d19d837 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/InequalitySearch.html @@ -0,0 +1,160 @@ + + + + +Uses of Enum Class org.apache.datasketches.quantilescommon.InequalitySearch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.quantilescommon.InequalitySearch

+
+
Packages that use InequalitySearch
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+
    +
  • +
    +

    Uses of InequalitySearch in org.apache.datasketches.quantilescommon

    +
    Subclasses with type arguments of type InequalitySearch in org.apache.datasketches.quantilescommon
    +
    +
    Modifier and Type
    +
    Class
    +
    Description
    +
    enum 
    + +
    +
    This provides efficient, unique and unambiguous binary searching for inequality comparison criteria +for ordered arrays of values that may include duplicate values.
    +
    +
    + +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + +
    InequalitySearch.valueOf(String name)
    +
    +
    Returns the enum constant of this class with the specified name.
    +
    + +
    InequalitySearch.values()
    +
    +
    Returns an array containing the constants of this enum class, in +the order they are declared.
    +
    +
    + +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static int
    +
    InequalitySearch.find(double[] arr, + int low, + int high, + double v, + InequalitySearch crit)
    +
    +
    Binary Search for the index of the double value in the given search range that satisfies +the given InequalitySearch criterion.
    +
    +
    static int
    +
    InequalitySearch.find(float[] arr, + int low, + int high, + float v, + InequalitySearch crit)
    +
    +
    Binary Search for the index of the float value in the given search range that satisfies +the given InequalitySearch criterion.
    +
    +
    static int
    +
    InequalitySearch.find(long[] arr, + int low, + int high, + double v, + InequalitySearch crit)
    +
    +
    Binary Search for the index of the double value in the given search range that satisfies +the given InequalitySearch criterion.
    +
    +
    static int
    +
    InequalitySearch.find(long[] arr, + int low, + int high, + long v, + InequalitySearch crit)
    +
    +
    Binary Search for the index of the long value in the given search range that satisfies +the given InequalitySearch criterion.
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/ItemsSketchSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/ItemsSketchSortedView.html new file mode 100644 index 000000000..9873b91f5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/ItemsSketchSortedView.html @@ -0,0 +1,113 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.ItemsSketchSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.ItemsSketchSortedView

+
+
Packages that use ItemsSketchSortedView
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/KolmogorovSmirnov.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/KolmogorovSmirnov.html new file mode 100644 index 000000000..093265f9f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/KolmogorovSmirnov.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.KolmogorovSmirnov (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.KolmogorovSmirnov

+
+No usage of org.apache.datasketches.quantilescommon.KolmogorovSmirnov +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/LongsSketchSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/LongsSketchSortedView.html new file mode 100644 index 000000000..6f4855c6a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/LongsSketchSortedView.html @@ -0,0 +1,94 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.LongsSketchSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.LongsSketchSortedView

+
+
Packages that use LongsSketchSortedView
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/LongsSortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/LongsSortedView.html new file mode 100644 index 000000000..5a260867a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/LongsSortedView.html @@ -0,0 +1,107 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.LongsSortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.LongsSortedView

+
+
Packages that use LongsSortedView
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/LongsSortedViewIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/LongsSortedViewIterator.html new file mode 100644 index 000000000..50f7c6fe5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/LongsSortedViewIterator.html @@ -0,0 +1,97 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.LongsSortedViewIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.LongsSortedViewIterator

+
+
Packages that use LongsSortedViewIterator
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/PartitioningFeature.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/PartitioningFeature.html new file mode 100644 index 000000000..893c8f6b5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/PartitioningFeature.html @@ -0,0 +1,184 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.PartitioningFeature (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.PartitioningFeature

+
+
Packages that use PartitioningFeature
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantileSearchCriteria.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantileSearchCriteria.html new file mode 100644 index 000000000..5f2dbd342 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantileSearchCriteria.html @@ -0,0 +1,760 @@ + + + + +Uses of Enum Class org.apache.datasketches.quantilescommon.QuantileSearchCriteria (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.quantilescommon.QuantileSearchCriteria

+
+
Packages that use QuantileSearchCriteria
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesAPI.html new file mode 100644 index 000000000..88003c7c3 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesAPI.html @@ -0,0 +1,234 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.QuantilesAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.QuantilesAPI

+
+
Packages that use QuantilesAPI
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesDoublesAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesDoublesAPI.html new file mode 100644 index 000000000..d36ead2e1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesDoublesAPI.html @@ -0,0 +1,164 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.QuantilesDoublesAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.QuantilesDoublesAPI

+
+
Packages that use QuantilesDoublesAPI
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesDoublesSketchIteratorAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesDoublesSketchIteratorAPI.html new file mode 100644 index 000000000..5d1d101ae --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesDoublesSketchIteratorAPI.html @@ -0,0 +1,156 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIteratorAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.QuantilesDoublesSketchIteratorAPI

+
+ +
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesFloatsAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesFloatsAPI.html new file mode 100644 index 000000000..41cdf535a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesFloatsAPI.html @@ -0,0 +1,153 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.QuantilesFloatsAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.QuantilesFloatsAPI

+
+
Packages that use QuantilesFloatsAPI
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesFloatsSketchIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesFloatsSketchIterator.html new file mode 100644 index 000000000..ee9d6139f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesFloatsSketchIterator.html @@ -0,0 +1,155 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.QuantilesFloatsSketchIterator

+
+ +
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesGenericAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesGenericAPI.html new file mode 100644 index 000000000..172c517a6 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesGenericAPI.html @@ -0,0 +1,170 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.QuantilesGenericAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.QuantilesGenericAPI

+
+
Packages that use QuantilesGenericAPI
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesGenericSketchIteratorAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesGenericSketchIteratorAPI.html new file mode 100644 index 000000000..71511eed5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesGenericSketchIteratorAPI.html @@ -0,0 +1,156 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.QuantilesGenericSketchIteratorAPI

+
+ +
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesLongsAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesLongsAPI.html new file mode 100644 index 000000000..66401330e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesLongsAPI.html @@ -0,0 +1,119 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.QuantilesLongsAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.QuantilesLongsAPI

+
+
Packages that use QuantilesLongsAPI
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesLongsSketchIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesLongsSketchIterator.html new file mode 100644 index 000000000..3918de611 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesLongsSketchIterator.html @@ -0,0 +1,126 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.QuantilesLongsSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.QuantilesLongsSketchIterator

+
+ +
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesSketchIteratorAPI.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesSketchIteratorAPI.html new file mode 100644 index 000000000..ed3dbf4a8 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesSketchIteratorAPI.html @@ -0,0 +1,199 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.QuantilesSketchIteratorAPI (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.QuantilesSketchIteratorAPI

+
+
Packages that use QuantilesSketchIteratorAPI
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesUtil.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesUtil.html new file mode 100644 index 000000000..58e87395e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/QuantilesUtil.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.QuantilesUtil (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.QuantilesUtil

+
+No usage of org.apache.datasketches.quantilescommon.QuantilesUtil +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/SketchPartitionLimits.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/SketchPartitionLimits.html new file mode 100644 index 000000000..12f5b3da7 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/SketchPartitionLimits.html @@ -0,0 +1,156 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.SketchPartitionLimits (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.SketchPartitionLimits

+
+
Packages that use SketchPartitionLimits
+
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/SortedView.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/SortedView.html new file mode 100644 index 000000000..39b6d44c9 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/SortedView.html @@ -0,0 +1,137 @@ + + + + +Uses of Interface org.apache.datasketches.quantilescommon.SortedView (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.quantilescommon.SortedView

+
+
Packages that use SortedView
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/SortedViewIterator.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/SortedViewIterator.html new file mode 100644 index 000000000..352239cc5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/class-use/SortedViewIterator.html @@ -0,0 +1,122 @@ + + + + +Uses of Class org.apache.datasketches.quantilescommon.SortedViewIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.quantilescommon.SortedViewIterator

+
+
Packages that use SortedViewIterator
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/package-summary.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/package-summary.html new file mode 100644 index 000000000..d70e97c83 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/package-summary.html @@ -0,0 +1,273 @@ + + + + +org.apache.datasketches.quantilescommon (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.quantilescommon

+
+
+
+
package org.apache.datasketches.quantilescommon
+
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/package-tree.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/package-tree.html new file mode 100644 index 000000000..f3d534724 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/package-tree.html @@ -0,0 +1,157 @@ + + + + +org.apache.datasketches.quantilescommon Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.quantilescommon

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Interface Hierarchy

+ +
+
+

Enum Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/quantilescommon/package-use.html b/target/site/apidocs/org/apache/datasketches/quantilescommon/package-use.html new file mode 100644 index 000000000..dcf4cd892 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/quantilescommon/package-use.html @@ -0,0 +1,441 @@ + + + + +Uses of Package org.apache.datasketches.quantilescommon (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.quantilescommon

+
+ +
+
Package
+
Description
+ +
+
This package is for the implementations of the sketch algorithm developed by Zohar Karnin, Kevin Lang, +and Edo Liberty that is commonly referred to as the "KLL" sketch after the authors' last names.
+
+ +
+
This package is for classes that simplify the task of partitioning large data into many approximately equal-sized +partitions.
+
+ +
+
The quantiles package contains stochastic streaming algorithms that enable single-pass +analysis of the distribution of a stream of quantiles.
+
+ +
+
This package contains common tools and methods for the quantiles, kll and +req packages.
+
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/req/ReqDebug.html b/target/site/apidocs/org/apache/datasketches/req/ReqDebug.html new file mode 100644 index 000000000..75a2bb1c7 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/req/ReqDebug.html @@ -0,0 +1,310 @@ + + + + +ReqDebug (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface ReqDebug

+
+
+
+
+
public interface ReqDebug
+
The signaling interface that allows comprehensive analysis of the ReqSketch and ReqCompactor +while eliminating code clutter in the main classes. The implementation of this interface can be +found in the test tree.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    void
    +
    emitAdjSecSizeNumSec(byte lgWeight)
    +
    +
    Emit adjusting section size and number of sections.
    +
    +
    void
    + +
    +
    Emit all horizontal lists
    +
    +
    void
    +
    emitCompactingStart(byte lgWeight)
    +
    +
    Emit Compaction Start.
    +
    +
    void
    +
    emitCompactionDetail(int compactionStart, + int compactionEnd, + int secsToCompact, + int promoteLen, + boolean coin)
    +
    +
    Emit Compaction details.
    +
    +
    void
    +
    emitCompactionDone(byte lgWeight)
    +
    +
    Emit compaction done and number of compactions so far.
    +
    +
    void
    + +
    +
    Emit compress done.
    +
    +
    void
    + +
    +
    Emit Must add compactor
    +
    +
    void
    +
    emitNewCompactor(byte lgWeight)
    +
    +
    Emit new compactor configuration
    +
    +
    void
    + +
    +
    Emit the start signal
    +
    +
    void
    + +
    +
    Emit Start Compress
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      emitStart

      +
      +
      void emitStart(ReqSketch sk)
      +
      Emit the start signal
      +
      +
      Parameters:
      +
      sk - the sketch
      +
      +
      +
      +
    • +
    • +
      +

      emitStartCompress

      +
      +
      void emitStartCompress()
      +
      Emit Start Compress
      +
      +
      +
    • +
    • +
      +

      emitCompressDone

      +
      +
      void emitCompressDone()
      +
      Emit compress done.
      +
      +
      +
    • +
    • +
      +

      emitAllHorizList

      +
      +
      void emitAllHorizList()
      +
      Emit all horizontal lists
      +
      +
      +
    • +
    • +
      +

      emitMustAddCompactor

      +
      +
      void emitMustAddCompactor()
      +
      Emit Must add compactor
      +
      +
      +
    • +
    • +
      +

      emitCompactingStart

      +
      +
      void emitCompactingStart(byte lgWeight)
      +
      Emit Compaction Start.
      +
      +
      Parameters:
      +
      lgWeight - compactor lgWeight or height
      +
      +
      +
      +
    • +
    • +
      +

      emitNewCompactor

      +
      +
      void emitNewCompactor(byte lgWeight)
      +
      Emit new compactor configuration
      +
      +
      Parameters:
      +
      lgWeight - the log weight
      +
      +
      +
      +
    • +
    • +
      +

      emitAdjSecSizeNumSec

      +
      +
      void emitAdjSecSizeNumSec(byte lgWeight)
      +
      Emit adjusting section size and number of sections.
      +
      +
      Parameters:
      +
      lgWeight - the log weight
      +
      +
      +
      +
    • +
    • +
      +

      emitCompactionDetail

      +
      +
      void emitCompactionDetail(int compactionStart, + int compactionEnd, + int secsToCompact, + int promoteLen, + boolean coin)
      +
      Emit Compaction details.
      +
      +
      Parameters:
      +
      compactionStart - the offset of compaction start
      +
      compactionEnd - the offset of compaction end
      +
      secsToCompact - the number of sections to compact
      +
      promoteLen - the length of the promotion field
      +
      coin - the state of the random coin.
      +
      +
      +
      +
    • +
    • +
      +

      emitCompactionDone

      +
      +
      void emitCompactionDone(byte lgWeight)
      +
      Emit compaction done and number of compactions so far.
      +
      +
      Parameters:
      +
      lgWeight - the log weight
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/req/ReqSketch.html b/target/site/apidocs/org/apache/datasketches/req/ReqSketch.html new file mode 100644 index 000000000..f95fb3704 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/req/ReqSketch.html @@ -0,0 +1,1162 @@ + + + + +ReqSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ReqSketch

+
+
java.lang.Object +
org.apache.datasketches.req.ReqSketch
+
+
+
+
All Implemented Interfaces:
+
QuantilesAPI, QuantilesFloatsAPI
+
+
+
+
public final class ReqSketch +extends Object
+
This Relative Error Quantiles Sketch is the Java implementation based on the paper +"Relative Error Streaming Quantiles" by Graham Cormode, Zohar Karnin, Edo Liberty, +Justin Thaler, Pavel Veselý, and loosely derived from a Python prototype written by Pavel Veselý. + +

Reference: https://arxiv.org/abs/2004.01668

+ +

This implementation differs from the algorithm described in the paper in the following:

+ +
    +
  • The algorithm requires no upper bound on the stream length. +Instead, each relative-compactor counts the number of compaction operations performed +so far (via variable state). Initially, the relative-compactor starts with INIT_NUMBER_OF_SECTIONS. +Each time the number of compactions (variable state) exceeds 2^{numSections - 1}, we double +numSections. Note that after merging the sketch with another one variable state may not correspond +to the number of compactions performed at a particular level, however, since the state variable +never exceeds the number of compactions, the guarantees of the sketch remain valid.
  • + +
  • The size of each section (variable k and sectionSize in the code and parameter k in +the paper) is initialized with a number set by the user via variable k. +When the number of sections doubles, we decrease sectionSize by a factor of sqrt(2). +This is applied at each level separately. Thus, when we double the number of sections, the +nominal compactor size increases by a factor of approx. sqrt(2) (+/- rounding).
  • + +
  • The merge operation here does not perform "special compactions", which are used in the paper +to allow for a tight mathematical analysis of the sketch.
  • +
+ +

This implementation provides a number of capabilities not discussed in the paper or provided +in the Python prototype.

+ +
  • The Python prototype only implemented high accuracy for low ranks. This implementation +provides the user with the ability to choose either high rank accuracy or low rank accuracy at +the time of sketch construction.
  • +
  • The Python prototype only implemented a comparison criterion of "INCLUSIVE". This implementation +allows the user to switch back and forth between the "INCLUSIVE" criterion and the "EXCLUSIVE" criterion.
  • +
  • This implementation provides extensive debug visibility into the operation of the sketch with +two levels of detail output. This is not only useful for debugging, but is a powerful tool to +help users understand how the sketch works.
  • +
+
+
Author:
+
Edo Liberty, Pavel Vesely, Lee Rhodes
+
See Also:
+
+ +
+
+
+
+
+
    + +
  • +
    +

    Field Summary

    + +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Returns a new ReqSketchBuilder
    +
    +
    double[]
    +
    getCDF(float[] splitPoints, + QuantileSearchCriteria searchCrit)
    +
    +
    Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints.
    +
    +
    boolean
    + +
    +
    If true, the high ranks are prioritized for better accuracy.
    +
    +
    int
    + +
    +
    Gets the user configured parameter k, which controls the accuracy of the sketch +and its memory space usage.
    +
    +
    float
    + +
    +
    Returns the maximum item of the stream.
    +
    +
    float
    + +
    +
    Returns the minimum item of the stream.
    +
    +
    long
    + +
    +
    Gets the length of the input stream offered to the sketch..
    +
    +
    double
    + +
    +
    Gets the approximate rank error of this sketch normalized as a fraction between zero and one.
    +
    +
    int
    + +
    +
    Gets the number of quantiles retained by the sketch.
    +
    +
    double[]
    +
    getPMF(float[] splitPoints, + QuantileSearchCriteria searchCrit)
    +
    +
    Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints.
    +
    +
    float
    +
    getQuantile(double normRank, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets the approximate quantile of the given normalized rank and the given search criterion.
    +
    +
    float
    +
    getQuantileLowerBound(double rank)
    +
    +
    Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
    +
    +
    float
    +
    getQuantileLowerBound(double rank, + int numStdDev)
    +
    +
    Gets an approximate lower bound of the quantile associated with the given rank.
    +
    +
    float[]
    +
    getQuantiles(double[] normRanks, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets an array of quantiles from the given array of normalized ranks.
    +
    +
    float
    +
    getQuantileUpperBound(double rank)
    +
    +
    Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
    +
    +
    float
    +
    getQuantileUpperBound(double rank, + int numStdDev)
    +
    +
    Gets an approximate upper bound of the quantile associated with the given rank.
    +
    +
    double
    +
    getRank(float quantile, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets the normalized rank corresponding to the given a quantile.
    +
    +
    double
    +
    getRankLowerBound(double rank)
    +
    +
    Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
    +
    +
    double
    +
    getRankLowerBound(double rank, + int numStdDev)
    +
    +
    Gets an approximate lower bound rank of the given normalized rank.
    +
    +
    double[]
    +
    getRanks(float[] quantiles, + QuantileSearchCriteria searchCrit)
    +
    +
    Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
    +
    +
    double
    +
    getRankUpperBound(double rank)
    +
    +
    Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
    +
    +
    double
    +
    getRankUpperBound(double rank, + int numStdDev)
    +
    +
    Gets an approximate upper bound rank of the given rank.
    +
    +
    static double
    +
    getRSE(int k, + double rank, + boolean hra, + long totalN)
    +
    +
    Returns an a priori estimate of relative standard error (RSE, expressed as a number in [0,1]).
    +
    +
    int
    + +
    +
    Returns the current number of bytes this Sketch would require if serialized.
    +
    + + +
    +
    Gets the sorted view of this sketch
    +
    +
    static ReqSketch
    + +
    +
    Returns an ReqSketch on the heap from a MemorySegment image of the sketch.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch is empty.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch is in estimation mode.
    +
    +
    boolean
    + +
    +
    Returns true if this sketch is read only.
    +
    + + +
    +
    Gets the iterator for this sketch, which is not sorted.
    +
    + + +
    +
    Merge other sketch into this one.
    +
    +
    void
    + +
    +
    Resets this sketch to the empty state.
    +
    +
    byte[]
    + +
    +
    Returns a byte array representation of this sketch.
    +
    + + +
    +
    Returns a summary of the key parameters of the sketch.
    +
    +
    void
    +
    update(float item)
    +
    +
    Updates this sketch with the given item.
    +
    + +
    viewCompactorDetail(String fmt, + boolean allData)
    +
    +
    A detailed, human readable view of the sketch compactors and their data.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +

    Methods inherited from interface QuantilesFloatsAPI

    +getCDF, getPMF, getQuantile, getQuantiles, getRank, getRanks
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      builder

      +
      +
      public static ReqSketchBuilder builder()
      +
      Returns a new ReqSketchBuilder
      +
      +
      Returns:
      +
      a new ReqSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static ReqSketch heapify(MemorySegment seg)
      +
      Returns an ReqSketch on the heap from a MemorySegment image of the sketch.
      +
      +
      Parameters:
      +
      seg - The MemorySegment object holding a valid image of an ReqSketch
      +
      Returns:
      +
      an ReqSketch on the heap from a MemorySegment image of the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getK

      +
      +
      public int getK()
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the user configured parameter k, which controls the accuracy of the sketch +and its memory space usage.
      +
      +
      Specified by:
      +
      getK in interface QuantilesAPI
      +
      Returns:
      +
      the user configured parameter k, which controls the accuracy of the sketch +and its memory space usage.
      +
      +
      +
      +
    • +
    • +
      +

      getCDF

      +
      +
      public double[] getCDF(float[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Returns an approximation to the Cumulative Distribution Function (CDF) of the input stream +as a monotonically increasing array of double ranks (or cumulative probabilities) on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(false) function.

      +
      +
      Specified by:
      +
      getCDF in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 overlapping intervals. +
      +

      The start of each interval is below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and the end of the interval +is the rank or cumulative probability corresponding to the split point.

      + +

      The (m+1)th interval represents 100% of the distribution represented by the sketch +and consistent with the definition of a cumulative probability distribution, thus the (m+1)th +rank or probability in the returned array is always 1.0.

      + +

      If a split point exactly equals a retained item of the sketch and the search criterion is:

      + +
        +
      • INCLUSIVE, the resulting cumulative probability will include that item.
      • +
      • EXCLUSIVE, the resulting cumulative probability will not include the weight of that split point.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a discrete CDF array of m+1 double ranks (or cumulative probabilities) on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getHighRankAccuracyMode

      +
      +
      public boolean getHighRankAccuracyMode()
      +
      If true, the high ranks are prioritized for better accuracy. Otherwise +the low ranks are prioritized for better accuracy. This state is chosen during sketch +construction.
      +
      +
      Returns:
      +
      the high ranks accuracy state.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxItem

      +
      +
      public float getMaxItem()
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Returns the maximum item of the stream. This is provided for convenience, but may be different from the largest +item retained by the sketch algorithm.
      +
      +
      Specified by:
      +
      getMaxItem in interface QuantilesFloatsAPI
      +
      Returns:
      +
      the maximum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getMinItem

      +
      +
      public float getMinItem()
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Returns the minimum item of the stream. This is provided for convenience, but is distinct from the smallest +item retained by the sketch algorithm.
      +
      +
      Specified by:
      +
      getMinItem in interface QuantilesFloatsAPI
      +
      Returns:
      +
      the minimum item of the stream
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      public long getN()
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the length of the input stream offered to the sketch..
      +
      +
      Specified by:
      +
      getN in interface QuantilesAPI
      +
      Returns:
      +
      the length of the input stream offered to the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getNormalizedRankError

      +
      +
      public double getNormalizedRankError(boolean pmf)
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the approximate rank error of this sketch normalized as a fraction between zero and one. +The epsilon returned is a best fit to 99 percent confidence empirically measured max error +in thousands of trials.
      +
      +
      Parameters:
      +
      pmf - if true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      Returns:
      +
      if pmf is true, returns the "double-sided" normalized rank error for the getPMF() function. +Otherwise, it is the "single-sided" normalized rank error for all the other queries.
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      public double[] getPMF(float[] splitPoints, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +as an array of probability masses as doubles on the interval [0.0, 1.0], +given a set of splitPoints. + +

      The resulting approximations have a probabilistic guarantee that can be obtained from the +getNormalizedRankError(true) function.

      +
      +
      Specified by:
      +
      getPMF in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing items +(of the same type as the input items) +that divide the item input domain into m+1 consecutive, non-overlapping intervals. +
      +

      Each interval except for the end intervals starts with a split point and ends with the next split +point in sequence.

      + +

      The first interval starts below the lowest item retained by the sketch +corresponding to a zero rank or zero probability, and ends with the first split point

      + +

      The last (m+1)th interval starts with the last split point and ends after the last +item retained by the sketch corresponding to a rank or probability of 1.0.

      + +

      The sum of the probability masses of all (m+1) intervals is 1.0.

      + +

      If the search criterion is:

      + +
        +
      • INCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will include that item. If the lower split point equals an item retained by the sketch, the interval will exclude +that item.
      • +
      • EXCLUSIVE, and the upper split point of an interval equals an item retained by the sketch, the interval +will exclude that item. If the lower split point equals an item retained by the sketch, the interval will include +that item.
      • +
      + +

      It is not recommended to include either the minimum or maximum items of the input stream.

      +
      +
      searchCrit - the desired search criteria.
      +
      Returns:
      +
      a PMF array of m+1 probability masses as doubles on the interval [0.0, 1.0].
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public float getQuantile(double normRank, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Gets the approximate quantile of the given normalized rank and the given search criterion.
      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      normRank - the given normalized rank, a double in the range [0.0, 1.0].
      +
      searchCrit - If INCLUSIVE, the given rank includes all quantiles ≤ +the quantile directly corresponding to the given rank. +If EXCLUSIVE, he given rank includes all quantiles < +the quantile directly corresponding to the given rank.
      +
      Returns:
      +
      the approximate quantile given the normalized rank.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantiles

      +
      +
      public float[] getQuantiles(double[] normRanks, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Gets an array of quantiles from the given array of normalized ranks.
      +
      +
      Specified by:
      +
      getQuantiles in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      normRanks - the given array of normalized ranks, each of which must be +in the interval [0.0,1.0].
      +
      searchCrit - if INCLUSIVE, the given ranks include all quantiles ≤ +the quantile directly corresponding to each rank.
      +
      Returns:
      +
      an array of quantiles corresponding to the given array of normalized ranks.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileLowerBound

      +
      +
      public float getQuantileLowerBound(double rank)
      +
      Gets the lower bound of the quantile confidence interval in which the quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile confidence interval +as an additive or multiplicative percent of the true quantile.

      +The approximate probability that the true quantile is within the confidence interval +specified by the upper and lower quantile bounds for this sketch is 0.95.
      +
      +
      Specified by:
      +
      getQuantileLowerBound in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the lower bound of the quantile confidence interval in which the quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileLowerBound

      +
      +
      public float getQuantileLowerBound(double rank, + int numStdDev)
      +
      Gets an approximate lower bound of the quantile associated with the given rank.
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a number between 0 and 1.0.
      +
      numStdDev - the number of standard deviations. Must be 1, 2, or 3.
      +
      Returns:
      +
      an approximate lower bound quantile, if it exists.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileUpperBound

      +
      +
      public float getQuantileUpperBound(double rank)
      +
      Gets the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists. + +

      Although it is possible to estimate the probability that the true quantile +exists within the quantile confidence interval specified by the upper and lower quantile bounds, +it is not possible to guarantee the width of the quantile interval +as an additive or multiplicative percent of the true quantile.

      +The approximate probability that the true quantile is within the confidence interval +specified by the upper and lower quantile bounds for this sketch is 0.95.
      +
      +
      Specified by:
      +
      getQuantileUpperBound in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      rank - the given normalized rank
      +
      Returns:
      +
      the upper bound of the quantile confidence interval in which the true quantile of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getQuantileUpperBound

      +
      +
      public float getQuantileUpperBound(double rank, + int numStdDev)
      +
      Gets an approximate upper bound of the quantile associated with the given rank.
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a number between 0 and 1.0.
      +
      numStdDev - the number of standard deviations. Must be 1, 2, or 3.
      +
      Returns:
      +
      an approximate upper bound quantile, if it exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      public double getRank(float quantile, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Gets the normalized rank corresponding to the given a quantile.
      +
      +
      Specified by:
      +
      getRank in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      quantile - the given quantile
      +
      searchCrit - if INCLUSIVE the given quantile is included into the rank.
      +
      Returns:
      +
      the normalized rank corresponding to the given quantile.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRankLowerBound

      +
      +
      public double getRankLowerBound(double rank)
      +
      Gets the lower bound of the rank confidence interval in which the true rank of the +given rank exists. +The approximate probability that the true rank is within the confidence interval +specified by the upper and lower rank bounds for this sketch is 0.95.
      +
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the lower bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRankLowerBound

      +
      +
      public double getRankLowerBound(double rank, + int numStdDev)
      +
      Gets an approximate lower bound rank of the given normalized rank.
      +
      +
      Parameters:
      +
      rank - the given normalized rank, a number between 0 and 1.0.
      +
      numStdDev - the number of standard deviations. Must be 1, 2, or 3.
      +
      Returns:
      +
      an approximate lower bound rank.
      +
      +
      +
      +
    • +
    • +
      +

      getRanks

      +
      +
      public double[] getRanks(float[] quantiles, + QuantileSearchCriteria searchCrit)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Gets an array of normalized ranks corresponding to the given array of quantiles and the given +search criterion.
      +
      +
      Specified by:
      +
      getRanks in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      quantiles - the given array of quantiles
      +
      searchCrit - if INCLUSIVE, the given quantiles include the rank directly corresponding to each quantile.
      +
      Returns:
      +
      an array of normalized ranks corresponding to the given array of quantiles.
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      getRankUpperBound

      +
      +
      public double getRankUpperBound(double rank)
      +
      Gets the upper bound of the rank confidence interval in which the true rank of the +given rank exists. +The approximate probability that the true rank is within the confidence interval +specified by the upper and lower rank bounds for this sketch is 0.95.
      +
      +
      Parameters:
      +
      rank - the given normalized rank.
      +
      Returns:
      +
      the upper bound of the rank confidence interval in which the true rank of the +given rank exists.
      +
      +
      +
      +
    • +
    • +
      +

      getRankUpperBound

      +
      +
      public double getRankUpperBound(double rank, + int numStdDev)
      +
      Gets an approximate upper bound rank of the given rank.
      +
      +
      Parameters:
      +
      rank - the given rank, a number between 0 and 1.0.
      +
      numStdDev - the number of standard deviations. Must be 1, 2, or 3.
      +
      Returns:
      +
      an approximate upper bound rank.
      +
      +
      +
      +
    • +
    • +
      +

      getNumRetained

      +
      +
      public int getNumRetained()
      +
      Description copied from interface: QuantilesAPI
      +
      Gets the number of quantiles retained by the sketch.
      +
      +
      Specified by:
      +
      getNumRetained in interface QuantilesAPI
      +
      Returns:
      +
      the number of quantiles retained by the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getSerializedSizeBytes

      +
      +
      public int getSerializedSizeBytes()
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Returns the current number of bytes this Sketch would require if serialized.
      +
      +
      Specified by:
      +
      getSerializedSizeBytes in interface QuantilesFloatsAPI
      +
      Returns:
      +
      the number of bytes this sketch would require if serialized.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is empty.
      +
      +
      Specified by:
      +
      isEmpty in interface QuantilesAPI
      +
      Returns:
      +
      true if this sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      isEstimationMode

      +
      +
      public boolean isEstimationMode()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is in estimation mode.
      +
      +
      Specified by:
      +
      isEstimationMode in interface QuantilesAPI
      +
      Returns:
      +
      true if this sketch is in estimation mode.
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public QuantilesFloatsSketchIterator iterator()
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Gets the iterator for this sketch, which is not sorted.
      +
      +
      Specified by:
      +
      iterator in interface QuantilesFloatsAPI
      +
      Returns:
      +
      the iterator for this sketch
      +
      +
      +
      +
    • +
    • +
      +

      merge

      +
      +
      public ReqSketch merge(ReqSketch other)
      +
      Merge other sketch into this one. The other sketch is not modified.
      +
      +
      Parameters:
      +
      other - sketch to be merged into this one.
      +
      Returns:
      +
      this
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch to the empty state. +If the sketch is read only this does nothing. + +

      The parameter k will not change.

      + +

      The parameters k, highRankAccuracy, and reqDebug will not change.

      +
      +
      Specified by:
      +
      reset in interface QuantilesAPI
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Returns a byte array representation of this sketch.
      +
      +
      Specified by:
      +
      toByteArray in interface QuantilesFloatsAPI
      +
      Returns:
      +
      a byte array representation of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns a summary of the key parameters of the sketch.
      +
      +
      Specified by:
      +
      toString in interface QuantilesAPI
      +
      Returns:
      +
      a summary of the key parameters of the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(float item)
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Updates this sketch with the given item.
      +
      +
      Specified by:
      +
      update in interface QuantilesFloatsAPI
      +
      Parameters:
      +
      item - from a stream of quantiles. NaNs are ignored.
      +
      +
      +
      +
    • +
    • +
      +

      viewCompactorDetail

      +
      +
      public String viewCompactorDetail(String fmt, + boolean allData)
      +
      A detailed, human readable view of the sketch compactors and their data. +Each compactor string is prepended by the compactor lgWeight, the current number of retained +quantiles of the compactor and the current nominal capacity of the compactor.
      +
      +
      Parameters:
      +
      fmt - the format string for the quantiles; example: "%4.0f".
      +
      allData - all the retained quantiles for the sketch will be output by +compactor level. Otherwise, just a summary will be output.
      +
      Returns:
      +
      a detailed view of the compactors and their data
      +
      +
      +
      +
    • +
    • +
      +

      getSortedView

      +
      +
      public FloatsSketchSortedView getSortedView()
      +
      Description copied from interface: QuantilesFloatsAPI
      +
      Gets the sorted view of this sketch
      +
      +
      Specified by:
      +
      getSortedView in interface QuantilesFloatsAPI
      +
      Returns:
      +
      the sorted view of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      getRSE

      +
      +
      public static double getRSE(int k, + double rank, + boolean hra, + long totalN)
      +
      Returns an a priori estimate of relative standard error (RSE, expressed as a number in [0,1]). +Derived from Lemma 12 in https://arxiv.org/abs/2004.01668v2, but the constant factors were +adjusted based on empirical measurements.
      +
      +
      Parameters:
      +
      k - the given size of k
      +
      rank - the given normalized rank, a number in [0,1].
      +
      hra - if true High Rank Accuracy mode is being selected, otherwise, Low Rank Accuracy.
      +
      totalN - an estimate of the total number of items submitted to the sketch.
      +
      Returns:
      +
      an a priori estimate of relative standard error (RSE, expressed as a number in [0,1]).
      +
      +
      +
      +
    • +
    • +
      +

      isReadOnly

      +
      +
      public boolean isReadOnly()
      +
      Description copied from interface: QuantilesAPI
      +
      Returns true if this sketch is read only.
      +
      +
      Specified by:
      +
      isReadOnly in interface QuantilesAPI
      +
      Returns:
      +
      true if this sketch is read only.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/req/ReqSketchBuilder.html b/target/site/apidocs/org/apache/datasketches/req/ReqSketchBuilder.html new file mode 100644 index 000000000..a7fa894a0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/req/ReqSketchBuilder.html @@ -0,0 +1,322 @@ + + + + +ReqSketchBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ReqSketchBuilder

+
+
java.lang.Object +
org.apache.datasketches.req.ReqSketchBuilder
+
+
+
+
+
public class ReqSketchBuilder +extends Object
+
For building a new ReqSketch
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ReqSketchBuilder

      +
      +
      public ReqSketchBuilder()
      +
      Constructor for the ReqSketchBuilder.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      build

      +
      +
      public ReqSketch build()
      +
      Returns a new ReqSketch with the current configuration of the builder.
      +
      +
      Returns:
      +
      a new ReqSketch
      +
      +
      +
      +
    • +
    • +
      +

      getHighRankAccuracy

      +
      +
      public boolean getHighRankAccuracy()
      +
      Gets the builder configured High Rank Accuracy.
      +
      +
      Returns:
      +
      the builder configured High Rank Accuracy.
      +
      +
      +
      +
    • +
    • +
      +

      getK

      +
      +
      public int getK()
      +
      Gets the builder configured k.
      +
      +
      Returns:
      +
      the builder configured k.
      +
      +
      +
      +
    • +
    • +
      +

      getReqDebug

      +
      +
      public ReqDebug getReqDebug()
      +
      Gets the builder configured ReqDebug
      +
      +
      Returns:
      +
      the builder configured ReqDebug, or null.
      +
      +
      +
      +
    • +
    • +
      +

      setHighRankAccuracy

      +
      +
      public ReqSketchBuilder setHighRankAccuracy(boolean hra)
      +
      This sets the parameter highRankAccuracy.
      +
      +
      Parameters:
      +
      hra - See ReqSketch#ReqSketch(int, boolean, ReqDebug)
      +
      Returns:
      +
      this
      +
      +
      +
      +
    • +
    • +
      +

      setK

      +
      +
      public ReqSketchBuilder setK(int k)
      +
      This sets the parameter k.
      +
      +
      Parameters:
      +
      k - See ReqSketch#ReqSketch(int, boolean, ReqDebug)
      +
      Returns:
      +
      this
      +
      +
      +
      +
    • +
    • +
      +

      setReqDebug

      +
      +
      public ReqSketchBuilder setReqDebug(ReqDebug reqDebug)
      +
      This sets the parameter reqDebug.
      +
      +
      Parameters:
      +
      reqDebug - See ReqSketch#ReqSketch(int, boolean, ReqDebug)
      +
      Returns:
      +
      this
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/req/ReqSketchIterator.html b/target/site/apidocs/org/apache/datasketches/req/ReqSketchIterator.html new file mode 100644 index 000000000..21e14472c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/req/ReqSketchIterator.html @@ -0,0 +1,207 @@ + + + + +ReqSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ReqSketchIterator

+
+
java.lang.Object +
org.apache.datasketches.req.ReqSketchIterator
+
+
+
+
All Implemented Interfaces:
+
QuantilesFloatsSketchIterator, QuantilesSketchIteratorAPI
+
+
+
+
public final class ReqSketchIterator +extends Object +implements QuantilesFloatsSketchIterator
+
Iterator over all retained items of the ReqSketch. The order is not defined.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    float
    + +
    +
    Gets the float quantile at the current index.
    +
    +
    long
    + +
    +
    Gets the natural weight at the current index.
    +
    +
    boolean
    + +
    +
    Advances the index and checks if it is valid.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getQuantile

      +
      +
      public float getQuantile()
      +
      Description copied from interface: QuantilesFloatsSketchIterator
      +
      Gets the float quantile at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Specified by:
      +
      getQuantile in interface QuantilesFloatsSketchIterator
      +
      Returns:
      +
      the float quantile at the current index.
      +
      +
      +
      +
    • +
    • +
      +

      getWeight

      +
      +
      public long getWeight()
      +
      Description copied from interface: QuantilesSketchIteratorAPI
      +
      Gets the natural weight at the current index. + +

      Don't call this before calling next() for the first time +or after getting false from next().

      +
      +
      Specified by:
      +
      getWeight in interface QuantilesSketchIteratorAPI
      +
      Returns:
      +
      the natural weight at the current index.
      +
      +
      +
      +
    • +
    • +
      +

      next

      +
      +
      public boolean next()
      +
      Description copied from interface: QuantilesSketchIteratorAPI
      +
      Advances the index and checks if it is valid. +The state of this iterator is undefined before the first call of this method.
      +
      +
      Specified by:
      +
      next in interface QuantilesSketchIteratorAPI
      +
      Returns:
      +
      true if the next index is valid.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/req/class-use/ReqDebug.html b/target/site/apidocs/org/apache/datasketches/req/class-use/ReqDebug.html new file mode 100644 index 000000000..944dea37a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/req/class-use/ReqDebug.html @@ -0,0 +1,106 @@ + + + + +Uses of Interface org.apache.datasketches.req.ReqDebug (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.req.ReqDebug

+
+
Packages that use ReqDebug
+
+
Package
+
Description
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/req/class-use/ReqSketch.html b/target/site/apidocs/org/apache/datasketches/req/class-use/ReqSketch.html new file mode 100644 index 000000000..92ad2dff3 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/req/class-use/ReqSketch.html @@ -0,0 +1,117 @@ + + + + +Uses of Class org.apache.datasketches.req.ReqSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.req.ReqSketch

+
+
Packages that use ReqSketch
+
+
Package
+
Description
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/req/class-use/ReqSketchBuilder.html b/target/site/apidocs/org/apache/datasketches/req/class-use/ReqSketchBuilder.html new file mode 100644 index 000000000..f8120919c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/req/class-use/ReqSketchBuilder.html @@ -0,0 +1,110 @@ + + + + +Uses of Class org.apache.datasketches.req.ReqSketchBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.req.ReqSketchBuilder

+
+
Packages that use ReqSketchBuilder
+
+
Package
+
Description
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/req/class-use/ReqSketchIterator.html b/target/site/apidocs/org/apache/datasketches/req/class-use/ReqSketchIterator.html new file mode 100644 index 000000000..1afc8f394 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/req/class-use/ReqSketchIterator.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.req.ReqSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.req.ReqSketchIterator

+
+No usage of org.apache.datasketches.req.ReqSketchIterator +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/req/package-summary.html b/target/site/apidocs/org/apache/datasketches/req/package-summary.html new file mode 100644 index 000000000..976411949 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/req/package-summary.html @@ -0,0 +1,135 @@ + + + + +org.apache.datasketches.req (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.req

+
+
+
+
package org.apache.datasketches.req
+
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
See Also:
+
+ +
+
+
+
+
+
    +
  • + +
  • +
  • +
    +
    +
    +
    +
    Class
    +
    Description
    + +
    +
    The signaling interface that allows comprehensive analysis of the ReqSketch and ReqCompactor +while eliminating code clutter in the main classes.
    +
    + +
    +
    This Relative Error Quantiles Sketch is the Java implementation based on the paper +"Relative Error Streaming Quantiles" by Graham Cormode, Zohar Karnin, Edo Liberty, +Justin Thaler, Pavel Veselý, and loosely derived from a Python prototype written by Pavel Veselý.
    +
    + +
    +
    For building a new ReqSketch
    +
    + +
    +
    Iterator over all retained items of the ReqSketch.
    +
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/req/package-tree.html b/target/site/apidocs/org/apache/datasketches/req/package-tree.html new file mode 100644 index 000000000..8013a939e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/req/package-tree.html @@ -0,0 +1,87 @@ + + + + +org.apache.datasketches.req Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.req

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Interface Hierarchy

+
    +
  • org.apache.datasketches.req.ReqDebug
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/req/package-use.html b/target/site/apidocs/org/apache/datasketches/req/package-use.html new file mode 100644 index 000000000..0cec5e2a0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/req/package-use.html @@ -0,0 +1,102 @@ + + + + +Uses of Package org.apache.datasketches.req (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.req

+
+
Packages that use org.apache.datasketches.req
+
+
Package
+
Description
+ +
+
This package is for the implementation of the Relative Error Quantiles sketch algorithm.
+
+
+
+
    +
  • +
    + +
    +
    Class
    +
    Description
    + +
    +
    The signaling interface that allows comprehensive analysis of the ReqSketch and ReqCompactor +while eliminating code clutter in the main classes.
    +
    + +
    +
    This Relative Error Quantiles Sketch is the Java implementation based on the paper +"Relative Error Streaming Quantiles" by Graham Cormode, Zohar Karnin, Edo Liberty, +Justin Thaler, Pavel Veselý, and loosely derived from a Python prototype written by Pavel Veselý.
    +
    + +
    +
    For building a new ReqSketch
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/EbppsItemsSketch.html b/target/site/apidocs/org/apache/datasketches/sampling/EbppsItemsSketch.html new file mode 100644 index 000000000..63346f50e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/EbppsItemsSketch.html @@ -0,0 +1,527 @@ + + + + +EbppsItemsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class EbppsItemsSketch<T>

+
+
java.lang.Object +
org.apache.datasketches.sampling.EbppsItemsSketch<T>
+
+
+
+
Type Parameters:
+
T - the item class type
+
+
+
+
public final class EbppsItemsSketch<T> +extends Object
+
An implementation of an Exact and Bounded Sampling Proportional to Size sketch. + +

From: "Exact PPS Sampling with Bounded Sample Size", +B. Hentschel, P. J. Haas, Y. Tian. Information Processing Letters, 2023. + +

This sketch samples data from a stream of items proportional to the weight of each item. +The sample guarantees the presence of an item in the result is proportional to that item's +portion of the total weight seen by the sketch, and returns a sample no larger than size k. + +

The sample may be smaller than k and the resulting size of the sample potentially includes +a probabilistic component, meaning the resulting sample size is not always constant.

+
+
Author:
+
Jon Malkin
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    Constructor
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    double
    + +
    +
    Returns the expected number of samples returned upon a call to +getResult().
    +
    +
    double
    + +
    +
    Returns the cumulative weight of items processed by the sketch.
    +
    +
    int
    + +
    +
    Returns the configured maximum sample size.
    +
    +
    long
    + +
    +
    Returns the number of items processed by the sketch, regardless +of item weight.
    +
    + + +
    +
    Returns a copy of the current sample.
    +
    +
    int
    + +
    +
    Returns the size of a byte array representation of this sketch.
    +
    +
    int
    +
    getSerializedSizeBytes(ArrayOfItemsSerDe<? super T> serDe, + Class<?> clazz)
    +
    +
    Returns the length of a byte array representation of this sketch.
    +
    +
    static <T> EbppsItemsSketch<T>
    + +
    +
    Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
    +
    +
    boolean
    + +
    +
    Returns true if the sketch is empty.
    +
    +
    void
    + +
    +
    Merges the provided sketch into the current one.
    +
    +
    void
    + +
    +
    Resets the sketch to its default, empty state.
    +
    +
    byte[]
    + +
    +
    Returns a byte array representation of this sketch.
    +
    +
    byte[]
    +
    toByteArray(ArrayOfItemsSerDe<? super T> serDe, + Class<?> clazz)
    +
    +
    Returns a byte array representation of this sketch.
    +
    + + +
    +
    Provides a human-readable summary of the sketch
    +
    +
    void
    +
    update(T item)
    +
    +
    Updates this sketch with the given data item with weight 1.0.
    +
    +
    void
    +
    update(T item, + double weight)
    +
    +
    Updates this sketch with the given data item with the given weight.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      EbppsItemsSketch

      +
      +
      public EbppsItemsSketch(int k)
      +
      Constructor
      +
      +
      Parameters:
      +
      k - The maximum number of samples to retain
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapify

      +
      +
      public static <T> EbppsItemsSketch<T> heapify(MemorySegment srcSeg, + ArrayOfItemsSerDe<T> serDe)
      +
      Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
      +
      +
      Type Parameters:
      +
      T - The type of item this sketch contains
      +
      Parameters:
      +
      srcSeg - a MemorySegment representation of a sketch of this class.
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      a sketch instance of this class
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(T item)
      +
      Updates this sketch with the given data item with weight 1.0.
      +
      +
      Parameters:
      +
      item - an item from a stream of items
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(T item, + double weight)
      +
      Updates this sketch with the given data item with the given weight.
      +
      +
      Parameters:
      +
      item - an item from a stream of items
      +
      weight - the weight of the item
      +
      +
      +
      +
    • +
    • +
      +

      merge

      +
      +
      public void merge(EbppsItemsSketch<T> other)
      +
      Merges the provided sketch into the current one.
      +
      +
      Parameters:
      +
      other - the sketch to merge into the current object
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public ArrayList<T> getResult()
      +
      Returns a copy of the current sample. The exact size may be +probabilistic, differing by at most 1 item.
      +
      +
      Returns:
      +
      the current sketch sample
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Provides a human-readable summary of the sketch
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      a summary of information in the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getK

      +
      +
      public int getK()
      +
      Returns the configured maximum sample size.
      +
      +
      Returns:
      +
      configured maximum sample size
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      public long getN()
      +
      Returns the number of items processed by the sketch, regardless +of item weight.
      +
      +
      Returns:
      +
      count of items processed by the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getCumulativeWeight

      +
      +
      public double getCumulativeWeight()
      +
      Returns the cumulative weight of items processed by the sketch.
      +
      +
      Returns:
      +
      cumulative weight of items seen
      +
      +
      +
      +
    • +
    • +
      +

      getC

      +
      +
      public double getC()
      +
      Returns the expected number of samples returned upon a call to +getResult(). The number is a floating point value, where the +fractional portion represents the probability of including a +"partial item" from the sample. + +

      The value C should be no larger than the sketch's configured +value of k, although numerical precision limitations mean it +may exceed k by double precision floating point error margins +in certain cases.

      +
      +
      Returns:
      +
      The expected number of samples returned when querying the sketch
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Returns true if the sketch is empty.
      +
      +
      Returns:
      +
      empty flag
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets the sketch to its default, empty state.
      +
      +
      +
    • +
    • +
      +

      getSerializedSizeBytes

      +
      +
      public int getSerializedSizeBytes(ArrayOfItemsSerDe<? super T> serDe)
      +
      Returns the size of a byte array representation of this sketch. May fail for polymorphic item types.
      +
      +
      Parameters:
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      the length of a byte array representation of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      getSerializedSizeBytes

      +
      +
      public int getSerializedSizeBytes(ArrayOfItemsSerDe<? super T> serDe, + Class<?> clazz)
      +
      Returns the length of a byte array representation of this sketch. Copies contents into an array of the +specified class for serialization to allow for polymorphic types.
      +
      +
      Parameters:
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      clazz - The class represented by <T>
      +
      Returns:
      +
      the length of a byte array representation of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<? super T> serDe)
      +
      Returns a byte array representation of this sketch. May fail for polymorphic item types.
      +
      +
      Parameters:
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      a byte array representation of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<? super T> serDe, + Class<?> clazz)
      +
      Returns a byte array representation of this sketch. Copies contents into an array of the +specified class for serialization to allow for polymorphic types.
      +
      +
      Parameters:
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      clazz - The class represented by <T>
      +
      Returns:
      +
      a byte array representation of this sketch
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/ReservoirItemsSketch.html b/target/site/apidocs/org/apache/datasketches/sampling/ReservoirItemsSketch.html new file mode 100644 index 000000000..dc18badd5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/ReservoirItemsSketch.html @@ -0,0 +1,499 @@ + + + + +ReservoirItemsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ReservoirItemsSketch<T>

+
+
java.lang.Object +
org.apache.datasketches.sampling.ReservoirItemsSketch<T>
+
+
+
+
Type Parameters:
+
T - The type of object held in the reservoir.
+
+
+
+
public final class ReservoirItemsSketch<T> +extends Object
+
This sketch provides a reservoir sample over an input stream of items. The sketch contains a +uniform random sample of unweighted items from the stream.
+
+
Author:
+
Jon Malkin, Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Computes an estimated subset sum from the entire stream for objects matching a given +predicate.
    +
    +
    int
    + +
    +
    Returns the sketch's value of k, the maximum number of samples stored in the +reservoir.
    +
    +
    long
    + +
    +
    Returns the number of items processed from the input stream
    +
    +
    int
    + +
    +
    Returns the current number of items in the reservoir, which may be smaller than the +reservoir capacity.
    +
    +
    T[]
    + +
    +
    Returns a copy of the items in the reservoir, or null if empty.
    +
    +
    T[]
    +
    getSamples(Class<?> clazz)
    +
    +
    Returns a copy of the items in the reservoir as members of Class clazz, or null +if empty.
    +
    +
    static <T> ReservoirItemsSketch<T>
    + +
    +
    Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
    +
    +
    static <T> ReservoirItemsSketch<T>
    +
    newInstance(int k)
    +
    +
    Construct a mergeable sampling sketch with up to k samples using the default resize +factor (8).
    +
    +
    static <T> ReservoirItemsSketch<T>
    +
    newInstance(int k, + ResizeFactor rf)
    +
    +
    Construct a mergeable sampling sketch with up to k samples using a specified resize factor.
    +
    +
    void
    + +
    +
    Resets this sketch to the empty state, but retains the original value of k.
    +
    +
    byte[]
    + +
    +
    Returns a byte array representation of this sketch.
    +
    +
    byte[]
    +
    toByteArray(ArrayOfItemsSerDe<? super T> serDe, + Class<?> clazz)
    +
    +
    Returns a byte array representation of this sketch.
    +
    + + +
    +
    Returns a human-readable summary of the sketch, without items.
    +
    +
    static String
    +
    toString(byte[] byteArr)
    +
    +
    Returns a human readable string of the preamble of a byte array image of a ReservoirItemsSketch.
    +
    +
    static String
    + +
    +
    Returns a human readable string of the preamble of a MemorySegment image of a ReservoirItemsSketch.
    +
    +
    void
    +
    update(T item)
    +
    +
    Randomly decide whether or not to include an item in the sample set.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      newInstance

      +
      +
      public static <T> ReservoirItemsSketch<T> newInstance(int k)
      +
      Construct a mergeable sampling sketch with up to k samples using the default resize +factor (8).
      +
      +
      Type Parameters:
      +
      T - The type of object held in the reservoir.
      +
      Parameters:
      +
      k - Maximum size of sampling. Allocated size may be smaller until reservoir fills. + Unlike many sketches in this package, this value does not need to be a + power of 2.
      +
      Returns:
      +
      A ReservoirLongsSketch initialized with maximum size k and the default resize factor.
      +
      +
      +
      +
    • +
    • +
      +

      newInstance

      +
      +
      public static <T> ReservoirItemsSketch<T> newInstance(int k, + ResizeFactor rf)
      +
      Construct a mergeable sampling sketch with up to k samples using a specified resize factor.
      +
      +
      Type Parameters:
      +
      T - The type of object held in the reservoir.
      +
      Parameters:
      +
      k - Maximum size of sampling. Allocated size may be smaller until reservoir fills. + Unlike many sketches in this package, this value does not need to be a + power of 2.
      +
      rf - See Resize Factor
      +
      Returns:
      +
      A ReservoirLongsSketch initialized with maximum size k and resize factor rf.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static <T> ReservoirItemsSketch<T> heapify(MemorySegment srcSeg, + ArrayOfItemsSerDe<T> serDe)
      +
      Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
      +
      +
      Type Parameters:
      +
      T - The type of item this sketch contains
      +
      Parameters:
      +
      srcSeg - a MemorySegment representation of a sketch of this class.
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      a sketch instance of this class
      +
      +
      +
      +
    • +
    • +
      +

      getK

      +
      +
      public int getK()
      +
      Returns the sketch's value of k, the maximum number of samples stored in the +reservoir. The current number of items in the sketch may be lower.
      +
      +
      Returns:
      +
      k, the maximum number of samples in the reservoir
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      public long getN()
      +
      Returns the number of items processed from the input stream
      +
      +
      Returns:
      +
      n, the number of stream items the sketch has seen
      +
      +
      +
      +
    • +
    • +
      +

      getNumSamples

      +
      +
      public int getNumSamples()
      +
      Returns the current number of items in the reservoir, which may be smaller than the +reservoir capacity.
      +
      +
      Returns:
      +
      the number of items currently in the reservoir
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(T item)
      +
      Randomly decide whether or not to include an item in the sample set.
      +
      +
      Parameters:
      +
      item - a unit-weight (equivalently, unweighted) item of the set being sampled from
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch to the empty state, but retains the original value of k.
      +
      +
      +
    • +
    • +
      +

      getSamples

      +
      +
      public T[] getSamples()
      +
      Returns a copy of the items in the reservoir, or null if empty. The returned array length +may be smaller than the reservoir capacity. + +

      In order to allocate an array of generic type T, uses the class of the first item in +the array. This method method may throw an ArrayAssignmentException if the +reservoir stores instances of a polymorphic base class.

      +
      +
      Returns:
      +
      A copy of the reservoir array
      +
      +
      +
      +
    • +
    • +
      +

      getSamples

      +
      +
      public T[] getSamples(Class<?> clazz)
      +
      Returns a copy of the items in the reservoir as members of Class clazz, or null +if empty. The returned array length may be smaller than the reservoir capacity. + +

      This method allocates an array of class clazz, which must either match or +extend T. This method should be used when objects in the array are all instances of T but +are not necessarily instances of the base class.

      +
      +
      Parameters:
      +
      clazz - A class to which the items are cast before returning
      +
      Returns:
      +
      A copy of the reservoir array
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns a human-readable summary of the sketch, without items.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      A string version of the sketch summary
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(byte[] byteArr)
      +
      Returns a human readable string of the preamble of a byte array image of a ReservoirItemsSketch.
      +
      +
      Parameters:
      +
      byteArr - the given byte array
      +
      Returns:
      +
      a human readable string of the preamble of a byte array image of a ReservoirItemsSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(MemorySegment seg)
      +
      Returns a human readable string of the preamble of a MemorySegment image of a ReservoirItemsSketch.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      a human readable string of the preamble of a MemorySegment image of a ReservoirItemsSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<? super T> serDe)
      +
      Returns a byte array representation of this sketch. May fail for polymorphic item types.
      +
      +
      Parameters:
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      a byte array representation of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<? super T> serDe, + Class<?> clazz)
      +
      Returns a byte array representation of this sketch. Copies contents into an array of the +specified class for serialization to allow for polymorphic types.
      +
      +
      Parameters:
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      clazz - The class represented by <T>
      +
      Returns:
      +
      a byte array representation of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      estimateSubsetSum

      +
      +
      public SampleSubsetSummary estimateSubsetSum(Predicate<T> predicate)
      +
      Computes an estimated subset sum from the entire stream for objects matching a given +predicate. Provides a lower bound, estimate, and upper bound using a target of 2 standard +deviations. + +

      This is technically a heuristic method, and tries to err on the conservative side.

      +
      +
      Parameters:
      +
      predicate - A predicate to use when identifying items.
      +
      Returns:
      +
      A summary object containing the estimate, upper and lower bounds, and the total +sketch weight.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/ReservoirItemsUnion.html b/target/site/apidocs/org/apache/datasketches/sampling/ReservoirItemsUnion.html new file mode 100644 index 000000000..6b6545bc7 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/ReservoirItemsUnion.html @@ -0,0 +1,394 @@ + + + + +ReservoirItemsUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ReservoirItemsUnion<T>

+
+
java.lang.Object +
org.apache.datasketches.sampling.ReservoirItemsUnion<T>
+
+
+
+
Type Parameters:
+
T - The specific Java type for this sketch
+
+
+
+
public final class ReservoirItemsUnion<T> +extends Object
+
Class to union reservoir samples of generic items. + +

For efficiency reasons, the unioning process picks one of the two sketches to use as the +base. As a result, we provide only a stateful union. Using the same approach for a merge would +result in unpredictable side effects on the underlying sketches.

+ +

A union object is created with a maximum value of k, represented using the +ReservoirSize class. The unioning process may cause the actual number of samples to fall below +that maximum value, but never to exceed it. The result of a union will be a reservoir where +each item from the global input has a uniform probability of selection, but there are no +claims about higher order statistics. For instance, in general all possible permutations of +the global input are not equally likely.

+ +

If taking the union of two reservoirs of different sizes, the output sample will contain no more +than MIN(k_1, k_2) samples.

+
+
Author:
+
Jon Malkin, Kevin Lang
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      newInstance

      +
      +
      public static <T> ReservoirItemsUnion<T> newInstance(int maxK)
      +
      Creates an empty Union with a maximum reservoir capacity of size k.
      +
      +
      Type Parameters:
      +
      T - The type of item this sketch contains
      +
      Parameters:
      +
      maxK - The maximum allowed reservoir capacity for any sketches in the union
      +
      Returns:
      +
      A new ReservoirItemsUnion
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static <T> ReservoirItemsUnion<T> heapify(MemorySegment srcSeg, + ArrayOfItemsSerDe<T> serDe)
      +
      Instantiates a Union from MemorySegment
      +
      +
      Type Parameters:
      +
      T - The type of item this sketch contains
      +
      Parameters:
      +
      srcSeg - MemorySegment object containing a serialized union
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      A ReservoirItemsUnion created from the provided MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      getMaxK

      +
      +
      public int getMaxK()
      +
      Returns the maximum allowed reservoir capacity in this union. The current reservoir capacity +may be lower.
      +
      +
      Returns:
      +
      The maximum allowed reservoir capacity in this union.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(ReservoirItemsSketch<T> sketchIn)
      +
      Union the given sketch. This method can be repeatedly called. If the given sketch is null it is +interpreted as an empty sketch.
      +
      +
      Parameters:
      +
      sketchIn - The incoming sketch.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(MemorySegment seg, + ArrayOfItemsSerDe<T> serDe)
      +
      Union the given MemorySegment image of the sketch. + +

      This method can be repeatedly called. If the given sketch is null it is interpreted as an + empty sketch.

      +
      +
      Parameters:
      +
      seg - MemorySegment image of sketch to be merged
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(T datum)
      +
      Present this union with a single item to be added to the union.
      +
      +
      Parameters:
      +
      datum - The given datum of type T.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long n, + int k, + ArrayList<T> input)
      +
      Present this union with raw elements of a sketch. Useful when operating in a distributed +environment like Pig Latin scripts, where an explicit SerDe may be overly complicated but +keeping raw values is simple. Values are not copied and the input array may be +modified.
      +
      +
      Parameters:
      +
      n - Total items seen
      +
      k - Reservoir size
      +
      input - Reservoir samples
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public ReservoirItemsSketch<T> getResult()
      +
      Returns a sketch representing the current state of the union.
      +
      +
      Returns:
      +
      The result of any unions already processed.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<T> serDe)
      +
      Returns a byte array representation of this union
      +
      +
      Parameters:
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      a byte array representation of this union
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns a human-readable summary of the sketch, without items.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      A string version of the sketch summary
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<T> serDe, + Class<?> clazz)
      +
      Returns a byte array representation of this union. This method should be used when the array +elements are subclasses of a common base class.
      +
      +
      Parameters:
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      clazz - A class to which the items are cast before serialization
      +
      Returns:
      +
      a byte array representation of this union
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/ReservoirLongsSketch.html b/target/site/apidocs/org/apache/datasketches/sampling/ReservoirLongsSketch.html new file mode 100644 index 000000000..2215daeab --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/ReservoirLongsSketch.html @@ -0,0 +1,427 @@ + + + + +ReservoirLongsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ReservoirLongsSketch

+
+
java.lang.Object +
org.apache.datasketches.sampling.ReservoirLongsSketch
+
+
+
+
+
public final class ReservoirLongsSketch +extends Object
+
This sketch provides a reservoir sample over an input stream of longs. The sketch +contains a uniform random sample of items from the stream.
+
+
Author:
+
Jon Malkin, Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Computes an estimated subset sum from the entire stream for objects matching a given +predicate.
    +
    +
    int
    + +
    +
    Returns the sketch's value of k, the maximum number of samples stored in the reservoir.
    +
    +
    long
    + +
    +
    Returns the number of items processed from the input stream
    +
    +
    int
    + +
    +
    Returns the current number of items in the reservoir, which may be smaller than the reservoir +capacity.
    +
    +
    long[]
    + +
    +
    Returns a copy of the items in the reservoir.
    +
    + + +
    +
    Returns a sketch instance of this class from the given srcSeg, which must be a MemorySegment +representation of this sketch class.
    +
    + +
    newInstance(int k)
    +
    +
    Construct a mergeable reservoir sampling sketch with up to k samples using the default resize +factor (8).
    +
    + +
    newInstance(int k, + ResizeFactor rf)
    +
    +
    Construct a mergeable reservoir sampling sketch with up to k samples using the default resize +factor (8).
    +
    +
    void
    + +
    +
    Resets this sketch to the empty state, but retains the original value of k.
    +
    +
    byte[]
    + +
    +
    Returns a byte array representation of this sketch
    +
    + + +
    +
    Returns a human-readable summary of the sketch, without items.
    +
    +
    static String
    +
    toString(byte[] byteArr)
    +
    +
    Returns a human readable string of the preamble of a byte array image of a ReservoirLongsSketch.
    +
    +
    static String
    + +
    +
    Returns a human readable string of the preamble of a MemorySegment image of a ReservoirLongsSketch.
    +
    +
    void
    +
    update(long item)
    +
    +
    Randomly decide whether or not to include an item in the sample set.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      newInstance

      +
      +
      public static ReservoirLongsSketch newInstance(int k)
      +
      Construct a mergeable reservoir sampling sketch with up to k samples using the default resize +factor (8).
      +
      +
      Parameters:
      +
      k - Maximum size of sampling. Allocated size may be smaller until sampling fills. Unlike + many sketches in this package, this value does not need to be a power of 2.
      +
      Returns:
      +
      A ReservoirLongsSketch initialized with maximum size k and the default resize factor.
      +
      +
      +
      +
    • +
    • +
      +

      newInstance

      +
      +
      public static ReservoirLongsSketch newInstance(int k, + ResizeFactor rf)
      +
      Construct a mergeable reservoir sampling sketch with up to k samples using the default resize +factor (8).
      +
      +
      Parameters:
      +
      k - Maximum size of sampling. Allocated size may be smaller until sampling fills. Unlike + many sketches in this package, this value does not need to be a power of 2.
      +
      rf - See Resize Factor
      +
      Returns:
      +
      A ReservoirLongsSketch initialized with maximum size k and ResizeFactor rf.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static ReservoirLongsSketch heapify(MemorySegment srcSeg)
      +
      Returns a sketch instance of this class from the given srcSeg, which must be a MemorySegment +representation of this sketch class.
      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment representation of a sketch of this class.
      +
      Returns:
      +
      a sketch instance of this class
      +
      +
      +
      +
    • +
    • +
      +

      getK

      +
      +
      public int getK()
      +
      Returns the sketch's value of k, the maximum number of samples stored in the reservoir. +The current number of items in the sketch may be lower.
      +
      +
      Returns:
      +
      k, the maximum number of samples in the reservoir
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      public long getN()
      +
      Returns the number of items processed from the input stream
      +
      +
      Returns:
      +
      n, the number of stream items the sketch has seen
      +
      +
      +
      +
    • +
    • +
      +

      getNumSamples

      +
      +
      public int getNumSamples()
      +
      Returns the current number of items in the reservoir, which may be smaller than the reservoir +capacity.
      +
      +
      Returns:
      +
      the number of items currently in the reservoir
      +
      +
      +
      +
    • +
    • +
      +

      getSamples

      +
      +
      public long[] getSamples()
      +
      Returns a copy of the items in the reservoir. The returned array length may be smaller than the +reservoir capacity.
      +
      +
      Returns:
      +
      A copy of the reservoir array
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long item)
      +
      Randomly decide whether or not to include an item in the sample set.
      +
      +
      Parameters:
      +
      item - a unit-weight (equivalently, unweighted) item of the set being sampled from
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch to the empty state, but retains the original value of k.
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns a human-readable summary of the sketch, without items.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      A string version of the sketch summary
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(byte[] byteArr)
      +
      Returns a human readable string of the preamble of a byte array image of a ReservoirLongsSketch.
      +
      +
      Parameters:
      +
      byteArr - the given byte array
      +
      Returns:
      +
      a human readable string of the preamble of a byte array image of a ReservoirLongsSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(MemorySegment seg)
      +
      Returns a human readable string of the preamble of a MemorySegment image of a ReservoirLongsSketch.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      a human readable string of the preamble of a MemorySegment image of a ReservoirLongsSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Returns a byte array representation of this sketch
      +
      +
      Returns:
      +
      a byte array representation of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      estimateSubsetSum

      +
      +
      public SampleSubsetSummary estimateSubsetSum(Predicate<Long> predicate)
      +
      Computes an estimated subset sum from the entire stream for objects matching a given +predicate. Provides a lower bound, estimate, and upper bound using a target of 2 standard +deviations. + +

      This is technically a heuristic method, and tries to err on the conservative side.

      +
      +
      Parameters:
      +
      predicate - A predicate to use when identifying items.
      +
      Returns:
      +
      A summary object containing the estimate, upper and lower bounds, and the total +sketch weight.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/ReservoirLongsUnion.html b/target/site/apidocs/org/apache/datasketches/sampling/ReservoirLongsUnion.html new file mode 100644 index 000000000..f6950de87 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/ReservoirLongsUnion.html @@ -0,0 +1,330 @@ + + + + +ReservoirLongsUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ReservoirLongsUnion

+
+
java.lang.Object +
org.apache.datasketches.sampling.ReservoirLongsUnion
+
+
+
+
+
public final class ReservoirLongsUnion +extends Object
+
Class to union reservoir samples of longs. + +

+For efficiency reasons, the unioning process picks one of the two sketches to use as the base. As +a result, we provide only a stateful union. Using the same approach for a merge would result in +unpredictable side effects on the underlying sketches. +

+ +

+A union object is created with a maximum value of k, represented using the ReservoirSize +class. The unioning process may cause the actual number of samples to fall below that maximum +value, but never to exceed it. The result of a union will be a reservoir where each item from the +global input has a uniform probability of selection, but there are no claims about higher order +statistics. For instance, in general all possible permutations of the global input are not +equally likely. +

+
+
Author:
+
Jon Malkin, Kevin Lang
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      newInstance

      +
      +
      public static ReservoirLongsUnion newInstance(int maxK)
      +
      Creates an empty Union with a maximum reservoir capacity of size k.
      +
      +
      Parameters:
      +
      maxK - The maximum allowed reservoir capacity for any sketches in the union
      +
      Returns:
      +
      A new ReservoirLongsUnion
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static ReservoirLongsUnion heapify(MemorySegment srcSeg)
      +
      Instantiates a Union from MemorySegment
      +
      +
      Parameters:
      +
      srcSeg - MemorySegment object containing a serialized union
      +
      Returns:
      +
      A ReservoirLongsUnion created from the provided MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      getMaxK

      +
      +
      public int getMaxK()
      +
      Returns the maximum allowed reservoir capacity in this union. The current reservoir capacity +may be lower.
      +
      +
      Returns:
      +
      The maximum allowed reservoir capacity in this union.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(ReservoirLongsSketch sketchIn)
      +
      Union the given sketch. + +

      This method can be repeatedly called. If the given sketch is null it is interpreted as an empty +sketch.

      +
      +
      Parameters:
      +
      sketchIn - The incoming sketch.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(MemorySegment seg)
      +
      Union the given MemorySegment image of the sketch. + +

      +This method can be repeatedly called. If the given sketch is null it is interpreted as an empty +sketch. +

      +
      +
      Parameters:
      +
      seg - MemorySegment image of sketch to be merged
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long datum)
      +
      Present this union with a long.
      +
      +
      Parameters:
      +
      datum - The given long datum.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public ReservoirLongsSketch getResult()
      +
      Returns a sketch representing the current state of the union.
      +
      +
      Returns:
      +
      The result of any unions already processed.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns a human-readable summary of the sketch, without items.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      A string version of the sketch summary
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Returns a byte array representation of this union
      +
      +
      Returns:
      +
      a byte array representation of this union
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/SampleSubsetSummary.html b/target/site/apidocs/org/apache/datasketches/sampling/SampleSubsetSummary.html new file mode 100644 index 000000000..5dc7eceb6 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/SampleSubsetSummary.html @@ -0,0 +1,205 @@ + + + + +SampleSubsetSummary (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class SampleSubsetSummary

+
+
java.lang.Object +
org.apache.datasketches.sampling.SampleSubsetSummary
+
+
+
+
+
public class SampleSubsetSummary +extends Object
+
A simple object o capture the results of a subset sum query on a sampling sketch.
+
+
Author:
+
Jon Malkin
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getLowerBound

      +
      +
      public double getLowerBound()
      +
      Returns the lower bound
      +
      +
      Returns:
      +
      the lower bound
      +
      +
      +
      +
    • +
    • +
      +

      getTotalSketchWeight

      +
      +
      public double getTotalSketchWeight()
      +
      Returns the total sketch weight
      +
      +
      Returns:
      +
      the total sketch weight
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public double getUpperBound()
      +
      Returns the upper bound
      +
      +
      Returns:
      +
      the upper bound
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public double getEstimate()
      +
      Returns the unique count estimate
      +
      +
      Returns:
      +
      the unique count estimate
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsSamples.VarOptItemsIterator.html b/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsSamples.VarOptItemsIterator.html new file mode 100644 index 000000000..873729644 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsSamples.VarOptItemsIterator.html @@ -0,0 +1,174 @@ + + + + +VarOptItemsSamples.VarOptItemsIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class VarOptItemsSamples.VarOptItemsIterator

+
+
java.lang.Object +
org.apache.datasketches.sampling.VarOptItemsSamples.VarOptItemsIterator
+
+
+
+
All Implemented Interfaces:
+
Iterator<VarOptItemsSamples<T>.WeightedSample>
+
+
+
Enclosing class:
+
VarOptItemsSamples<T>
+
+
+
+
public class VarOptItemsSamples.VarOptItemsIterator +extends Object +implements Iterator<VarOptItemsSamples<T>.WeightedSample>
+
The standard iterator
+
+
Author:
+
Jon Malkin
+
+
+
+
+ +
+
+ +
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsSamples.WeightedSample.html b/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsSamples.WeightedSample.html new file mode 100644 index 000000000..6ade77a16 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsSamples.WeightedSample.html @@ -0,0 +1,172 @@ + + + + +VarOptItemsSamples.WeightedSample (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class VarOptItemsSamples.WeightedSample

+
+
java.lang.Object +
org.apache.datasketches.sampling.VarOptItemsSamples.WeightedSample
+
+
+
+
Enclosing class:
+
VarOptItemsSamples<T>
+
+
+
+
public final class VarOptItemsSamples.WeightedSample +extends Object
+
A convenience class to allow easy iterator access to a VarOpt sample.
+
+
Author:
+
Jon Malkin
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getItem

      +
      +
      public T getItem()
      +
      Accesses the iterator's current object
      +
      +
      Returns:
      +
      An item from the sketch's data sample
      +
      +
      +
      +
    • +
    • +
      +

      getWeight

      +
      +
      public double getWeight()
      +
      Accesses the iterator's current weight value
      +
      +
      Returns:
      +
      A weight from the sketch's data sample
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsSamples.html b/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsSamples.html new file mode 100644 index 000000000..a8c9376f0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsSamples.html @@ -0,0 +1,326 @@ + + + + +VarOptItemsSamples (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class VarOptItemsSamples<T>

+
+
java.lang.Object +
org.apache.datasketches.sampling.VarOptItemsSamples<T>
+
+
+
+
Type Parameters:
+
T - an item of type T
+
+
+
All Implemented Interfaces:
+
Iterable<VarOptItemsSamples<T>.WeightedSample>
+
+
+
+
public class VarOptItemsSamples<T> +extends Object +implements Iterable<VarOptItemsSamples<T>.WeightedSample>
+
This class provides access to the samples contained in a VarOptItemsSketch. It provides two +mechanisms for access: +
    +
  • An Iterator over WeightedSample objects which can can be used to + access both the items and weights in the sample, and which avoids copying data from the + sketch.
  • +
  • Getter methods to obtain items or weights as arrays, or individual items. These + methods create a (shallow) copy of data from the sketch on the first call to any get + method.
  • +
+ +

If using getters with a sketch storing heterogeneous items from a polymorphic base class, you +must call setClass() prior to calling one of the getter methods. This is not +necessary if using the iterator.

+ +

The class also implements Iterable to allow the use of forEach loops for +convenience.

+
+
Author:
+
Jon Malkin
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      iterator

      +
      + +
      +
      Specified by:
      +
      iterator in interface Iterable<T>
      +
      +
      +
      +
    • +
    • +
      +

      setClass

      +
      +
      public void setClass(Class<?> clazz)
      +
      Specifies the class to use when copying the item array from the sketch. This method is +required if the sketch stores heterogeneous item types of some base class, for instance a +sketch over Numbers.
      +
      +
      Parameters:
      +
      clazz - The class to use when creating the item array result
      +
      +
      +
      +
    • +
    • +
      +

      getNumSamples

      +
      +
      public int getNumSamples()
      +
      Returns the length Copies items and weights from the sketch, if necessary, and returns the +length of +any +resulting array. The result will be 0 for an empty sketch.
      +
      +
      Returns:
      +
      The number of items and weights in the sketch
      +
      +
      +
      +
    • +
    • +
      +

      items

      +
      +
      public T[] items()
      +
      Returns a shallow copy of the array of sample items contained in the sketch. If this is the +first getter call, copies data arrays from the sketch.
      +
      +
      Returns:
      +
      The number of samples contained in the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      items

      +
      +
      public T items(int i)
      +
      Returns a single item from the samples contained in the sketch. Does not perform bounds +checking on the input. If this is the first getter call, copies data arrays from the sketch.
      +
      +
      Parameters:
      +
      i - An index into the list of samples
      +
      Returns:
      +
      The sample at array position i
      +
      +
      +
      +
    • +
    • +
      +

      weights

      +
      +
      public double[] weights()
      +
      Returns a copy of the array of weights contained in the sketch. If this is the first +getter call, copies data arrays from the sketch.
      +
      +
      Returns:
      +
      The number of samples contained in the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      weights

      +
      +
      public double weights(int i)
      +
      Returns a single weight from the samples contained in the sketch. Does not perform bounds +checking on the input. If this is the first getter call, copies data arrays from the sketch.
      +
      +
      Parameters:
      +
      i - An index into the list of weights
      +
      Returns:
      +
      The weight at array position i
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsSketch.html b/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsSketch.html new file mode 100644 index 000000000..274d8e6ee --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsSketch.html @@ -0,0 +1,472 @@ + + + + +VarOptItemsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class VarOptItemsSketch<T>

+
+
java.lang.Object +
org.apache.datasketches.sampling.VarOptItemsSketch<T>
+
+
+
+
Type Parameters:
+
T - The type of object held in the sketch.
+
+
+
+
public final class VarOptItemsSketch<T> +extends Object
+
This sketch provides a variance optimal sample over an input stream of weighted items. The +sketch can be used to compute subset sums over predicates, producing estimates with optimal +variance for a given sketch size. + +

Using this sketch with uniformly constant item weights (e.g. 1.0) will produce a standard +reservoir sample over the steam.

+
+
Author:
+
Jon Malkin, Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Computes an estimated subset sum from the entire stream for objects matching a given +predicate.
    +
    +
    int
    + +
    +
    Returns the sketch's value of k, the maximum number of samples stored in the +sketch.
    +
    +
    long
    + +
    +
    Returns the number of items processed from the input stream
    +
    +
    int
    + +
    +
    Returns the current number of items in the sketch, which may be smaller than the +sketch capacity.
    +
    + + +
    +
    Gets a result iterator object.
    +
    +
    static <T> VarOptItemsSketch<T>
    + +
    +
    Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
    +
    +
    static <T> VarOptItemsSketch<T>
    +
    newInstance(int k)
    +
    +
    Construct a varopt sampling sketch with up to k samples using the default resize factor (8).
    +
    +
    static <T> VarOptItemsSketch<T>
    +
    newInstance(int k, + ResizeFactor rf)
    +
    +
    Construct a varopt sampling sketch with up to k samples using the specified resize factor.
    +
    +
    void
    + +
    +
    Resets this sketch to the empty state, but retains the original value of k.
    +
    +
    byte[]
    + +
    +
    Returns a byte array representation of this sketch.
    +
    +
    byte[]
    +
    toByteArray(ArrayOfItemsSerDe<? super T> serDe, + Class<?> clazz)
    +
    +
    Returns a byte array representation of this sketch.
    +
    + + +
    +
    Returns a human-readable summary of the sketch.
    +
    +
    static String
    +
    toString(byte[] byteArr)
    +
    +
    Returns a human readable string of the preamble of a byte array image of a VarOptItemsSketch.
    +
    +
    static String
    + +
    +
    Returns a human readable string of the preamble of a MemorySegment image of a VarOptItemsSketch.
    +
    +
    void
    +
    update(T item, + double weight)
    +
    +
    Randomly decide whether or not to include an item in the sample set.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      newInstance

      +
      +
      public static <T> VarOptItemsSketch<T> newInstance(int k)
      +
      Construct a varopt sampling sketch with up to k samples using the default resize factor (8).
      +
      +
      Type Parameters:
      +
      T - The type of object held in the sketch.
      +
      Parameters:
      +
      k - Maximum size of sampling. Allocated size may be smaller until sketch fills. + Unlike many sketches in this package, this value does not need to be a + power of 2.
      +
      Returns:
      +
      A VarOptItemsSketch initialized with maximum size k and resize factor rf.
      +
      +
      +
      +
    • +
    • +
      +

      newInstance

      +
      +
      public static <T> VarOptItemsSketch<T> newInstance(int k, + ResizeFactor rf)
      +
      Construct a varopt sampling sketch with up to k samples using the specified resize factor.
      +
      +
      Type Parameters:
      +
      T - The type of object held in the sketch.
      +
      Parameters:
      +
      k - Maximum size of sampling. Allocated size may be smaller until sketch fills. + Unlike many sketches in this package, this value does not need to be a + power of 2. The maximum size is Integer.MAX_VALUE-1.
      +
      rf - See Resize Factor
      +
      Returns:
      +
      A VarOptItemsSketch initialized with maximum size k and resize factor rf.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static <T> VarOptItemsSketch<T> heapify(MemorySegment srcSeg, + ArrayOfItemsSerDe<T> serDe)
      +
      Returns a sketch instance of this class from the given srcSeg, +which must be a MemorySegment representation of this sketch class.
      +
      +
      Type Parameters:
      +
      T - The type of item this sketch contains
      +
      Parameters:
      +
      srcSeg - a MemorySegment representation of a sketch of this class.
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      a sketch instance of this class
      +
      +
      +
      +
    • +
    • +
      +

      getK

      +
      +
      public int getK()
      +
      Returns the sketch's value of k, the maximum number of samples stored in the +sketch. The current number of items in the sketch may be lower.
      +
      +
      Returns:
      +
      k, the maximum number of samples in the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getN

      +
      +
      public long getN()
      +
      Returns the number of items processed from the input stream
      +
      +
      Returns:
      +
      n, the number of stream items the sketch has seen
      +
      +
      +
      +
    • +
    • +
      +

      getNumSamples

      +
      +
      public int getNumSamples()
      +
      Returns the current number of items in the sketch, which may be smaller than the +sketch capacity.
      +
      +
      Returns:
      +
      the number of items currently in the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getSketchSamples

      +
      +
      public VarOptItemsSamples<T> getSketchSamples()
      +
      Gets a result iterator object.
      +
      +
      Returns:
      +
      An object with an iterator over the results
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(T item, + double weight)
      +
      Randomly decide whether or not to include an item in the sample set.
      +
      +
      Parameters:
      +
      item - an item of the set being sampled from
      +
      weight - a strictly positive weight associated with the item
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch to the empty state, but retains the original value of k.
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns a human-readable summary of the sketch.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      A string version of the sketch summary
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(byte[] byteArr)
      +
      Returns a human readable string of the preamble of a byte array image of a VarOptItemsSketch.
      +
      +
      Parameters:
      +
      byteArr - the given byte array
      +
      Returns:
      +
      a human readable string of the preamble of a byte array image of a VarOptItemsSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(MemorySegment seg)
      +
      Returns a human readable string of the preamble of a MemorySegment image of a VarOptItemsSketch.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      a human readable string of the preamble of a MemorySegment image of a VarOptItemsSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<? super T> serDe)
      +
      Returns a byte array representation of this sketch. May fail for polymorphic item types.
      +
      +
      Parameters:
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      a byte array representation of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<? super T> serDe, + Class<?> clazz)
      +
      Returns a byte array representation of this sketch. Copies contents into an array of the +specified class for serialization to allow for polymorphic types.
      +
      +
      Parameters:
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      clazz - The class represented by <T>
      +
      Returns:
      +
      a byte array representation of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      estimateSubsetSum

      +
      +
      public SampleSubsetSummary estimateSubsetSum(Predicate<T> predicate)
      +
      Computes an estimated subset sum from the entire stream for objects matching a given +predicate. Provides a lower bound, estimate, and upper bound using a target of 2 standard +deviations. + +

      This is technically a heuristic method, and tries to err on the conservative side.

      +
      +
      Parameters:
      +
      predicate - A predicate to use when identifying items.
      +
      Returns:
      +
      A summary object containing the estimate, upper and lower bounds, and the total +sketch weight.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsUnion.html b/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsUnion.html new file mode 100644 index 000000000..b8202e8d5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/VarOptItemsUnion.html @@ -0,0 +1,349 @@ + + + + +VarOptItemsUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class VarOptItemsUnion<T>

+
+
java.lang.Object +
org.apache.datasketches.sampling.VarOptItemsUnion<T>
+
+
+
+
Type Parameters:
+
T - Type of items
+
+
+
+
public final class VarOptItemsUnion<T> +extends Object
+
Provides a unioning operation over varopt sketches. This union allows the sample size k to float, +possibly increasing or decreasing as warranted by the available data.
+
+
Author:
+
Jon Malkin, Kevin Lang
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      newInstance

      +
      +
      public static <T> VarOptItemsUnion<T> newInstance(int maxK)
      +
      Creates an empty Union with a maximum capacity of size k.
      +
      +
      Type Parameters:
      +
      T - The type of item this union contains
      +
      Parameters:
      +
      maxK - The maximum allowed capacity of the unioned result
      +
      Returns:
      +
      A new VarOptItemsUnion
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static <T> VarOptItemsUnion<T> heapify(MemorySegment srcSeg, + ArrayOfItemsSerDe<T> serDe)
      +
      Instantiates a Union from MemorySegment
      +
      +
      Type Parameters:
      +
      T - The type of item this sketch contains
      +
      Parameters:
      +
      srcSeg - MemorySegment object containing a serialized union
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      A VarOptItemsUnion created from the provided MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(VarOptItemsSketch<T> sketchIn)
      +
      Union the given sketch. + +

      This method can be repeatedly called.

      +
      +
      Parameters:
      +
      sketchIn - The sketch to be merged
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(MemorySegment seg, + ArrayOfItemsSerDe<T> serDe)
      +
      Union the given MemorySegment image of the sketch. + +

      This method can be repeatedly called.

      +
      +
      Parameters:
      +
      seg - MemorySegment image of sketch to be merged
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(ReservoirItemsSketch<T> reservoirIn)
      +
      Union a reservoir sketch. The reservoir sample is treated as if all items were added with a +weight of 1.0.
      +
      +
      Parameters:
      +
      reservoirIn - The reservoir sketch to be merged
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public VarOptItemsSketch<T> getResult()
      +
      Gets the varopt sketch resulting from the union of any input sketches.
      +
      +
      Returns:
      +
      A varopt sketch
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch to the empty state, but retains the original value of max k.
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns a human-readable summary of the sketch, without items.
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      A string version of the sketch summary
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<T> serDe)
      +
      Returns a byte array representation of this union
      +
      +
      Parameters:
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      Returns:
      +
      a byte array representation of this union
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray(ArrayOfItemsSerDe<T> serDe, + Class<?> clazz)
      +
      Returns a byte array representation of this union. This method should be used when the array +elements are subclasses of a common base class.
      +
      +
      Parameters:
      +
      serDe - An instance of ArrayOfItemsSerDe
      +
      clazz - A class to which the items are cast before serialization
      +
      Returns:
      +
      a byte array representation of this union
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/class-use/EbppsItemsSketch.html b/target/site/apidocs/org/apache/datasketches/sampling/class-use/EbppsItemsSketch.html new file mode 100644 index 000000000..bb884bd75 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/class-use/EbppsItemsSketch.html @@ -0,0 +1,109 @@ + + + + +Uses of Class org.apache.datasketches.sampling.EbppsItemsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.sampling.EbppsItemsSketch

+
+
Packages that use EbppsItemsSketch
+
+
Package
+
Description
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/class-use/ReservoirItemsSketch.html b/target/site/apidocs/org/apache/datasketches/sampling/class-use/ReservoirItemsSketch.html new file mode 100644 index 000000000..5bfc5e54a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/class-use/ReservoirItemsSketch.html @@ -0,0 +1,131 @@ + + + + +Uses of Class org.apache.datasketches.sampling.ReservoirItemsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.sampling.ReservoirItemsSketch

+
+
Packages that use ReservoirItemsSketch
+
+
Package
+
Description
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/class-use/ReservoirItemsUnion.html b/target/site/apidocs/org/apache/datasketches/sampling/class-use/ReservoirItemsUnion.html new file mode 100644 index 000000000..440c65d01 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/class-use/ReservoirItemsUnion.html @@ -0,0 +1,102 @@ + + + + +Uses of Class org.apache.datasketches.sampling.ReservoirItemsUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.sampling.ReservoirItemsUnion

+
+
Packages that use ReservoirItemsUnion
+
+
Package
+
Description
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/class-use/ReservoirLongsSketch.html b/target/site/apidocs/org/apache/datasketches/sampling/class-use/ReservoirLongsSketch.html new file mode 100644 index 000000000..a64ca9ea8 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/class-use/ReservoirLongsSketch.html @@ -0,0 +1,126 @@ + + + + +Uses of Class org.apache.datasketches.sampling.ReservoirLongsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.sampling.ReservoirLongsSketch

+
+
Packages that use ReservoirLongsSketch
+
+
Package
+
Description
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/class-use/ReservoirLongsUnion.html b/target/site/apidocs/org/apache/datasketches/sampling/class-use/ReservoirLongsUnion.html new file mode 100644 index 000000000..51fb669ce --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/class-use/ReservoirLongsUnion.html @@ -0,0 +1,101 @@ + + + + +Uses of Class org.apache.datasketches.sampling.ReservoirLongsUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.sampling.ReservoirLongsUnion

+
+
Packages that use ReservoirLongsUnion
+
+
Package
+
Description
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/class-use/SampleSubsetSummary.html b/target/site/apidocs/org/apache/datasketches/sampling/class-use/SampleSubsetSummary.html new file mode 100644 index 000000000..7da0c0c91 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/class-use/SampleSubsetSummary.html @@ -0,0 +1,109 @@ + + + + +Uses of Class org.apache.datasketches.sampling.SampleSubsetSummary (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.sampling.SampleSubsetSummary

+
+
Packages that use SampleSubsetSummary
+
+
Package
+
Description
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsSamples.VarOptItemsIterator.html b/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsSamples.VarOptItemsIterator.html new file mode 100644 index 000000000..3cfb75dbb --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsSamples.VarOptItemsIterator.html @@ -0,0 +1,68 @@ + + + + +Uses of Class org.apache.datasketches.sampling.VarOptItemsSamples.VarOptItemsIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.sampling.VarOptItemsSamples.VarOptItemsIterator

+
+No usage of org.apache.datasketches.sampling.VarOptItemsSamples.VarOptItemsIterator +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsSamples.WeightedSample.html b/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsSamples.WeightedSample.html new file mode 100644 index 000000000..391e4525b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsSamples.WeightedSample.html @@ -0,0 +1,120 @@ + + + + +Uses of Class org.apache.datasketches.sampling.VarOptItemsSamples.WeightedSample (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.sampling.VarOptItemsSamples.WeightedSample

+
+ +
+
Package
+
Description
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsSamples.html b/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsSamples.html new file mode 100644 index 000000000..3e53682e2 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsSamples.html @@ -0,0 +1,96 @@ + + + + +Uses of Class org.apache.datasketches.sampling.VarOptItemsSamples (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.sampling.VarOptItemsSamples

+
+
Packages that use VarOptItemsSamples
+
+
Package
+
Description
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsSketch.html b/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsSketch.html new file mode 100644 index 000000000..9e3dab25f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsSketch.html @@ -0,0 +1,125 @@ + + + + +Uses of Class org.apache.datasketches.sampling.VarOptItemsSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.sampling.VarOptItemsSketch

+
+
Packages that use VarOptItemsSketch
+
+
Package
+
Description
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsUnion.html b/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsUnion.html new file mode 100644 index 000000000..a5019c3ab --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/class-use/VarOptItemsUnion.html @@ -0,0 +1,102 @@ + + + + +Uses of Class org.apache.datasketches.sampling.VarOptItemsUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.sampling.VarOptItemsUnion

+
+
Packages that use VarOptItemsUnion
+
+
Package
+
Description
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/package-summary.html b/target/site/apidocs/org/apache/datasketches/sampling/package-summary.html new file mode 100644 index 000000000..402d91781 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/package-summary.html @@ -0,0 +1,156 @@ + + + + +org.apache.datasketches.sampling (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.sampling

+
+
+
+
package org.apache.datasketches.sampling
+
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream. + +

These sketches are mergeable and can be serialized and deserialized to/from a compact +form.

+
+
See Also:
+
+ +
+
+
+
+
+
    +
  • + +
  • +
  • +
    +
    Classes
    +
    +
    Class
    +
    Description
    + +
    +
    An implementation of an Exact and Bounded Sampling Proportional to Size sketch.
    +
    + +
    +
    This sketch provides a reservoir sample over an input stream of items.
    +
    + +
    +
    Class to union reservoir samples of generic items.
    +
    + +
    +
    This sketch provides a reservoir sample over an input stream of longs.
    +
    + +
    +
    Class to union reservoir samples of longs.
    +
    + +
    +
    A simple object o capture the results of a subset sum query on a sampling sketch.
    +
    + +
    +
    This class provides access to the samples contained in a VarOptItemsSketch.
    +
    + +
    +
    This sketch provides a variance optimal sample over an input stream of weighted items.
    +
    + +
    +
    Provides a unioning operation over varopt sketches.
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/package-tree.html b/target/site/apidocs/org/apache/datasketches/sampling/package-tree.html new file mode 100644 index 000000000..2ff916009 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/package-tree.html @@ -0,0 +1,89 @@ + + + + +org.apache.datasketches.sampling Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.sampling

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/sampling/package-use.html b/target/site/apidocs/org/apache/datasketches/sampling/package-use.html new file mode 100644 index 000000000..2f1e4f439 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/sampling/package-use.html @@ -0,0 +1,128 @@ + + + + +Uses of Package org.apache.datasketches.sampling (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.sampling

+
+ +
+
Package
+
Description
+ +
+
This package is dedicated to streaming algorithms that enable fixed size, uniform sampling of +weighted and unweighted items from a stream.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tdigest/BinarySearch.html b/target/site/apidocs/org/apache/datasketches/tdigest/BinarySearch.html new file mode 100644 index 000000000..36108947a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tdigest/BinarySearch.html @@ -0,0 +1,141 @@ + + + + +BinarySearch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class BinarySearch

+
+
java.lang.Object +
org.apache.datasketches.tdigest.BinarySearch
+
+
+
+
+
public final class BinarySearch +extends Object
+
Algorithms with logarithmic complexity for searching in an array.
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      BinarySearch

      +
      +
      public BinarySearch()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tdigest/Sort.html b/target/site/apidocs/org/apache/datasketches/tdigest/Sort.html new file mode 100644 index 000000000..de1989401 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tdigest/Sort.html @@ -0,0 +1,233 @@ + + + + +Sort (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class Sort

+
+
java.lang.Object +
org.apache.datasketches.tdigest.Sort
+
+
+
+
+
public final class Sort +extends Object
+
Specialized sorting algorithm that can sort one array and permute another array the same way.
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    No argument constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static void
    +
    reverse(double[] values, + int n)
    +
    +
    Reverse the first n elements of the given array.
    +
    +
    static void
    +
    reverse(long[] values, + int n)
    +
    +
    Reverse the first n elements of the given array.
    +
    +
    static void
    +
    stableSort(double[] keys, + long[] values, + int n)
    +
    +
    Stable sort two arrays.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      Sort

      +
      +
      public Sort()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      stableSort

      +
      +
      public static void stableSort(double[] keys, + long[] values, + int n)
      +
      Stable sort two arrays. +The first array is sorted while the second array is permuted the same way.
      +
      +
      Parameters:
      +
      keys - array to be sorted
      +
      values - array to be permuted the same way
      +
      n - number of elements to sort from the beginning of the arrays
      +
      +
      +
      +
    • +
    • +
      +

      reverse

      +
      +
      public static void reverse(double[] values, + int n)
      +
      Reverse the first n elements of the given array.
      +
      +
      Parameters:
      +
      values - array to be reversed
      +
      n - number of elements to reverse
      +
      +
      +
      +
    • +
    • +
      +

      reverse

      +
      +
      public static void reverse(long[] values, + int n)
      +
      Reverse the first n elements of the given array.
      +
      +
      Parameters:
      +
      values - array to be reversed
      +
      n - number of elements to reverse
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tdigest/TDigestDouble.html b/target/site/apidocs/org/apache/datasketches/tdigest/TDigestDouble.html new file mode 100644 index 000000000..9778eac66 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tdigest/TDigestDouble.html @@ -0,0 +1,575 @@ + + + + +TDigestDouble (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class TDigestDouble

+
+
java.lang.Object +
org.apache.datasketches.tdigest.TDigestDouble
+
+
+
+
+
public final class TDigestDouble +extends Object
+
t-Digest for estimating quantiles and ranks. +This implementation is based on the following paper: +Ted Dunning, Otmar Ertl. Extremely Accurate Quantiles Using t-Digests +and the following implementation: +https://github.com/tdunning/t-digest +This implementation is similar to MergingDigest in the above implementation
+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    static final short
    + +
    +
    the default value of K if one is not specified
    +
    +
    +
    +
  • + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    Constructor with the default K
    +
    +
    TDigestDouble(short k)
    +
    +
    Constructor
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    double[]
    +
    getCDF(double[] splitPoints)
    +
    +
    Returns an approximation to the Cumulative Distribution Function (CDF), which is the +cumulative analog of the PMF, of the input stream given a set of split points.
    +
    +
    short
    + +
    +
    Returns parameter k (compression) that was used to configure this TDigest
    +
    +
    double
    + +
    +
    Returns maximum value seen by TDigest
    +
    +
    double
    + +
    +
    Returns minimum value seen by TDigest
    +
    +
    double[]
    +
    getPMF(double[] splitPoints)
    +
    +
    Returns an approximation to the Probability Mass Function (PMF) of the input stream +given a set of split points.
    +
    +
    double
    +
    getQuantile(double rank)
    +
    +
    Compute approximate quantile value corresponding to the given normalized rank
    +
    +
    double
    +
    getRank(double value)
    +
    +
    Compute approximate normalized rank of the given value.
    +
    +
    long
    + +
    +
    Returns total weight
    +
    + + +
    +
    Deserialize TDigest from a given MemorySegment.
    +
    + +
    heapify(MemorySegment seg, + boolean isFloat)
    +
    +
    Deserialize TDigest from a given MemorySegment.
    +
    +
    boolean
    + +
    +
    Returns true if TDigest has not seen any data
    +
    +
    void
    + +
    +
    Merge the given TDigest into this one
    +
    +
    byte[]
    + +
    +
    Serialize this TDigest to a byte array form.
    +
    + + +
    +
    Human-readable summary of this TDigest as a string
    +
    + +
    toString(boolean printCentroids)
    +
    +
    Human-readable summary of this TDigest as a string
    +
    +
    void
    +
    update(double value)
    +
    +
    Update this TDigest with the given value
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      DEFAULT_K

      +
      +
      public static final short DEFAULT_K
      +
      the default value of K if one is not specified
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      TDigestDouble

      +
      +
      public TDigestDouble()
      +
      Constructor with the default K
      +
      +
      +
    • +
    • +
      +

      TDigestDouble

      +
      +
      public TDigestDouble(short k)
      +
      Constructor
      +
      +
      Parameters:
      +
      k - affects the size of TDigest and its estimation error
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getK

      +
      +
      public short getK()
      +
      Returns parameter k (compression) that was used to configure this TDigest
      +
      +
      Returns:
      +
      parameter k (compression) that was used to configure this TDigest
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(double value)
      +
      Update this TDigest with the given value
      +
      +
      Parameters:
      +
      value - to update the TDigest with
      +
      +
      +
      +
    • +
    • +
      +

      merge

      +
      +
      public void merge(TDigestDouble other)
      +
      Merge the given TDigest into this one
      +
      +
      Parameters:
      +
      other - TDigest to merge
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      +
      Returns true if TDigest has not seen any data
      +
      +
      Returns:
      +
      true if TDigest has not seen any data
      +
      +
      +
      +
    • +
    • +
      +

      getMinValue

      +
      +
      public double getMinValue()
      +
      Returns minimum value seen by TDigest
      +
      +
      Returns:
      +
      minimum value seen by TDigest
      +
      +
      +
      +
    • +
    • +
      +

      getMaxValue

      +
      +
      public double getMaxValue()
      +
      Returns maximum value seen by TDigest
      +
      +
      Returns:
      +
      maximum value seen by TDigest
      +
      +
      +
      +
    • +
    • +
      +

      getTotalWeight

      +
      +
      public long getTotalWeight()
      +
      Returns total weight
      +
      +
      Returns:
      +
      total weight
      +
      +
      +
      +
    • +
    • +
      +

      getRank

      +
      +
      public double getRank(double value)
      +
      Compute approximate normalized rank of the given value.
      +
      +
      Parameters:
      +
      value - to be ranked
      +
      Returns:
      +
      normalized rank (from 0 to 1 inclusive)
      +
      +
      +
      +
    • +
    • +
      +

      getQuantile

      +
      +
      public double getQuantile(double rank)
      +
      Compute approximate quantile value corresponding to the given normalized rank
      +
      +
      Parameters:
      +
      rank - normalized rank (from 0 to 1 inclusive)
      +
      Returns:
      +
      quantile value corresponding to the given rank
      +
      +
      +
      +
    • +
    • +
      +

      getPMF

      +
      +
      public double[] getPMF(double[] splitPoints)
      +
      Returns an approximation to the Probability Mass Function (PMF) of the input stream +given a set of split points.
      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing values +that divide the input domain into m+1 consecutive disjoint intervals (bins).
      +
      Returns:
      +
      an array of m+1 doubles each of which is an approximation +to the fraction of the input stream values (the mass) that fall into one of those intervals.
      +
      Throws:
      +
      SketchesStateException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      getCDF

      +
      +
      public double[] getCDF(double[] splitPoints)
      +
      Returns an approximation to the Cumulative Distribution Function (CDF), which is the +cumulative analog of the PMF, of the input stream given a set of split points.
      +
      +
      Parameters:
      +
      splitPoints - an array of m unique, monotonically increasing values +that divide the input domain into m+1 consecutive disjoint intervals.
      +
      Returns:
      +
      an array of m+1 doubles, which are a consecutive approximation to the CDF +of the input stream given the splitPoints. The value at array position j of the returned +CDF array is the sum of the returned values in positions 0 through j of the returned PMF +array. This can be viewed as array of ranks of the given split points plus one more value +that is always 1.
      +
      Throws:
      +
      SketchesStateException - if sketch is empty.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Serialize this TDigest to a byte array form.
      +
      +
      Returns:
      +
      byte array
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static TDigestDouble heapify(MemorySegment seg)
      +
      Deserialize TDigest from a given MemorySegment. +Supports reading format of the reference implementation (auto-detected).
      +
      +
      Parameters:
      +
      seg - instance of MemorySegment
      +
      Returns:
      +
      an instance of TDigest
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static TDigestDouble heapify(MemorySegment seg, + boolean isFloat)
      +
      Deserialize TDigest from a given MemorySegment. Supports reading compact format +with (float, int) centroids as opposed to (double, long) to represent (mean, weight). +Supports reading format of the reference implementation (auto-detected).
      +
      +
      Parameters:
      +
      seg - instance of MemorySegment
      +
      isFloat - if true the input represents (float, int) format
      +
      Returns:
      +
      an instance of TDigest
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Human-readable summary of this TDigest as a string
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      summary of this TDigest
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean printCentroids)
      +
      Human-readable summary of this TDigest as a string
      +
      +
      Parameters:
      +
      printCentroids - if true append the list of centroids with weights
      +
      Returns:
      +
      summary of this TDigest
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tdigest/class-use/BinarySearch.html b/target/site/apidocs/org/apache/datasketches/tdigest/class-use/BinarySearch.html new file mode 100644 index 000000000..422f5d605 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tdigest/class-use/BinarySearch.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tdigest.BinarySearch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tdigest.BinarySearch

+
+No usage of org.apache.datasketches.tdigest.BinarySearch +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tdigest/class-use/Sort.html b/target/site/apidocs/org/apache/datasketches/tdigest/class-use/Sort.html new file mode 100644 index 000000000..76c1c466e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tdigest/class-use/Sort.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tdigest.Sort (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tdigest.Sort

+
+No usage of org.apache.datasketches.tdigest.Sort +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tdigest/class-use/TDigestDouble.html b/target/site/apidocs/org/apache/datasketches/tdigest/class-use/TDigestDouble.html new file mode 100644 index 000000000..eac3738d9 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tdigest/class-use/TDigestDouble.html @@ -0,0 +1,112 @@ + + + + +Uses of Class org.apache.datasketches.tdigest.TDigestDouble (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tdigest.TDigestDouble

+
+
Packages that use TDigestDouble
+
+
Package
+
Description
+ +
+
t-Digest for estimating quantiles and ranks.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tdigest/package-summary.html b/target/site/apidocs/org/apache/datasketches/tdigest/package-summary.html new file mode 100644 index 000000000..54c9ba38f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tdigest/package-summary.html @@ -0,0 +1,118 @@ + + + + +org.apache.datasketches.tdigest (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.tdigest

+
+
+
+
package org.apache.datasketches.tdigest
+
+
t-Digest for estimating quantiles and ranks.
+
+
+
+
    +
  • + +
  • +
  • +
    +
    Classes
    +
    +
    Class
    +
    Description
    + +
    +
    Algorithms with logarithmic complexity for searching in an array.
    +
    + +
    +
    Specialized sorting algorithm that can sort one array and permute another array the same way.
    +
    + +
    +
    t-Digest for estimating quantiles and ranks.
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tdigest/package-tree.html b/target/site/apidocs/org/apache/datasketches/tdigest/package-tree.html new file mode 100644 index 000000000..9766c637b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tdigest/package-tree.html @@ -0,0 +1,81 @@ + + + + +org.apache.datasketches.tdigest Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.tdigest

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tdigest/package-use.html b/target/site/apidocs/org/apache/datasketches/tdigest/package-use.html new file mode 100644 index 000000000..9ed856e10 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tdigest/package-use.html @@ -0,0 +1,91 @@ + + + + +Uses of Package org.apache.datasketches.tdigest (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.tdigest

+
+ +
+
Package
+
Description
+ +
+
t-Digest for estimating quantiles and ranks.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/CompactThetaSketch.html b/target/site/apidocs/org/apache/datasketches/theta/CompactThetaSketch.html new file mode 100644 index 000000000..21cd00c7f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/CompactThetaSketch.html @@ -0,0 +1,596 @@ + + + + +CompactThetaSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class CompactThetaSketch

+
+
java.lang.Object +
org.apache.datasketches.theta.ThetaSketch +
org.apache.datasketches.theta.CompactThetaSketch
+
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus
+
+
+
+
public abstract class CompactThetaSketch +extends ThetaSketch
+
The parent class of all the CompactThetaSketches. CompactThetaSketches are never created directly. +They are created as a result of the compact() method of an UpdatableThetaSketch, a result of a +getResult() of a ThetaSetOperation, or from a heapify method. + +

A CompactThetaSketch is the simplest form of a ThetaSketches. It consists of a compact list +(i.e., no intervening spaces) of hash values, which may be ordered or not, a value for theta +and a seed hash. A CompactThetaSketch is immutable (read-only), +and the space required when stored is only the space required for the hash values and 8 to 24 +bytes of preamble. An empty CompactThetaSketch consumes only 8 bytes.

+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      CompactThetaSketch

      +
      +
      public CompactThetaSketch()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapify

      +
      +
      public static CompactThetaSketch heapify(MemorySegment srcSeg)
      +
      Heapify takes a CompactThetaSketch image in a MemorySegment and instantiates an on-heap CompactThetaSketch. + +

      The resulting sketch will not retain any link to the source MemorySegment and all of its data will be +copied to the heap CompactThetaSketch.

      + +

      The DEFAULT_UPDATE_SEED is assumed.

      +
      +
      Parameters:
      +
      srcSeg - an image of a CompactThetaSketch.
      +
      Returns:
      +
      a CompactThetaSketch on the heap.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static CompactThetaSketch heapify(MemorySegment srcSeg, + long expectedSeed)
      +
      Heapify takes a CompactThetaSketch image in a MemorySegment and instantiates an on-heap CompactThetaSketch. + +

      The resulting sketch will not retain any link to the source MemorySegment and all of its data will be +copied to the heap CompactThetaSketch.

      + +

      This method checks if the given expectedSeed was used to create the source MemorySegment image.

      +
      +
      Parameters:
      +
      srcSeg - an image of a CompactThetaSketch that was created using the given expectedSeed.
      +
      expectedSeed - the seed used to validate the given MemorySegment image. +See Update Hash Seed.
      +
      Returns:
      +
      a CompactThetaSketch on the heap.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static CompactThetaSketch wrap(MemorySegment srcSeg)
      +
      Wrap takes the CompactThetaSketch image in given MemorySegment and refers to it directly. +There is no data copying onto the java heap. +The wrap operation enables fast read-only merging and access to all the public read-only API. + +

      Wrapping any subclass of this class that is empty or contains only a single item will +result in heapified forms of empty and single item sketch respectively. +This is actually faster and consumes less overall space.

      + +

      The DEFAULT_UPDATE_SEED is assumed.

      +
      +
      Parameters:
      +
      srcSeg - an image of a CompactThetaSketch.
      +
      Returns:
      +
      a CompactThetaSketch backed by the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static CompactThetaSketch wrap(MemorySegment srcSeg, + long expectedSeed)
      +
      Wrap takes the sketch image in the given MemorySegment and refers to it directly. +There is no data copying onto the java heap. +The wrap operation enables fast read-only merging and access to all the public read-only API. + +

      Wrapping any subclass of this class that is empty or contains only a single item will +result in heapified forms of empty and single item sketch respectively. +This is actually faster and consumes less overall space.

      + +

      This method checks if the given expectedSeed was used to create the source MemorySegment image.

      +
      +
      Parameters:
      +
      srcSeg - an image of a CompactThetaSketch that was created using the given expectedSeed.
      +
      expectedSeed - the seed used to validate the given MemorySegment image. +See Update Hash Seed.
      +
      Returns:
      +
      a CompactThetaketch backed by the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static CompactThetaSketch wrap(byte[] bytes)
      +
      Wrap takes the sketch image in the given byte array and refers to it directly. +There is no data copying onto the java heap. +The wrap operation enables fast read-only merging and access to all the public read-only API. + +

      Only sketches that have been explicitly stored as direct sketches can be wrapped.

      + +

      Wrapping any subclass of this class that is empty or contains only a single item will +result in heapified forms of empty and single item sketch respectively. +This is actually faster and consumes less overall space.

      + +

      This method checks if the DEFAULT_UPDATE_SEED was used to create the source byte array image.

      +
      +
      Parameters:
      +
      bytes - a byte array image of a CompactThetaSketch that was created using the DEFAULT_UPDATE_SEED.
      +
      Returns:
      +
      a CompactThetaSketch backed by the given byte array except as above.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static CompactThetaSketch wrap(byte[] bytes, + long expectedSeed)
      +
      Wrap takes the sketch image in the given byte array and refers to it directly. +There is no data copying onto the java heap. +The wrap operation enables fast read-only merging and access to all the public read-only API. + +

      Only sketches that have been explicitly stored as direct sketches can be wrapped.

      + +

      Wrapping any subclass of this class that is empty or contains only a single item will +result in heapified forms of empty and single item sketch respectively. +This is actually faster and consumes less overall space.

      + +

      This method checks if the given expectedSeed was used to create the source byte array image.

      +
      +
      Parameters:
      +
      bytes - a byte array image of a CompactThetaSketch that was created using the given expectedSeed.
      +
      expectedSeed - the seed used to validate the given byte array image. +See Update Hash Seed.
      +
      Returns:
      +
      a CompactThetaSketch backed by the given byte array except as above.
      +
      +
      +
      +
    • +
    • +
      +

      compact

      +
      +
      public abstract CompactThetaSketch compact(boolean dstOrdered, + MemorySegment dstSeg)
      +
      Description copied from class: ThetaSketch
      +
      Convert this sketch to a CompactThetaSketch. + +

      If this sketch is a type of UpdatableThetaSketch, the compacting process converts the hash table + of the UpdatableThetaketch to a simple list of the valid hash values. + Any hash values of zero or equal-to or greater than theta will be discarded. + The number of valid values remaining in the CompactThetaSketch depends on a number of factors, + but may be larger or smaller than Nominal Entries (or k). + It will never exceed 2k. + If it is critical to always limit the size to no more than k, + then rebuild() should be called on the UpdatableThetaSketch prior to calling this method.

      + +

      A CompactThetaSketch is always immutable.

      + +

      A new CompactThetaSketch object is created:

      +
      • if dstSeg!= null
      • +
      • if dstSeg == null and this.hasMemorySegment() == true
      • +
      • if dstSeg == null and this has more than 1 item and this.isOrdered() == false + and dstOrdered == true.
      • +
      + +

      Otherwise, this operation returns this.

      +
      +
      Specified by:
      +
      compact in class ThetaSketch
      +
      Parameters:
      +
      dstOrdered - assumed true if this sketch is empty or has only one value + See Destination Ordered
      +
      dstSeg - See Destination MemorySegment.
      +
      Returns:
      +
      this sketch as a CompactThetaSketch.
      +
      +
      +
      +
    • +
    • +
      +

      getCompactBytes

      +
      +
      public int getCompactBytes()
      +
      Description copied from class: ThetaSketch
      +
      Returns the number of storage bytes required for this ThetaSketch if its current state were +compacted. It this sketch is already in the compact form this is equivalent to +calling ThetaSketch.getCurrentBytes().
      +
      +
      Specified by:
      +
      getCompactBytes in class ThetaSketch
      +
      Returns:
      +
      number of compact bytes
      +
      +
      +
      +
    • +
    • +
      +

      getFamily

      +
      +
      public Family getFamily()
      +
      Description copied from class: ThetaSketch
      +
      Returns the Family that this sketch belongs to
      +
      +
      Specified by:
      +
      getFamily in class ThetaSketch
      +
      Returns:
      +
      the Family that this sketch belongs to
      +
      +
      +
      +
    • +
    • +
      +

      hasMemorySegment

      +
      +
      public boolean hasMemorySegment()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
      +
      +
      Returns:
      +
      true if this object's internal data is backed by a MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isCompact

      +
      +
      public boolean isCompact()
      +
      Description copied from class: ThetaSketch
      +
      Returns true if this sketch is in compact form.
      +
      +
      Specified by:
      +
      isCompact in class ThetaSketch
      +
      Returns:
      +
      true if this sketch is in compact form.
      +
      +
      +
      +
    • +
    • +
      +

      isOffHeap

      +
      +
      public boolean isOffHeap()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      Returns:
      +
      true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isSameResource

      +
      +
      public boolean isSameResource(MemorySegment that)
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap. This applies to both on-heap and off-heap MemorySegments. + +

      Note: If both segments are on-heap and not read-only, it can be determined if they were derived from +the same backing memory (array). However, this is not always possible off-heap. Because of this asymmetry, this definition +of "isSameResource" is confined to the existence of an overlap.

      +
      +
      Parameters:
      +
      that - The given MemorySegment.
      +
      Returns:
      +
      true if an internally referenced MemorySegment has the same backing resource as that.
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public double getEstimate()
      +
      Description copied from class: ThetaSketch
      +
      Gets the unique count estimate.
      +
      +
      Specified by:
      +
      getEstimate in class ThetaSketch
      +
      Returns:
      +
      the sketch's best estimate of the cardinality of the input stream.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArrayCompressed

      +
      +
      public byte[] toByteArrayCompressed()
      +
      gets the sketch as a compressed byte array
      +
      +
      Returns:
      +
      the sketch as a compressed byte array
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/HashIterator.html b/target/site/apidocs/org/apache/datasketches/theta/HashIterator.html new file mode 100644 index 000000000..7ade88338 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/HashIterator.html @@ -0,0 +1,161 @@ + + + + +HashIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface HashIterator

+
+
+
+
+
public interface HashIterator
+
This is used to iterate over the retained hash values of the Theta sketch.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    long
    +
    get()
    +
    +
    Gets the hash value
    +
    +
    boolean
    + +
    +
    Returns true at the next hash value in sequence.
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      get

      +
      +
      long get()
      +
      Gets the hash value
      +
      +
      Returns:
      +
      the hash value
      +
      +
      +
      +
    • +
    • +
      +

      next

      +
      +
      boolean next()
      +
      Returns true at the next hash value in sequence. +If false, the iteration is done.
      +
      +
      Returns:
      +
      true at the next hash value in sequence.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/JaccardSimilarity.html b/target/site/apidocs/org/apache/datasketches/theta/JaccardSimilarity.html new file mode 100644 index 000000000..555b08975 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/JaccardSimilarity.html @@ -0,0 +1,252 @@ + + + + +JaccardSimilarity (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class JaccardSimilarity

+
+
java.lang.Object +
org.apache.datasketches.theta.JaccardSimilarity
+
+
+
+
+
public final class JaccardSimilarity +extends Object
+
Jaccard similarity of two ThetaSketches.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      jaccard

      +
      +
      public static double[] jaccard(ThetaSketch sketchA, + ThetaSketch sketchB)
      +
      Computes the Jaccard similarity index with upper and lower bounds. The Jaccard similarity index +J(A,B) = (A ^ B)/(A U B) is used to measure how similar the two sketches are to each +other. If J = 1.0, the sketches are considered equal. If J = 0, the two sketches are +distinct from each other. A Jaccard of .95 means the overlap between the two +populations is 95% of the union of the two populations. + +

      Note: For very large pairs of sketches, where the configured nominal entries of the sketches +are 2^25 or 2^26, this method may produce unpredictable results.

      +
      +
      Parameters:
      +
      sketchA - given sketch A
      +
      sketchB - given sketch B
      +
      Returns:
      +
      a double array {LowerBound, Estimate, UpperBound} of the Jaccard index. +The Upper and Lower bounds are for a confidence interval of 95.4% or +/- 2 standard deviations.
      +
      +
      +
      +
    • +
    • +
      +

      exactlyEqual

      +
      +
      public static boolean exactlyEqual(ThetaSketch sketchA, + ThetaSketch sketchB)
      +
      Returns true if the two given sketches have exactly the same hash values and the same +theta values. Thus, they are equivalent.
      +
      +
      Parameters:
      +
      sketchA - the given sketch A
      +
      sketchB - the given sketch B
      +
      Returns:
      +
      true if the two given sketches have exactly the same hash values and the same +theta values.
      +
      +
      +
      +
    • +
    • +
      +

      similarityTest

      +
      +
      public static boolean similarityTest(ThetaSketch measured, + ThetaSketch expected, + double threshold)
      +
      Tests similarity of a measured ThetaSketch against an expected ThetaSketch. +Computes the lower bound of the Jaccard index JLB of the measured and +expected sketches. +if JLB ≥ threshold, then the sketches are considered to be +similar with a confidence of 97.7%.
      +
      +
      Parameters:
      +
      measured - the sketch to be tested
      +
      expected - the reference sketch that is considered to be correct.
      +
      threshold - a real value between zero and one.
      +
      Returns:
      +
      if true, the similarity of the two sketches is greater than the given threshold +with at least 97.7% confidence.
      +
      +
      +
      +
    • +
    • +
      +

      dissimilarityTest

      +
      +
      public static boolean dissimilarityTest(ThetaSketch measured, + ThetaSketch expected, + double threshold)
      +
      Tests dissimilarity of a measured ThetaSketch against an expected ThetaSketch. +Computes the upper bound of the Jaccard index JUB of the measured and +expected sketches. +if JUB ≤ threshold, then the sketches are considered to be +dissimilar with a confidence of 97.7%.
      +
      +
      Parameters:
      +
      measured - the sketch to be tested
      +
      expected - the reference sketch that is considered to be correct.
      +
      threshold - a real value between zero and one.
      +
      Returns:
      +
      if true, the dissimilarity of the two sketches is greater than the given threshold +with at least 97.7% confidence.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/ThetaAnotB.html b/target/site/apidocs/org/apache/datasketches/theta/ThetaAnotB.html new file mode 100644 index 000000000..4dea1dce2 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/ThetaAnotB.html @@ -0,0 +1,409 @@ + + + + +ThetaAnotB (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ThetaAnotB

+
+
java.lang.Object +
org.apache.datasketches.theta.ThetaSetOperation +
org.apache.datasketches.theta.ThetaAnotB
+
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus
+
+
+
+
public abstract class ThetaAnotB +extends ThetaSetOperation
+
Computes a set difference, A-AND-NOT-B, of two ThetaSketches. +This class includes both stateful and stateless operations. + +

The stateful operation is as follows:

+
ThetaAnotB anotb = ThetaSetOperationBuilder.buildAnotB();
+
+anotb.setA(ThetaSketch skA); //The first argument.
+anotb.notB(ThetaSketch skB); //The second (subtraction) argument.
+anotb.notB(ThetaSketch skC); // ...any number of additional subtractions...
+anotb.getResult(false); //Get an interim result.
+anotb.notB(ThetaSketch skD); //Additional subtractions.
+anotb.getResult(true);  //Final result and resets the ThetaAnotB operator.
+
+ +

The stateless operation is as follows:

+
ThetaAnotB anotb = ThetaSetOperationBuilder.buildAnotB();
+
+CompactThetaSketch csk = anotb.aNotB(ThetaSketch skA, ThetaSketch skB);
+
+ +

Calling the setA operation a second time essentially clears the internal state and loads +the new ThetaSketch.

+ +

The stateless and stateful operations are independent of each other with the exception of +sharing the same update hash seed loaded as the default seed or specified by the user as an +argument to the builder.

+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getFamily

      +
      +
      public Family getFamily()
      +
      Description copied from class: ThetaSetOperation
      +
      Gets the Family of this ThetaSetOperation
      +
      +
      Specified by:
      +
      getFamily in class ThetaSetOperation
      +
      Returns:
      +
      the Family of this ThetaSetOperation
      +
      +
      +
      +
    • +
    • +
      +

      setA

      +
      +
      public abstract void setA(ThetaSketch skA)
      +
      This is part of a multistep, stateful ThetaAnotB operation and sets the given ThetaSketch as the +first argument A of A-AND-NOT-B. This overwrites the internal state of this +ThetaAnotB operator with the contents of the given sketch. +This sets the stage for multiple following notB steps. + +

      An input argument of null will throw an exception.

      + +

      Rationale: In mathematics a "null set" is a set with no members, which we call an empty set. +That is distinctly different from the java null, which represents a nonexistent object. +In most cases it is a programming error due to some object that was not properly initialized. +With a null as the first argument, we cannot know what the user's intent is. +Since it is very likely that a null is a programming error, we throw a an exception.

      + +

      An empty input argument will set the internal state to empty.

      + +

      Rationale: An empty set is a mathematically legal concept. Although it makes any subsequent, +valid argument for B irrelevant, we must allow this and assume the user knows what they are +doing.

      + +

      Performing getResult(boolean) just after this step will return a compact form of +the given argument.

      +
      +
      Parameters:
      +
      skA - The incoming sketch for the first argument, A.
      +
      +
      +
      +
    • +
    • +
      +

      notB

      +
      +
      public abstract void notB(ThetaSketch skB)
      +
      This is part of a multistep, stateful ThetaAnotB operation and sets the given ThetaSketch as the +second (or n+1th) argument B of A-AND-NOT-B. +Performs an AND NOT operation with the existing internal state of this ThetaAnotB operator. + +

      An input argument of null or empty is ignored.

      + +

      Rationale: A null for the second or following arguments is more tolerable because +A NOT null is still A even if we don't know exactly what the null represents. It +clearly does not have any content that overlaps with A. Also, because this can be part of +a multistep operation with multiple notB steps. Other following steps can still produce +a valid result.

      + +

      Use getResult(boolean) to obtain the result.

      +
      +
      Parameters:
      +
      skB - The incoming ThetaSketch for the second (or following) argument B.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public abstract CompactThetaSketch getResult(boolean reset)
      +
      Gets the result of the multistep, stateful operation ThetaAnotB that have been executed with calls +to setA(ThetaSketch) and (notB(ThetaSketch) or +notB(org.apache.datasketches.theta.ThetaSketch)).
      +
      +
      Parameters:
      +
      reset - If true, clears this operator to the empty state after this result is +returned. Set this to false if you wish to obtain an intermediate result.
      +
      Returns:
      +
      the result of this operation as an ordered, on-heap CompactThetaSketch.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public abstract CompactThetaSketch getResult(boolean dstOrdered, + MemorySegment dstSeg, + boolean reset)
      +
      Gets the result of the multistep, stateful operation ThetaAnotB that have been executed with calls +to setA(ThetaSketch) and (notB(ThetaSketch) or +notB(org.apache.datasketches.theta.ThetaSketch)).
      +
      +
      Parameters:
      +
      dstOrdered - If true, the result will be an ordered CompactThetaSketch. +See Destination Ordered.
      +
      dstSeg - if not null the given MemorySegment will be the target location of the result.
      +
      reset - If true, clears this operator to the empty state after this result is +returned. Set this to false if you wish to obtain an intermediate result.
      +
      Returns:
      +
      the result of this operation as a CompactThetaSketch in the given dstSeg.
      +
      +
      +
      +
    • +
    • +
      +

      aNotB

      +
      +
      public CompactThetaSketch aNotB(ThetaSketch skA, + ThetaSketch skB)
      +
      Perform A-and-not-B set operation on the two given sketches and return the result as an +ordered CompactThetaSketch on the heap. + +

      This a stateless operation and has no impact on the internal state of this operator. +Thus, this is not an accumulating update and does not interact with the setA(ThetaSketch), +notB(ThetaSketch), getResult(boolean), or +getResult(boolean, MemorySegment, boolean) methods.

      + +

      If either argument is null an exception is thrown.

      + +

      Rationale: In mathematics a "null set" is a set with no members, which we call an empty set. +That is distinctly different from the java null, which represents a nonexistent object. +In most cases null is a programming error due to a non-initialized object.

      + +

      With a null as the first argument we cannot know what the user's intent is and throw an +exception. With a null as the second argument for this method we must return a result and +there is no following possible viable arguments for the second argument so we thrown an +exception.

      +
      +
      Parameters:
      +
      skA - The incoming sketch for the first argument. It must not be null.
      +
      skB - The incoming sketch for the second argument. It must not be null.
      +
      Returns:
      +
      an ordered CompactThetaSketch on the heap
      +
      +
      +
      +
    • +
    • +
      +

      aNotB

      +
      +
      public abstract CompactThetaSketch aNotB(ThetaSketch skA, + ThetaSketch skB, + boolean dstOrdered, + MemorySegment dstSeg)
      +
      Perform A-and-not-B set operation on the two given sketches and return the result as a +CompactThetaSketch. + +

      This a stateless operation and has no impact on the internal state of this operator. +Thus, this is not an accumulating update and does not interact with the setA(ThetaSketch), +notB(ThetaSketch), getResult(boolean), or +getResult(boolean, MemorySegment, boolean) methods.

      + +

      If either argument is null an exception is thrown.

      + +

      Rationale: In mathematics a "null set" is a set with no members, which we call an empty set. +That is distinctly different from the java null, which represents a nonexistent object. +In most cases null is a programming error due to a non-initialized object.

      + +

      With a null as the first argument we cannot know what the user's intent is and throw an +exception. With a null as the second argument for this method we must return a result and +there is no following possible viable arguments for the second argument so we thrown an +exception.

      +
      +
      Parameters:
      +
      skA - The incoming sketch for the first argument. It must not be null.
      +
      skB - The incoming sketch for the second argument. It must not be null.
      +
      dstOrdered - See Destination Ordered.
      +
      dstSeg - the destination MemorySegment
      +
      Returns:
      +
      the result as a CompactThetaSketch.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/ThetaIntersection.html b/target/site/apidocs/org/apache/datasketches/theta/ThetaIntersection.html new file mode 100644 index 000000000..a4f882f96 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/ThetaIntersection.html @@ -0,0 +1,443 @@ + + + + +ThetaIntersection (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ThetaIntersection

+
+
java.lang.Object +
org.apache.datasketches.theta.ThetaSetOperation +
org.apache.datasketches.theta.ThetaIntersection
+
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus
+
+
+
+
public abstract class ThetaIntersection +extends ThetaSetOperation
+
The API for intersection operations
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ThetaIntersection

      +
      +
      public ThetaIntersection()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getFamily

      +
      +
      public Family getFamily()
      +
      Description copied from class: ThetaSetOperation
      +
      Gets the Family of this ThetaSetOperation
      +
      +
      Specified by:
      +
      getFamily in class ThetaSetOperation
      +
      Returns:
      +
      the Family of this ThetaSetOperation
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public CompactThetaSketch getResult()
      +
      Gets the result of this operation as an ordered CompactThetaSketch on the Java heap. +This does not disturb the underlying data structure of this intersection. +The intersect(ThetaSketch) method must have been called at least once, otherwise an +exception will be thrown. This is because a virgin intersection represents the +Universal Set, which has an infinite number of values.
      +
      +
      Returns:
      +
      the result of this operation as an ordered CompactThetaSketch on the Java heap
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public abstract CompactThetaSketch getResult(boolean dstOrdered, + MemorySegment dstSeg)
      +
      Gets the result of this operation as a CompactThetaSketch in the given dstSeg. +This does not disturb the underlying data structure of this intersection. +The intersect(ThetaSketch) method must have been called at least once, otherwise an +exception will be thrown. This is because a virgin intersection represents the +Universal Set, which has an infinite number of values. + +

      Note that presenting an intersection with an empty sketch sets the internal +state of the intersection to empty = true, and current count = 0. This is consistent with +the mathematical definition of the intersection of any set with the empty set is +always empty.

      + +

      Presenting an intersection with a null argument will throw an exception.

      +
      +
      Parameters:
      +
      dstOrdered - See Destination Ordered
      +
      dstSeg - the destination MemorySegment.
      +
      Returns:
      +
      the result of this operation as a CompactThetaSketch stored in the given dstSeg, +which can be either on or off-heap..
      +
      +
      +
      +
    • +
    • +
      +

      hasResult

      +
      +
      public abstract boolean hasResult()
      +
      Returns true if there is a valid intersection result available
      +
      +
      Returns:
      +
      true if there is a valid intersection result available
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public abstract void reset()
      +
      Resets this ThetaIntersection for stateful operations only. +The seed remains intact, otherwise reverts to +the Universal Set: theta = 1.0, no retained data and empty = false.
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public abstract byte[] toByteArray()
      +
      Serialize this intersection to a byte array form.
      +
      +
      Returns:
      +
      byte array of this intersection
      +
      +
      +
      +
    • +
    • +
      +

      intersect

      +
      +
      public abstract void intersect(ThetaSketch sketchIn)
      +
      Intersect the given sketch with the internal state. +This method can be repeatedly called. +If the given sketch is null the internal state becomes the empty sketch. +Theta will become the minimum of thetas seen so far.
      +
      +
      Parameters:
      +
      sketchIn - the given sketch
      +
      +
      +
      +
    • +
    • +
      +

      intersect

      +
      +
      public CompactThetaSketch intersect(ThetaSketch a, + ThetaSketch b)
      +
      Perform intersect set operation on the two given sketch arguments and return the result as an +ordered CompactThetaSketch on the heap.
      +
      +
      Parameters:
      +
      a - The first sketch argument
      +
      b - The second sketch argument
      +
      Returns:
      +
      an ordered CompactThetaSketch on the heap
      +
      +
      +
      +
    • +
    • +
      +

      intersect

      +
      +
      public abstract CompactThetaSketch intersect(ThetaSketch a, + ThetaSketch b, + boolean dstOrdered, + MemorySegment dstSeg)
      +
      Perform intersect set operation on the two given sketches and return the result as a +CompactThetaSketch.
      +
      +
      Parameters:
      +
      a - The first sketch argument
      +
      b - The second sketch argument
      +
      dstOrdered - See Destination Ordered.
      +
      dstSeg - the destination MemorySegment.
      +
      Returns:
      +
      the result as a CompactThetaSketch.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ThetaIntersection wrap(MemorySegment srcSeg)
      +
      Factory: Wrap a ThetaIntersection target around the given source MemorySegment containing intersection data. +This method assumes the Default Update Seed. +If the given source MemorySegment is read-only, the returned object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - The source MemorySegment image.
      +
      Returns:
      +
      a ThetaIntersection that wraps a source MemorySegment that contains a ThetaIntersection image
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ThetaIntersection wrap(MemorySegment srcSeg, + long expectedSeed)
      +
      Factory: Wrap a ThetaIntersection target around the given source MemorySegment containing intersection data. +If the given source MemorySegment is read-only, the returned object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - The source MemorySegment image.
      +
      expectedSeed - See seed
      +
      Returns:
      +
      a ThetaIntersection that wraps a source MemorySegment that contains a ThetaIntersection image
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/ThetaSetOperation.html b/target/site/apidocs/org/apache/datasketches/theta/ThetaSetOperation.html new file mode 100644 index 000000000..3ffd22d2f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/ThetaSetOperation.html @@ -0,0 +1,363 @@ + + + + +ThetaSetOperation (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ThetaSetOperation

+
+
java.lang.Object +
org.apache.datasketches.theta.ThetaSetOperation
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus
+
+
+
Direct Known Subclasses:
+
ThetaAnotB, ThetaIntersection, ThetaUnion
+
+
+
+
public abstract class ThetaSetOperation +extends Object +implements MemorySegmentStatus
+
The parent API for all Set Operations
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      builder

      +
      +
      public static final ThetaSetOperationBuilder builder()
      +
      Makes a new builder
      +
      +
      Returns:
      +
      a new builder
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static ThetaSetOperation heapify(MemorySegment srcSeg)
      +
      Heapify takes the ThetaSetOperation image in MemorySegment and instantiates an on-heap +ThetaSetOperation using the +Default Update Seed. +The resulting ThetaSetOperation will not retain any link to the source MemorySegment. + +

      Note: Only certain set operators during stateful operations can be serialized and thus +heapified.

      +
      +
      Parameters:
      +
      srcSeg - an image of a ThetaSetOperation where the image seed hash matches the default seed hash.
      +
      Returns:
      +
      a Heap-based ThetaSetOperation from the given MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static ThetaSetOperation heapify(MemorySegment srcSeg, + long expectedSeed)
      +
      Heapify takes the ThetaSetOperation image in MemorySegment and instantiates an on-heap +ThetaSetOperation using the given expectedSeed. +The resulting ThetaSetOperation will not retain any link to the source MemorySegment. + +

      Note: Only certain set operators during stateful operations can be serialized and thus +heapified.

      +
      +
      Parameters:
      +
      srcSeg - an image of a ThetaSetOperation where the hash of the given expectedSeed matches the image seed hash.
      +
      expectedSeed - the seed used to validate the given MemorySegment image. +See Update Hash Seed.
      +
      Returns:
      +
      a Heap-based ThetaSetOperation from the given MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ThetaSetOperation wrap(MemorySegment srcSeg)
      +
      Wrap takes the ThetaSetOperation image in MemorySegment and refers to it directly. +There is no data copying onto the java heap. +This method assumes the Default Update Seed. +If the given source MemorySegment is read-only, the returned object will also be read-only. + +

      Note: Only certain set operators during stateful operations can be serialized and thus wrapped.

      +
      +
      Parameters:
      +
      srcSeg - an image of a ThetaSetOperation where the image seed hash matches the default seed hash.
      +
      Returns:
      +
      a ThetaSetOperation backed by the given MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ThetaSetOperation wrap(MemorySegment srcSeg, + long expectedSeed)
      +
      Wrap takes the ThetaSetOperation image in MemorySegment and refers to it directly. +There is no data copying onto the java heap. +If the given source MemorySegment is read-only, the returned object will also be read-only. + +

      Note: Only certain set operators during stateful operations can be serialized and thus wrapped.

      +
      +
      Parameters:
      +
      srcSeg - an image of a ThetaSetOperation where the hash of the given expectedSeed matches the image seed hash.
      +
      expectedSeed - the seed used to validate the given MemorySegment image. +See Update Hash Seed.
      +
      Returns:
      +
      a ThetaSetOperation backed by the given MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      getMaxUnionBytes

      +
      +
      public static int getMaxUnionBytes(int nomEntries)
      +
      Returns the maximum required storage bytes given a nomEntries parameter for ThetaUnion operations
      +
      +
      Parameters:
      +
      nomEntries - Nominal Entries +This will become the ceiling power of 2 if it is not.
      +
      Returns:
      +
      the maximum required storage bytes given a nomEntries parameter
      +
      +
      +
      +
    • +
    • +
      +

      getMaxIntersectionBytes

      +
      +
      public static int getMaxIntersectionBytes(int nomEntries)
      +
      Returns the maximum required storage bytes given a nomEntries parameter for intersection +operations
      +
      +
      Parameters:
      +
      nomEntries - Nominal Entries +This will become the ceiling power of 2 if it is not.
      +
      Returns:
      +
      the maximum required storage bytes given a nomEntries parameter
      +
      +
      +
      +
    • +
    • +
      +

      getMaxAnotBResultBytes

      +
      +
      public static int getMaxAnotBResultBytes(int nomEntries)
      +
      Returns the maximum number of bytes for the returned CompactThetaSketch, given the +value of nomEntries of the first sketch A of ThetaAnotB.
      +
      +
      Parameters:
      +
      nomEntries - this value must be a power of 2.
      +
      Returns:
      +
      the maximum number of bytes.
      +
      +
      +
      +
    • +
    • +
      +

      getFamily

      +
      +
      public abstract Family getFamily()
      +
      Gets the Family of this ThetaSetOperation
      +
      +
      Returns:
      +
      the Family of this ThetaSetOperation
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/ThetaSetOperationBuilder.html b/target/site/apidocs/org/apache/datasketches/theta/ThetaSetOperationBuilder.html new file mode 100644 index 000000000..539a0c4ef --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/ThetaSetOperationBuilder.html @@ -0,0 +1,540 @@ + + + + +ThetaSetOperationBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ThetaSetOperationBuilder

+
+
java.lang.Object +
org.apache.datasketches.theta.ThetaSetOperationBuilder
+
+
+
+
+
public final class ThetaSetOperationBuilder +extends Object
+
For building a new ThetaSetOperation.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ThetaSetOperationBuilder

      +
      +
      public ThetaSetOperationBuilder()
      +
      Constructor for building a new ThetaSetOperation. The default configuration is +
        +
      • Max Nominal Entries (max K): + 4096
      • +
      • Seed: 9001L
      • +
      • ResizeFactor.X8
      • +
      • Input Sampling Probability: 1.0
      • +
      • MemorySegment: null
      • +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      setNominalEntries

      +
      +
      public ThetaSetOperationBuilder setNominalEntries(int nomEntries)
      +
      Sets the Maximum Nominal Entries (max K) for this set operation. The effective value of K of the result of a +Set Operation can be less than max K, but never greater. +The minimum value is 16 and the maximum value is 67,108,864, which is 2^26.
      +
      +
      Parameters:
      +
      nomEntries - Nominal Entries +This will become the ceiling power of 2 if it is not a power of 2.
      +
      Returns:
      +
      this ThetaSetOperationBuilder
      +
      +
      +
      +
    • +
    • +
      +

      setLogNominalEntries

      +
      +
      public ThetaSetOperationBuilder setLogNominalEntries(int lgNomEntries)
      +
      Alternative method of setting the Nominal Entries for this set operation from the log_base2 value. +The minimum value is 4 and the maximum value is 26. +Be aware that set operations as large as this maximum value may not have been +thoroughly characterized for performance.
      +
      +
      Parameters:
      +
      lgNomEntries - the log_base2 Nominal Entries.
      +
      Returns:
      +
      this ThetaSetOperationBuilder
      +
      +
      +
      +
    • +
    • +
      +

      getLgNominalEntries

      +
      +
      public int getLgNominalEntries()
      +
      Returns Log-base 2 Nominal Entries
      +
      +
      Returns:
      +
      Log-base 2 Nominal Entries
      +
      +
      +
      +
    • +
    • +
      +

      setSeed

      +
      +
      public ThetaSetOperationBuilder setSeed(long seed)
      +
      Sets the long seed value that is require by the hashing function.
      +
      +
      Parameters:
      +
      seed - See seed
      +
      Returns:
      +
      this ThetaSetOperationBuilder
      +
      +
      +
      +
    • +
    • +
      +

      getSeed

      +
      +
      public long getSeed()
      +
      Returns the seed
      +
      +
      Returns:
      +
      the seed
      +
      +
      +
      +
    • +
    • +
      +

      setP

      +
      +
      public ThetaSetOperationBuilder setP(float p)
      +
      Sets the upfront uniform sampling probability, p. Although this functionality is +implemented for ThetaUnions only, it rarely makes sense to use it. The proper use of upfront +sampling is when building the sketches.
      +
      +
      Parameters:
      +
      p - See Sampling Probability, p
      +
      Returns:
      +
      this ThetaSetOperationBuilder
      +
      +
      +
      +
    • +
    • +
      +

      getP

      +
      +
      public float getP()
      +
      Returns the pre-sampling probability p
      +
      +
      Returns:
      +
      the pre-sampling probability p
      +
      +
      +
      +
    • +
    • +
      +

      setResizeFactor

      +
      +
      public ThetaSetOperationBuilder setResizeFactor(ResizeFactor rf)
      +
      Sets the cache Resize Factor
      +
      +
      Parameters:
      +
      rf - See Resize Factor
      +
      Returns:
      +
      this ThetaSetOperationBuilder
      +
      +
      +
      +
    • +
    • +
      +

      getResizeFactor

      +
      +
      public ResizeFactor getResizeFactor()
      +
      Returns the Resize Factor
      +
      +
      Returns:
      +
      the Resize Factor
      +
      +
      +
      +
    • +
    • +
      +

      build

      +
      +
      public ThetaSetOperation build(Family family)
      +
      Returns a ThetaSetOperation with the current configuration of this Builder and the given Family.
      +
      +
      Parameters:
      +
      family - the chosen ThetaSetOperation family
      +
      Returns:
      +
      a ThetaSetOperation
      +
      +
      +
      +
    • +
    • +
      +

      build

      +
      +
      public ThetaSetOperation build(Family family, + MemorySegment dstSeg)
      +
      Returns a ThetaSetOperation with the current configuration of this Builder, the given Family +and the given destination MemorySegment. Note that the destination MemorySegment cannot be used with ThetaAnotB.
      +
      +
      Parameters:
      +
      family - the chosen ThetaSetOperation family
      +
      dstSeg - The destination MemorySegment.
      +
      Returns:
      +
      a ThetaSetOperation
      +
      +
      +
      +
    • +
    • +
      +

      buildUnion

      +
      +
      public ThetaUnion buildUnion()
      +
      Convenience method, returns a configured ThetaSetOperation ThetaUnion with +Default Nominal Entries
      +
      +
      Returns:
      +
      a ThetaUnion object
      +
      +
      +
      +
    • +
    • +
      +

      buildUnion

      +
      +
      public ThetaUnion buildUnion(MemorySegment dstSeg)
      +
      Convenience method, returns a configured ThetaSetOperation ThetaUnion with +Default Nominal Entries +and the given destination MemorySegment.
      +
      +
      Parameters:
      +
      dstSeg - The destination MemorySegment.
      +
      Returns:
      +
      a ThetaUnion object
      +
      +
      +
      +
    • +
    • +
      +

      buildIntersection

      +
      +
      public ThetaIntersection buildIntersection()
      +
      Convenience method, returns a configured ThetaIntersection with +Default Nominal Entries
      +
      +
      Returns:
      +
      a ThetaIntersection object
      +
      +
      +
      +
    • +
    • +
      +

      buildIntersection

      +
      +
      public ThetaIntersection buildIntersection(MemorySegment dstSeg)
      +
      Convenience method, returns a configured ThetaIntersection with +Default Nominal Entries +and the given destination MemorySegment.
      +
      +
      Parameters:
      +
      dstSeg - The destination MemorySegment.
      +
      Returns:
      +
      a ThetaIntersection object
      +
      +
      +
      +
    • +
    • +
      +

      buildANotB

      +
      +
      public ThetaAnotB buildANotB()
      +
      Convenience method, returns a configured ThetaSetOperation ANotB with +Default Update Seed
      +
      +
      Returns:
      +
      a ThetaANotB object
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/ThetaSketch.html b/target/site/apidocs/org/apache/datasketches/theta/ThetaSketch.html new file mode 100644 index 000000000..3ca2fcca5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/ThetaSketch.html @@ -0,0 +1,993 @@ + + + + +ThetaSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ThetaSketch

+
+
java.lang.Object +
org.apache.datasketches.theta.ThetaSketch
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus
+
+
+
Direct Known Subclasses:
+
CompactThetaSketch, UpdatableThetaSketch
+
+
+
+
public abstract class ThetaSketch +extends Object +implements MemorySegmentStatus
+
The top-level class for all theta sketches. This class is never constructed directly. +Use the UpdatableThetaSketchBuilder() methods to create UpdatableThetaSketches.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Converts this sketch to a ordered CompactThetaSketch.
    +
    + +
    compact(boolean dstOrdered, + MemorySegment dstSeg)
    +
    +
    Convert this sketch to a CompactThetaSketch.
    +
    +
    abstract int
    + +
    +
    Returns the number of storage bytes required for this ThetaSketch if its current state were +compacted.
    +
    +
    static int
    +
    getCompactSketchMaxBytes(int lgNomEntries)
    +
    +
    Returns the maximum number of storage bytes required for a CompactThetaSketch given the configured +log_base2 of the number of nominal entries, which is a power of 2.
    +
    +
    int
    +
    getCountLessThanThetaLong(long thetaLong)
    +
    +
    Gets the number of hash values less than the given theta expressed as a long.
    +
    +
    abstract int
    + +
    +
    Returns the number of storage bytes required for this sketch in its current state.
    +
    +
    abstract double
    + +
    +
    Gets the unique count estimate.
    +
    +
    static double
    + +
    +
    Gets the estimate from the given MemorySegment
    +
    +
    abstract Family
    + +
    +
    Returns the Family that this sketch belongs to
    +
    +
    double
    +
    getLowerBound(int numStdDev)
    +
    +
    Gets the approximate lower error bound given the specified number of Standard Deviations.
    +
    +
    static double
    +
    getLowerBound(int numStdDev, + MemorySegment srcSeg)
    +
    +
    Gets the approximate lower error bound from a valid MemorySegment image of a ThetaSketch +given the specified number of Standard Deviations.
    +
    +
    static int
    +
    getMaxCompactSketchBytes(int numberOfEntries)
    +
    +
    Returns the maximum number of storage bytes required for a CompactThetaSketch with the given +number of actual entries.
    +
    +
    static int
    +
    getMaxUpdateSketchBytes(int nomEntries)
    +
    +
    Returns the maximum number of storage bytes required for an UpdatableThetaSketch with the given +number of nominal entries (power of 2).
    +
    +
    int
    + +
    +
    Returns the number of valid entries that have been retained by the sketch.
    +
    +
    abstract int
    +
    getRetainedEntries(boolean valid)
    +
    +
    Returns the number of entries that have been retained by the sketch.
    +
    +
    static int
    + +
    +
    Returns the number of valid entries that have been retained by the sketch from the given MemorySegment
    +
    +
    static int
    + +
    +
    Returns the serialization version from the given MemorySegment
    +
    +
    double
    + +
    +
    Gets the value of theta as a double with a value between zero and one
    +
    +
    abstract long
    + +
    +
    Gets the value of theta as a long
    +
    +
    static int
    +
    getUpdateSketchMaxBytes(int lgNomEntries)
    +
    +
    Returns the maximum number of storage bytes required for an UpdatableThetaSketch with the given +log_base2 of the nominal entries.
    +
    +
    double
    +
    getUpperBound(int numStdDev)
    +
    +
    Gets the approximate upper error bound given the specified number of Standard Deviations.
    +
    +
    static double
    +
    getUpperBound(int numStdDev, + MemorySegment srcSeg)
    +
    +
    Gets the approximate upper error bound from a valid MemorySegment image of a ThetaSketch +given the specified number of Standard Deviations.
    +
    + + +
    +
    Heapify takes the sketch image in MemorySegment and instantiates an on-heap ThetaSketch.
    +
    + +
    heapify(MemorySegment srcSeg, + long expectedSeed)
    +
    +
    Heapify takes the sketch image in MemorySegment and instantiates an on-heap ThetaSketch.
    +
    +
    abstract boolean
    + +
    +
    Returns true if this sketch is in compact form.
    +
    +
    abstract boolean
    + + +
    boolean
    + +
    +
    Returns true if the sketch is Estimation Mode (as opposed to Exact Mode).
    +
    +
    abstract boolean
    + +
    +
    Returns true if internal cache is ordered
    +
    +
    abstract HashIterator
    + +
    +
    Returns a HashIterator that can be used to iterate over the retained hash values of the +Theta sketch.
    +
    +
    abstract byte[]
    + +
    +
    Serialize this sketch to a byte array form.
    +
    + + +
    +
    Returns a human readable summary of the sketch.
    +
    + +
    toString(boolean sketchSummary, + boolean dataDetail, + int width, + boolean hexMode)
    +
    +
    Gets a human readable listing of contents and summary of the given sketch.
    +
    +
    static String
    +
    toString(byte[] byteArr)
    +
    +
    Returns a human readable string of the preamble of a byte array image of a ThetaSketch.
    +
    +
    static String
    + +
    +
    Returns a human readable string of the preamble of a MemorySegment image of a ThetaSketch.
    +
    + + +
    +
    Wrap takes the sketch image in the given MemorySegment and refers to it directly.
    +
    + +
    wrap(MemorySegment srcSeg, + long expectedSeed)
    +
    +
    Wrap takes the sketch image in the given MemorySegment and refers to it directly.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +

    Methods inherited from interface MemorySegmentStatus

    +hasMemorySegment, isOffHeap, isSameResource
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapify

      +
      +
      public static ThetaSketch heapify(MemorySegment srcSeg)
      +
      Heapify takes the sketch image in MemorySegment and instantiates an on-heap ThetaSketch. + +

      The resulting sketch will not retain any link to the source MemorySegment.

      + +

      For UpdatableThetaSketches this method checks if the +Default Update Seed

      +was used to create the source MemorySegment image.
      +
      +
      Parameters:
      +
      srcSeg - an image of a ThetaSketch.
      +
      Returns:
      +
      a ThetaSketch on the heap.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static ThetaSketch heapify(MemorySegment srcSeg, + long expectedSeed)
      +
      Heapify takes the sketch image in MemorySegment and instantiates an on-heap ThetaSketch. + +

      The resulting sketch will not retain any link to the source MemorySegment.

      + +

      For UpdatableThetaSketches this method checks if the expectedSeed +was used to create the source MemorySegment image.

      +
      +
      Parameters:
      +
      srcSeg - an image of a ThetaSketch that was created using the given expectedSeed.
      +
      expectedSeed - the seed used to validate the given MemorySegment image. + See Update Hash Seed. +Compact sketches store a 16-bit hash of the seed, but not the seed itself.
      +
      Returns:
      +
      a ThetaSketch on the heap.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ThetaSketch wrap(MemorySegment srcSeg)
      +
      Wrap takes the sketch image in the given MemorySegment and refers to it directly. +There is no data copying onto the java heap. +The wrap operation enables fast read-only merging and access to all the public read-only API. + +

      Only sketches that have been explicitly stored as direct sketches can be wrapped.

      + +

      Wrapping any subclass of this class that is empty or contains only a single item will +result in on-heap equivalent forms of empty and single item sketch respectively. +This is actually faster and consumes less overall space.

      + +

      This method checks if the +Default Update Seed +was used to create the source MemorySegment image.

      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment with an image of a ThetaSketch.
      +
      Returns:
      +
      a read-only ThetaSketch backed by the given MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ThetaSketch wrap(MemorySegment srcSeg, + long expectedSeed)
      +
      Wrap takes the sketch image in the given MemorySegment and refers to it directly. +There is no data copying onto the java heap. +The wrap operation enables fast read-only merging and access to all the public read-only API. + +

      Only sketches that have been explicitly stored as direct sketches can be wrapped.

      + +

      Wrapping any subclass of this class that is empty or contains only a single item will +result in on-heap equivalent forms of empty and single item sketch respectively. +This is actually faster and consumes less overall space.

      + +

      This method checks if the given expectedSeed +was used to create the source MemorySegment image.

      +
      +
      Parameters:
      +
      srcSeg - a MemorySegment with an image of a ThetaSketch.
      +
      expectedSeed - the seed used to validate the given MemorySegment image. +See Update Hash Seed.
      +
      Returns:
      +
      a read-only ThetaSketch backed by the given MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      compact

      +
      +
      public CompactThetaSketch compact()
      +
      Converts this sketch to a ordered CompactThetaSketch. + +

      If this.isCompact() == true this method returns this, +otherwise, this method is equivalent to +compact(true, null). + +

      A CompactThetaSketch is always immutable.

      +
      +
      Returns:
      +
      this sketch as an ordered CompactThetaSketch.
      +
      +
      +
      +
    • +
    • +
      +

      compact

      +
      +
      public abstract CompactThetaSketch compact(boolean dstOrdered, + MemorySegment dstSeg)
      +
      Convert this sketch to a CompactThetaSketch. + +

      If this sketch is a type of UpdatableThetaSketch, the compacting process converts the hash table + of the UpdatableThetaketch to a simple list of the valid hash values. + Any hash values of zero or equal-to or greater than theta will be discarded. + The number of valid values remaining in the CompactThetaSketch depends on a number of factors, + but may be larger or smaller than Nominal Entries (or k). + It will never exceed 2k. + If it is critical to always limit the size to no more than k, + then rebuild() should be called on the UpdatableThetaSketch prior to calling this method.

      + +

      A CompactThetaSketch is always immutable.

      + +

      A new CompactThetaSketch object is created:

      +
      • if dstSeg!= null
      • +
      • if dstSeg == null and this.hasMemorySegment() == true
      • +
      • if dstSeg == null and this has more than 1 item and this.isOrdered() == false + and dstOrdered == true.
      • +
      + +

      Otherwise, this operation returns this.

      +
      +
      Parameters:
      +
      dstOrdered - assumed true if this sketch is empty or has only one value + See Destination Ordered
      +
      dstSeg - See Destination MemorySegment.
      +
      Returns:
      +
      this sketch as a CompactThetaSketch.
      +
      +
      +
      +
    • +
    • +
      +

      getCompactBytes

      +
      +
      public abstract int getCompactBytes()
      +
      Returns the number of storage bytes required for this ThetaSketch if its current state were +compacted. It this sketch is already in the compact form this is equivalent to +calling getCurrentBytes().
      +
      +
      Returns:
      +
      number of compact bytes
      +
      +
      +
      +
    • +
    • +
      +

      getCountLessThanThetaLong

      +
      +
      public int getCountLessThanThetaLong(long thetaLong)
      +
      Gets the number of hash values less than the given theta expressed as a long.
      +
      +
      Parameters:
      +
      thetaLong - the given theta as a long between zero and Long.MAX_VALUE.
      +
      Returns:
      +
      the number of hash values less than the given thetaLong.
      +
      +
      +
      +
    • +
    • +
      +

      getCurrentBytes

      +
      +
      public abstract int getCurrentBytes()
      +
      Returns the number of storage bytes required for this sketch in its current state.
      +
      +
      Returns:
      +
      the number of storage bytes required for this sketch
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public abstract double getEstimate()
      +
      Gets the unique count estimate.
      +
      +
      Returns:
      +
      the sketch's best estimate of the cardinality of the input stream.
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public static double getEstimate(MemorySegment srcSeg)
      +
      Gets the estimate from the given MemorySegment
      +
      +
      Parameters:
      +
      srcSeg - the given MemorySegment
      +
      Returns:
      +
      the result estimate
      +
      +
      +
      +
    • +
    • +
      +

      getFamily

      +
      +
      public abstract Family getFamily()
      +
      Returns the Family that this sketch belongs to
      +
      +
      Returns:
      +
      the Family that this sketch belongs to
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public double getLowerBound(int numStdDev)
      +
      Gets the approximate lower error bound given the specified number of Standard Deviations. +This will return getEstimate() if isEmpty() is true.
      +
      +
      Parameters:
      +
      numStdDev - See Number of Standard Deviations
      +
      Returns:
      +
      the lower bound.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxCompactSketchBytes

      +
      +
      public static int getMaxCompactSketchBytes(int numberOfEntries)
      +
      Returns the maximum number of storage bytes required for a CompactThetaSketch with the given +number of actual entries.
      +
      +
      Parameters:
      +
      numberOfEntries - the actual number of retained entries stored in the sketch.
      +
      Returns:
      +
      the maximum number of storage bytes required for a CompactThetaSketch with the given number +of retained entries.
      +
      +
      +
      +
    • +
    • +
      +

      getCompactSketchMaxBytes

      +
      +
      public static int getCompactSketchMaxBytes(int lgNomEntries)
      +
      Returns the maximum number of storage bytes required for a CompactThetaSketch given the configured +log_base2 of the number of nominal entries, which is a power of 2.
      +
      +
      Parameters:
      +
      lgNomEntries - Nominal Entries
      +
      Returns:
      +
      the maximum number of storage bytes required for a CompactThetaSketch with the given +lgNomEntries.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxUpdateSketchBytes

      +
      +
      public static int getMaxUpdateSketchBytes(int nomEntries)
      +
      Returns the maximum number of storage bytes required for an UpdatableThetaSketch with the given +number of nominal entries (power of 2).
      +
      +
      Parameters:
      +
      nomEntries - Nominal Entries +This will become the ceiling power of 2 if it is not.
      +
      Returns:
      +
      the maximum number of storage bytes required for a UpdatableThetaSketch with the given +nomEntries
      +
      +
      +
      +
    • +
    • +
      +

      getUpdateSketchMaxBytes

      +
      +
      public static int getUpdateSketchMaxBytes(int lgNomEntries)
      +
      Returns the maximum number of storage bytes required for an UpdatableThetaSketch with the given +log_base2 of the nominal entries.
      +
      +
      Parameters:
      +
      lgNomEntries - log_base2 of Nominal Entries
      +
      Returns:
      +
      the maximum number of storage bytes required for a UpdatableThetaSketch with the given lgNomEntries
      +
      +
      +
      +
    • +
    • +
      +

      getRetainedEntries

      +
      +
      public int getRetainedEntries()
      +
      Returns the number of valid entries that have been retained by the sketch. +For the AlphaSketch this returns only valid entries.
      +
      +
      Returns:
      +
      the number of valid retained entries.
      +
      +
      +
      +
    • +
    • +
      +

      getRetainedEntries

      +
      +
      public abstract int getRetainedEntries(boolean valid)
      +
      Returns the number of entries that have been retained by the sketch.
      +
      +
      Parameters:
      +
      valid - This parameter is only relevant for the AlphaSketch. +if true, returns the number of valid entries, which are less than theta and used +for estimation. Otherwise, return the number of all entries, valid or not, that are currently in the +internal sketch cache.
      +
      Returns:
      +
      the number of retained entries
      +
      +
      +
      +
    • +
    • +
      +

      getRetainedEntries

      +
      +
      public static int getRetainedEntries(MemorySegment srcSeg)
      +
      Returns the number of valid entries that have been retained by the sketch from the given MemorySegment
      +
      +
      Parameters:
      +
      srcSeg - the given MemorySegment that has an image of a ThetaSketch
      +
      Returns:
      +
      the number of valid retained entries
      +
      +
      +
      +
    • +
    • +
      +

      getSerializationVersion

      +
      +
      public static int getSerializationVersion(MemorySegment seg)
      +
      Returns the serialization version from the given MemorySegment
      +
      +
      Parameters:
      +
      seg - the sketch MemorySegment
      +
      Returns:
      +
      the serialization version from the MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      getTheta

      +
      +
      public double getTheta()
      +
      Gets the value of theta as a double with a value between zero and one
      +
      +
      Returns:
      +
      the value of theta as a double
      +
      +
      +
      +
    • +
    • +
      +

      getThetaLong

      +
      +
      public abstract long getThetaLong()
      +
      Gets the value of theta as a long
      +
      +
      Returns:
      +
      the value of theta as a long
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public double getUpperBound(int numStdDev)
      +
      Gets the approximate upper error bound given the specified number of Standard Deviations. +This will return getEstimate() if isEmpty() is true.
      +
      +
      Parameters:
      +
      numStdDev - See Number of Standard Deviations
      +
      Returns:
      +
      the upper bound.
      +
      +
      +
      +
    • +
    • +
      +

      isCompact

      +
      +
      public abstract boolean isCompact()
      +
      Returns true if this sketch is in compact form.
      +
      +
      Returns:
      +
      true if this sketch is in compact form.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public abstract boolean isEmpty()
      + +
      +
      Returns:
      +
      true if empty.
      +
      +
      +
      +
    • +
    • +
      +

      isEstimationMode

      +
      +
      public boolean isEstimationMode()
      +
      Returns true if the sketch is Estimation Mode (as opposed to Exact Mode). +This is true if theta < 1.0 AND isEmpty() is false.
      +
      +
      Returns:
      +
      true if the sketch is in estimation mode.
      +
      +
      +
      +
    • +
    • +
      +

      isOrdered

      +
      +
      public abstract boolean isOrdered()
      +
      Returns true if internal cache is ordered
      +
      +
      Returns:
      +
      true if internal cache is ordered
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public abstract HashIterator iterator()
      +
      Returns a HashIterator that can be used to iterate over the retained hash values of the +Theta sketch.
      +
      +
      Returns:
      +
      a HashIterator that can be used to iterate over the retained hash values of the +Theta sketch.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public abstract byte[] toByteArray()
      +
      Serialize this sketch to a byte array form.
      +
      +
      Returns:
      +
      byte array of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      Returns a human readable summary of the sketch. This method is equivalent to the parameterized +call:
      +ThetaSketch.toString(ThetaSketch, true, false, 8, true);
      +
      +
      Overrides:
      +
      toString in class Object
      +
      Returns:
      +
      summary
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString(boolean sketchSummary, + boolean dataDetail, + int width, + boolean hexMode)
      +
      Gets a human readable listing of contents and summary of the given sketch. +This can be a very long string. If this sketch is in a "dirty" state there +may be values in the dataDetail view that are ≥ theta.
      +
      +
      Parameters:
      +
      sketchSummary - If true the sketch summary will be output at the end.
      +
      dataDetail - If true, includes all valid hash values in the sketch.
      +
      width - The number of columns of hash values. Default is 8.
      +
      hexMode - If true, hashes will be output in hex.
      +
      Returns:
      +
      The result string, which can be very long.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(byte[] byteArr)
      +
      Returns a human readable string of the preamble of a byte array image of a ThetaSketch.
      +
      +
      Parameters:
      +
      byteArr - the given byte array
      +
      Returns:
      +
      a human readable string of the preamble of a byte array image of a ThetaSketch.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public static String toString(MemorySegment seg)
      +
      Returns a human readable string of the preamble of a MemorySegment image of a ThetaSketch.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment object
      +
      Returns:
      +
      a human readable string of the preamble of a MemorySegment image of a ThetaSketch.
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public static double getLowerBound(int numStdDev, + MemorySegment srcSeg)
      +
      Gets the approximate lower error bound from a valid MemorySegment image of a ThetaSketch +given the specified number of Standard Deviations. +This will return getEstimate() if isEmpty() is true.
      +
      +
      Parameters:
      +
      numStdDev - See Number of Standard Deviations
      +
      srcSeg - the source MemorySegment
      +
      Returns:
      +
      the lower bound.
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public static double getUpperBound(int numStdDev, + MemorySegment srcSeg)
      +
      Gets the approximate upper error bound from a valid MemorySegment image of a ThetaSketch +given the specified number of Standard Deviations. +This will return getEstimate() if isEmpty() is true.
      +
      +
      Parameters:
      +
      numStdDev - See Number of Standard Deviations
      +
      srcSeg - the source MemorySegment
      +
      Returns:
      +
      the upper bound.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/ThetaUnion.html b/target/site/apidocs/org/apache/datasketches/theta/ThetaUnion.html new file mode 100644 index 000000000..433bec1be --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/ThetaUnion.html @@ -0,0 +1,716 @@ + + + + +ThetaUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ThetaUnion

+
+
java.lang.Object +
org.apache.datasketches.theta.ThetaSetOperation +
org.apache.datasketches.theta.ThetaUnion
+
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus
+
+
+
+
public abstract class ThetaUnion +extends ThetaSetOperation
+
Compute the union of two or more theta sketches. +A new instance represents an empty set.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ThetaUnion

      +
      +
      public ThetaUnion()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      fastWrap

      +
      +
      public static ThetaUnion fastWrap(MemorySegment srcSeg)
      +
      Wrap a ThetaUnion object around a ThetaUnion MemorySegment object containing data. +This method assumes the Default Update Seed. +This does NO validity checking of the given MemorySegment. +If the given source MemorySegment is read-only, the returned ThetaUnion object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - The source MemorySegment object.
      +
      Returns:
      +
      this class
      +
      +
      +
      +
    • +
    • +
      +

      fastWrap

      +
      +
      public static ThetaUnion fastWrap(MemorySegment srcSeg, + long expectedSeed)
      +
      Wrap a ThetaUnion object around a ThetaUnion MemorySegment object containing data. +This does NO validity checking of the given MemorySegment. +If the given source MemorySegment is read-only, the returned ThetaUnion object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - The source MemorySegment object.
      +
      expectedSeed - the seed used to validate the given MemorySegment image. +See seed
      +
      Returns:
      +
      this class
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ThetaUnion wrap(MemorySegment srcSeg)
      +
      Wrap a ThetaUnion object around a ThetaUnion MemorySegment object containing data. +This method assumes the Default Update Seed. +If the given source MemorySegment is read-only, the returned ThetaUnion object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - The source MemorySegment object.
      +
      Returns:
      +
      this class
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ThetaUnion wrap(MemorySegment srcSeg, + long expectedSeed)
      +
      Wrap a ThetaUnion object around a ThetaUnion MemorySegment object containing data. +If the given source MemorySegment is read-only, the returned ThetaUnion object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - The source MemorySegment object.
      +
      expectedSeed - the seed used to validate the given MemorySegment image. +See seed
      +
      Returns:
      +
      this class
      +
      +
      +
      +
    • +
    • +
      +

      getCurrentBytes

      +
      +
      public abstract int getCurrentBytes()
      +
      Returns the number of storage bytes required for this union in its current state.
      +
      +
      Returns:
      +
      the number of storage bytes required for this union in its current state.
      +
      +
      +
      +
    • +
    • +
      +

      getFamily

      +
      +
      public Family getFamily()
      +
      Description copied from class: ThetaSetOperation
      +
      Gets the Family of this ThetaSetOperation
      +
      +
      Specified by:
      +
      getFamily in class ThetaSetOperation
      +
      Returns:
      +
      the Family of this ThetaSetOperation
      +
      +
      +
      +
    • +
    • +
      +

      getMaxUnionBytes

      +
      +
      public abstract int getMaxUnionBytes()
      +
      Returns the maximum required storage bytes for this union.
      +
      +
      Returns:
      +
      the maximum required storage bytes for this union.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public abstract CompactThetaSketch getResult()
      +
      Gets the result of this operation as an ordered CompactThetaSketch on the Java heap. +This does not disturb the underlying data structure of the union. +Therefore, it is OK to continue updating the union after this operation.
      +
      +
      Returns:
      +
      the result of this operation as an ordered CompactThetaSketch on the Java heap
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public abstract CompactThetaSketch getResult(boolean dstOrdered, + MemorySegment dstSeg)
      +
      Gets the result of this operation as a CompactThetaSketch of the chosen form. +This does not disturb the underlying data structure of the union. +Therefore, it is OK to continue updating the union after this operation.
      +
      +
      Parameters:
      +
      dstOrdered - See Destination Ordered
      +
      dstSeg - destination MemorySegment
      +
      Returns:
      +
      the result of this operation as a CompactThetaSketch of the chosen form
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public abstract void reset()
      +
      Resets this ThetaUnion. The seed remains intact, everything else reverts back to its virgin state.
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public abstract byte[] toByteArray()
      +
      Returns a byte array image of this ThetaUnion object
      +
      +
      Returns:
      +
      a byte array image of this ThetaUnion object
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public CompactThetaSketch union(ThetaSketch sketchA, + ThetaSketch sketchB)
      +
      This implements a stateless, pair-wise union operation. The returned sketch will be cut back to +the smaller of the two k values if required. + +

      Nulls and empty sketches are ignored.

      +
      +
      Parameters:
      +
      sketchA - The first argument
      +
      sketchB - The second argument
      +
      Returns:
      +
      the result ordered CompactThetaSketch on the heap.
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public abstract CompactThetaSketch union(ThetaSketch sketchA, + ThetaSketch sketchB, + boolean dstOrdered, + MemorySegment dstSeg)
      +
      This implements a stateless, pair-wise union operation. The returned sketch will be cut back to +k if required, similar to the regular ThetaUnion operation. + +

      Nulls and empty sketches are ignored.

      +
      +
      Parameters:
      +
      sketchA - The first argument
      +
      sketchB - The second argument
      +
      dstOrdered - If true, the returned CompactThetaSketch will be ordered.
      +
      dstSeg - If not null, the returned CompactThetaSketch will be placed in this MemorySegment.
      +
      Returns:
      +
      the result CompactThetaSketch.
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public abstract void union(ThetaSketch sketchIn)
      +
      Perform a union operation with this ThetaUnion and the given on-heap sketch of the Theta Family. + +

      This method can be repeatedly called. + +

      Nulls and empty sketches are ignored.

      +
      +
      Parameters:
      +
      sketchIn - The incoming sketch.
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public abstract void union(MemorySegment seg)
      +
      Perform a union operation with this ThetaUnion and the given MemorySegment image of any sketch of the +Theta Family. + +

      This method can be repeatedly called. + +

      Nulls and empty sketches are ignored.

      +
      +
      Parameters:
      +
      seg - MemorySegment image of sketch to be merged
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public abstract void update(long datum)
      +
      Update this union with the given long data item.
      +
      +
      Parameters:
      +
      datum - The given long datum.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public abstract void update(double datum)
      +
      Update this union with the given double (or float) data item. +The double will be converted to a long using Double.doubleToLongBits(datum), +which normalizes all NaN values to a single NaN representation. +Plus and minus zero will be normalized to plus zero. +Each of the special floating-point values NaN and +/- Infinity are treated as distinct.
      +
      +
      Parameters:
      +
      datum - The given double datum.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public abstract void update(String datum)
      +
      Update this union with the with the given String data item. +The string is converted to a byte array using UTF8 encoding. +If the string is null or empty no update attempt is made and the method returns. + +

      Note: this will not produce the same output hash values as the update(char[]) +method and will generally be a little slower depending on the complexity of the UTF8 encoding. +

      + +

      Note: this is not a union operation. This treats the given string as a data item.

      +
      +
      Parameters:
      +
      datum - The given String.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public abstract void update(byte[] data)
      +
      Update this union with the given byte array item. +If the byte array is null or empty no update attempt is made and the method returns. + +

      Note: this is not a union operation. This treats the given byte array as a data +item.

      +
      +
      Parameters:
      +
      data - The given byte array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public abstract void update(ByteBuffer data)
      +
      Update this union with the given ByteBuffer item. +If the ByteBuffer is null or empty no update attempt is made and the method returns. + +

      Note: this is not a union operation. This treats the given ByteBuffer as a data +item.

      +
      +
      Parameters:
      +
      data - The given ByteBuffer.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public abstract void update(int[] data)
      +
      Update this union with the given integer array item. +If the integer array is null or empty no update attempt is made and the method returns. + +

      Note: this is not a union operation. This treats the given integer array as a data +item.

      +
      +
      Parameters:
      +
      data - The given int array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public abstract void update(char[] data)
      +
      Update this union with the given char array item. +If the char array is null or empty no update attempt is made and the method returns. + +

      Note: this will not produce the same output hash values as the update(String) +method but will be a little faster as it avoids the complexity of the UTF8 encoding.

      + +

      Note: this is not a union operation. This treats the given char array as a data +item.

      +
      +
      Parameters:
      +
      data - The given char array.
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public abstract void update(long[] data)
      +
      Update this union with the given long array item. +If the long array is null or empty no update attempt is made and the method returns. + +

      Note: this is not a union operation. This treats the given char array as a data +item.

      +
      +
      Parameters:
      +
      data - The given long array.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/UpdatableThetaSketch.html b/target/site/apidocs/org/apache/datasketches/theta/UpdatableThetaSketch.html new file mode 100644 index 000000000..70062a42f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/UpdatableThetaSketch.html @@ -0,0 +1,751 @@ + + + + +UpdatableThetaSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class UpdatableThetaSketch

+
+
java.lang.Object +
org.apache.datasketches.theta.ThetaSketch +
org.apache.datasketches.theta.UpdatableThetaSketch
+
+
+
+
+
All Implemented Interfaces:
+
MemorySegmentStatus
+
+
+
+
public abstract class UpdatableThetaSketch +extends ThetaSketch
+
The parent class for the UpdatableThetaSketch families, such as QuickSelectThetaSketch and AlphaSketch. +The primary task of an UpdatableThetaSketch is to consider datums presented via the update() methods +for inclusion in its internal cache. This is the sketch building process.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      wrap

      +
      +
      public static UpdatableThetaSketch wrap(MemorySegment srcWSeg)
      +
      Wrap takes the writable sketch image in MemorySegment and refers to it directly. There is no data copying onto +the java heap. Only "Direct" Serialization Version 3 (i.e, OpenSource) sketches that have +been explicitly stored as writable, direct objects can be wrapped. This method assumes the +Util.DEFAULT_UPDATE_SEED. +Default Update Seed.
      +
      +
      Parameters:
      +
      srcWSeg - an image of a writable sketch where the image seed hash matches the default seed hash. +It must have a size of at least 24 bytes.
      +
      Returns:
      +
      an UpdatableThetaSketch backed by the given MemorySegment
      +
      Throws:
      +
      SketchesArgumentException - if the provided MemorySegment +is invalid, corrupted, or incompatible with this sketch type. +Callers must treat this as a fatal error for that segment.
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static UpdatableThetaSketch wrap(MemorySegment srcWSeg, + MemorySegmentRequest mSegReq, + long expectedSeed)
      +
      Wrap takes the sketch image in MemorySegment and refers to it directly. There is no data copying onto +the java heap. Only "Direct" Serialization Version 3 (i.e, OpenSource) sketches that have +been explicitly stored as writable direct objects can be wrapped. +An attempt to "wrap" earlier version sketches will result in a "heapified", normal +Java Heap version of the sketch where all data will be copied to the heap.
      +
      +
      Parameters:
      +
      srcWSeg - an image of a writable sketch where the image seed hash matches the given seed hash. +It must have a size of at least 24 bytes.
      +
      mSegReq - an implementation of the MemorySegmentRequest interface or null.
      +
      expectedSeed - the seed used to validate the given MemorySegment image. +See Update Hash Seed. +Compact sketches store a 16-bit hash of the seed, but not the seed itself.
      +
      Returns:
      +
      a UpdatableThetaSketch backed by the given MemorySegment
      +
      Throws:
      +
      SketchesArgumentException - if the provided MemorySegment +is invalid, corrupted, or incompatible with this sketch type. +Callers must treat this as a fatal error for that segment.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static UpdatableThetaSketch heapify(MemorySegment srcSeg)
      +
      Instantiates an on-heap UpdatableThetaSketch from a MemorySegment. This method assumes the +Util.DEFAULT_UPDATE_SEED.
      +
      +
      Parameters:
      +
      srcSeg - the given MemorySegment with a sketch image. +It must have a size of at least 24 bytes.
      +
      Returns:
      +
      an UpdatableThetaSketch
      +
      Throws:
      +
      SketchesArgumentException - if the provided MemorySegment +is invalid, corrupted, or incompatible with this sketch type. +Callers must treat this as a fatal error for that segment.
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static UpdatableThetaSketch heapify(MemorySegment srcSeg, + long expectedSeed)
      +
      Instantiates an on-heap UpdatableThetaSketch from a MemorySegment.
      +
      +
      Parameters:
      +
      srcSeg - the given MemorySegment. +It must have a size of at least 24 bytes.
      +
      expectedSeed - the seed used to validate the given MemorySegment image. +See Update Hash Seed.
      +
      Returns:
      +
      an UpdatableThetaSketch
      +
      Throws:
      +
      SketchesArgumentException - if the provided MemorySegment +is invalid, corrupted, or incompatible with this sketch type. +Callers must treat this as a fatal error for that segment.
      +
      +
      +
      +
    • +
    • +
      +

      compact

      +
      +
      public CompactThetaSketch compact(boolean dstOrdered, + MemorySegment dstWSeg)
      +
      Description copied from class: ThetaSketch
      +
      Convert this sketch to a CompactThetaSketch. + +

      If this sketch is a type of UpdatableThetaSketch, the compacting process converts the hash table + of the UpdatableThetaketch to a simple list of the valid hash values. + Any hash values of zero or equal-to or greater than theta will be discarded. + The number of valid values remaining in the CompactThetaSketch depends on a number of factors, + but may be larger or smaller than Nominal Entries (or k). + It will never exceed 2k. + If it is critical to always limit the size to no more than k, + then rebuild() should be called on the UpdatableThetaSketch prior to calling this method.

      + +

      A CompactThetaSketch is always immutable.

      + +

      A new CompactThetaSketch object is created:

      +
      • if dstSeg!= null
      • +
      • if dstSeg == null and this.hasMemorySegment() == true
      • +
      • if dstSeg == null and this has more than 1 item and this.isOrdered() == false + and dstOrdered == true.
      • +
      + +

      Otherwise, this operation returns this.

      +
      +
      Specified by:
      +
      compact in class ThetaSketch
      +
      Parameters:
      +
      dstOrdered - assumed true if this sketch is empty or has only one value + See Destination Ordered
      +
      dstWSeg - See Destination MemorySegment.
      +
      Returns:
      +
      this sketch as a CompactThetaSketch.
      +
      +
      +
      +
    • +
    • +
      +

      getCompactBytes

      +
      +
      public int getCompactBytes()
      +
      Description copied from class: ThetaSketch
      +
      Returns the number of storage bytes required for this ThetaSketch if its current state were +compacted. It this sketch is already in the compact form this is equivalent to +calling ThetaSketch.getCurrentBytes().
      +
      +
      Specified by:
      +
      getCompactBytes in class ThetaSketch
      +
      Returns:
      +
      number of compact bytes
      +
      +
      +
      +
    • +
    • +
      +

      hasMemorySegment

      +
      +
      public boolean hasMemorySegment()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by a MemorySegment, +which may be on-heap or off-heap.
      +
      +
      Returns:
      +
      true if this object's internal data is backed by a MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isCompact

      +
      +
      public boolean isCompact()
      +
      Description copied from class: ThetaSketch
      +
      Returns true if this sketch is in compact form.
      +
      +
      Specified by:
      +
      isCompact in class ThetaSketch
      +
      Returns:
      +
      true if this sketch is in compact form.
      +
      +
      +
      +
    • +
    • +
      +

      isOffHeap

      +
      +
      public boolean isOffHeap()
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      Returns:
      +
      true if this object's internal data is backed by an off-heap (direct or native)) MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isOrdered

      +
      +
      public boolean isOrdered()
      +
      Description copied from class: ThetaSketch
      +
      Returns true if internal cache is ordered
      +
      +
      Specified by:
      +
      isOrdered in class ThetaSketch
      +
      Returns:
      +
      true if internal cache is ordered
      +
      +
      +
      +
    • +
    • +
      +

      isSameResource

      +
      +
      public boolean isSameResource(MemorySegment that)
      +
      Description copied from interface: MemorySegmentStatus
      +
      Returns true if an internally referenced MemorySegment has the same backing resource as that, +or equivalently, if their two memory regions overlap. This applies to both on-heap and off-heap MemorySegments. + +

      Note: If both segments are on-heap and not read-only, it can be determined if they were derived from +the same backing memory (array). However, this is not always possible off-heap. Because of this asymmetry, this definition +of "isSameResource" is confined to the existence of an overlap.

      +
      +
      Parameters:
      +
      that - The given MemorySegment.
      +
      Returns:
      +
      true if an internally referenced MemorySegment has the same backing resource as that.
      +
      +
      +
      +
    • +
    • +
      +

      builder

      +
      +
      public static final UpdatableThetaSketchBuilder builder()
      +
      Returns a new builder
      +
      +
      Returns:
      +
      a new builder
      +
      +
      +
      +
    • +
    • +
      +

      getResizeFactor

      +
      +
      public abstract ResizeFactor getResizeFactor()
      +
      Returns the configured ResizeFactor
      +
      +
      Returns:
      +
      the configured ResizeFactor
      +
      +
      +
      +
    • +
    • +
      +

      getSeed

      +
      +
      public long getSeed()
      +
      Gets the configured seed
      +
      +
      Returns:
      +
      the configured seed
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public abstract void reset()
      +
      Resets this sketch back to a virgin empty state.
      +
      +
      +
    • +
    • +
      +

      rebuild

      +
      +
      public abstract UpdatableThetaSketch rebuild()
      +
      Rebuilds the hash table to remove dirty values or to reduce the size +to nominal entries.
      +
      +
      Returns:
      +
      this sketch
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public UpdateReturnState update(long datum)
      +
      Present this sketch with a long.
      +
      +
      Parameters:
      +
      datum - The given long datum.
      +
      Returns:
      +
      See Update Return State
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public UpdateReturnState update(double datum)
      +
      Present this sketch with the given double (or float) datum. +The double will be converted to a long using Double.doubleToLongBits(datum), +which normalizes all NaN values to a single NaN representation. +Plus and minus zero will be normalized to plus zero. +The special floating-point values NaN and +/- Infinity are treated as distinct.
      +
      +
      Parameters:
      +
      datum - The given double datum.
      +
      Returns:
      +
      See Update Return State
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public UpdateReturnState update(String datum)
      +
      Present this sketch with the given String. +The string is converted to a byte array using UTF8 encoding. +If the string is null or empty no update attempt is made and the method returns. + +

      Note: this will not produce the same output hash values as the update(char[]) +method and will generally be a little slower depending on the complexity of the UTF8 encoding. +

      +
      +
      Parameters:
      +
      datum - The given String.
      +
      Returns:
      +
      See Update Return State
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public UpdateReturnState update(byte[] data)
      +
      Present this sketch with the given byte array. +If the byte array is null or empty no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      data - The given byte array.
      +
      Returns:
      +
      See Update Return State
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public UpdateReturnState update(ByteBuffer buffer)
      +
      Present this sketch with the given ByteBuffer +If the ByteBuffer is null or empty, no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      buffer - the input ByteBuffer
      +
      Returns:
      +
      See Update Return State
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public UpdateReturnState update(char[] data)
      +
      Present this sketch with the given char array. +If the char array is null or empty no update attempt is made and the method returns. + +

      Note: this will not produce the same output hash values as the update(String) +method but will be a little faster as it avoids the complexity of the UTF8 encoding.

      +
      +
      Parameters:
      +
      data - The given char array.
      +
      Returns:
      +
      See Update Return State
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public UpdateReturnState update(int[] data)
      +
      Present this sketch with the given integer array. +If the integer array is null or empty no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      data - The given int array.
      +
      Returns:
      +
      See Update Return State
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public UpdateReturnState update(long[] data)
      +
      Present this sketch with the given long array. +If the long array is null or empty no update attempt is made and the method returns.
      +
      +
      Parameters:
      +
      data - The given long array.
      +
      Returns:
      +
      See Update Return State
      +
      +
      +
      +
    • +
    • +
      +

      getLgNomLongs

      +
      +
      public abstract int getLgNomLongs()
      +
      Gets the Log base 2 of the configured nominal entries
      +
      +
      Returns:
      +
      the Log base 2 of the configured nominal entries
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/UpdatableThetaSketchBuilder.html b/target/site/apidocs/org/apache/datasketches/theta/UpdatableThetaSketchBuilder.html new file mode 100644 index 000000000..1a9aa06cd --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/UpdatableThetaSketchBuilder.html @@ -0,0 +1,906 @@ + + + + +UpdatableThetaSketchBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class UpdatableThetaSketchBuilder

+
+
java.lang.Object +
org.apache.datasketches.theta.UpdatableThetaSketchBuilder
+
+
+
+
+
public final class UpdatableThetaSketchBuilder +extends Object
+
For building a new UpdatableThetaSketch.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      UpdatableThetaSketchBuilder

      +
      +
      public UpdatableThetaSketchBuilder()
      +
      Constructor for building a new UpdatableThetaSketch. The default configuration is + +Parameters unique to the concurrent sketches only: +
        +
      • Concurrent NumPoolThreads: 3
      • +
      • Number of local Nominal Entries: 4
      • +
      • Concurrent PropagateOrderedCompact: true
      • +
      • Concurrent MaxConcurrencyError: 0
      • +
      • Concurrent MaxNumLocalThreads: 1
      • +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      setNominalEntries

      +
      +
      public UpdatableThetaSketchBuilder setNominalEntries(int nomEntries)
      +
      Sets the local Nominal Entries for this builder. +This value is also used for building a shared concurrent sketch. +The minimum value is 16 (2^4) and the maximum value is 67,108,864 (2^26). +Be aware that sketches as large as this maximum value may not have been +thoroughly tested or characterized for performance.
      +
      +
      Parameters:
      +
      nomEntries - Nominal Entries +This will become the ceiling power of 2 if the given value is not.
      +
      Returns:
      +
      this UpdatableThetaSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      setLogNominalEntries

      +
      +
      public UpdatableThetaSketchBuilder setLogNominalEntries(int lgNomEntries)
      +
      Alternative method of setting the local Nominal Entries for this builder from the log_base2 value. +This value is also used for building a shared concurrent sketch. +The minimum value is 4 and the maximum value is 26. +Be aware that sketches as large as this maximum value may not have been +thoroughly characterized for performance.
      +
      +
      Parameters:
      +
      lgNomEntries - the Log Nominal Entries. Also for the concurrent shared sketch
      +
      Returns:
      +
      this UpdatableThetaSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      setLgK

      +
      +
      public UpdatableThetaSketchBuilder setLgK(int lgK)
      +
      Alternative method of setting the Nominal Entries for this builder from the log_base2 value, commonly called LgK. +This value is also used for building a shared concurrent sketch. +The minimum value is 4 and the maximum value is 26. +Be aware that sketches as large as 26 may not have been +thoroughly characterized for performance.
      +
      +
      Parameters:
      +
      lgK - the Log Nominal Entries. Also for the concurrent shared sketch.
      +
      Returns:
      +
      this UpdatableThetaSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      getLgNominalEntries

      +
      +
      public int getLgNominalEntries()
      +
      Returns the local Log-base 2 Nominal Entries
      +
      +
      Returns:
      +
      Log-base 2 Nominal Entries
      +
      +
      +
      +
    • +
    • +
      +

      setConCurNominalEntries

      +
      +
      public UpdatableThetaSketchBuilder setConCurNominalEntries(int nomEntries)
      +
      Sets the local (default) Concurrent Nominal Entries for the concurrent local sketch. The minimum value is 16 and the +maximum value is 67,108,864, which is 2^26. +Be aware that sketches as large as this maximum +value have not been thoroughly tested or characterized for performance.
      +
      +
      Parameters:
      +
      nomEntries - Nominal Entries + This will become the ceiling power of 2 if it is not.
      +
      Returns:
      +
      this UpdatableThetaSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      setConCurLogNominalEntries

      +
      +
      public UpdatableThetaSketchBuilder setConCurLogNominalEntries(int lgNomEntries)
      +
      Alternative method of setting the local (default) Nominal Entries for a local concurrent sketch from the log_base2 value. +The minimum value is 4 and the maximum value is 26. +Be aware that sketches as large as this maximum +value have not been thoroughly tested or characterized for performance.
      +
      +
      Parameters:
      +
      lgNomEntries - the Log Nominal Entries for a concurrent local sketch
      +
      Returns:
      +
      this UpdatableThetaSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      getConCurLgNominalEntries

      +
      +
      public int getConCurLgNominalEntries()
      +
      Returns local Log-base 2 Nominal Entries for the concurrent local sketch
      +
      +
      Returns:
      +
      Log-base 2 Nominal Entries for the concurrent local sketch
      +
      +
      +
      +
    • +
    • +
      +

      setSeed

      +
      +
      public UpdatableThetaSketchBuilder setSeed(long seed)
      +
      Sets the local long seed value that is required by the hashing function.
      +
      +
      Parameters:
      +
      seed - See seed
      +
      Returns:
      +
      this UpdatableThetaSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      getSeed

      +
      +
      public long getSeed()
      +
      Returns the local long seed value that is required by the hashing function.
      +
      +
      Returns:
      +
      the seed
      +
      +
      +
      +
    • +
    • +
      +

      setP

      +
      +
      public UpdatableThetaSketchBuilder setP(float p)
      +
      Sets the local upfront uniform pre-sampling probability, p
      +
      +
      Parameters:
      +
      p - See Sampling Probability, p
      +
      Returns:
      +
      this UpdatableThetaSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      getP

      +
      +
      public float getP()
      +
      Returns the local upfront uniform pre-sampling probability p
      +
      +
      Returns:
      +
      the pre-sampling probability p
      +
      +
      +
      +
    • +
    • +
      +

      setResizeFactor

      +
      +
      public UpdatableThetaSketchBuilder setResizeFactor(ResizeFactor rf)
      +
      Sets the local cache Resize Factor.
      +
      +
      Parameters:
      +
      rf - See Resize Factor
      +
      Returns:
      +
      this UpdatableThetaSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      getResizeFactor

      +
      +
      public ResizeFactor getResizeFactor()
      +
      Returns the local Resize Factor
      +
      +
      Returns:
      +
      the Resize Factor
      +
      +
      +
      +
    • +
    • +
      +

      setFamily

      +
      +
      public UpdatableThetaSketchBuilder setFamily(Family family)
      +
      Set the local Family. Choose either Family.ALPHA or Family.QUICKSELECT.
      +
      +
      Parameters:
      +
      family - the family for this builder
      +
      Returns:
      +
      this UpdatableThetaSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      getFamily

      +
      +
      public Family getFamily()
      +
      Returns the local Family
      +
      +
      Returns:
      +
      the Family
      +
      +
      +
      +
    • +
    • +
      +

      setMemorySegmentRequest

      +
      +
      public UpdatableThetaSketchBuilder setMemorySegmentRequest(MemorySegmentRequest mSegReq)
      +
      Sets the local MemorySegmentRequest
      +
      +
      Parameters:
      +
      mSegReq - the given MemorySegmentRequest
      +
      Returns:
      +
      this UpdatableThetaSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      getMemorySegmentRequest

      +
      +
      public MemorySegmentRequest getMemorySegmentRequest()
      +
      Returns the local MemorySegmentRequest
      +
      +
      Returns:
      +
      the local MemorySegmentRequest
      +
      +
      +
      +
    • +
    • +
      +

      setNumPoolThreads

      +
      +
      public void setNumPoolThreads(int numPoolThreads)
      +
      Sets the local number of pool threads used for background propagation in the concurrent sketches.
      +
      +
      Parameters:
      +
      numPoolThreads - the given number of pool threads
      +
      +
      +
      +
    • +
    • +
      +

      getNumPoolThreads

      +
      +
      public int getNumPoolThreads()
      +
      Gets the local number of background pool threads used for propagation in the concurrent sketches.
      +
      +
      Returns:
      +
      the number of background pool threads
      +
      +
      +
      +
    • +
    • +
      +

      setPropagateOrderedCompact

      +
      +
      public UpdatableThetaSketchBuilder setPropagateOrderedCompact(boolean prop)
      +
      Sets the local Propagate Ordered Compact flag to the given value. Used with concurrent sketches.
      +
      +
      Parameters:
      +
      prop - the given value
      +
      Returns:
      +
      this UpdatableThetaSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      getPropagateOrderedCompact

      +
      +
      public boolean getPropagateOrderedCompact()
      +
      Gets the local Propagate Ordered Compact flag used with concurrent sketches.
      +
      +
      Returns:
      +
      the Propagate Ordered Compact flag
      +
      +
      +
      +
    • +
    • +
      +

      setMaxConcurrencyError

      +
      +
      public void setMaxConcurrencyError(double maxConcurrencyError)
      +
      Sets the local Maximum Concurrency Error.
      +
      +
      Parameters:
      +
      maxConcurrencyError - the given Maximum Concurrency Error.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxConcurrencyError

      +
      +
      public double getMaxConcurrencyError()
      +
      Gets the local Maximum Concurrency Error
      +
      +
      Returns:
      +
      the Maximum Concurrency Error
      +
      +
      +
      +
    • +
    • +
      +

      setMaxNumLocalThreads

      +
      +
      public void setMaxNumLocalThreads(int maxNumLocalThreads)
      +
      Sets the local Maximum Number of Local Threads. +This is used to set the size of the local concurrent buffers.
      +
      +
      Parameters:
      +
      maxNumLocalThreads - the given Maximum Number of Local Threads
      +
      +
      +
      +
    • +
    • +
      +

      getMaxNumLocalThreads

      +
      +
      public int getMaxNumLocalThreads()
      +
      Gets the local Maximum Number of Local Threads.
      +
      +
      Returns:
      +
      the Maximum Number of Local Threads.
      +
      +
      +
      +
    • +
    • +
      +

      build

      +
      +
      public UpdatableThetaSketch build()
      +
      Returns an UpdatableThetaSketch with the current configuration of this Builder.
      +
      +
      Returns:
      +
      an UpdatableThetaSketch
      +
      +
      +
      +
    • +
    • +
      +

      build

      +
      +
      public UpdatableThetaSketch build(MemorySegment dstSeg)
      +
      Returns an UpdatableThetaSketch with the current configuration of this Builder +with the specified backing destination MemorySegment store. +Note: this can only be used with the QUICKSELECT Family of sketches +and cannot be used with the Alpha Family of sketches.
      +
      +
      Parameters:
      +
      dstSeg - The destination MemorySegment.
      +
      Returns:
      +
      an UpdatableThetaSketch
      +
      +
      +
      +
    • +
    • +
      +

      buildShared

      +
      +
      public UpdatableThetaSketch buildShared()
      +
      Returns an on-heap concurrent shared UpdatableThetaSketch with the current configuration of the +Builder. + +

      The parameters unique to the shared concurrent sketch are: +

        +
      • Number of Pool Threads (default is 3)
      • +
      • Maximum Concurrency Error
      • +
      + +

      Key parameters that are in common with other ThetaSketches: +

        +
      • Nominal Entries or Log Nominal Entries (for the shared concurrent sketch)
      • +
      +
      +
      Returns:
      +
      an on-heap concurrent UpdatableThetaSketch with the current configuration of the Builder.
      +
      +
      +
      +
    • +
    • +
      +

      buildShared

      +
      +
      public UpdatableThetaSketch buildShared(MemorySegment dstSeg)
      +
      Returns a concurrent shared UpdatableThetaSketch with the current +configuration of the Builder and the given destination MemorySegment. If the destination +MemorySegment is null, this defaults to an on-heap concurrent shared UpdatableThetaSketch. + +

      The parameters unique to the shared concurrent sketch are: +

        +
      • Number of Pool Threads (default is 3)
      • +
      • Maximum Concurrency Error
      • +
      + +

      Key parameters that are in common with other Theta sketches: +

        +
      • Nominal Entries or Log Nominal Entries (for the shared concurrent sketch)
      • +
      • Destination MemorySegment (if not null, returned sketch is Direct. Default is null.)
      • +
      +
      +
      Parameters:
      +
      dstSeg - the given MemorySegment for Direct, otherwise null.
      +
      Returns:
      +
      a concurrent UpdatableThetaSketch with the current configuration of the Builder +and the given destination MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      buildSharedFromSketch

      +
      +
      public UpdatableThetaSketch buildSharedFromSketch(UpdatableThetaSketch sketch, + MemorySegment dstSeg)
      +
      Returns a direct (potentially off-heap) concurrent shared UpdatableThetaSketch with the current +configuration of the Builder, the data from the given sketch, and the given destination +MemorySegment. If the destination MemorySegment is null, this defaults to an on-heap +concurrent shared UpdatableThetaSketch. + +

      The parameters unique to the shared concurrent sketch are: +

        +
      • Number of Pool Threads (default is 3)
      • +
      • Maximum Concurrency Error
      • +
      + +

      Key parameters that are in common with other Theta sketches: +

        +
      • Nominal Entries or Log Nominal Entries (for the shared concurrent sketch)
      • +
      • Destination MemorySegment (if not null, returned sketch is Direct. Default is null.)
      • +
      +
      +
      Parameters:
      +
      sketch - a given UpdatableThetaSketch from which the data is used to initialize the returned +shared sketch.
      +
      dstSeg - the given MemorySegment for Direct, otherwise null.
      +
      Returns:
      +
      a concurrent UpdatableThetaSketch with the current configuration of the Builder +and the given destination MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      buildLocal

      +
      +
      public UpdatableThetaSketch buildLocal(UpdatableThetaSketch shared)
      +
      Returns a local, on-heap, concurrent UpdatableThetaSketch to be used as a per-thread local buffer +along with the given concurrent shared UpdatableThetaSketch and the current configuration of this +Builder. + +

      The parameters unique to the local concurrent sketch are: +

        +
      • Local Nominal Entries or Local Log Nominal Entries
      • +
      • Propagate Ordered Compact flag
      • +
      +
      +
      Parameters:
      +
      shared - the concurrent shared sketch to be accessed via the concurrent local sketch.
      +
      Returns:
      +
      an UpdatableThetaSketch to be used as a per-thread local buffer.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/UpdateReturnState.html b/target/site/apidocs/org/apache/datasketches/theta/UpdateReturnState.html new file mode 100644 index 000000000..67cfb1989 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/UpdateReturnState.html @@ -0,0 +1,353 @@ + + + + +UpdateReturnState (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class UpdateReturnState

+
+
java.lang.Object +
java.lang.Enum<UpdateReturnState> +
org.apache.datasketches.theta.UpdateReturnState
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<UpdateReturnState>, Constable
+
+
+
+
public enum UpdateReturnState +extends Enum<UpdateReturnState>
+ +
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Enum Constant Details

    +
      +
    • +
      +

      InsertedCountIncremented

      +
      +
      public static final UpdateReturnState InsertedCountIncremented
      +
      The hash was accepted into the sketch and the retained count was incremented.
      +
      +
      +
    • +
    • +
      +

      InsertedCountIncrementedResized

      +
      +
      public static final UpdateReturnState InsertedCountIncrementedResized
      +
      The hash was accepted into the sketch, the retained count was incremented. +The current cache was out of room and resized larger based on the Resize Factor.
      +
      +
      +
    • +
    • +
      +

      InsertedCountIncrementedRebuilt

      +
      +
      public static final UpdateReturnState InsertedCountIncrementedRebuilt
      +
      The hash was accepted into the sketch, the retained count was incremented. +The current cache was out of room and at maximum size, so the cache was rebuilt.
      +
      +
      +
    • +
    • +
      +

      InsertedCountNotIncremented

      +
      +
      public static final UpdateReturnState InsertedCountNotIncremented
      +
      The hash was accepted into the sketch and the retained count was not incremented.
      +
      +
      +
    • +
    • +
      +

      ConcurrentBufferInserted

      +
      +
      public static final UpdateReturnState ConcurrentBufferInserted
      +
      The hash was inserted into the local concurrent buffer, +but has not yet been propagated to the concurrent shared sketch.
      +
      +
      +
    • +
    • +
      +

      ConcurrentPropagated

      +
      +
      public static final UpdateReturnState ConcurrentPropagated
      +
      The hash has been propagated to the concurrent shared sketch. +This does not reflect the action taken by the shared sketch.
      +
      +
      +
    • +
    • +
      +

      RejectedDuplicate

      +
      +
      public static final UpdateReturnState RejectedDuplicate
      +
      The hash was rejected as a duplicate.
      +
      +
      +
    • +
    • +
      +

      RejectedNullOrEmpty

      +
      +
      public static final UpdateReturnState RejectedNullOrEmpty
      +
      The hash was rejected because it was null or empty.
      +
      +
      +
    • +
    • +
      +

      RejectedOverTheta

      +
      +
      public static final UpdateReturnState RejectedOverTheta
      +
      The hash was rejected because the value was negative, zero or +greater than theta.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static UpdateReturnState[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static UpdateReturnState valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/class-use/CompactThetaSketch.html b/target/site/apidocs/org/apache/datasketches/theta/class-use/CompactThetaSketch.html new file mode 100644 index 000000000..f453a85eb --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/class-use/CompactThetaSketch.html @@ -0,0 +1,227 @@ + + + + +Uses of Class org.apache.datasketches.theta.CompactThetaSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.theta.CompactThetaSketch

+
+
Packages that use CompactThetaSketch
+
+
Package
+
Description
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/class-use/HashIterator.html b/target/site/apidocs/org/apache/datasketches/theta/class-use/HashIterator.html new file mode 100644 index 000000000..f502c634e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/class-use/HashIterator.html @@ -0,0 +1,97 @@ + + + + +Uses of Interface org.apache.datasketches.theta.HashIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.theta.HashIterator

+
+
Packages that use HashIterator
+
+
Package
+
Description
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/class-use/JaccardSimilarity.html b/target/site/apidocs/org/apache/datasketches/theta/class-use/JaccardSimilarity.html new file mode 100644 index 000000000..4aa5df757 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/class-use/JaccardSimilarity.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.theta.JaccardSimilarity (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.theta.JaccardSimilarity

+
+No usage of org.apache.datasketches.theta.JaccardSimilarity +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaAnotB.html b/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaAnotB.html new file mode 100644 index 000000000..fad1fbe52 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaAnotB.html @@ -0,0 +1,97 @@ + + + + +Uses of Class org.apache.datasketches.theta.ThetaAnotB (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.theta.ThetaAnotB

+
+
Packages that use ThetaAnotB
+
+
Package
+
Description
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaIntersection.html b/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaIntersection.html new file mode 100644 index 000000000..c82b841ed --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaIntersection.html @@ -0,0 +1,115 @@ + + + + +Uses of Class org.apache.datasketches.theta.ThetaIntersection (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.theta.ThetaIntersection

+
+
Packages that use ThetaIntersection
+
+
Package
+
Description
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaSetOperation.html b/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaSetOperation.html new file mode 100644 index 000000000..067865196 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaSetOperation.html @@ -0,0 +1,149 @@ + + + + +Uses of Class org.apache.datasketches.theta.ThetaSetOperation (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.theta.ThetaSetOperation

+
+
Packages that use ThetaSetOperation
+
+
Package
+
Description
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaSetOperationBuilder.html b/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaSetOperationBuilder.html new file mode 100644 index 000000000..28bad9ef5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaSetOperationBuilder.html @@ -0,0 +1,121 @@ + + + + +Uses of Class org.apache.datasketches.theta.ThetaSetOperationBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.theta.ThetaSetOperationBuilder

+
+
Packages that use ThetaSetOperationBuilder
+
+
Package
+
Description
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaSketch.html b/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaSketch.html new file mode 100644 index 000000000..dfd99dc19 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaSketch.html @@ -0,0 +1,376 @@ + + + + +Uses of Class org.apache.datasketches.theta.ThetaSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.theta.ThetaSketch

+
+
Packages that use ThetaSketch
+
+
Package
+
Description
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+ +
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaUnion.html b/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaUnion.html new file mode 100644 index 000000000..3807a1aff --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/class-use/ThetaUnion.html @@ -0,0 +1,126 @@ + + + + +Uses of Class org.apache.datasketches.theta.ThetaUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.theta.ThetaUnion

+
+
Packages that use ThetaUnion
+
+
Package
+
Description
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/class-use/UpdatableThetaSketch.html b/target/site/apidocs/org/apache/datasketches/theta/class-use/UpdatableThetaSketch.html new file mode 100644 index 000000000..62d0a67a0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/class-use/UpdatableThetaSketch.html @@ -0,0 +1,179 @@ + + + + +Uses of Class org.apache.datasketches.theta.UpdatableThetaSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.theta.UpdatableThetaSketch

+
+
Packages that use UpdatableThetaSketch
+
+
Package
+
Description
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/class-use/UpdatableThetaSketchBuilder.html b/target/site/apidocs/org/apache/datasketches/theta/class-use/UpdatableThetaSketchBuilder.html new file mode 100644 index 000000000..72369c8d5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/class-use/UpdatableThetaSketchBuilder.html @@ -0,0 +1,151 @@ + + + + +Uses of Class org.apache.datasketches.theta.UpdatableThetaSketchBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.theta.UpdatableThetaSketchBuilder

+
+
Packages that use UpdatableThetaSketchBuilder
+
+
Package
+
Description
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/class-use/UpdateReturnState.html b/target/site/apidocs/org/apache/datasketches/theta/class-use/UpdateReturnState.html new file mode 100644 index 000000000..85b88d3ef --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/class-use/UpdateReturnState.html @@ -0,0 +1,154 @@ + + + + +Uses of Enum Class org.apache.datasketches.theta.UpdateReturnState (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.theta.UpdateReturnState

+
+
Packages that use UpdateReturnState
+
+
Package
+
Description
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/package-summary.html b/target/site/apidocs/org/apache/datasketches/theta/package-summary.html new file mode 100644 index 000000000..4a4ea09a2 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/package-summary.html @@ -0,0 +1,160 @@ + + + + +org.apache.datasketches.theta (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.theta

+
+
+
+
package org.apache.datasketches.theta
+
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework. + +

There is a separate /tuple/ package for many of the sketches that are derived from the +same algorithms defined in the Theta-Sketch Framework paper.

+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/package-tree.html b/target/site/apidocs/org/apache/datasketches/theta/package-tree.html new file mode 100644 index 000000000..ca993e085 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/package-tree.html @@ -0,0 +1,114 @@ + + + + +org.apache.datasketches.theta Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.theta

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Interface Hierarchy

+ +
+
+

Enum Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/theta/package-use.html b/target/site/apidocs/org/apache/datasketches/theta/package-use.html new file mode 100644 index 000000000..6bba6e8c3 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/theta/package-use.html @@ -0,0 +1,169 @@ + + + + +Uses of Package org.apache.datasketches.theta (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.theta

+
+ +
+
Package
+
Description
+ +
+
The theta package contains the basic sketch classes that are members of the +Theta-Sketch Framework.
+
+ +
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/BinomialBoundsN.html b/target/site/apidocs/org/apache/datasketches/thetacommon/BinomialBoundsN.html new file mode 100644 index 000000000..f6a99eb19 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/BinomialBoundsN.html @@ -0,0 +1,200 @@ + + + + +BinomialBoundsN (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class BinomialBoundsN

+
+
java.lang.Object +
org.apache.datasketches.thetacommon.BinomialBoundsN
+
+
+
+
+
public final class BinomialBoundsN +extends Object
+
This class enables the estimation of error bounds given a sample set size, the sampling +probability theta, the number of standard deviations and a simple noDataSeen flag. This can +be used to estimate error bounds for fixed threshold sampling as well as the error bounds +calculations for sketches.
+
+
Author:
+
Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static double
    +
    getLowerBound(long numSamples, + double theta, + int numSDev, + boolean noDataSeen)
    +
    +
    Returns the approximate lower bound value
    +
    +
    static double
    +
    getUpperBound(long numSamples, + double theta, + int numSDev, + boolean noDataSeen)
    +
    +
    Returns the approximate upper bound value
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getLowerBound

      +
      +
      public static double getLowerBound(long numSamples, + double theta, + int numSDev, + boolean noDataSeen)
      +
      Returns the approximate lower bound value
      +
      +
      Parameters:
      +
      numSamples - the number of samples in the sample set
      +
      theta - the sampling probability
      +
      numSDev - the number of "standard deviations" from the mean for the tail bounds. +This must be an integer value of 1, 2 or 3.
      +
      noDataSeen - this is normally false. However, in the case where you have zero samples +and a theta < 1.0, this flag enables the distinction between a virgin case when no actual +data has been seen and the case where the estimate may be zero but an upper error bound may +still exist.
      +
      Returns:
      +
      the approximate lower bound value
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public static double getUpperBound(long numSamples, + double theta, + int numSDev, + boolean noDataSeen)
      +
      Returns the approximate upper bound value
      +
      +
      Parameters:
      +
      numSamples - the number of samples in the sample set
      +
      theta - the sampling probability
      +
      numSDev - the number of "standard deviations" from the mean for the tail bounds. +This must be an integer value of 1, 2 or 3.
      +
      noDataSeen - this is normally false. However, in the case where you have zero samples +and a theta < 1.0, this flag enables the distinction between a virgin case when no actual +data has been seen and the case where the estimate may be zero but an upper error bound may +still exist.
      +
      Returns:
      +
      the approximate upper bound value
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/BoundsOnRatiosInThetaSketchedSets.html b/target/site/apidocs/org/apache/datasketches/thetacommon/BoundsOnRatiosInThetaSketchedSets.html new file mode 100644 index 000000000..4a0f010d4 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/BoundsOnRatiosInThetaSketchedSets.html @@ -0,0 +1,216 @@ + + + + +BoundsOnRatiosInThetaSketchedSets (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class BoundsOnRatiosInThetaSketchedSets

+
+
java.lang.Object +
org.apache.datasketches.thetacommon.BoundsOnRatiosInThetaSketchedSets
+
+
+
+
+
public final class BoundsOnRatiosInThetaSketchedSets +extends Object
+
This class is used to compute the bounds on the estimate of the ratio B / A, where: +
    +
  • A is a Theta Sketch of population PopA.
  • +
  • B is a Theta Sketch of population PopB that is a subset of A, +obtained by an intersection of A with some other Theta Sketch C, +which acts like a predicate or selection clause.
  • +
  • The estimate of the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(A, B).
  • +
  • The Upper Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(A, B).
  • +
  • The Lower Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(A, B).
  • +
+Note: The theta of A cannot be greater than the theta of B. +If B is formed as an intersection of A and some other set C, +then the theta of B is guaranteed to be less than or equal to the theta of B.
+
+
Author:
+
Kevin Lang, Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getLowerBoundForBoverA

      +
      +
      public static double getLowerBoundForBoverA(ThetaSketch sketchA, + ThetaSketch sketchB)
      +
      Gets the approximate lower bound for B over A based on a 95% confidence interval
      +
      +
      Parameters:
      +
      sketchA - the sketch A
      +
      sketchB - the sketch B
      +
      Returns:
      +
      the approximate lower bound for B over A
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBoundForBoverA

      +
      +
      public static double getUpperBoundForBoverA(ThetaSketch sketchA, + ThetaSketch sketchB)
      +
      Gets the approximate upper bound for B over A based on a 95% confidence interval
      +
      +
      Parameters:
      +
      sketchA - the sketch A
      +
      sketchB - the sketch B
      +
      Returns:
      +
      the approximate upper bound for B over A
      +
      +
      +
      +
    • +
    • +
      +

      getEstimateOfBoverA

      +
      +
      public static double getEstimateOfBoverA(ThetaSketch sketchA, + ThetaSketch sketchB)
      +
      Gets the estimate for B over A
      +
      +
      Parameters:
      +
      sketchA - the sketch A
      +
      sketchB - the sketch B
      +
      Returns:
      +
      the estimate for B over A
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/BoundsOnRatiosInTupleSketchedSets.html b/target/site/apidocs/org/apache/datasketches/thetacommon/BoundsOnRatiosInTupleSketchedSets.html new file mode 100644 index 000000000..1b189b0a9 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/BoundsOnRatiosInTupleSketchedSets.html @@ -0,0 +1,300 @@ + + + + +BoundsOnRatiosInTupleSketchedSets (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class BoundsOnRatiosInTupleSketchedSets

+
+
java.lang.Object +
org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets
+
+
+
+
+
public final class BoundsOnRatiosInTupleSketchedSets +extends Object
+
This class is used to compute the bounds on the estimate of the ratio B / A, where: +
    +
  • A is a Tuple Sketch of population PopA.
  • +
  • B is a Tuple or Theta Sketch of population PopB that is a subset of A, +obtained by an intersection of A with some other Tuple or Theta Sketch C, +which acts like a predicate or selection clause.
  • +
  • The estimate of the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(A, B).
  • +
  • The Upper Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(A, B).
  • +
  • The Lower Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(A, B).
  • +
+Note: The theta of A cannot be greater than the theta of B. +If B is formed as an intersection of A and some other set C, +then the theta of B is guaranteed to be less than or equal to the theta of B.
+
+
Author:
+
Kevin Lang, Lee Rhodes, David Cromberge
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getLowerBoundForBoverA

      +
      +
      public static <S extends Summary> double getLowerBoundForBoverA(TupleSketch<S> sketchA, + TupleSketch<S> sketchB)
      +
      Gets the approximate lower bound for B over A based on a 95% confidence interval
      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      sketchA - the Tuple sketch A with summary type S
      +
      sketchB - the Tuple sketch B with summary type S
      +
      Returns:
      +
      the approximate lower bound for B over A
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBoundForBoverA

      +
      +
      public static <S extends Summary> double getLowerBoundForBoverA(TupleSketch<S> sketchA, + ThetaSketch sketchB)
      +
      Gets the approximate lower bound for B over A based on a 95% confidence interval
      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      sketchA - the Tuple sketch A with summary type S
      +
      sketchB - the Theta sketch B
      +
      Returns:
      +
      the approximate lower bound for B over A
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBoundForBoverA

      +
      +
      public static <S extends Summary> double getUpperBoundForBoverA(TupleSketch<S> sketchA, + TupleSketch<S> sketchB)
      +
      Gets the approximate upper bound for B over A based on a 95% confidence interval
      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      sketchA - the Tuple sketch A with summary type S
      +
      sketchB - the Tuple sketch B with summary type S
      +
      Returns:
      +
      the approximate upper bound for B over A
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBoundForBoverA

      +
      +
      public static <S extends Summary> double getUpperBoundForBoverA(TupleSketch<S> sketchA, + ThetaSketch sketchB)
      +
      Gets the approximate upper bound for B over A based on a 95% confidence interval
      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      sketchA - the Tuple sketch A with summary type S
      +
      sketchB - the Theta sketch B
      +
      Returns:
      +
      the approximate upper bound for B over A
      +
      +
      +
      +
    • +
    • +
      +

      getEstimateOfBoverA

      +
      +
      public static <S extends Summary> double getEstimateOfBoverA(TupleSketch<S> sketchA, + TupleSketch<S> sketchB)
      +
      Gets the estimate for B over A
      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      sketchA - the Tuple sketch A with summary type S
      +
      sketchB - the Tuple sketch B with summary type S
      +
      Returns:
      +
      the estimate for B over A
      +
      +
      +
      +
    • +
    • +
      +

      getEstimateOfBoverA

      +
      +
      public static <S extends Summary> double getEstimateOfBoverA(TupleSketch<S> sketchA, + ThetaSketch sketchB)
      +
      Gets the estimate for B over A
      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      sketchA - the Tuple sketch A with summary type S
      +
      sketchB - the Theta sketch B
      +
      Returns:
      +
      the estimate for B over A
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/HashOperations.html b/target/site/apidocs/org/apache/datasketches/thetacommon/HashOperations.html new file mode 100644 index 000000000..e0c3e9da9 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/HashOperations.html @@ -0,0 +1,587 @@ + + + + +HashOperations (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class HashOperations

+
+
java.lang.Object +
org.apache.datasketches.thetacommon.HashOperations
+
+
+
+
+
public final class HashOperations +extends Object
+
Helper class for the common hash table methods.
+
+
Author:
+
Lee Rhodes, Kevin Lang
+
+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    static final int
    + +
    +
    The stride mask for the Open Address, Double Hashing (OADH) hash table algorithm.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static void
    + +
    +
    Checks that the given hash value is not negative.
    +
    +
    static void
    +
    checkThetaCorruption(long thetaLong)
    +
    +
    Checks that the given theta is not negative nor zero.
    +
    +
    static boolean
    +
    continueCondition(long thetaLong, + long hash)
    +
    +
    Return true (continue) if hash is greater than or equal to thetaLong, or if hash == 0, +or if hash == Long.MAX_VALUE.
    +
    +
    static long[]
    +
    convertToHashTable(long[] hashArr, + int count, + long thetaLong, + double rebuildThreshold)
    +
    +
    Converts the given array to a hash table.
    +
    +
    static int
    +
    count(long[] srcArr, + long thetaLong)
    +
    +
    Counts the cardinality of the given source array.
    +
    +
    static int
    +
    countPart(long[] srcArr, + int lgArrLongs, + long thetaLong)
    +
    +
    Counts the cardinality of the first Log2 values of the given source array.
    +
    +
    static int
    +
    hashArrayInsert(long[] srcArr, + long[] hashTable, + int lgArrLongs, + long thetaLong)
    +
    +
    Inserts the given long array into the given OADH hashTable of the target size, +ignores duplicates and counts the values inserted.
    +
    +
    static int
    +
    hashInsertOnly(long[] hashTable, + int lgArrLongs, + long hash)
    +
    +
    This is a classical Knuth-style Open Addressing, Double Hash (OADH) insert scheme for on-heap.
    +
    +
    static int
    +
    hashInsertOnlyMemorySegment(MemorySegment wseg, + int lgArrLongs, + long hash, + int segOffsetBytes)
    +
    +
    This is a classical Knuth-style Open Addressing, Double Hash (OADH) insert scheme for MemorySegment.
    +
    +
    static int
    +
    hashSearch(long[] hashTable, + int lgArrLongs, + long hash)
    +
    +
    This is a classical Knuth-style Open Addressing, Double Hash (OADH) search scheme for on-heap.
    +
    +
    static int
    +
    hashSearchMemorySegment(MemorySegment seg, + int lgArrLongs, + long hash, + int segOffsetBytes)
    +
    +
    This is a classical Knuth-style Open Addressing, Double Hash (OADH) search scheme for MemorySegment.
    +
    +
    static int
    +
    hashSearchOrInsert(long[] hashTable, + int lgArrLongs, + long hash)
    +
    +
    This is a classical Knuth-style Open Addressing, Double Hash (OADH) insert scheme for on-heap.
    +
    +
    static int
    +
    hashSearchOrInsertMemorySegment(MemorySegment wseg, + int lgArrLongs, + long hash, + int segOffsetBytes)
    +
    +
    This is a classical Knuth-style Open Addressing, Double Hash insert scheme, but inserts +values directly into a writable MemorySegment.
    +
    +
    static int
    +
    minLgHashTableSize(int count, + double rebuild_threshold)
    +
    +
    Returns the smallest log hash table size given the count of items and the rebuild threshold.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      STRIDE_MASK

      +
      +
      public static final int STRIDE_MASK
      +
      The stride mask for the Open Address, Double Hashing (OADH) hash table algorithm.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      hashSearch

      +
      +
      public static int hashSearch(long[] hashTable, + int lgArrLongs, + long hash)
      +
      This is a classical Knuth-style Open Addressing, Double Hash (OADH) search scheme for on-heap. +Returns the index if found, -1 if not found.
      +
      +
      Parameters:
      +
      hashTable - The hash table to search. Its size must be a power of 2.
      +
      lgArrLongs - The log_base2(hashTable.length). +See lgArrLongs.
      +
      hash - The hash value to search for. It must not be zero.
      +
      Returns:
      +
      Current probe index if found, -1 if not found.
      +
      +
      +
      +
    • +
    • +
      +

      hashInsertOnly

      +
      +
      public static int hashInsertOnly(long[] hashTable, + int lgArrLongs, + long hash)
      +
      This is a classical Knuth-style Open Addressing, Double Hash (OADH) insert scheme for on-heap. +This method assumes that the input hash is not a duplicate. +Useful for rebuilding tables to avoid unnecessary comparisons. +Returns the index of insertion, which is always positive or zero. +Throws an exception if the table has no empty slot.
      +
      +
      Parameters:
      +
      hashTable - the hash table to insert into. Its size must be a power of 2.
      +
      lgArrLongs - The log_base2(hashTable.length). +See lgArrLongs.
      +
      hash - The hash value to be potentially inserted into an empty slot. It must not be zero.
      +
      Returns:
      +
      index of insertion. Always positive or zero.
      +
      +
      +
      +
    • +
    • +
      +

      hashSearchOrInsert

      +
      +
      public static int hashSearchOrInsert(long[] hashTable, + int lgArrLongs, + long hash)
      +
      This is a classical Knuth-style Open Addressing, Double Hash (OADH) insert scheme for on-heap. +Returns index ≥ 0 if found (duplicate); < 0 if inserted, inserted at -(index + 1). +Throws an exception if the value is not found and table has no empty slot.
      +
      +
      Parameters:
      +
      hashTable - The hash table to insert into. Its size must be a power of 2.
      +
      lgArrLongs - The log_base2(hashTable.length). +See lgArrLongs.
      +
      hash - The hash value to be potentially inserted into an empty slot only if it is not +a duplicate of any other hash value in the table. It must not be zero.
      +
      Returns:
      +
      index ≥ 0 if found (duplicate); < 0 if inserted, inserted at -(index + 1).
      +
      +
      +
      +
    • +
    • +
      +

      hashArrayInsert

      +
      +
      public static int hashArrayInsert(long[] srcArr, + long[] hashTable, + int lgArrLongs, + long thetaLong)
      +
      Inserts the given long array into the given OADH hashTable of the target size, +ignores duplicates and counts the values inserted. +The hash values must not be negative, zero values and values ≥ thetaLong are ignored. +The given hash table may have values, but they must have been inserted by this method or one +of the other OADH insert methods in this class. +This method performs additional checks against potentially invalid hash values or theta values. +Returns the count of values actually inserted.
      +
      +
      Parameters:
      +
      srcArr - the source hash array to be potentially inserted
      +
      hashTable - The hash table to insert into. Its size must be a power of 2.
      +
      lgArrLongs - The log_base2(hashTable.length). +See lgArrLongs.
      +
      thetaLong - The theta value that all input hash values are compared against. +It must greater than zero. +See Theta Long
      +
      Returns:
      +
      the count of values actually inserted
      +
      +
      +
      +
    • +
    • +
      +

      hashSearchMemorySegment

      +
      +
      public static int hashSearchMemorySegment(MemorySegment seg, + int lgArrLongs, + long hash, + int segOffsetBytes)
      +
      This is a classical Knuth-style Open Addressing, Double Hash (OADH) search scheme for MemorySegment. +Returns the index if found, -1 if not found. The input MemorySegment may be read only.
      +
      +
      Parameters:
      +
      seg - The MemorySegment containing the hash table to search. +The hash table portion must be a power of 2 in size.
      +
      lgArrLongs - The log_base2(hashTable.length). +See lgArrLongs.
      +
      hash - The hash value to search for. Must not be zero.
      +
      segOffsetBytes - offset in the MemorySegment where the hashTable starts
      +
      Returns:
      +
      Current probe index if found, -1 if not found.
      +
      +
      +
      +
    • +
    • +
      +

      hashInsertOnlyMemorySegment

      +
      +
      public static int hashInsertOnlyMemorySegment(MemorySegment wseg, + int lgArrLongs, + long hash, + int segOffsetBytes)
      +
      This is a classical Knuth-style Open Addressing, Double Hash (OADH) insert scheme for MemorySegment. +This method assumes that the input hash is not a duplicate. +Useful for rebuilding tables to avoid unnecessary comparisons. +Returns the index of insertion, which is always positive or zero. +Throws an exception if table has no empty slot.
      +
      +
      Parameters:
      +
      wseg - The writable MemorySegment that contains the hashTable to insert into. +The size of the hashTable portion must be a power of 2.
      +
      lgArrLongs - The log_base2(hashTable.length. +See lgArrLongs.
      +
      hash - value that must not be zero and will be inserted into the array into an empty slot.
      +
      segOffsetBytes - offset in the writable MemorySegment where the hashTable starts
      +
      Returns:
      +
      index of insertion. Always positive or zero.
      +
      +
      +
      +
    • +
    • +
      +

      hashSearchOrInsertMemorySegment

      +
      +
      public static int hashSearchOrInsertMemorySegment(MemorySegment wseg, + int lgArrLongs, + long hash, + int segOffsetBytes)
      +
      This is a classical Knuth-style Open Addressing, Double Hash insert scheme, but inserts +values directly into a writable MemorySegment. +Returns index ≥ 0 if found (duplicate); < 0 if inserted, inserted at -(index + 1). +Throws an exception if the value is not found and table has no empty slot.
      +
      +
      Parameters:
      +
      wseg - The writable MemorySegment that contains the hashTable to insert into.
      +
      lgArrLongs - The log_base2(hashTable.length). +See lgArrLongs.
      +
      hash - The hash value to be potentially inserted into an empty slot only if it is not +a duplicate of any other hash value in the table. It must not be zero.
      +
      segOffsetBytes - offset in the writable MemorySegment where the hash array starts
      +
      Returns:
      +
      index ≥ 0 if found (duplicate); < 0 if inserted, inserted at -(index + 1).
      +
      +
      +
      +
    • +
    • +
      +

      checkThetaCorruption

      +
      +
      public static void checkThetaCorruption(long thetaLong)
      +
      Checks that the given theta is not negative nor zero.
      +
      +
      Parameters:
      +
      thetaLong - must be greater than zero otherwise throws an exception. +See Theta Long
      +
      +
      +
      +
    • +
    • +
      +

      checkHashCorruption

      +
      +
      public static void checkHashCorruption(long hash)
      +
      Checks that the given hash value is not negative.
      +
      +
      Parameters:
      +
      hash - must be greater than -1 otherwise throws an exception. +Note a hash of zero is normally ignored, but a negative hash is never allowed.
      +
      +
      +
      +
    • +
    • +
      +

      continueCondition

      +
      +
      public static boolean continueCondition(long thetaLong, + long hash)
      +
      Return true (continue) if hash is greater than or equal to thetaLong, or if hash == 0, +or if hash == Long.MAX_VALUE.
      +
      +
      Parameters:
      +
      thetaLong - must be greater than the hash value +See Theta Long
      +
      hash - must be less than thetaLong and not less than or equal to zero.
      +
      Returns:
      +
      true (continue) if hash is greater than or equal to thetaLong, or if hash == 0, +or if hash == Long.MAX_VALUE.
      +
      +
      +
      +
    • +
    • +
      +

      convertToHashTable

      +
      +
      public static long[] convertToHashTable(long[] hashArr, + int count, + long thetaLong, + double rebuildThreshold)
      +
      Converts the given array to a hash table.
      +
      +
      Parameters:
      +
      hashArr - The given array of hashes. Gaps are OK.
      +
      count - The number of valid hashes in the array
      +
      thetaLong - Any hashes equal to or greater than thetaLong will be ignored
      +
      rebuildThreshold - The fill fraction for the hash table forcing a rebuild or resize.
      +
      Returns:
      +
      a HashTable
      +
      +
      +
      +
    • +
    • +
      +

      minLgHashTableSize

      +
      +
      public static int minLgHashTableSize(int count, + double rebuild_threshold)
      +
      Returns the smallest log hash table size given the count of items and the rebuild threshold.
      +
      +
      Parameters:
      +
      count - the given count of items
      +
      rebuild_threshold - the rebuild threshold as a fraction between zero and one.
      +
      Returns:
      +
      the smallest log hash table size
      +
      +
      +
      +
    • +
    • +
      +

      countPart

      +
      +
      public static int countPart(long[] srcArr, + int lgArrLongs, + long thetaLong)
      +
      Counts the cardinality of the first Log2 values of the given source array.
      +
      +
      Parameters:
      +
      srcArr - the given source array
      +
      lgArrLongs - See lgArrLongs
      +
      thetaLong - See Theta Long
      +
      Returns:
      +
      the cardinality
      +
      +
      +
      +
    • +
    • +
      +

      count

      +
      +
      public static int count(long[] srcArr, + long thetaLong)
      +
      Counts the cardinality of the given source array.
      +
      +
      Parameters:
      +
      srcArr - the given source array
      +
      thetaLong - See Theta Long
      +
      Returns:
      +
      the cardinality
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.AnotbAction.html b/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.AnotbAction.html new file mode 100644 index 000000000..f73021b8b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.AnotbAction.html @@ -0,0 +1,347 @@ + + + + +SetOperationCornerCases.AnotbAction (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class SetOperationCornerCases.AnotbAction

+
+
java.lang.Object +
java.lang.Enum<SetOperationCornerCases.AnotbAction> +
org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<SetOperationCornerCases.AnotbAction>, Constable
+
+
+
Enclosing class:
+
SetOperationCornerCases
+
+
+
+
public static enum SetOperationCornerCases.AnotbAction +extends Enum<SetOperationCornerCases.AnotbAction>
+
A not B actions
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Enum Constant Details

    + +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static SetOperationCornerCases.AnotbAction[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static SetOperationCornerCases.AnotbAction valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    • +
      +

      getActionId

      +
      +
      public String getActionId()
      +
      Gets the Action ID
      +
      +
      Returns:
      +
      the actionId
      +
      +
      +
      +
    • +
    • +
      +

      getActionDescription

      +
      +
      public String getActionDescription()
      +
      Gets the action description
      +
      +
      Returns:
      +
      the action description
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.CornerCase.html b/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.CornerCase.html new file mode 100644 index 000000000..374ac243e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.CornerCase.html @@ -0,0 +1,565 @@ + + + + +SetOperationCornerCases.CornerCase (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class SetOperationCornerCases.CornerCase

+
+
java.lang.Object +
java.lang.Enum<SetOperationCornerCases.CornerCase> +
org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<SetOperationCornerCases.CornerCase>, Constable
+
+
+
Enclosing class:
+
SetOperationCornerCases
+
+
+
+
public static enum SetOperationCornerCases.CornerCase +extends Enum<SetOperationCornerCases.CornerCase>
+
List of corner cases
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+ +
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.IntersectAction.html b/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.IntersectAction.html new file mode 100644 index 000000000..1c1bd5792 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.IntersectAction.html @@ -0,0 +1,305 @@ + + + + +SetOperationCornerCases.IntersectAction (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class SetOperationCornerCases.IntersectAction

+
+
java.lang.Object +
java.lang.Enum<SetOperationCornerCases.IntersectAction> +
org.apache.datasketches.thetacommon.SetOperationCornerCases.IntersectAction
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<SetOperationCornerCases.IntersectAction>, Constable
+
+
+
Enclosing class:
+
SetOperationCornerCases
+
+
+
+
public static enum SetOperationCornerCases.IntersectAction +extends Enum<SetOperationCornerCases.IntersectAction>
+
Intersection actions
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Enum Constant Details

    + +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static SetOperationCornerCases.IntersectAction[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static SetOperationCornerCases.IntersectAction valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    • +
      +

      getActionId

      +
      +
      public String getActionId()
      +
      Gets the Action ID
      +
      +
      Returns:
      +
      the actionId
      +
      +
      +
      +
    • +
    • +
      +

      getActionDescription

      +
      +
      public String getActionDescription()
      +
      Gets the Action Description
      +
      +
      Returns:
      +
      the actionDescription
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.UnionAction.html b/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.UnionAction.html new file mode 100644 index 000000000..3d42d3099 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.UnionAction.html @@ -0,0 +1,389 @@ + + + + +SetOperationCornerCases.UnionAction (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class SetOperationCornerCases.UnionAction

+
+
java.lang.Object +
java.lang.Enum<SetOperationCornerCases.UnionAction> +
org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<SetOperationCornerCases.UnionAction>, Constable
+
+
+
Enclosing class:
+
SetOperationCornerCases
+
+
+
+
public static enum SetOperationCornerCases.UnionAction +extends Enum<SetOperationCornerCases.UnionAction>
+
List of union actions
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+ +
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.html b/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.html new file mode 100644 index 000000000..cc5f53c09 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/SetOperationCornerCases.html @@ -0,0 +1,263 @@ + + + + +SetOperationCornerCases (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class SetOperationCornerCases

+
+
java.lang.Object +
org.apache.datasketches.thetacommon.SetOperationCornerCases
+
+
+
+
+
public class SetOperationCornerCases +extends Object
+
Simplifies and speeds up set operations by resolving specific corner cases.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      SetOperationCornerCases

      +
      +
      public SetOperationCornerCases()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      createCornerCaseId

      +
      +
      public static int createCornerCaseId(long thetaLongA, + int countA, + boolean emptyA, + long thetaLongB, + int countB, + boolean emptyB)
      +
      Creates the CornerCase ID
      +
      +
      Parameters:
      +
      thetaLongA - the theta of A as a long
      +
      countA - the count of A
      +
      emptyA - true if A is empty
      +
      thetaLongB - the theta of B as a long
      +
      countB - the count of B
      +
      emptyB - true if B is empty
      +
      Returns:
      +
      the Corner Case ID
      +
      +
      +
      +
    • +
    • +
      +

      sketchStateId

      +
      +
      public static int sketchStateId(boolean isEmpty, + int numRetained, + long thetaLong)
      +
      Returns the sketch state ID
      +
      +
      Parameters:
      +
      isEmpty - true if empty
      +
      numRetained - the number of items retained
      +
      thetaLong - the value of theta as a long
      +
      Returns:
      +
      the sketch state ID
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/ThetaUtil.html b/target/site/apidocs/org/apache/datasketches/thetacommon/ThetaUtil.html new file mode 100644 index 000000000..06744ad06 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/ThetaUtil.html @@ -0,0 +1,351 @@ + + + + +ThetaUtil (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ThetaUtil

+
+
java.lang.Object +
org.apache.datasketches.thetacommon.ThetaUtil
+
+
+
+
+
public final class ThetaUtil +extends Object
+
Utility methods for the Theta Family of sketches
+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Field Summary

    +
    Fields
    +
    +
    Modifier and Type
    +
    Field
    +
    Description
    +
    static final int
    + +
    +
    The default nominal entries is provided as a convenience for those cases where the +nominal sketch size in number of entries is not provided.
    +
    +
    static final int
    + +
    +
    The largest Log2 nom entries allowed: 26.
    +
    +
    static final int
    + +
    +
    The smallest Log2 cache size allowed: 5.
    +
    +
    static final int
    + +
    +
    The smallest Log2 nom entries allowed: 4.
    +
    +
    static final double
    + +
    +
    The hash table rebuild threshold = 15.0/16.0.
    +
    +
    static final double
    + +
    +
    The resize threshold = 0.5; tuned for speed.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static int
    +
    checkNomLongs(int nomLongs)
    +
    +
    Checks that the given nomLongs is within bounds and returns the Log2 of the ceiling power of 2 +of the given nomLongs.
    +
    +
    static int
    +
    startingSubMultiple(int lgTarget, + int lgRF, + int lgMin)
    +
    +
    Gets the smallest allowed exponent of 2 that it is a sub-multiple of the target by zero, +one or more resize factors.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      MIN_LG_NOM_LONGS

      +
      +
      public static final int MIN_LG_NOM_LONGS
      +
      The smallest Log2 nom entries allowed: 4.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      MAX_LG_NOM_LONGS

      +
      +
      public static final int MAX_LG_NOM_LONGS
      +
      The largest Log2 nom entries allowed: 26.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      REBUILD_THRESHOLD

      +
      +
      public static final double REBUILD_THRESHOLD
      +
      The hash table rebuild threshold = 15.0/16.0.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      RESIZE_THRESHOLD

      +
      +
      public static final double RESIZE_THRESHOLD
      +
      The resize threshold = 0.5; tuned for speed.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      DEFAULT_NOMINAL_ENTRIES

      +
      +
      public static final int DEFAULT_NOMINAL_ENTRIES
      +
      The default nominal entries is provided as a convenience for those cases where the +nominal sketch size in number of entries is not provided. +A sketch of 4096 entries has a Relative Standard Error (RSE) of +/- 1.56% at a confidence of +68%; or equivalently, a Relative Error of +/- 3.1% at a confidence of 95.4%. +See Default Nominal Entries
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      MIN_LG_ARR_LONGS

      +
      +
      public static final int MIN_LG_ARR_LONGS
      +
      The smallest Log2 cache size allowed: 5.
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      startingSubMultiple

      +
      +
      public static int startingSubMultiple(int lgTarget, + int lgRF, + int lgMin)
      +
      Gets the smallest allowed exponent of 2 that it is a sub-multiple of the target by zero, +one or more resize factors.
      +
      +
      Parameters:
      +
      lgTarget - Log2 of the target size
      +
      lgRF - Log_base2 of Resize Factor. +See Resize Factor
      +
      lgMin - Log2 of the minimum allowed starting size
      +
      Returns:
      +
      The Log2 of the starting size
      +
      +
      +
      +
    • +
    • +
      +

      checkNomLongs

      +
      +
      public static int checkNomLongs(int nomLongs)
      +
      Checks that the given nomLongs is within bounds and returns the Log2 of the ceiling power of 2 +of the given nomLongs.
      +
      +
      Parameters:
      +
      nomLongs - the given number of nominal longs. This can be any value from 16 to +67108864, inclusive.
      +
      Returns:
      +
      The Log2 of the ceiling power of 2 of the given nomLongs.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/BinomialBoundsN.html b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/BinomialBoundsN.html new file mode 100644 index 000000000..f7bbb9f74 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/BinomialBoundsN.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.thetacommon.BinomialBoundsN (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.thetacommon.BinomialBoundsN

+
+No usage of org.apache.datasketches.thetacommon.BinomialBoundsN +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/BoundsOnRatiosInThetaSketchedSets.html b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/BoundsOnRatiosInThetaSketchedSets.html new file mode 100644 index 000000000..adb6760ef --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/BoundsOnRatiosInThetaSketchedSets.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.thetacommon.BoundsOnRatiosInThetaSketchedSets (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.thetacommon.BoundsOnRatiosInThetaSketchedSets

+
+No usage of org.apache.datasketches.thetacommon.BoundsOnRatiosInThetaSketchedSets +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/BoundsOnRatiosInTupleSketchedSets.html b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/BoundsOnRatiosInTupleSketchedSets.html new file mode 100644 index 000000000..00cfea671 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/BoundsOnRatiosInTupleSketchedSets.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets

+
+No usage of org.apache.datasketches.thetacommon.BoundsOnRatiosInTupleSketchedSets +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/HashOperations.html b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/HashOperations.html new file mode 100644 index 000000000..ed81a45ff --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/HashOperations.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.thetacommon.HashOperations (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.thetacommon.HashOperations

+
+No usage of org.apache.datasketches.thetacommon.HashOperations +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.AnotbAction.html b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.AnotbAction.html new file mode 100644 index 000000000..99d475702 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.AnotbAction.html @@ -0,0 +1,119 @@ + + + + +Uses of Enum Class org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.thetacommon.SetOperationCornerCases.AnotbAction

+
+ +
+
Package
+
Description
+ +
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.CornerCase.html b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.CornerCase.html new file mode 100644 index 000000000..75dade313 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.CornerCase.html @@ -0,0 +1,119 @@ + + + + +Uses of Enum Class org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.thetacommon.SetOperationCornerCases.CornerCase

+
+ +
+
Package
+
Description
+ +
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.IntersectAction.html b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.IntersectAction.html new file mode 100644 index 000000000..0d04b4f92 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.IntersectAction.html @@ -0,0 +1,119 @@ + + + + +Uses of Enum Class org.apache.datasketches.thetacommon.SetOperationCornerCases.IntersectAction (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.thetacommon.SetOperationCornerCases.IntersectAction

+
+ +
+
Package
+
Description
+ +
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.UnionAction.html b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.UnionAction.html new file mode 100644 index 000000000..eb3a1876d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.UnionAction.html @@ -0,0 +1,119 @@ + + + + +Uses of Enum Class org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.thetacommon.SetOperationCornerCases.UnionAction

+
+ +
+
Package
+
Description
+ +
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.html b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.html new file mode 100644 index 000000000..d72e5931d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/SetOperationCornerCases.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.thetacommon.SetOperationCornerCases (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.thetacommon.SetOperationCornerCases

+
+No usage of org.apache.datasketches.thetacommon.SetOperationCornerCases +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/ThetaUtil.html b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/ThetaUtil.html new file mode 100644 index 000000000..916b1cc28 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/class-use/ThetaUtil.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.thetacommon.ThetaUtil (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.thetacommon.ThetaUtil

+
+No usage of org.apache.datasketches.thetacommon.ThetaUtil +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/package-summary.html b/target/site/apidocs/org/apache/datasketches/thetacommon/package-summary.html new file mode 100644 index 000000000..5a8fb2e51 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/package-summary.html @@ -0,0 +1,176 @@ + + + + +org.apache.datasketches.thetacommon (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.thetacommon

+
+
+
+
package org.apache.datasketches.thetacommon
+
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+
+
+
    +
  • + +
  • +
  • +
    +
    +
    +
    +
    Class
    +
    Description
    + +
    +
    This class enables the estimation of error bounds given a sample set size, the sampling +probability theta, the number of standard deviations and a simple noDataSeen flag.
    +
    + +
    +
    This class is used to compute the bounds on the estimate of the ratio B / A, where: + +A is a Theta Sketch of population PopA. +B is a Theta Sketch of population PopB that is a subset of A, +obtained by an intersection of A with some other Theta Sketch C, +which acts like a predicate or selection clause. +The estimate of the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(A, B). +The Upper Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(A, B). +The Lower Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(A, B). + +Note: The theta of A cannot be greater than the theta of B.
    +
    + +
    +
    This class is used to compute the bounds on the estimate of the ratio B / A, where: + +A is a Tuple Sketch of population PopA. +B is a Tuple or Theta Sketch of population PopB that is a subset of A, +obtained by an intersection of A with some other Tuple or Theta Sketch C, +which acts like a predicate or selection clause. +The estimate of the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getEstimateOfBoverA(A, B). +The Upper Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getUpperBoundForBoverA(A, B). +The Lower Bound estimate on the ratio PopB/PopA is +BoundsOnRatiosInThetaSketchedSets.getLowerBoundForBoverA(A, B). + +Note: The theta of A cannot be greater than the theta of B.
    +
    + +
    +
    Helper class for the common hash table methods.
    +
    + +
    +
    Simplifies and speeds up set operations by resolving specific corner cases.
    +
    + +
    +
    A not B actions
    +
    + +
    +
    List of corner cases
    +
    + +
    +
    Intersection actions
    +
    + +
    +
    List of union actions
    +
    + +
    +
    Utility methods for the Theta Family of sketches
    +
    +
    +
    +
    +
  • +
+
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/package-tree.html b/target/site/apidocs/org/apache/datasketches/thetacommon/package-tree.html new file mode 100644 index 000000000..ef3bc2f78 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/package-tree.html @@ -0,0 +1,101 @@ + + + + +org.apache.datasketches.thetacommon Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.thetacommon

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Enum Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/thetacommon/package-use.html b/target/site/apidocs/org/apache/datasketches/thetacommon/package-use.html new file mode 100644 index 000000000..b7253206f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/thetacommon/package-use.html @@ -0,0 +1,104 @@ + + + + +Uses of Package org.apache.datasketches.thetacommon (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.thetacommon

+
+ +
+
Package
+
Description
+ +
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/CompactTupleSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/CompactTupleSketch.html new file mode 100644 index 000000000..0b0327997 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/CompactTupleSketch.html @@ -0,0 +1,257 @@ + + + + +CompactTupleSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class CompactTupleSketch<S extends Summary>

+
+
java.lang.Object +
org.apache.datasketches.tuple.TupleSketch<S> +
org.apache.datasketches.tuple.CompactTupleSketch<S>
+
+
+
+
+
Type Parameters:
+
S - type of Summary
+
+
+
+
public final class CompactTupleSketch<S extends Summary> +extends TupleSketch<S>
+
CompactTupleSketches are never created directly. They are created as a result of +the compact() method of an UpdatableTupleSketch or as a result of the getResult() +method of a set operation like TupleUnion, TupleIntersection or TupleAnotB. +CompactTupleSketch consists of a compact list (i.e. no intervening spaces) of hash values, +corresponding list of Summaries, and a value for theta. The lists may or may +not be ordered. CompactTupleSketch is read-only.
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      compact

      +
      +
      public CompactTupleSketch<S> compact()
      +
      Description copied from class: TupleSketch
      +
      Converts this TupleSketch to a CompactTupleSketch on the Java heap. + +

      If this sketch is already in compact form this operation returns this.

      +
      +
      Specified by:
      +
      compact in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      this sketch as a CompactTupleSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      getRetainedEntries

      +
      +
      public int getRetainedEntries()
      +
      Description copied from class: TupleSketch
      +
      Returns number of retained entries
      +
      +
      Specified by:
      +
      getRetainedEntries in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      number of retained entries
      +
      +
      +
      +
    • +
    • +
      +

      getCountLessThanThetaLong

      +
      +
      public int getCountLessThanThetaLong(long thetaLong)
      +
      Description copied from class: TupleSketch
      +
      Gets the number of hash values less than the given theta expressed as a long.
      +
      +
      Specified by:
      +
      getCountLessThanThetaLong in class TupleSketch<S extends Summary>
      +
      Parameters:
      +
      thetaLong - the given theta as a long in the range (zero, Long.MAX_VALUE].
      +
      Returns:
      +
      the number of hash values less than the given thetaLong.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Description copied from class: TupleSketch
      +
      Serialize this sketch to a byte array. + +

      As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Serializing a CompactTupleSketch is not deprecated.

      +
      +
      Specified by:
      +
      toByteArray in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      serialized representation of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public TupleSketchIterator<S> iterator()
      +
      Description copied from class: TupleSketch
      +
      Returns a SketchIterator
      +
      +
      Specified by:
      +
      iterator in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      a SketchIterator
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/DeserializeResult.html b/target/site/apidocs/org/apache/datasketches/tuple/DeserializeResult.html new file mode 100644 index 000000000..c26f5976b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/DeserializeResult.html @@ -0,0 +1,212 @@ + + + + +DeserializeResult (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class DeserializeResult<T>

+
+
java.lang.Object +
org.apache.datasketches.tuple.DeserializeResult<T>
+
+
+
+
Type Parameters:
+
T - Type of object
+
+
+
+
public class DeserializeResult<T> +extends Object
+
Returns an object and its size in bytes as a result of a deserialize operation
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    +
    DeserializeResult(T object, + int size)
    +
    +
    Creates an instance.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Returns Deserialized object
    +
    +
    int
    + +
    +
    Returns size in bytes occupied by the object in the serialized form
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      DeserializeResult

      +
      +
      public DeserializeResult(T object, + int size)
      +
      Creates an instance.
      +
      +
      Parameters:
      +
      object - Deserialized object.
      +
      size - Deserialized size in bytes.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getObject

      +
      +
      public T getObject()
      +
      Returns Deserialized object
      +
      +
      Returns:
      +
      Deserialized object
      +
      +
      +
      +
    • +
    • +
      +

      getSize

      +
      +
      public int getSize()
      +
      Returns size in bytes occupied by the object in the serialized form
      +
      +
      Returns:
      +
      size in bytes occupied by the object in the serialized form
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/Filter.html b/target/site/apidocs/org/apache/datasketches/tuple/Filter.html new file mode 100644 index 000000000..767101ba9 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/Filter.html @@ -0,0 +1,194 @@ + + + + +Filter (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class Filter<T extends Summary>

+
+
java.lang.Object +
org.apache.datasketches.tuple.Filter<T>
+
+
+
+
Type Parameters:
+
T - Summary type against which apply the Predicate
+
+
+
+
public class Filter<T extends Summary> +extends Object
+
Class for filtering entries from a TupleSketch given a Summary
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      Filter

      +
      +
      public Filter(Predicate<T> predicate)
      +
      Filter constructor with a Predicate
      +
      +
      Parameters:
      +
      predicate - Predicate to use in this filter. If the Predicate returns False, the + element is discarded. If the Predicate returns True, then the element is kept in the + TupleSketch
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      filter

      +
      +
      public CompactTupleSketch<T> filter(TupleSketch<T> sketchIn)
      +
      Filters elements on the provided TupleSketch
      +
      +
      Parameters:
      +
      sketchIn - The sketch against which to apply the Predicate
      +
      Returns:
      +
      A new CompactTupleSketch with some of the entries filtered out based on the Predicate
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/JaccardSimilarity.html b/target/site/apidocs/org/apache/datasketches/tuple/JaccardSimilarity.html new file mode 100644 index 000000000..f66985e89 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/JaccardSimilarity.html @@ -0,0 +1,472 @@ + + + + +JaccardSimilarity (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class JaccardSimilarity

+
+
java.lang.Object +
org.apache.datasketches.tuple.JaccardSimilarity
+
+
+
+
+
public final class JaccardSimilarity +extends Object
+
Jaccard similarity of two TupleSketches, or alternatively, of a TupleSketch and a ThetaSketch. + +

Note: only retained hash values are compared, and the Tuple summary values are not accounted for in the +similarity measure.

+
+
Author:
+
Lee Rhodes, David Cromberge
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      JaccardSimilarity

      +
      +
      public JaccardSimilarity()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      jaccard

      +
      +
      public static <S extends Summary> double[] jaccard(TupleSketch<S> sketchA, + TupleSketch<S> sketchB, + SummarySetOperations<S> summarySetOps)
      +
      Computes the Jaccard similarity index with upper and lower bounds. The Jaccard similarity index +J(A,B) = (A ^ B)/(A U B) is used to measure how similar the two sketches are to each +other. If J = 1.0, the sketches are considered equal. If J = 0, the two sketches are +distinct from each other. A Jaccard of .95 means the overlap between the two +populations is 95% of the union of the two populations. + +

      Note: For very large pairs of sketches, where the configured nominal entries of the sketches +are 2^25 or 2^26, this method may produce unpredictable results.

      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      sketchA - The first argument, a TupleSketch with summary type S
      +
      sketchB - The second argument, a TupleSketch with summary type S
      +
      summarySetOps - instance of SummarySetOperations used to unify or intersect summaries.
      +
      Returns:
      +
      a double array {LowerBound, Estimate, UpperBound} of the Jaccard index. +The Upper and Lower bounds are for a confidence interval of 95.4% or +/- 2 standard deviations.
      +
      +
      +
      +
    • +
    • +
      +

      jaccard

      +
      +
      public static <S extends Summary> double[] jaccard(TupleSketch<S> sketchA, + ThetaSketch sketchB, + S summary, + SummarySetOperations<S> summarySetOps)
      +
      Computes the Jaccard similarity index with upper and lower bounds. The Jaccard similarity index +J(A,B) = (A ^ B)/(A U B) is used to measure how similar the two sketches are to each +other. If J = 1.0, the sketches are considered equal. If J = 0, the two sketches are +distinct from each other. A Jaccard of .95 means the overlap between the two +populations is 95% of the union of the two populations. + +

      Note: For very large pairs of sketches, where the configured nominal entries of the sketches +are 2^25 or 2^26, this method may produce unpredictable results.

      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      sketchA - The first argument, a TupleSketch with summary type S
      +
      sketchB - The second argument, a ThetaSketch
      +
      summary - the given proxy summary for the ThetaSketch, which doesn't have one. +This may not be null.
      +
      summarySetOps - instance of SummarySetOperations used to unify or intersect summaries.
      +
      Returns:
      +
      a double array {LowerBound, Estimate, UpperBound} of the Jaccard index. +The Upper and Lower bounds are for a confidence interval of 95.4% or +/- 2 standard deviations.
      +
      +
      +
      +
    • +
    • +
      +

      exactlyEqual

      +
      +
      public static <S extends Summary> boolean exactlyEqual(TupleSketch<S> sketchA, + TupleSketch<S> sketchB, + SummarySetOperations<S> summarySetOps)
      +
      Returns true if the two given sketches have exactly the same hash values and the same +theta values. Thus, they are equivalent.
      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      sketchA - The first argument, a TupleSketch with summary type S
      +
      sketchB - The second argument, a TupleSketch with summary type S
      +
      summarySetOps - instance of SummarySetOperations used to unify or intersect summaries.
      +
      Returns:
      +
      true if the two given sketches have exactly the same hash values and the same +theta values.
      +
      +
      +
      +
    • +
    • +
      +

      exactlyEqual

      +
      +
      public static <S extends Summary> boolean exactlyEqual(TupleSketch<S> sketchA, + ThetaSketch sketchB, + S summary, + SummarySetOperations<S> summarySetOps)
      +
      Returns true if the two given sketches have exactly the same hash values and the same +theta values. Thus, they are equivalent.
      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      sketchA - The first argument, a TupleSketch with summary type S
      +
      sketchB - The second argument, a ThetaSketch
      +
      summary - the given proxy summary for the ThetaSketch, which doesn't have one. +This may not be null.
      +
      summarySetOps - instance of SummarySetOperations used to unify or intersect summaries.
      +
      Returns:
      +
      true if the two given sketches have exactly the same hash values and the same +theta values.
      +
      +
      +
      +
    • +
    • +
      +

      similarityTest

      +
      +
      public static <S extends Summary> boolean similarityTest(TupleSketch<S> measured, + TupleSketch<S> expected, + SummarySetOperations<S> summarySetOps, + double threshold)
      +
      Tests similarity of a measured TupleSketch against an expected TupleSketch. +Computes the lower bound of the Jaccard index JLB of the measured and +expected sketches. +if JLB ≥ threshold, then the sketches are considered to be +similar with a confidence of 97.7%.
      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      measured - a TupleSketch with summary type S to be tested
      +
      expected - the reference TupleSketch with summary type S that is considered to be correct.
      +
      summarySetOps - instance of SummarySetOperations used to unify or intersect summaries.
      +
      threshold - a real value between zero and one.
      +
      Returns:
      +
      if true, the similarity of the two sketches is greater than the given threshold +with at least 97.7% confidence.
      +
      +
      +
      +
    • +
    • +
      +

      similarityTest

      +
      +
      public static <S extends Summary> boolean similarityTest(TupleSketch<S> measured, + ThetaSketch expected, + S summary, + SummarySetOperations<S> summarySetOps, + double threshold)
      +
      Tests similarity of a measured TupleSketch against an expected ThetaSketch. +Computes the lower bound of the Jaccard index JLB of the measured and +expected sketches. +if JLB ≥ threshold, then the sketches are considered to be +similar with a confidence of 97.7%.
      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      measured - a TupleSketch with summary type S to be tested
      +
      expected - the reference ThetaSketch that is considered to be correct.
      +
      summary - the given proxy summary for the ThetaSketch, which doesn't have one. +This may not be null.
      +
      summarySetOps - instance of SummarySetOperations used to unify or intersect summaries.
      +
      threshold - a real value between zero and one.
      +
      Returns:
      +
      if true, the similarity of the two sketches is greater than the given threshold +with at least 97.7% confidence.
      +
      +
      +
      +
    • +
    • +
      +

      dissimilarityTest

      +
      +
      public static <S extends Summary> boolean dissimilarityTest(TupleSketch<S> measured, + TupleSketch<S> expected, + SummarySetOperations<S> summarySetOps, + double threshold)
      +
      Tests dissimilarity of a measured TupleSketch against an expected TupleSketch. +Computes the upper bound of the Jaccard index JUB of the measured and +expected sketches. +if JUB ≤ threshold, then the sketches are considered to be +dissimilar with a confidence of 97.7%.
      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      measured - a TupleSketch with summary type S to be tested
      +
      expected - the reference TupleSketch that is considered to be correct.
      +
      summarySetOps - instance of SummarySetOperations used to unify or intersect summaries.
      +
      threshold - a real value between zero and one.
      +
      Returns:
      +
      if true, the dissimilarity of the two sketches is greater than the given threshold +with at least 97.7% confidence.
      +
      +
      +
      +
    • +
    • +
      +

      dissimilarityTest

      +
      +
      public static <S extends Summary> boolean dissimilarityTest(TupleSketch<S> measured, + ThetaSketch expected, + S summary, + SummarySetOperations<S> summarySetOps, + double threshold)
      +
      Tests dissimilarity of a measured TupleSketch against an expected ThetaSketch. +Computes the upper bound of the Jaccard index JUB of the measured and +expected sketches. +if JUB ≤ threshold, then the sketches are considered to be +dissimilar with a confidence of 97.7%.
      +
      +
      Type Parameters:
      +
      S - Summary
      +
      Parameters:
      +
      measured - a TupleSketch with summary type S to be tested
      +
      expected - the reference ThetaSketch that is considered to be correct.
      +
      summary - the given proxy summary for the ThetaSketch, which doesn't have one. +This may not be null.
      +
      summarySetOps - instance of SummarySetOperations used to unify or intersect summaries.
      +
      threshold - a real value between zero and one.
      +
      Returns:
      +
      if true, the dissimilarity of the two sketches is greater than the given threshold +with at least 97.7% confidence.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/SerializerDeserializer.SketchType.html b/target/site/apidocs/org/apache/datasketches/tuple/SerializerDeserializer.SketchType.html new file mode 100644 index 000000000..0006de479 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/SerializerDeserializer.SketchType.html @@ -0,0 +1,291 @@ + + + + +SerializerDeserializer.SketchType (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class SerializerDeserializer.SketchType

+
+
java.lang.Object +
java.lang.Enum<SerializerDeserializer.SketchType> +
org.apache.datasketches.tuple.SerializerDeserializer.SketchType
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<SerializerDeserializer.SketchType>, Constable
+
+
+
Enclosing class:
+
SerializerDeserializer
+
+
+
+
public static enum SerializerDeserializer.SketchType +extends Enum<SerializerDeserializer.SketchType>
+
Defines the sketch classes that this SerializerDeserializer can handle.
+
+
+
+ +
+
+
    + +
  • +
    +

    Enum Constant Details

    + +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static SerializerDeserializer.SketchType[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static SerializerDeserializer.SketchType valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/SerializerDeserializer.html b/target/site/apidocs/org/apache/datasketches/tuple/SerializerDeserializer.html new file mode 100644 index 000000000..fa5ebecc0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/SerializerDeserializer.html @@ -0,0 +1,246 @@ + + + + +SerializerDeserializer (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class SerializerDeserializer

+
+
java.lang.Object +
org.apache.datasketches.tuple.SerializerDeserializer
+
+
+
+
+
public final class SerializerDeserializer +extends Object
+
Multipurpose serializer-deserializer for a collection of sketches defined by the enum.
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      SerializerDeserializer

      +
      +
      public SerializerDeserializer()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      validateFamily

      +
      +
      public static void validateFamily(byte familyId, + byte preambleLongs)
      +
      Validates the preamble-Longs value given the family ID
      +
      +
      Parameters:
      +
      familyId - the given family ID
      +
      preambleLongs - the given preambleLongs value
      +
      +
      +
      +
    • +
    • +
      +

      validateType

      +
      +
      public static void validateType(byte sketchTypeByte, + SerializerDeserializer.SketchType expectedType)
      +
      Validates the sketch type byte versus the expected value
      +
      +
      Parameters:
      +
      sketchTypeByte - the given sketch type byte
      +
      expectedType - the expected value
      +
      +
      +
      +
    • +
    • +
      +

      getSketchType

      +
      +
      public static SerializerDeserializer.SketchType getSketchType(MemorySegment seg)
      +
      Gets the sketch type byte from the given MemorySegment image
      +
      +
      Parameters:
      +
      seg - the given MemorySegment image
      +
      Returns:
      +
      the SketchType
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/Summary.html b/target/site/apidocs/org/apache/datasketches/tuple/Summary.html new file mode 100644 index 000000000..88b47bc93 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/Summary.html @@ -0,0 +1,169 @@ + + + + +Summary (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface Summary

+
+
+
+
All Known Subinterfaces:
+
UpdatableSummary<U>
+
+
+
All Known Implementing Classes:
+
ArrayOfStringsSummary, DoubleSummary, IntegerSummary
+
+
+
+
public interface Summary
+
Interface for user-defined Summary, which is associated with every hash in a tuple sketch
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Deep copy.
    +
    +
    byte[]
    + +
    +
    This is to serialize a Summary instance to a byte array.
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      copy

      +
      +
      Summary copy()
      +
      Deep copy. + +

      Caution: This must implement a deep copy.

      +
      +
      Returns:
      +
      deep copy of the Summary
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      byte[] toByteArray()
      +
      This is to serialize a Summary instance to a byte array. + +

      The user should encode in the byte array its total size, which is used during +deserialization, especially if the Summary has variable sized elements.

      +
      +
      Returns:
      +
      serialized representation of the Summary
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/SummaryDeserializer.html b/target/site/apidocs/org/apache/datasketches/tuple/SummaryDeserializer.html new file mode 100644 index 000000000..21d262125 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/SummaryDeserializer.html @@ -0,0 +1,152 @@ + + + + +SummaryDeserializer (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface SummaryDeserializer<S extends Summary>

+
+
+
+
Type Parameters:
+
S - type of Summary
+
+
+
All Known Implementing Classes:
+
ArrayOfStringsSummaryDeserializer, DoubleSummaryDeserializer, IntegerSummaryDeserializer
+
+
+
+
public interface SummaryDeserializer<S extends Summary>
+
Interface for deserializing user-defined Summary
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    This is to create an instance of a Summary given a serialized representation.
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapifySummary

      +
      +
      DeserializeResult<S> heapifySummary(MemorySegment seg)
      +
      This is to create an instance of a Summary given a serialized representation. +The user may assume that the start of the given MemorySegment is the correct place to start +deserializing. However, the user must be able to determine the number of bytes required to +deserialize the summary as the capacity of the given MemorySegment may +include multiple such summaries and may be much larger than required for a single summary.
      +
      +
      Parameters:
      +
      seg - MemorySegment object with serialized representation of a Summary
      +
      Returns:
      +
      DeserializedResult object, which contains a Summary object and number of bytes read +from the MemorySegment
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/SummaryFactory.html b/target/site/apidocs/org/apache/datasketches/tuple/SummaryFactory.html new file mode 100644 index 000000000..958f2a72d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/SummaryFactory.html @@ -0,0 +1,145 @@ + + + + +SummaryFactory (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface SummaryFactory<S extends Summary>

+
+
+
+
Type Parameters:
+
S - type of Summary
+
+
+
All Known Implementing Classes:
+
ArrayOfStringsSummaryFactory, DoubleSummaryFactory, IntegerSummaryFactory
+
+
+
+
public interface SummaryFactory<S extends Summary>
+
Interface for user-defined SummaryFactory
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Returns new instance of Summary
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      newSummary

      +
      +
      S newSummary()
      +
      Returns new instance of Summary
      +
      +
      Returns:
      +
      new instance of Summary
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/SummarySetOperations.html b/target/site/apidocs/org/apache/datasketches/tuple/SummarySetOperations.html new file mode 100644 index 000000000..2b6d91b50 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/SummarySetOperations.html @@ -0,0 +1,184 @@ + + + + +SummarySetOperations (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface SummarySetOperations<S extends Summary>

+
+
+
+
Type Parameters:
+
S - type of Summary
+
+
+
All Known Implementing Classes:
+
ArrayOfStringsSummarySetOperations, DoubleSummarySetOperations, IntegerSummarySetOperations
+
+
+
+
public interface SummarySetOperations<S extends Summary>
+
This is to provide methods of producing unions and intersections of two Summary objects.
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + +
    intersection(S a, + S b)
    +
    +
    This is called by the intersection operator when both sketches have the same hash value.
    +
    + +
    union(S a, + S b)
    +
    +
    This is called by the union operator when both sketches have the same hash value.
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      union

      +
      +
      S union(S a, + S b)
      +
      This is called by the union operator when both sketches have the same hash value. + +

      Caution: Do not modify the input Summary objects. Also do not return them directly, +unless they are immutable (most Summary objects are not). For mutable Summary objects, it is +important to create a new Summary object with the correct contents to be returned. Do not +return null summaries.

      +
      +
      Parameters:
      +
      a - Summary from sketch A
      +
      b - Summary from sketch B
      +
      Returns:
      +
      union of Summary A and Summary B
      +
      +
      +
      +
    • +
    • +
      +

      intersection

      +
      +
      S intersection(S a, + S b)
      +
      This is called by the intersection operator when both sketches have the same hash value. + +

      Caution: Do not modify the input Summary objects. Also do not return them directly, +unless they are immutable (most Summary objects are not). For mutable Summary objects, it is +important to create a new Summary object with the correct contents to be returned. Do not +return null summaries.

      +
      +
      Parameters:
      +
      a - Summary from sketch A
      +
      b - Summary from sketch B
      +
      Returns:
      +
      intersection of Summary A and Summary B
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/TupleAnotB.html b/target/site/apidocs/org/apache/datasketches/tuple/TupleAnotB.html new file mode 100644 index 000000000..abe784a4c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/TupleAnotB.html @@ -0,0 +1,426 @@ + + + + +TupleAnotB (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class TupleAnotB<S extends Summary>

+
+
java.lang.Object +
org.apache.datasketches.tuple.TupleAnotB<S>
+
+
+
+
Type Parameters:
+
S - Type of Summary
+
+
+
+
public final class TupleAnotB<S extends Summary> +extends Object
+
Computes a set difference, A-AND-NOT-B, of two generic TupleSketches. +This class includes both stateful and stateless operations. + +

The stateful operation is as in the following example:

+
TupleAnotB anotb = new TupleAnotB();
+
+anotb.setA(TupleSketch skA); //The first argument.
+anotb.notB(TupleSketch skB); //The second (subtraction) argument.
+anotb.notB(TupleSketch skC); // ...any number of additional subtractions...
+anotb.getResult(false); //Get an interim result.
+anotb.notB(TupleSketch skD); //Additional subtractions.
+anotb.getResult(true);  //Final result and resets the TupleAnotB operator.
+
+ +

The stateless operation is as in the following example:

+
TupleAnotB anotb = new TupleAnotB();
+
+CompactTupleSketch csk = anotb.aNotB(TupleSketch skA, TupleSketch skB);
+
+ +

Calling the setA operation a second time essentially clears the internal state and loads +the new sketch.

+ +

The stateless and stateful operations are independent of each other.

+
+
Author:
+
Lee Rhodes
+
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    No argument constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static <S extends Summary>
    CompactTupleSketch<S>
    +
    aNotB(TupleSketch<S> skA, + ThetaSketch skB)
    +
    +
    Returns the A-and-not-B set operation on a TupleSketch and a ThetaSketch.
    +
    +
    static <S extends Summary>
    CompactTupleSketch<S>
    +
    aNotB(TupleSketch<S> skA, + TupleSketch<S> skB)
    +
    +
    Returns the A-and-not-B set operation on the two given TupleSketches.
    +
    + +
    getResult(boolean reset)
    +
    +
    Gets the result of the multistep, stateful operation TupleAnotB that have been executed with calls +to setA(TupleSketch) and (notB(TupleSketch) or +notB(ThetaSketch)).
    +
    +
    void
    + +
    +
    This is part of a multistep, stateful TupleAnotB operation and sets the given ThetaSketch as the +second (or n+1th) argument B of A-AND-NOT-B.
    +
    +
    void
    + +
    +
    This is part of a multistep, stateful TupleAnotB operation and sets the given TupleSketch as the +second (or n+1th) argument B of A-AND-NOT-B.
    +
    +
    void
    + +
    +
    Resets this operation back to the empty state.
    +
    +
    void
    + +
    +
    This is part of a multistep, stateful TupleAnotB operation and sets the given TupleSketch as the +first argument A of A-AND-NOT-B.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      TupleAnotB

      +
      +
      public TupleAnotB()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      setA

      +
      +
      public void setA(TupleSketch<S> skA)
      +
      This is part of a multistep, stateful TupleAnotB operation and sets the given TupleSketch as the +first argument A of A-AND-NOT-B. This overwrites the internal state of this +TupleAnotB operator with the contents of the given sketch. +This sets the stage for multiple following notB steps. + +

      An input argument of null will throw an exception.

      + +

      Rationale: In mathematics a "null set" is a set with no members, which we call an empty set. +That is distinctly different from the java null, which represents a nonexistent object. +In most cases it is a programming error due to some object that was not properly initialized. +With a null as the first argument, we cannot know what the user's intent is. +Since it is very likely that a null is a programming error, we throw a an exception.

      + +

      An empty input argument will set the internal state to empty.

      + +

      Rationale: An empty set is a mathematically legal concept. Although it makes any subsequent, +valid argument for B irrelevant, we must allow this and assume the user knows what they are +doing.

      + +

      Performing getResult(boolean) just after this step will return a compact form of +the given argument.

      +
      +
      Parameters:
      +
      skA - The incoming sketch for the first argument, A.
      +
      +
      +
      +
    • +
    • +
      +

      notB

      +
      +
      public void notB(TupleSketch<S> skB)
      +
      This is part of a multistep, stateful TupleAnotB operation and sets the given TupleSketch as the +second (or n+1th) argument B of A-AND-NOT-B. +Performs an AND NOT operation with the existing internal state of this TupleAnotB operator. + +

      An input argument of null or empty is ignored.

      + +

      Rationale: A null for the second or following arguments is more tolerable because +A NOT null is still A even if we don't know exactly what the null represents. It +clearly does not have any content that overlaps with A. Also, because this can be part of +a multistep operation with multiple notB steps. Other following steps can still produce +a valid result.

      + +

      Use getResult(boolean) to obtain the result.

      +
      +
      Parameters:
      +
      skB - The incoming Tuple sketch for the second (or following) argument B.
      +
      +
      +
      +
    • +
    • +
      +

      notB

      +
      +
      public void notB(ThetaSketch skB)
      +
      This is part of a multistep, stateful TupleAnotB operation and sets the given ThetaSketch as the +second (or n+1th) argument B of A-AND-NOT-B. +Performs an AND NOT operation with the existing internal state of this TupleAnotB operator. +Calls to this method can be intermingled with calls to +notB(ThetaSketch). + +

      An input argument of null or empty is ignored.

      + +

      Rationale: A null for the second or following arguments is more tolerable because +A NOT null is still A even if we don't know exactly what the null represents. It +clearly does not have any content that overlaps with A. Also, because this can be part of +a multistep operation with multiple notB steps. Other following steps can still produce +a valid result.

      + +

      Use getResult(boolean) to obtain the result.

      +
      +
      Parameters:
      +
      skB - The incoming ThetaSketch for the second (or following) argument B.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public CompactTupleSketch<S> getResult(boolean reset)
      +
      Gets the result of the multistep, stateful operation TupleAnotB that have been executed with calls +to setA(TupleSketch) and (notB(TupleSketch) or +notB(ThetaSketch)).
      +
      +
      Parameters:
      +
      reset - If true, clears this operator to the empty state after this result is +returned. Set this to false if you wish to obtain an intermediate result.
      +
      Returns:
      +
      the result of this operation as an unordered CompactTupleSketch.
      +
      +
      +
      +
    • +
    • +
      +

      aNotB

      +
      +
      public static <S extends Summary> +CompactTupleSketch<S> aNotB(TupleSketch<S> skA, + TupleSketch<S> skB)
      +
      Returns the A-and-not-B set operation on the two given TupleSketches. + +

      This a stateless operation and has no impact on the internal state of this operator. +Thus, this is not an accumulating update and is independent of the setA(TupleSketch), +notB(TupleSketch), notB(ThetaSketch), and +getResult(boolean) methods.

      + +

      If either argument is null an exception is thrown.

      + +

      Rationale: In mathematics a "null set" is a set with no members, which we call an empty set. +That is distinctly different from the java null, which represents a nonexistent object. +In most cases it is a programming error due to some object that was not properly initialized. +With a null as the first argument, we cannot know what the user's intent is. +With a null as the second argument, we can't ignore it as we must return a result and there is +no following possible viable arguments for the second argument. +Since it is very likely that a null is a programming error, we throw an exception.

      +
      +
      Type Parameters:
      +
      S - Type of Summary
      +
      Parameters:
      +
      skA - The incoming TupleSketch for the first argument
      +
      skB - The incoming TupleSketch for the second argument
      +
      Returns:
      +
      the result as an unordered CompactTupleSketch
      +
      +
      +
      +
    • +
    • +
      +

      aNotB

      +
      +
      public static <S extends Summary> +CompactTupleSketch<S> aNotB(TupleSketch<S> skA, + ThetaSketch skB)
      +
      Returns the A-and-not-B set operation on a TupleSketch and a ThetaSketch. + +

      This a stateless operation and has no impact on the internal state of this operator. +Thus, this is not an accumulating update and is independent of the setA(TupleSketch), +notB(TupleSketch), notB(ThetaSketch), and +getResult(boolean) methods.

      + +

      If either argument is null an exception is thrown.

      + +

      Rationale: In mathematics a "null set" is a set with no members, which we call an empty set. +That is distinctly different from the java null, which represents a nonexistent object. +In most cases it is a programming error due to some object that was not properly initialized. +With a null as the first argument, we cannot know what the user's intent is. +With a null as the second argument, we can't ignore it as we must return a result and there is +no following possible viable arguments for the second argument. +Since it is very likely that a null is a programming error for either argument +we throw a an exception.

      +
      +
      Type Parameters:
      +
      S - Type of Summary
      +
      Parameters:
      +
      skA - The incoming TupleSketch for the first argument
      +
      skB - The incoming ThetaSketch for the second argument
      +
      Returns:
      +
      the result as an unordered CompactTupleSketch
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this operation back to the empty state.
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/TupleIntersection.html b/target/site/apidocs/org/apache/datasketches/tuple/TupleIntersection.html new file mode 100644 index 000000000..0469c8f54 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/TupleIntersection.html @@ -0,0 +1,331 @@ + + + + +TupleIntersection (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class TupleIntersection<S extends Summary>

+
+
java.lang.Object +
org.apache.datasketches.tuple.TupleIntersection<S>
+
+
+
+
Type Parameters:
+
S - Type of Summary
+
+
+
+
public class TupleIntersection<S extends Summary> +extends Object
+
Computes an intersection of two or more generic TupleSketches or generic TupleSketches +combined with ThetaSketches. +A new instance represents the Universal Set. Because the Universal Set +cannot be realized a getResult() on a new instance will produce an error. +Every update() computes an intersection with the internal state, which will never +grow larger and may be reduced to zero.
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    Creates new TupleIntersection instance with instructions on how to process two summaries that intersect.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Gets the internal set as an unordered CompactTupleSketch
    +
    +
    boolean
    + +
    +
    Returns true if there is a valid intersection result available
    +
    +
    void
    +
    intersect(ThetaSketch thetaSketch, + S summary)
    +
    +
    Performs a stateful intersection of the internal set with the given ThetaSketch by combining entries +using the hashes from the ThetaSketch and summary values from the given summary and rules +from the summarySetOps defined by the TupleIntersection constructor.
    +
    +
    void
    +
    intersect(TupleSketch<S> tupleSketch)
    +
    +
    Performs a stateful intersection of the internal set with the given TupleSketch.
    +
    + +
    intersect(TupleSketch<S> tupleSketch, + ThetaSketch thetaSketch, + S summary)
    +
    +
    Perform a stateless intersect set operation on a TupleSketch and a ThetaSketch and returns the +result as an unordered CompactTupleSketch on the heap.
    +
    + +
    intersect(TupleSketch<S> tupleSketchA, + TupleSketch<S> tupleSketchB)
    +
    +
    Perform a stateless intersect set operation on the two given TupleSketches and returns the +result as an unordered CompactTupleSketch on the heap.
    +
    +
    void
    + +
    +
    Resets the internal set to the initial state, which represents the Universal Set
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      TupleIntersection

      +
      +
      public TupleIntersection(SummarySetOperations<S> summarySetOps)
      +
      Creates new TupleIntersection instance with instructions on how to process two summaries that intersect.
      +
      +
      Parameters:
      +
      summarySetOps - instance of SummarySetOperations
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      intersect

      +
      +
      public CompactTupleSketch<S> intersect(TupleSketch<S> tupleSketchA, + TupleSketch<S> tupleSketchB)
      +
      Perform a stateless intersect set operation on the two given TupleSketches and returns the +result as an unordered CompactTupleSketch on the heap.
      +
      +
      Parameters:
      +
      tupleSketchA - The first sketch argument. It must not be null.
      +
      tupleSketchB - The second sketch argument. It must not be null.
      +
      Returns:
      +
      an unordered CompactTupleSketch on the heap
      +
      +
      +
      +
    • +
    • +
      +

      intersect

      +
      +
      public CompactTupleSketch<S> intersect(TupleSketch<S> tupleSketch, + ThetaSketch thetaSketch, + S summary)
      +
      Perform a stateless intersect set operation on a TupleSketch and a ThetaSketch and returns the +result as an unordered CompactTupleSketch on the heap.
      +
      +
      Parameters:
      +
      tupleSketch - The first sketch argument. It must not be null.
      +
      thetaSketch - The second sketch argument. It must not be null.
      +
      summary - the given proxy summary for the ThetaSketch, which doesn't have one. +This must not be null.
      +
      Returns:
      +
      an unordered CompactTupleSketch on the heap
      +
      +
      +
      +
    • +
    • +
      +

      intersect

      +
      +
      public void intersect(TupleSketch<S> tupleSketch)
      +
      Performs a stateful intersection of the internal set with the given TupleSketch.
      +
      +
      Parameters:
      +
      tupleSketch - input sketch to intersect with the internal state. It must not be null.
      +
      +
      +
      +
    • +
    • +
      +

      intersect

      +
      +
      public void intersect(ThetaSketch thetaSketch, + S summary)
      +
      Performs a stateful intersection of the internal set with the given ThetaSketch by combining entries +using the hashes from the ThetaSketch and summary values from the given summary and rules +from the summarySetOps defined by the TupleIntersection constructor.
      +
      +
      Parameters:
      +
      thetaSketch - input ThetaSketch to intersect with the internal state. It must not be null.
      +
      summary - the given proxy summary for the theta sketch, which doesn't have one. +It will be copied for each matching index. It must not be null.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public CompactTupleSketch<S> getResult()
      +
      Gets the internal set as an unordered CompactTupleSketch
      +
      +
      Returns:
      +
      result of the intersections so far
      +
      +
      +
      +
    • +
    • +
      +

      hasResult

      +
      +
      public boolean hasResult()
      +
      Returns true if there is a valid intersection result available
      +
      +
      Returns:
      +
      true if there is a valid intersection result available
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets the internal set to the initial state, which represents the Universal Set
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/TupleSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/TupleSketch.html new file mode 100644 index 000000000..57e9a5b62 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/TupleSketch.html @@ -0,0 +1,571 @@ + + + + +TupleSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class TupleSketch<S extends Summary>

+
+
java.lang.Object +
org.apache.datasketches.tuple.TupleSketch<S>
+
+
+
+
Type Parameters:
+
S - Type of Summary
+
+
+
Direct Known Subclasses:
+
CompactTupleSketch, UpdatableTupleSketch
+
+
+
+
public abstract class TupleSketch<S extends Summary> +extends Object
+
The top-level class for all Tuple sketches. This class is never constructed directly. +Use the UpdatableTupleSketchBuilder() methods to create UpdatableTupleSketches. +This is similar to ThetaSketch with +addition of a user-defined Summary object associated with every unique entry +in the sketch.
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Converts this TupleSketch to a CompactTupleSketch on the Java heap.
    +
    +
    static <S extends Summary>
    TupleSketch<S>
    + +
    +
    Creates an empty CompactTupleSketch.
    +
    +
    abstract int
    +
    getCountLessThanThetaLong(long thetaLong)
    +
    +
    Gets the number of hash values less than the given theta expressed as a long.
    +
    +
    double
    + +
    +
    Estimates the cardinality of the set (number of unique values presented to the sketch)
    +
    +
    double
    +
    getEstimate(int numSubsetEntries)
    +
    +
    Gets the estimate of the true distinct population of subset tuples represented by the count +of entries in a subset of the total retained entries of the sketch.
    +
    +
    double
    +
    getLowerBound(int numStdDev)
    +
    +
    Gets the approximate lower error bound given the specified number of Standard Deviations.
    +
    +
    double
    +
    getLowerBound(int numStdDev, + int numSubsetEntries)
    +
    +
    Gets the estimate of the lower bound of the true distinct population represented by the count +of entries in a subset of the total retained entries of the sketch.
    +
    +
    abstract int
    + +
    +
    Returns number of retained entries
    +
    + + +
    +
    Gets the Summary Factory class of type S
    +
    +
    double
    + +
    +
    Gets the value of theta as a double between zero and one
    +
    +
    long
    + +
    +
    Returns Theta as a long
    +
    +
    double
    +
    getUpperBound(int numStdDev)
    +
    +
    Gets the approximate upper error bound given the specified number of Standard Deviations.
    +
    +
    double
    +
    getUpperBound(int numStdDev, + int numSubsetEntries)
    +
    +
    Gets the estimate of the upper bound of the true distinct population represented by the count +of entries in a subset of the total retained entries of the sketch.
    +
    +
    static <S extends Summary>
    TupleSketch<S>
    + +
    +
    Instantiate a TupleSketch from a given MemorySegment.
    +
    +
    static <U, S extends UpdatableSummary<U>>
    UpdatableTupleSketch<U,S>
    +
    heapifyUpdatableSketch(MemorySegment seg, + SummaryDeserializer<S> deserializer, + SummaryFactory<S> summaryFactory)
    +
    +
    Instantiate an UpdatableTupleSketch from a given MemorySegment on the heap,
    +
    +
    boolean
    + + +
    boolean
    + +
    +
    Returns true if the sketch is Estimation Mode (as opposed to Exact Mode).
    +
    + + +
    +
    Returns a SketchIterator
    +
    +
    abstract byte[]
    + +
    +
    Serialize this sketch to a byte array.
    +
    + + +
     
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      compact

      +
      +
      public abstract CompactTupleSketch<S> compact()
      +
      Converts this TupleSketch to a CompactTupleSketch on the Java heap. + +

      If this sketch is already in compact form this operation returns this.

      +
      +
      Returns:
      +
      this sketch as a CompactTupleSketch on the Java heap.
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public double getEstimate()
      +
      Estimates the cardinality of the set (number of unique values presented to the sketch)
      +
      +
      Returns:
      +
      best estimate of the number of unique values
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public double getUpperBound(int numStdDev)
      +
      Gets the approximate upper error bound given the specified number of Standard Deviations. +This will return getEstimate() if isEmpty() is true.
      +
      +
      Parameters:
      +
      numStdDev - See Number of Standard Deviations
      +
      Returns:
      +
      the upper bound.
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public double getLowerBound(int numStdDev)
      +
      Gets the approximate lower error bound given the specified number of Standard Deviations. +This will return getEstimate() if isEmpty() is true.
      +
      +
      Parameters:
      +
      numStdDev - See Number of Standard Deviations
      +
      Returns:
      +
      the lower bound.
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public double getEstimate(int numSubsetEntries)
      +
      Gets the estimate of the true distinct population of subset tuples represented by the count +of entries in a subset of the total retained entries of the sketch.
      +
      +
      Parameters:
      +
      numSubsetEntries - number of entries for a chosen subset of the sketch.
      +
      Returns:
      +
      the estimate of the true distinct population of subset tuples represented by the count +of entries in a subset of the total retained entries of the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public double getLowerBound(int numStdDev, + int numSubsetEntries)
      +
      Gets the estimate of the lower bound of the true distinct population represented by the count +of entries in a subset of the total retained entries of the sketch.
      +
      +
      Parameters:
      +
      numStdDev - See Number of Standard Deviations
      +
      numSubsetEntries - number of entries for a chosen subset of the sketch.
      +
      Returns:
      +
      the estimate of the lower bound of the true distinct population represented by the count +of entries in a subset of the total retained entries of the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public double getUpperBound(int numStdDev, + int numSubsetEntries)
      +
      Gets the estimate of the upper bound of the true distinct population represented by the count +of entries in a subset of the total retained entries of the sketch.
      +
      +
      Parameters:
      +
      numStdDev - See Number of Standard Deviations
      +
      numSubsetEntries - number of entries for a chosen subset of the sketch.
      +
      Returns:
      +
      the estimate of the upper bound of the true distinct population represented by the count +of entries in a subset of the total retained entries of the sketch.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      + +
      +
      Returns:
      +
      true if empty.
      +
      +
      +
      +
    • +
    • +
      +

      isEstimationMode

      +
      +
      public boolean isEstimationMode()
      +
      Returns true if the sketch is Estimation Mode (as opposed to Exact Mode). +This is true if theta < 1.0 AND isEmpty() is false.
      +
      +
      Returns:
      +
      true if the sketch is in estimation mode.
      +
      +
      +
      +
    • +
    • +
      +

      getRetainedEntries

      +
      +
      public abstract int getRetainedEntries()
      +
      Returns number of retained entries
      +
      +
      Returns:
      +
      number of retained entries
      +
      +
      +
      +
    • +
    • +
      +

      getCountLessThanThetaLong

      +
      +
      public abstract int getCountLessThanThetaLong(long thetaLong)
      +
      Gets the number of hash values less than the given theta expressed as a long.
      +
      +
      Parameters:
      +
      thetaLong - the given theta as a long in the range (zero, Long.MAX_VALUE].
      +
      Returns:
      +
      the number of hash values less than the given thetaLong.
      +
      +
      +
      +
    • +
    • +
      +

      getSummaryFactory

      +
      +
      public SummaryFactory<S> getSummaryFactory()
      +
      Gets the Summary Factory class of type S
      +
      +
      Returns:
      +
      the Summary Factory class of type S
      +
      +
      +
      +
    • +
    • +
      +

      getTheta

      +
      +
      public double getTheta()
      +
      Gets the value of theta as a double between zero and one
      +
      +
      Returns:
      +
      the value of theta as a double
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public abstract byte[] toByteArray()
      +
      Serialize this sketch to a byte array. + +

      As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Serializing a CompactTupleSketch is not deprecated.

      +
      +
      Returns:
      +
      serialized representation of this sketch.
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public abstract TupleSketchIterator<S> iterator()
      +
      Returns a SketchIterator
      +
      +
      Returns:
      +
      a SketchIterator
      +
      +
      +
      +
    • +
    • +
      +

      getThetaLong

      +
      +
      public long getThetaLong()
      +
      Returns Theta as a long
      +
      +
      Returns:
      +
      Theta as a long
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    • +
      +

      heapifyUpdatableSketch

      +
      +
      public static <U, S extends UpdatableSummary<U>> +UpdatableTupleSketch<U,S> heapifyUpdatableSketch(MemorySegment seg, + SummaryDeserializer<S> deserializer, + SummaryFactory<S> summaryFactory)
      +
      Instantiate an UpdatableTupleSketch from a given MemorySegment on the heap,
      +
      +
      Type Parameters:
      +
      U - Type of update value
      +
      S - Type of Summary
      +
      Parameters:
      +
      seg - MemorySegment object representing an UpdatableTupleSketch
      +
      deserializer - instance of SummaryDeserializer
      +
      summaryFactory - instance of SummaryFactory
      +
      Returns:
      +
      UpdatableTupleSketch created from its MemorySegment representation
      +
      +
      +
      +
    • +
    • +
      +

      heapifySketch

      +
      +
      public static <S extends Summary> TupleSketch<S> heapifySketch(MemorySegment seg, + SummaryDeserializer<S> deserializer)
      +
      Instantiate a TupleSketch from a given MemorySegment.
      +
      +
      Type Parameters:
      +
      S - Type of Summary
      +
      Parameters:
      +
      seg - MemorySegment object representing a TupleSketch
      +
      deserializer - instance of SummaryDeserializer
      +
      Returns:
      +
      TupleSketch created from its MemorySegment representation
      +
      +
      +
      +
    • +
    • +
      +

      createEmptySketch

      +
      +
      public static <S extends Summary> TupleSketch<S> createEmptySketch()
      +
      Creates an empty CompactTupleSketch.
      +
      +
      Type Parameters:
      +
      S - Type of Summary
      +
      Returns:
      +
      an empty instance of a CompactTupleSketch
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/TupleSketchIterator.html b/target/site/apidocs/org/apache/datasketches/tuple/TupleSketchIterator.html new file mode 100644 index 000000000..d9f941dad --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/TupleSketchIterator.html @@ -0,0 +1,195 @@ + + + + +TupleSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class TupleSketchIterator<S extends Summary>

+
+
java.lang.Object +
org.apache.datasketches.tuple.TupleSketchIterator<S>
+
+
+
+
Type Parameters:
+
S - Type of Summary
+
+
+
+
public class TupleSketchIterator<S extends Summary> +extends Object
+
Iterator over a generic tuple sketch
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    long
    + +
    +
    Gets the hash from the current entry in the sketch, which is a hash +of the original key passed to update().
    +
    + + +
    +
    Gets a Summary object from the current entry in the sketch.
    +
    +
    boolean
    + +
    +
    Advancing the iterator and checking existence of the next entry +is combined here for efficiency.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      next

      +
      +
      public boolean next()
      +
      Advancing the iterator and checking existence of the next entry +is combined here for efficiency. This results in an undefined +state of the iterator before the first call of this method.
      +
      +
      Returns:
      +
      true if the next element exists
      +
      +
      +
      +
    • +
    • +
      +

      getHash

      +
      +
      public long getHash()
      +
      Gets the hash from the current entry in the sketch, which is a hash +of the original key passed to update(). The original keys are not +retained. Don't call this before calling next() for the first time +or after getting false from next().
      +
      +
      Returns:
      +
      hash from the current entry
      +
      +
      +
      +
    • +
    • +
      +

      getSummary

      +
      +
      public S getSummary()
      +
      Gets a Summary object from the current entry in the sketch. +Don't call this before calling next() for the first time +or after getting false from next().
      +
      +
      Returns:
      +
      Summary object for the current entry (this is not a copy!)
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/TupleUnion.html b/target/site/apidocs/org/apache/datasketches/tuple/TupleUnion.html new file mode 100644 index 000000000..1204ab838 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/TupleUnion.html @@ -0,0 +1,357 @@ + + + + +TupleUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class TupleUnion<S extends Summary>

+
+
java.lang.Object +
org.apache.datasketches.tuple.TupleUnion<S>
+
+
+
+
Type Parameters:
+
S - Type of Summary
+
+
+
+
public class TupleUnion<S extends Summary> +extends Object
+
Compute the union of two or more generic tuple sketches or generic TupleSketches combined with +ThetaSketches. A new instance represents an empty set.
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    +
    TupleUnion(int nomEntries, + SummarySetOperations<S> summarySetOps)
    +
    +
    Creates new TupleUnion instance.
    +
    + +
    +
    Creates new TupleUnion instance with instructions on how to process two summaries that +overlap.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + + +
    +
    Gets the result of a sequence of stateful union operations as an unordered CompactTupleSketch
    +
    + +
    getResult(boolean reset)
    +
    +
    Gets the result of a sequence of stateful union operations as an unordered CompactTupleSketch.
    +
    +
    void
    + +
    +
    Resets the internal set to the initial state, which represents an empty set.
    +
    +
    void
    +
    union(ThetaSketch thetaSketch, + S summary)
    +
    +
    Performs a stateful union of the internal set with the given ThetaSketch by combining entries +using the hashes from the ThetaSketch and summary values from the given summary.
    +
    +
    void
    +
    union(TupleSketch<S> tupleSketch)
    +
    +
    Performs a stateful union of the internal set with the given TupleSketch.
    +
    + +
    union(TupleSketch<S> tupleSketch, + ThetaSketch thetaSketch, + S summary)
    +
    +
    Perform a stateless, pair-wise union operation between a tupleSketch and a ThetaSketch.
    +
    + +
    union(TupleSketch<S> tupleSketchA, + TupleSketch<S> tupleSketchB)
    +
    +
    Perform a stateless, pair-wise union operation between two tuple sketches.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      TupleUnion

      +
      +
      public TupleUnion(SummarySetOperations<S> summarySetOps)
      +
      Creates new TupleUnion instance with instructions on how to process two summaries that +overlap. This will have the default nominal entries (K).
      +
      +
      Parameters:
      +
      summarySetOps - instance of SummarySetOperations
      +
      +
      +
      +
    • +
    • +
      +

      TupleUnion

      +
      +
      public TupleUnion(int nomEntries, + SummarySetOperations<S> summarySetOps)
      +
      Creates new TupleUnion instance.
      +
      +
      Parameters:
      +
      nomEntries - nominal entries (K). Forced to the nearest power of 2 greater than +given value.
      +
      summarySetOps - instance of SummarySetOperations
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      union

      +
      +
      public CompactTupleSketch<S> union(TupleSketch<S> tupleSketchA, + TupleSketch<S> tupleSketchB)
      +
      Perform a stateless, pair-wise union operation between two tuple sketches. +The returned sketch will be cut back to the smaller of the two k values if required. + +

      Nulls and empty sketches are ignored.

      +
      +
      Parameters:
      +
      tupleSketchA - The first argument
      +
      tupleSketchB - The second argument
      +
      Returns:
      +
      the result ordered CompactTupleSketch on the heap.
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public CompactTupleSketch<S> union(TupleSketch<S> tupleSketch, + ThetaSketch thetaSketch, + S summary)
      +
      Perform a stateless, pair-wise union operation between a tupleSketch and a ThetaSketch. +The returned sketch will be cut back to the smaller of the two k values if required. + +

      Nulls and empty sketches are ignored.

      +
      +
      Parameters:
      +
      tupleSketch - The first argument
      +
      thetaSketch - The second argument
      +
      summary - the given proxy summary for the ThetaSketch, which doesn't have one. +This may not be null.
      +
      Returns:
      +
      the result ordered CompactTupleSketch on the heap.
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public void union(TupleSketch<S> tupleSketch)
      +
      Performs a stateful union of the internal set with the given TupleSketch.
      +
      +
      Parameters:
      +
      tupleSketch - input tuple sketch to merge with the internal set. +Nulls and empty sketches are ignored.
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public void union(ThetaSketch thetaSketch, + S summary)
      +
      Performs a stateful union of the internal set with the given ThetaSketch by combining entries +using the hashes from the ThetaSketch and summary values from the given summary.
      +
      +
      Parameters:
      +
      thetaSketch - the given ThetaSketch input. If null or empty, it is ignored.
      +
      summary - the given proxy summary for the ThetaSketch, which doesn't have one. This may +not be null.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public CompactTupleSketch<S> getResult()
      +
      Gets the result of a sequence of stateful union operations as an unordered CompactTupleSketch
      +
      +
      Returns:
      +
      result of the stateful unions so far. The state of this operation is not reset after the +result is returned.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public CompactTupleSketch<S> getResult(boolean reset)
      +
      Gets the result of a sequence of stateful union operations as an unordered CompactTupleSketch.
      +
      +
      Parameters:
      +
      reset - If true, clears this operator to the empty state after this result is +returned. Set this to false if you wish to obtain an intermediate result.
      +
      Returns:
      +
      result of the stateful union
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets the internal set to the initial state, which represents an empty set. This is only useful +after sequences of stateful union operations.
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/UpdatableSummary.html b/target/site/apidocs/org/apache/datasketches/tuple/UpdatableSummary.html new file mode 100644 index 000000000..e9ce6448b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/UpdatableSummary.html @@ -0,0 +1,156 @@ + + + + +UpdatableSummary (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface UpdatableSummary<U>

+
+
+
+
Type Parameters:
+
U - type of update value
+
+
+
All Superinterfaces:
+
Summary
+
+
+
All Known Implementing Classes:
+
ArrayOfStringsSummary, DoubleSummary, IntegerSummary
+
+
+
+
public interface UpdatableSummary<U> +extends Summary
+
Interface for updating user-defined Summary
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    + +
    update(U value)
    +
    +
    This is to provide a method of updating summaries.
    +
    +
    +
    +
    +
    +

    Methods inherited from interface Summary

    +copy, toByteArray
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      update

      +
      +
      UpdatableSummary<U> update(U value)
      +
      This is to provide a method of updating summaries. +This is primarily used internally.
      +
      +
      Parameters:
      +
      value - update value
      +
      Returns:
      +
      this
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/UpdatableTupleSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/UpdatableTupleSketch.html new file mode 100644 index 000000000..988d83e94 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/UpdatableTupleSketch.html @@ -0,0 +1,677 @@ + + + + +UpdatableTupleSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class UpdatableTupleSketch<U, S extends UpdatableSummary<U>>

+
+
java.lang.Object +
org.apache.datasketches.tuple.TupleSketch<S> +
org.apache.datasketches.tuple.UpdatableTupleSketch<U,S>
+
+
+
+
+
Type Parameters:
+
U - Type of the value, which is passed to update method of a Summary
+
S - Type of the UpdatableSummary<U>
+
+
+
Direct Known Subclasses:
+
ArrayOfStringsTupleSketch, DoubleTupleSketch, IntegerTupleSketch
+
+
+
+
public class UpdatableTupleSketch<U, S extends UpdatableSummary<U>> +extends TupleSketch<S>
+
An extension of QuickSelectSketch<S>, which can be updated with many types of keys. +Summary objects are created using a user-defined SummaryFactory class, +which should allow very flexible parameterization if needed. +Keys are presented to a sketch along with values of a user-defined +update type U. When an entry is inserted into a sketch or a duplicate key is +presented to a sketch then summary.update(U value) method will be called. So +any kind of user-defined accumulation is possible. Summaries also must know +how to copy themselves. Also union and intersection of summaries can be +implemented in a sub-class of SummarySetOperations, which will be used in +case TupleUnion or TupleIntersection of two instances of TupleSketch is needed
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      UpdatableTupleSketch

      +
      +
      public UpdatableTupleSketch(int nomEntries, + int lgResizeFactor, + float samplingProbability, + SummaryFactory<S> summaryFactory)
      +
      This is to create a new instance of an UpdatableQuickSelectSketch.
      +
      +
      Parameters:
      +
      nomEntries - Nominal number of entries. Forced to the nearest power of 2 greater than +or equal to the given value.
      +
      lgResizeFactor - log2(resizeFactor) - value from 0 to 3: +
      +0 - no resizing (max size allocated),
      +1 - double internal hash table each time it reaches a threshold
      +2 - grow four times
      +3 - grow eight times (default)
      +
      +
      samplingProbability - See Sampling Probability
      +
      summaryFactory - An instance of a SummaryFactory.
      +
      +
      +
      +
    • +
    • +
      +

      UpdatableTupleSketch

      +
      +
      @Deprecated +public UpdatableTupleSketch(MemorySegment srcSeg, + SummaryDeserializer<S> deserializer, + SummaryFactory<S> summaryFactory)
      +
      Deprecated. +
      As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Heapifying a CompactTupleSketch is not deprecated.
      +
      +
      This is to create an instance of an UpdatableTupleSketch given a serialized form
      +
      +
      Parameters:
      +
      srcSeg - MemorySegment object with data of a serialized UpdatableTupleSketch
      +
      deserializer - instance of SummaryDeserializer
      +
      summaryFactory - instance of SummaryFactory
      +
      +
      +
      +
    • +
    • +
      +

      UpdatableTupleSketch

      +
      +
      public UpdatableTupleSketch(UpdatableTupleSketch<U,S> sketch)
      +
      Copy Constructor
      +
      +
      Parameters:
      +
      sketch - the sketch to copy
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      copy

      +
      +
      public UpdatableTupleSketch<U,S> copy()
      +
      +
      Returns:
      +
      a deep copy of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long key, + U value)
      +
      Updates this sketch with a long key and U value. +The value is passed to update() method of the Summary object associated with the key
      +
      +
      Parameters:
      +
      key - The given long key
      +
      value - The given U value
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(double key, + U value)
      +
      Updates this sketch with a double key and U value. +The value is passed to update() method of the Summary object associated with the key
      +
      +
      Parameters:
      +
      key - The given double key
      +
      value - The given U value
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(String key, + U value)
      +
      Updates this sketch with a String key and U value. +The value is passed to update() method of the Summary object associated with the key
      +
      +
      Parameters:
      +
      key - The given String key
      +
      value - The given U value
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(byte[] key, + U value)
      +
      Updates this sketch with a byte[] key and U value. +The value is passed to update() method of the Summary object associated with the key
      +
      +
      Parameters:
      +
      key - The given byte[] key
      +
      value - The given U value
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(ByteBuffer buffer, + U value)
      +
      Updates this sketch with a ByteBuffer and U value +The value is passed to the update() method of the Summary object associated with the key
      +
      +
      Parameters:
      +
      buffer - The given ByteBuffer key
      +
      value - The given U value
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(int[] key, + U value)
      +
      Updates this sketch with a int[] key and U value. +The value is passed to update() method of the Summary object associated with the key
      +
      +
      Parameters:
      +
      key - The given int[] key
      +
      value - The given U value
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long[] key, + U value)
      +
      Updates this sketch with a long[] key and U value. +The value is passed to update() method of the Summary object associated with the key
      +
      +
      Parameters:
      +
      key - The given long[] key
      +
      value - The given U value
      +
      +
      +
      +
    • +
    • +
      +

      getRetainedEntries

      +
      +
      public int getRetainedEntries()
      +
      Description copied from class: TupleSketch
      +
      Returns number of retained entries
      +
      +
      Specified by:
      +
      getRetainedEntries in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      number of retained entries
      +
      +
      +
      +
    • +
    • +
      +

      getCountLessThanThetaLong

      +
      +
      public int getCountLessThanThetaLong(long thetaLong)
      +
      Description copied from class: TupleSketch
      +
      Gets the number of hash values less than the given theta expressed as a long.
      +
      +
      Specified by:
      +
      getCountLessThanThetaLong in class TupleSketch<S extends Summary>
      +
      Parameters:
      +
      thetaLong - the given theta as a long in the range (zero, Long.MAX_VALUE].
      +
      Returns:
      +
      the number of hash values less than the given thetaLong.
      +
      +
      +
      +
    • +
    • +
      +

      getNominalEntries

      +
      +
      public int getNominalEntries()
      +
      Get configured nominal number of entries
      +
      +
      Returns:
      +
      nominal number of entries
      +
      +
      +
      +
    • +
    • +
      +

      getLgK

      +
      +
      public int getLgK()
      +
      Get log_base2 of Nominal Entries
      +
      +
      Returns:
      +
      log_base2 of Nominal Entries
      +
      +
      +
      +
    • +
    • +
      +

      getSamplingProbability

      +
      +
      public float getSamplingProbability()
      +
      Get configured sampling probability
      +
      +
      Returns:
      +
      sampling probability
      +
      +
      +
      +
    • +
    • +
      +

      getCurrentCapacity

      +
      +
      public int getCurrentCapacity()
      +
      Get current capacity
      +
      +
      Returns:
      +
      current capacity
      +
      +
      +
      +
    • +
    • +
      +

      getResizeFactor

      +
      +
      public ResizeFactor getResizeFactor()
      +
      Get configured resize factor
      +
      +
      Returns:
      +
      resize factor
      +
      +
      +
      +
    • +
    • +
      +

      trim

      +
      +
      public void trim()
      +
      Rebuilds reducing the actual number of entries to the nominal number of entries if needed
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch an empty state.
      +
      +
      +
    • +
    • +
      +

      compact

      +
      +
      public CompactTupleSketch<S> compact()
      +
      Converts the current state of the sketch into a compact sketch
      +
      +
      Specified by:
      +
      compact in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      compact sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      @Deprecated +public byte[] toByteArray()
      +
      Deprecated. +
      As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Serializing a CompactTupleSketch is not deprecated.
      +
      +
      This serializes an UpdatableTupleSketch (QuickSelectSketch).
      +
      +
      Specified by:
      +
      toByteArray in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      serialized representation of an UpdatableTupleSketch (QuickSelectSketch).
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public TupleSketchIterator<S> iterator()
      +
      Description copied from class: TupleSketch
      +
      Returns a SketchIterator
      +
      +
      Specified by:
      +
      iterator in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      a SketchIterator
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/UpdatableTupleSketchBuilder.html b/target/site/apidocs/org/apache/datasketches/tuple/UpdatableTupleSketchBuilder.html new file mode 100644 index 000000000..f4db2c894 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/UpdatableTupleSketchBuilder.html @@ -0,0 +1,274 @@ + + + + +UpdatableTupleSketchBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class UpdatableTupleSketchBuilder<U, S extends UpdatableSummary<U>>

+
+
java.lang.Object +
org.apache.datasketches.tuple.UpdatableTupleSketchBuilder<U,S>
+
+
+
+
Type Parameters:
+
U - Type of update value
+
S - Type of Summary
+
+
+
+
public class UpdatableTupleSketchBuilder<U, S extends UpdatableSummary<U>> +extends Object
+
For building a new generic tuple UpdatableTupleSketch
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      UpdatableTupleSketchBuilder

      +
      +
      public UpdatableTupleSketchBuilder(SummaryFactory<S> summaryFactory)
      +
      Creates an instance of UpdatableTupleSketchBuilder with default parameters
      +
      +
      Parameters:
      +
      summaryFactory - An instance of SummaryFactory.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      setNominalEntries

      +
      +
      public UpdatableTupleSketchBuilder<U,S> setNominalEntries(int nomEntries)
      +
      This is to set the nominal number of entries.
      +
      +
      Parameters:
      +
      nomEntries - Nominal number of entries. Forced to the nearest power of 2 greater than +or equal to the given value.
      +
      Returns:
      +
      this UpdatableTupleSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      setResizeFactor

      +
      +
      public UpdatableTupleSketchBuilder<U,S> setResizeFactor(ResizeFactor resizeFactor)
      +
      This is to set the resize factor. +Value of X1 means that the maximum capacity is allocated from the start. +Default resize factor is X8.
      +
      +
      Parameters:
      +
      resizeFactor - value of X1, X2, X4 or X8
      +
      Returns:
      +
      this UpdatableTupleSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      setSamplingProbability

      +
      +
      public UpdatableTupleSketchBuilder<U,S> setSamplingProbability(float samplingProbability)
      +
      This is to set sampling probability. +Default probability is 1.
      +
      +
      Parameters:
      +
      samplingProbability - sampling probability from 0 to 1
      +
      Returns:
      +
      this UpdatableTupleSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      build

      +
      +
      public UpdatableTupleSketch<U,S> build()
      +
      Returns an UpdatableTupleSketch with the current configuration of this Builder.
      +
      +
      Returns:
      +
      an UpdatableTupleSketch
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets the Nominal Entries, Resize Factor and Sampling Probability to their default values. +The assignment of U and S remain the same.
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/Util.html b/target/site/apidocs/org/apache/datasketches/tuple/Util.html new file mode 100644 index 000000000..767b9e097 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/Util.html @@ -0,0 +1,342 @@ + + + + +Util (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class Util

+
+
java.lang.Object +
org.apache.datasketches.tuple.Util
+
+
+
+
+
public final class Util +extends Object
+
Common utility functions for Tuples
+
+
+
+
    + +
  • +
    +

    Constructor Summary

    +
    Constructors
    +
    +
    Constructor
    +
    Description
    + +
    +
    No argument constructor.
    +
    +
    +
    +
  • + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    static <S extends Summary>
    S[]
    +
    copySummaryArray(S[] summaryArr)
    +
    +
    Will copy compact summary arrays as well as hashed summary tables (with nulls).
    +
    +
    static final long[]
    +
    doubleToLongArray(double value)
    +
    +
    Converts a double to a long[].
    +
    +
    static int
    +
    getStartingCapacity(int nomEntries, + int lgResizeFactor)
    +
    +
    Gets the starting capacity of a new sketch given the Nominal Entries and the log Resize Factor.
    +
    +
    static <S extends Summary>
    S[]
    +
    newSummaryArray(S[] summaryArr, + int length)
    +
    +
    Creates a new Summary Array with the specified length
    +
    +
    static long
    +
    stringArrHash(String[] strArray)
    +
    +
    Returns the hash of the concatenated strings
    +
    +
    static String
    +
    stringConcat(String[] strArr)
    +
    +
    Concatenate array of Strings to a single String.
    +
    +
    static long
    + +
    +
    Returns the hash of the given string
    +
    +
    static final byte[]
    + +
    +
    Converts a String to a UTF_8 byte array.
    +
    +
    +
    +
    +
    +

    Methods inherited from class Object

    +equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      Util

      +
      +
      public Util()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      doubleToLongArray

      +
      +
      public static final long[] doubleToLongArray(double value)
      +
      Converts a double to a long[].
      +
      +
      Parameters:
      +
      value - the given double value
      +
      Returns:
      +
      the long array
      +
      +
      +
      +
    • +
    • +
      +

      stringToByteArray

      +
      +
      public static final byte[] stringToByteArray(String value)
      +
      Converts a String to a UTF_8 byte array. If the given value is either null or empty this +method returns null.
      +
      +
      Parameters:
      +
      value - the given String value
      +
      Returns:
      +
      the UTF_8 byte array
      +
      +
      +
      +
    • +
    • +
      +

      getStartingCapacity

      +
      +
      public static int getStartingCapacity(int nomEntries, + int lgResizeFactor)
      +
      Gets the starting capacity of a new sketch given the Nominal Entries and the log Resize Factor.
      +
      +
      Parameters:
      +
      nomEntries - the given Nominal Entries
      +
      lgResizeFactor - the given log Resize Factor
      +
      Returns:
      +
      the starting capacity
      +
      +
      +
      +
    • +
    • +
      +

      stringConcat

      +
      +
      public static String stringConcat(String[] strArr)
      +
      Concatenate array of Strings to a single String.
      +
      +
      Parameters:
      +
      strArr - the given String array
      +
      Returns:
      +
      the concatenated String
      +
      +
      +
      +
    • +
    • +
      +

      stringHash

      +
      +
      public static long stringHash(String s)
      +
      Returns the hash of the given string
      +
      +
      Parameters:
      +
      s - the string to hash
      +
      Returns:
      +
      the hash of the given string
      +
      +
      +
      +
    • +
    • +
      +

      stringArrHash

      +
      +
      public static long stringArrHash(String[] strArray)
      +
      Returns the hash of the concatenated strings
      +
      +
      Parameters:
      +
      strArray - array of Strings
      +
      Returns:
      +
      the hash of concatenated strings.
      +
      +
      +
      +
    • +
    • +
      +

      copySummaryArray

      +
      +
      public static <S extends Summary> S[] copySummaryArray(S[] summaryArr)
      +
      Will copy compact summary arrays as well as hashed summary tables (with nulls).
      +
      +
      Type Parameters:
      +
      S - type of summary
      +
      Parameters:
      +
      summaryArr - the given summary array or table
      +
      Returns:
      +
      the copy
      +
      +
      +
      +
    • +
    • +
      +

      newSummaryArray

      +
      +
      public static <S extends Summary> S[] newSummaryArray(S[] summaryArr, + int length)
      +
      Creates a new Summary Array with the specified length
      +
      +
      Type Parameters:
      +
      S - the summary class type
      +
      Parameters:
      +
      summaryArr - example array, only used to obtain the component type. It has no data.
      +
      length - the desired length of the returned array.
      +
      Returns:
      +
      a new Summary Array with the specified length
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummary.Mode.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummary.Mode.html new file mode 100644 index 000000000..7ac4f84ee --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummary.Mode.html @@ -0,0 +1,285 @@ + + + + +DoubleSummary.Mode (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class DoubleSummary.Mode

+
+
java.lang.Object +
java.lang.Enum<DoubleSummary.Mode> +
org.apache.datasketches.tuple.adouble.DoubleSummary.Mode
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<DoubleSummary.Mode>, Constable
+
+
+
Enclosing class:
+
DoubleSummary
+
+
+
+
public static enum DoubleSummary.Mode +extends Enum<DoubleSummary.Mode>
+
The aggregation modes for this Summary
+
+
+
+ +
+
+
    + +
  • +
    +

    Enum Constant Details

    +
      +
    • +
      +

      Sum

      +
      +
      public static final DoubleSummary.Mode Sum
      +
      The aggregation mode is the summation function. + +

      New retained value = previous retained value + incoming value

      +
      +
      +
    • +
    • +
      +

      Min

      +
      +
      public static final DoubleSummary.Mode Min
      +
      The aggregation mode is the minimum function. + +

      New retained value = min(previous retained value, incoming value)

      +
      +
      +
    • +
    • +
      +

      Max

      +
      +
      public static final DoubleSummary.Mode Max
      +
      The aggregation mode is the maximum function. + +

      New retained value = max(previous retained value, incoming value)

      +
      +
      +
    • +
    • +
      +

      AlwaysOne

      +
      +
      public static final DoubleSummary.Mode AlwaysOne
      +
      The aggregation mode is always one. + +

      New retained value = 1.0

      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static DoubleSummary.Mode[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static DoubleSummary.Mode valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummary.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummary.html new file mode 100644 index 000000000..26b1e47e4 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummary.html @@ -0,0 +1,308 @@ + + + + +DoubleSummary (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class DoubleSummary

+
+
java.lang.Object +
org.apache.datasketches.tuple.adouble.DoubleSummary
+
+
+
+
All Implemented Interfaces:
+
Summary, UpdatableSummary<Double>
+
+
+
+
public final class DoubleSummary +extends Object +implements UpdatableSummary<Double>
+
Summary for generic tuple sketches of type Double. +This summary keeps a double value. On update a predefined operation is performed depending on +the mode. +Supported modes: Sum, Min, Max, AlwaysOne, Increment. The default mode is Sum.
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      DoubleSummary

      +
      +
      public DoubleSummary(DoubleSummary.Mode mode)
      +
      Creates an instance of DoubleSummary with a given mode.
      +
      +
      Parameters:
      +
      mode - update mode
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      update

      +
      +
      public DoubleSummary update(Double value)
      +
      Description copied from interface: UpdatableSummary
      +
      This is to provide a method of updating summaries. +This is primarily used internally.
      +
      +
      Specified by:
      +
      update in interface UpdatableSummary<Double>
      +
      Parameters:
      +
      value - update value
      +
      Returns:
      +
      this
      +
      +
      +
      +
    • +
    • +
      +

      copy

      +
      +
      public DoubleSummary copy()
      +
      Description copied from interface: Summary
      +
      Deep copy. + +

      Caution: This must implement a deep copy.

      +
      +
      Specified by:
      +
      copy in interface Summary
      +
      Returns:
      +
      deep copy of the Summary
      +
      +
      +
      +
    • +
    • +
      +

      getValue

      +
      +
      public double getValue()
      +
      Returns current value of the DoubleSummary
      +
      +
      Returns:
      +
      current value of the DoubleSummary
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Description copied from interface: Summary
      +
      This is to serialize a Summary instance to a byte array. + +

      The user should encode in the byte array its total size, which is used during +deserialization, especially if the Summary has variable sized elements.

      +
      +
      Specified by:
      +
      toByteArray in interface Summary
      +
      Returns:
      +
      serialized representation of the Summary
      +
      +
      +
      +
    • +
    • +
      +

      fromMemorySegment

      +
      +
      public static DeserializeResult<DoubleSummary> fromMemorySegment(MemorySegment seg)
      +
      Creates an instance of the DoubleSummary given a serialized representation
      +
      +
      Parameters:
      +
      seg - MemorySegment object with serialized DoubleSummary
      +
      Returns:
      +
      DeserializedResult object, which contains a DoubleSummary object and number of bytes +read from the MemorySegment
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummaryDeserializer.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummaryDeserializer.html new file mode 100644 index 000000000..10e5caa71 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummaryDeserializer.html @@ -0,0 +1,201 @@ + + + + +DoubleSummaryDeserializer (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class DoubleSummaryDeserializer

+
+
java.lang.Object +
org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer
+
+
+
+
All Implemented Interfaces:
+
SummaryDeserializer<DoubleSummary>
+
+
+
+
public class DoubleSummaryDeserializer +extends Object +implements SummaryDeserializer<DoubleSummary>
+
Implements SummaryDeserializer<DoubleSummary>
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      DoubleSummaryDeserializer

      +
      +
      public DoubleSummaryDeserializer()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapifySummary

      +
      +
      public DeserializeResult<DoubleSummary> heapifySummary(MemorySegment seg)
      +
      Description copied from interface: SummaryDeserializer
      +
      This is to create an instance of a Summary given a serialized representation. +The user may assume that the start of the given MemorySegment is the correct place to start +deserializing. However, the user must be able to determine the number of bytes required to +deserialize the summary as the capacity of the given MemorySegment may +include multiple such summaries and may be much larger than required for a single summary.
      +
      +
      Specified by:
      +
      heapifySummary in interface SummaryDeserializer<DoubleSummary>
      +
      Parameters:
      +
      seg - MemorySegment object with serialized representation of a Summary
      +
      Returns:
      +
      DeserializedResult object, which contains a Summary object and number of bytes read +from the MemorySegment
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummaryFactory.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummaryFactory.html new file mode 100644 index 000000000..35f495e6e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummaryFactory.html @@ -0,0 +1,198 @@ + + + + +DoubleSummaryFactory (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class DoubleSummaryFactory

+
+
java.lang.Object +
org.apache.datasketches.tuple.adouble.DoubleSummaryFactory
+
+
+
+
All Implemented Interfaces:
+
SummaryFactory<DoubleSummary>
+
+
+
+
public final class DoubleSummaryFactory +extends Object +implements SummaryFactory<DoubleSummary>
+
Factory for DoubleSummary.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      DoubleSummaryFactory

      +
      +
      public DoubleSummaryFactory(DoubleSummary.Mode summaryMode)
      +
      Creates an instance of DoubleSummaryFactory with a given mode
      +
      +
      Parameters:
      +
      summaryMode - summary mode
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    + +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummarySetOperations.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummarySetOperations.html new file mode 100644 index 000000000..fe081ef4b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleSummarySetOperations.html @@ -0,0 +1,275 @@ + + + + +DoubleSummarySetOperations (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class DoubleSummarySetOperations

+
+
java.lang.Object +
org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations
+
+
+
+
All Implemented Interfaces:
+
SummarySetOperations<DoubleSummary>
+
+
+
+
public final class DoubleSummarySetOperations +extends Object +implements SummarySetOperations<DoubleSummary>
+
Methods for defining how unions and intersections of two objects of type DoubleSummary +are performed.
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      DoubleSummarySetOperations

      +
      +
      public DoubleSummarySetOperations()
      +
      Creates an instance with default mode of sum for both union and intersection. +This exists for backward compatibility.
      +
      +
      +
    • +
    • +
      +

      DoubleSummarySetOperations

      +
      +
      public DoubleSummarySetOperations(DoubleSummary.Mode summaryMode)
      +
      Creates an instance given a DoubleSummary update mode where the mode is the same for both +union and intersection. This exists for backward compatibility.
      +
      +
      Parameters:
      +
      summaryMode - DoubleSummary update mode.
      +
      +
      +
      +
    • +
    • +
      +

      DoubleSummarySetOperations

      +
      +
      public DoubleSummarySetOperations(DoubleSummary.Mode unionSummaryMode, + DoubleSummary.Mode intersectionSummaryMode)
      +
      Creates an instance with two modes.
      +
      +
      Parameters:
      +
      unionSummaryMode - for unions
      +
      intersectionSummaryMode - for intersections
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      union

      +
      +
      public DoubleSummary union(DoubleSummary a, + DoubleSummary b)
      +
      Description copied from interface: SummarySetOperations
      +
      This is called by the union operator when both sketches have the same hash value. + +

      Caution: Do not modify the input Summary objects. Also do not return them directly, +unless they are immutable (most Summary objects are not). For mutable Summary objects, it is +important to create a new Summary object with the correct contents to be returned. Do not +return null summaries.

      +
      +
      Specified by:
      +
      union in interface SummarySetOperations<DoubleSummary>
      +
      Parameters:
      +
      a - Summary from sketch A
      +
      b - Summary from sketch B
      +
      Returns:
      +
      union of Summary A and Summary B
      +
      +
      +
      +
    • +
    • +
      +

      intersection

      +
      +
      public DoubleSummary intersection(DoubleSummary a, + DoubleSummary b)
      +
      Description copied from interface: SummarySetOperations
      +
      This is called by the intersection operator when both sketches have the same hash value. + +

      Caution: Do not modify the input Summary objects. Also do not return them directly, +unless they are immutable (most Summary objects are not). For mutable Summary objects, it is +important to create a new Summary object with the correct contents to be returned. Do not +return null summaries.

      +
      +
      Specified by:
      +
      intersection in interface SummarySetOperations<DoubleSummary>
      +
      Parameters:
      +
      a - Summary from sketch A
      +
      b - Summary from sketch B
      +
      Returns:
      +
      intersection of Summary A and Summary B
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleTupleSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleTupleSketch.html new file mode 100644 index 000000000..f767dc111 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/DoubleTupleSketch.html @@ -0,0 +1,543 @@ + + + + +DoubleTupleSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class DoubleTupleSketch

+
+ +
+
+
+
public class DoubleTupleSketch +extends UpdatableTupleSketch<Double, DoubleSummary>
+
Extends UpdatableTupleSketch<Double, DoubleSummary>
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      DoubleTupleSketch

      +
      +
      public DoubleTupleSketch(int lgK, + DoubleSummary.Mode mode)
      +
      Constructs this sketch with given lgK.
      +
      +
      Parameters:
      +
      lgK - Log_base2 of Nominal Entries. +See Nominal Entries
      +
      mode - The DoubleSummary mode to be used
      +
      +
      +
      +
    • +
    • +
      +

      DoubleTupleSketch

      +
      +
      public DoubleTupleSketch(int lgK, + int lgResizeFactor, + float samplingProbability, + DoubleSummary.Mode mode)
      +
      Creates this sketch with the following parameters:
      +
      +
      Parameters:
      +
      lgK - Log_base2 of Nominal Entries.
      +
      lgResizeFactor - log2(resizeFactor) - value from 0 to 3: +
      +0 - no resizing (max size allocated),
      +1 - double internal hash table each time it reaches a threshold
      +2 - grow four times
      +3 - grow eight times (default)
      +
      +
      samplingProbability - See Sampling Probability
      +
      mode - The DoubleSummary mode to be used
      +
      +
      +
      +
    • +
    • +
      +

      DoubleTupleSketch

      +
      +
      @Deprecated +public DoubleTupleSketch(MemorySegment seg, + DoubleSummary.Mode mode)
      +
      Deprecated. +
      As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Heapifying a CompactTupleSketch is not deprecated.
      +
      +
      Constructs this sketch from a MemorySegment image, which must be from an DoubleTupleSketch, and +usually with data.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      mode - The DoubleSummary mode to be used
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      update

      +
      +
      public void update(String key, + Double value)
      +
      Description copied from class: UpdatableTupleSketch
      +
      Updates this sketch with a String key and U value. +The value is passed to update() method of the Summary object associated with the key
      +
      +
      Overrides:
      +
      update in class UpdatableTupleSketch<Double, DoubleSummary>
      +
      Parameters:
      +
      key - The given String key
      +
      value - The given U value
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long key, + Double value)
      +
      Description copied from class: UpdatableTupleSketch
      +
      Updates this sketch with a long key and U value. +The value is passed to update() method of the Summary object associated with the key
      +
      +
      Overrides:
      +
      update in class UpdatableTupleSketch<Double, DoubleSummary>
      +
      Parameters:
      +
      key - The given long key
      +
      value - The given U value
      +
      +
      +
      +
    • +
    • +
      +

      getRetainedEntries

      +
      +
      public int getRetainedEntries()
      +
      Description copied from class: TupleSketch
      +
      Returns number of retained entries
      +
      +
      Specified by:
      +
      getRetainedEntries in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      number of retained entries
      +
      +
      +
      +
    • +
    • +
      +

      getCountLessThanThetaLong

      +
      +
      public int getCountLessThanThetaLong(long thetaLong)
      +
      Description copied from class: TupleSketch
      +
      Gets the number of hash values less than the given theta expressed as a long.
      +
      +
      Specified by:
      +
      getCountLessThanThetaLong in class TupleSketch<S extends Summary>
      +
      Parameters:
      +
      thetaLong - the given theta as a long in the range (zero, Long.MAX_VALUE].
      +
      Returns:
      +
      the number of hash values less than the given thetaLong.
      +
      +
      +
      +
    • +
    • +
      +

      getNominalEntries

      +
      +
      public int getNominalEntries()
      +
      Get configured nominal number of entries
      +
      +
      Returns:
      +
      nominal number of entries
      +
      +
      +
      +
    • +
    • +
      +

      getLgK

      +
      +
      public int getLgK()
      +
      Get log_base2 of Nominal Entries
      +
      +
      Returns:
      +
      log_base2 of Nominal Entries
      +
      +
      +
      +
    • +
    • +
      +

      getSamplingProbability

      +
      +
      public float getSamplingProbability()
      +
      Get configured sampling probability
      +
      +
      Returns:
      +
      sampling probability
      +
      +
      +
      +
    • +
    • +
      +

      getCurrentCapacity

      +
      +
      public int getCurrentCapacity()
      +
      Get current capacity
      +
      +
      Returns:
      +
      current capacity
      +
      +
      +
      +
    • +
    • +
      +

      getResizeFactor

      +
      +
      public ResizeFactor getResizeFactor()
      +
      Get configured resize factor
      +
      +
      Returns:
      +
      resize factor
      +
      +
      +
      +
    • +
    • +
      +

      trim

      +
      +
      public void trim()
      +
      Rebuilds reducing the actual number of entries to the nominal number of entries if needed
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch an empty state.
      +
      +
      +
    • +
    • +
      +

      compact

      +
      +
      public CompactTupleSketch<DoubleSummary> compact()
      +
      Converts the current state of the sketch into a compact sketch
      +
      +
      Specified by:
      +
      compact in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      compact sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      @Deprecated +public byte[] toByteArray()
      +
      Deprecated. +
      As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Serializing a CompactTupleSketch is not deprecated.
      +
      +
      This serializes an UpdatableTupleSketch (QuickSelectSketch).
      +
      +
      Specified by:
      +
      toByteArray in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      serialized representation of an UpdatableTupleSketch (QuickSelectSketch).
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public TupleSketchIterator<DoubleSummary> iterator()
      +
      Description copied from class: TupleSketch
      +
      Returns a SketchIterator
      +
      +
      Specified by:
      +
      iterator in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      a SketchIterator
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummary.Mode.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummary.Mode.html new file mode 100644 index 000000000..fa3d75779 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummary.Mode.html @@ -0,0 +1,163 @@ + + + + +Uses of Enum Class org.apache.datasketches.tuple.adouble.DoubleSummary.Mode (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.tuple.adouble.DoubleSummary.Mode

+
+
Packages that use DoubleSummary.Mode
+
+
Package
+
Description
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummary.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummary.html new file mode 100644 index 000000000..70f50ff6e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummary.html @@ -0,0 +1,168 @@ + + + + +Uses of Class org.apache.datasketches.tuple.adouble.DoubleSummary (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.adouble.DoubleSummary

+
+
Packages that use DoubleSummary
+
+
Package
+
Description
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummaryDeserializer.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummaryDeserializer.html new file mode 100644 index 000000000..de8c0335f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummaryDeserializer.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer

+
+No usage of org.apache.datasketches.tuple.adouble.DoubleSummaryDeserializer +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummaryFactory.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummaryFactory.html new file mode 100644 index 000000000..fac1720b4 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummaryFactory.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.adouble.DoubleSummaryFactory (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.adouble.DoubleSummaryFactory

+
+No usage of org.apache.datasketches.tuple.adouble.DoubleSummaryFactory +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummarySetOperations.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummarySetOperations.html new file mode 100644 index 000000000..7704de11b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleSummarySetOperations.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations

+
+No usage of org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleTupleSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleTupleSketch.html new file mode 100644 index 000000000..881de5a16 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/class-use/DoubleTupleSketch.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.adouble.DoubleTupleSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.adouble.DoubleTupleSketch

+
+No usage of org.apache.datasketches.tuple.adouble.DoubleTupleSketch +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/package-summary.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/package-summary.html new file mode 100644 index 000000000..e0dd3672d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/package-summary.html @@ -0,0 +1,147 @@ + + + + +org.apache.datasketches.tuple.adouble (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.tuple.adouble

+
+
+
+
package org.apache.datasketches.tuple.adouble
+
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/package-tree.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/package-tree.html new file mode 100644 index 000000000..91725edd5 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/package-tree.html @@ -0,0 +1,105 @@ + + + + +org.apache.datasketches.tuple.adouble Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.tuple.adouble

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Enum Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/adouble/package-use.html b/target/site/apidocs/org/apache/datasketches/tuple/adouble/package-use.html new file mode 100644 index 000000000..17cc2cc35 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/adouble/package-use.html @@ -0,0 +1,95 @@ + + + + +Uses of Package org.apache.datasketches.tuple.adouble (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.tuple.adouble

+
+ +
+
Package
+
Description
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummary.Mode.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummary.Mode.html new file mode 100644 index 000000000..563d3af27 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummary.Mode.html @@ -0,0 +1,285 @@ + + + + +IntegerSummary.Mode (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Enum Class IntegerSummary.Mode

+
+
java.lang.Object +
java.lang.Enum<IntegerSummary.Mode> +
org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode
+
+
+
+
+
All Implemented Interfaces:
+
Serializable, Comparable<IntegerSummary.Mode>, Constable
+
+
+
Enclosing class:
+
IntegerSummary
+
+
+
+
public static enum IntegerSummary.Mode +extends Enum<IntegerSummary.Mode>
+
The aggregation modes for this Summary
+
+
+
+ +
+
+
    + +
  • +
    +

    Enum Constant Details

    +
      +
    • +
      +

      Sum

      +
      +
      public static final IntegerSummary.Mode Sum
      +
      The aggregation mode is the summation function. + +

      New retained value = previous retained value + incoming value

      +
      +
      +
    • +
    • +
      +

      Min

      +
      +
      public static final IntegerSummary.Mode Min
      +
      The aggregation mode is the minimum function. + +

      New retained value = min(previous retained value, incoming value)

      +
      +
      +
    • +
    • +
      +

      Max

      +
      +
      public static final IntegerSummary.Mode Max
      +
      The aggregation mode is the maximum function. + +

      New retained value = max(previous retained value, incoming value)

      +
      +
      +
    • +
    • +
      +

      AlwaysOne

      +
      +
      public static final IntegerSummary.Mode AlwaysOne
      +
      The aggregation mode is always one. + +

      New retained value = 1

      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      values

      +
      +
      public static IntegerSummary.Mode[] values()
      +
      Returns an array containing the constants of this enum class, in +the order they are declared.
      +
      +
      Returns:
      +
      an array containing the constants of this enum class, in the order they are declared
      +
      +
      +
      +
    • +
    • +
      +

      valueOf

      +
      +
      public static IntegerSummary.Mode valueOf(String name)
      +
      Returns the enum constant of this class with the specified name. +The string must match exactly an identifier used to declare an +enum constant in this class. (Extraneous whitespace characters are +not permitted.)
      +
      +
      Parameters:
      +
      name - the name of the enum constant to be returned.
      +
      Returns:
      +
      the enum constant with the specified name
      +
      Throws:
      +
      IllegalArgumentException - if this enum class has no constant with the specified name
      +
      NullPointerException - if the argument is null
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummary.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummary.html new file mode 100644 index 000000000..4618a7181 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummary.html @@ -0,0 +1,308 @@ + + + + +IntegerSummary (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class IntegerSummary

+
+
java.lang.Object +
org.apache.datasketches.tuple.aninteger.IntegerSummary
+
+
+
+
All Implemented Interfaces:
+
Summary, UpdatableSummary<Integer>
+
+
+
+
public class IntegerSummary +extends Object +implements UpdatableSummary<Integer>
+
Summary for generic tuple sketches of type Integer. +This summary keeps an Integer value. On update a predefined operation is performed depending on +the mode. +Supported modes: Sum, Min, Max, AlwaysOne, Increment. The default mode is Sum.
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      IntegerSummary

      +
      +
      public IntegerSummary(IntegerSummary.Mode mode)
      +
      Creates an instance of IntegerSummary with a given mode.
      +
      +
      Parameters:
      +
      mode - update mode. This should not be called by a user.
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      update

      +
      +
      public IntegerSummary update(Integer value)
      +
      Description copied from interface: UpdatableSummary
      +
      This is to provide a method of updating summaries. +This is primarily used internally.
      +
      +
      Specified by:
      +
      update in interface UpdatableSummary<Integer>
      +
      Parameters:
      +
      value - update value
      +
      Returns:
      +
      this
      +
      +
      +
      +
    • +
    • +
      +

      copy

      +
      +
      public IntegerSummary copy()
      +
      Description copied from interface: Summary
      +
      Deep copy. + +

      Caution: This must implement a deep copy.

      +
      +
      Specified by:
      +
      copy in interface Summary
      +
      Returns:
      +
      deep copy of the Summary
      +
      +
      +
      +
    • +
    • +
      +

      getValue

      +
      +
      public int getValue()
      +
      Returns the current value of the IntegerSummary
      +
      +
      Returns:
      +
      current value of the IntegerSummary
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Description copied from interface: Summary
      +
      This is to serialize a Summary instance to a byte array. + +

      The user should encode in the byte array its total size, which is used during +deserialization, especially if the Summary has variable sized elements.

      +
      +
      Specified by:
      +
      toByteArray in interface Summary
      +
      Returns:
      +
      serialized representation of the Summary
      +
      +
      +
      +
    • +
    • +
      +

      fromMemorySegment

      +
      +
      public static DeserializeResult<IntegerSummary> fromMemorySegment(MemorySegment seg)
      +
      Creates an instance of the IntegerSummary given a serialized representation
      +
      +
      Parameters:
      +
      seg - MemorySegment object with serialized IntegerSummary
      +
      Returns:
      +
      DeserializedResult object, which contains a IntegerSummary object and number of bytes +read from the MemorySegment
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummaryDeserializer.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummaryDeserializer.html new file mode 100644 index 000000000..3817c8a0f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummaryDeserializer.html @@ -0,0 +1,201 @@ + + + + +IntegerSummaryDeserializer (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class IntegerSummaryDeserializer

+
+
java.lang.Object +
org.apache.datasketches.tuple.aninteger.IntegerSummaryDeserializer
+
+
+
+
All Implemented Interfaces:
+
SummaryDeserializer<IntegerSummary>
+
+
+
+
public class IntegerSummaryDeserializer +extends Object +implements SummaryDeserializer<IntegerSummary>
+
Implements SummaryDeserializer<IntegerSummary>
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      IntegerSummaryDeserializer

      +
      +
      public IntegerSummaryDeserializer()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapifySummary

      +
      +
      public DeserializeResult<IntegerSummary> heapifySummary(MemorySegment seg)
      +
      Description copied from interface: SummaryDeserializer
      +
      This is to create an instance of a Summary given a serialized representation. +The user may assume that the start of the given MemorySegment is the correct place to start +deserializing. However, the user must be able to determine the number of bytes required to +deserialize the summary as the capacity of the given MemorySegment may +include multiple such summaries and may be much larger than required for a single summary.
      +
      +
      Specified by:
      +
      heapifySummary in interface SummaryDeserializer<IntegerSummary>
      +
      Parameters:
      +
      seg - MemorySegment object with serialized representation of a Summary
      +
      Returns:
      +
      DeserializedResult object, which contains a Summary object and number of bytes read +from the MemorySegment
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummaryFactory.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummaryFactory.html new file mode 100644 index 000000000..7b2976187 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummaryFactory.html @@ -0,0 +1,198 @@ + + + + +IntegerSummaryFactory (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class IntegerSummaryFactory

+
+
java.lang.Object +
org.apache.datasketches.tuple.aninteger.IntegerSummaryFactory
+
+
+
+
All Implemented Interfaces:
+
SummaryFactory<IntegerSummary>
+
+
+
+
public class IntegerSummaryFactory +extends Object +implements SummaryFactory<IntegerSummary>
+
Factory for IntegerSummary.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      IntegerSummaryFactory

      +
      +
      public IntegerSummaryFactory(IntegerSummary.Mode summaryMode)
      +
      Creates an instance of IntegerSummaryFactory with a given mode
      +
      +
      Parameters:
      +
      summaryMode - summary mode
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    + +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummarySetOperations.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummarySetOperations.html new file mode 100644 index 000000000..1d835d1a0 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerSummarySetOperations.html @@ -0,0 +1,244 @@ + + + + +IntegerSummarySetOperations (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class IntegerSummarySetOperations

+
+
java.lang.Object +
org.apache.datasketches.tuple.aninteger.IntegerSummarySetOperations
+
+
+
+
All Implemented Interfaces:
+
SummarySetOperations<IntegerSummary>
+
+
+
+
public class IntegerSummarySetOperations +extends Object +implements SummarySetOperations<IntegerSummary>
+
Methods for defining how unions and intersections of two objects of type IntegerSummary +are performed.
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      IntegerSummarySetOperations

      +
      +
      public IntegerSummarySetOperations(IntegerSummary.Mode unionSummaryMode, + IntegerSummary.Mode intersectionSummaryMode)
      +
      Creates a new instance with two modes
      +
      +
      Parameters:
      +
      unionSummaryMode - for unions
      +
      intersectionSummaryMode - for intersections
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      union

      +
      + +
      Description copied from interface: SummarySetOperations
      +
      This is called by the union operator when both sketches have the same hash value. + +

      Caution: Do not modify the input Summary objects. Also do not return them directly, +unless they are immutable (most Summary objects are not). For mutable Summary objects, it is +important to create a new Summary object with the correct contents to be returned. Do not +return null summaries.

      +
      +
      Specified by:
      +
      union in interface SummarySetOperations<IntegerSummary>
      +
      Parameters:
      +
      a - Summary from sketch A
      +
      b - Summary from sketch B
      +
      Returns:
      +
      union of Summary A and Summary B
      +
      +
      +
      +
    • +
    • +
      +

      intersection

      +
      +
      public IntegerSummary intersection(IntegerSummary a, + IntegerSummary b)
      +
      Description copied from interface: SummarySetOperations
      +
      This is called by the intersection operator when both sketches have the same hash value. + +

      Caution: Do not modify the input Summary objects. Also do not return them directly, +unless they are immutable (most Summary objects are not). For mutable Summary objects, it is +important to create a new Summary object with the correct contents to be returned. Do not +return null summaries.

      +
      +
      Specified by:
      +
      intersection in interface SummarySetOperations<IntegerSummary>
      +
      Parameters:
      +
      a - Summary from sketch A
      +
      b - Summary from sketch B
      +
      Returns:
      +
      intersection of Summary A and Summary B
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerTupleSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerTupleSketch.html new file mode 100644 index 000000000..99f1bca3d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/IntegerTupleSketch.html @@ -0,0 +1,543 @@ + + + + +IntegerTupleSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class IntegerTupleSketch

+
+ +
+
+
+
public class IntegerTupleSketch +extends UpdatableTupleSketch<Integer, IntegerSummary>
+
Extends UpdatableTupleSketch<Integer, IntegerSummary>
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      IntegerTupleSketch

      +
      +
      public IntegerTupleSketch(int lgK, + IntegerSummary.Mode mode)
      +
      Constructs this sketch with given lgK.
      +
      +
      Parameters:
      +
      lgK - Log_base2 of Nominal Entries. +See Nominal Entries
      +
      mode - The IntegerSummary mode to be used
      +
      +
      +
      +
    • +
    • +
      +

      IntegerTupleSketch

      +
      +
      public IntegerTupleSketch(int lgK, + int lgResizeFactor, + float samplingProbability, + IntegerSummary.Mode mode)
      +
      Creates this sketch with the following parameters:
      +
      +
      Parameters:
      +
      lgK - Log_base2 of Nominal Entries.
      +
      lgResizeFactor - log2(resizeFactor) - value from 0 to 3: +
      +0 - no resizing (max size allocated),
      +1 - double internal hash table each time it reaches a threshold
      +2 - grow four times
      +3 - grow eight times (default)
      +
      +
      samplingProbability - See Sampling Probability
      +
      mode - The IntegerSummary mode to be used
      +
      +
      +
      +
    • +
    • +
      +

      IntegerTupleSketch

      +
      +
      @Deprecated +public IntegerTupleSketch(MemorySegment seg, + IntegerSummary.Mode mode)
      +
      Deprecated. +
      As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Heapifying a CompactTupleSketch is not deprecated.
      +
      +
      Constructs this sketch from a MemorySegment image, which must be from an IntegerTupleSketch, and +usually with data.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      mode - The IntegerSummary mode to be used
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      update

      +
      +
      public void update(String key, + Integer value)
      +
      Description copied from class: UpdatableTupleSketch
      +
      Updates this sketch with a String key and U value. +The value is passed to update() method of the Summary object associated with the key
      +
      +
      Overrides:
      +
      update in class UpdatableTupleSketch<Integer, IntegerSummary>
      +
      Parameters:
      +
      key - The given String key
      +
      value - The given U value
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long key, + Integer value)
      +
      Description copied from class: UpdatableTupleSketch
      +
      Updates this sketch with a long key and U value. +The value is passed to update() method of the Summary object associated with the key
      +
      +
      Overrides:
      +
      update in class UpdatableTupleSketch<Integer, IntegerSummary>
      +
      Parameters:
      +
      key - The given long key
      +
      value - The given U value
      +
      +
      +
      +
    • +
    • +
      +

      getRetainedEntries

      +
      +
      public int getRetainedEntries()
      +
      Description copied from class: TupleSketch
      +
      Returns number of retained entries
      +
      +
      Specified by:
      +
      getRetainedEntries in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      number of retained entries
      +
      +
      +
      +
    • +
    • +
      +

      getCountLessThanThetaLong

      +
      +
      public int getCountLessThanThetaLong(long thetaLong)
      +
      Description copied from class: TupleSketch
      +
      Gets the number of hash values less than the given theta expressed as a long.
      +
      +
      Specified by:
      +
      getCountLessThanThetaLong in class TupleSketch<S extends Summary>
      +
      Parameters:
      +
      thetaLong - the given theta as a long in the range (zero, Long.MAX_VALUE].
      +
      Returns:
      +
      the number of hash values less than the given thetaLong.
      +
      +
      +
      +
    • +
    • +
      +

      getNominalEntries

      +
      +
      public int getNominalEntries()
      +
      Get configured nominal number of entries
      +
      +
      Returns:
      +
      nominal number of entries
      +
      +
      +
      +
    • +
    • +
      +

      getLgK

      +
      +
      public int getLgK()
      +
      Get log_base2 of Nominal Entries
      +
      +
      Returns:
      +
      log_base2 of Nominal Entries
      +
      +
      +
      +
    • +
    • +
      +

      getSamplingProbability

      +
      +
      public float getSamplingProbability()
      +
      Get configured sampling probability
      +
      +
      Returns:
      +
      sampling probability
      +
      +
      +
      +
    • +
    • +
      +

      getCurrentCapacity

      +
      +
      public int getCurrentCapacity()
      +
      Get current capacity
      +
      +
      Returns:
      +
      current capacity
      +
      +
      +
      +
    • +
    • +
      +

      getResizeFactor

      +
      +
      public ResizeFactor getResizeFactor()
      +
      Get configured resize factor
      +
      +
      Returns:
      +
      resize factor
      +
      +
      +
      +
    • +
    • +
      +

      trim

      +
      +
      public void trim()
      +
      Rebuilds reducing the actual number of entries to the nominal number of entries if needed
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch an empty state.
      +
      +
      +
    • +
    • +
      +

      compact

      +
      + +
      Converts the current state of the sketch into a compact sketch
      +
      +
      Specified by:
      +
      compact in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      compact sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      @Deprecated +public byte[] toByteArray()
      +
      Deprecated. +
      As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Serializing a CompactTupleSketch is not deprecated.
      +
      +
      This serializes an UpdatableTupleSketch (QuickSelectSketch).
      +
      +
      Specified by:
      +
      toByteArray in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      serialized representation of an UpdatableTupleSketch (QuickSelectSketch).
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public TupleSketchIterator<IntegerSummary> iterator()
      +
      Description copied from class: TupleSketch
      +
      Returns a SketchIterator
      +
      +
      Specified by:
      +
      iterator in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      a SketchIterator
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummary.Mode.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummary.Mode.html new file mode 100644 index 000000000..72e1d7d82 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummary.Mode.html @@ -0,0 +1,157 @@ + + + + +Uses of Enum Class org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.tuple.aninteger.IntegerSummary.Mode

+
+
Packages that use IntegerSummary.Mode
+
+
Package
+
Description
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummary.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummary.html new file mode 100644 index 000000000..0328cf953 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummary.html @@ -0,0 +1,168 @@ + + + + +Uses of Class org.apache.datasketches.tuple.aninteger.IntegerSummary (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.aninteger.IntegerSummary

+
+
Packages that use IntegerSummary
+
+
Package
+
Description
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummaryDeserializer.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummaryDeserializer.html new file mode 100644 index 000000000..538ebf0cc --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummaryDeserializer.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.aninteger.IntegerSummaryDeserializer (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.aninteger.IntegerSummaryDeserializer

+
+No usage of org.apache.datasketches.tuple.aninteger.IntegerSummaryDeserializer +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummaryFactory.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummaryFactory.html new file mode 100644 index 000000000..81f1450cf --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummaryFactory.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.aninteger.IntegerSummaryFactory (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.aninteger.IntegerSummaryFactory

+
+No usage of org.apache.datasketches.tuple.aninteger.IntegerSummaryFactory +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummarySetOperations.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummarySetOperations.html new file mode 100644 index 000000000..8b50be58d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerSummarySetOperations.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.aninteger.IntegerSummarySetOperations (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.aninteger.IntegerSummarySetOperations

+
+No usage of org.apache.datasketches.tuple.aninteger.IntegerSummarySetOperations +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerTupleSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerTupleSketch.html new file mode 100644 index 000000000..590a414aa --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/class-use/IntegerTupleSketch.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.aninteger.IntegerTupleSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.aninteger.IntegerTupleSketch

+
+No usage of org.apache.datasketches.tuple.aninteger.IntegerTupleSketch +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/package-summary.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/package-summary.html new file mode 100644 index 000000000..092a6394e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/package-summary.html @@ -0,0 +1,147 @@ + + + + +org.apache.datasketches.tuple.aninteger (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.tuple.aninteger

+
+
+
+
package org.apache.datasketches.tuple.aninteger
+
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/package-tree.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/package-tree.html new file mode 100644 index 000000000..85dfeef89 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/package-tree.html @@ -0,0 +1,105 @@ + + + + +org.apache.datasketches.tuple.aninteger Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.tuple.aninteger

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Enum Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/aninteger/package-use.html b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/package-use.html new file mode 100644 index 000000000..5c36e75c1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/aninteger/package-use.html @@ -0,0 +1,95 @@ + + + + +Uses of Package org.apache.datasketches.tuple.aninteger (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.tuple.aninteger

+
+ +
+
Package
+
Description
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotB.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotB.html new file mode 100644 index 000000000..2317c07c1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotB.html @@ -0,0 +1,196 @@ + + + + +ArrayOfDoublesAnotB (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfDoublesAnotB

+
+
java.lang.Object +
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotB
+
+
+
+
Direct Known Subclasses:
+
ArrayOfDoublesAnotBImpl
+
+
+
+
public abstract class ArrayOfDoublesAnotB +extends Object
+
Computes a set difference of two tuple sketches of type ArrayOfDoubles
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      update

      +
      +
      public abstract void update(ArrayOfDoublesSketch a, + ArrayOfDoublesSketch b)
      +
      Perform A-and-not-B set operation on the two given sketches. +A null sketch is interpreted as an empty sketch. +This is not an accumulating update. Calling update() more than once +without calling getResult() will discard the result of previous update(). +Both input sketches must have the same numValues.
      +
      +
      Parameters:
      +
      a - The incoming sketch for the first argument
      +
      b - The incoming sketch for the second argument
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public abstract ArrayOfDoublesCompactSketch getResult()
      +
      Gets the result of this operation in the form of a ArrayOfDoublesCompactSketch
      +
      +
      Returns:
      +
      compact sketch representing the result of the operation
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public abstract ArrayOfDoublesCompactSketch getResult(MemorySegment seg)
      +
      Gets the result of this operation in the form of a ArrayOfDoublesCompactSketch
      +
      +
      Parameters:
      +
      seg - MemorySegment for the result (can be null)
      +
      Returns:
      +
      compact sketch representing the result of the operation (off-heap if MemorySegment is +provided)
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotBImpl.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotBImpl.html new file mode 100644 index 000000000..f2180832e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesAnotBImpl.html @@ -0,0 +1,212 @@ + + + + +ArrayOfDoublesAnotBImpl (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfDoublesAnotBImpl

+
+
java.lang.Object +
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotB +
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotBImpl
+
+
+
+
+
+
public class ArrayOfDoublesAnotBImpl +extends ArrayOfDoublesAnotB
+
Computes a set difference, A-AND-NOT-B, of two ArrayOfDoublesSketches. + +

This class includes a stateless operation as follows:

+ +
CompactTupleSketch csk = anotb.aNotB(ArrayOfDoublesSketch skA, ArrayOfDoublesSketch skB);
+
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      update

      +
      +
      public void update(ArrayOfDoublesSketch skA, + ArrayOfDoublesSketch skB)
      +
      Description copied from class: ArrayOfDoublesAnotB
      +
      Perform A-and-not-B set operation on the two given sketches. +A null sketch is interpreted as an empty sketch. +This is not an accumulating update. Calling update() more than once +without calling getResult() will discard the result of previous update(). +Both input sketches must have the same numValues.
      +
      +
      Specified by:
      +
      update in class ArrayOfDoublesAnotB
      +
      Parameters:
      +
      skA - The incoming sketch for the first argument
      +
      skB - The incoming sketch for the second argument
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public ArrayOfDoublesCompactSketch getResult()
      +
      Description copied from class: ArrayOfDoublesAnotB
      +
      Gets the result of this operation in the form of a ArrayOfDoublesCompactSketch
      +
      +
      Specified by:
      +
      getResult in class ArrayOfDoublesAnotB
      +
      Returns:
      +
      compact sketch representing the result of the operation
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public ArrayOfDoublesCompactSketch getResult(MemorySegment dstSeg)
      +
      Description copied from class: ArrayOfDoublesAnotB
      +
      Gets the result of this operation in the form of a ArrayOfDoublesCompactSketch
      +
      +
      Specified by:
      +
      getResult in class ArrayOfDoublesAnotB
      +
      Parameters:
      +
      dstSeg - MemorySegment for the result (can be null)
      +
      Returns:
      +
      compact sketch representing the result of the operation (off-heap if MemorySegment is +provided)
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCombiner.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCombiner.html new file mode 100644 index 000000000..db3488c81 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCombiner.html @@ -0,0 +1,142 @@ + + + + +ArrayOfDoublesCombiner (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface ArrayOfDoublesCombiner

+
+
+
+
+
public interface ArrayOfDoublesCombiner
+
Combines two arrays of double values for use with ArrayOfDoubles tuple sketches
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    double[]
    +
    combine(double[] a, + double[] b)
    +
    +
    Method of combining two arrays of double values
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      combine

      +
      +
      double[] combine(double[] a, + double[] b)
      +
      Method of combining two arrays of double values
      +
      +
      Parameters:
      +
      a - Array A.
      +
      b - Array B.
      +
      Returns:
      +
      Result of combining A and B
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCompactSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCompactSketch.html new file mode 100644 index 000000000..15884b772 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesCompactSketch.html @@ -0,0 +1,179 @@ + + + + +ArrayOfDoublesCompactSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfDoublesCompactSketch

+
+
java.lang.Object +
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch +
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCompactSketch
+
+
+
+
+
+
public abstract class ArrayOfDoublesCompactSketch +extends ArrayOfDoublesSketch
+
Top level compact tuple sketch of type ArrayOfDoubles. Compact sketches are never created +directly. They are created as a result of the compact() method on a QuickSelectSketch +or the getResult() method of a set operation like TupleUnion, TupleIntersection or TupleAnotB. +A CompactTupleSketch consists of a compact list (i.e. no intervening spaces) of hash values, +a corresponding list of double values, and a value for theta. The lists may or may +not be ordered. It is read-only.
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      getCurrentBytes

      +
      +
      public int getCurrentBytes()
      +
      Description copied from class: ArrayOfDoublesSketch
      +
      For compact sketches this is the same as getMaxBytes().
      +
      +
      Specified by:
      +
      getCurrentBytes in class ArrayOfDoublesSketch
      +
      Returns:
      +
      the current number of bytes for this sketch when serialized.
      +
      +
      +
      +
    • +
    • +
      +

      getMaxBytes

      +
      +
      public int getMaxBytes()
      +
      Description copied from class: ArrayOfDoublesSketch
      +
      Returns the maximum number of bytes for this sketch when serialized.
      +
      +
      Specified by:
      +
      getMaxBytes in class ArrayOfDoublesSketch
      +
      Returns:
      +
      the maximum number of bytes for this sketch when serialized.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesIntersection.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesIntersection.html new file mode 100644 index 000000000..327a3a010 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesIntersection.html @@ -0,0 +1,206 @@ + + + + +ArrayOfDoublesIntersection (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfDoublesIntersection

+
+
java.lang.Object +
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesIntersection
+
+
+
+
+
public abstract class ArrayOfDoublesIntersection +extends Object
+
Computes the intersection of two or more tuple sketches of type ArrayOfDoubles. +A new instance represents the Universal Set. +Every update() computes an intersection with the internal set +and can only reduce the internal set.
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      intersect

      +
      +
      public void intersect(ArrayOfDoublesSketch tupleSketch, + ArrayOfDoublesCombiner combiner)
      +
      Performs a stateful intersection of the internal set with the given TupleSketch. +The given TupleSketch and the internal state must have the same numValues.
      +
      +
      Parameters:
      +
      tupleSketch - Input sketch to intersect with the internal set.
      +
      combiner - Method of combining two arrays of double values
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public ArrayOfDoublesCompactSketch getResult()
      +
      Gets the internal set as an on-heap compact sketch.
      +
      +
      Returns:
      +
      Result of the intersections so far as a compact sketch.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public ArrayOfDoublesCompactSketch getResult(MemorySegment dstSeg)
      +
      Gets the result of stateful intersections so far.
      +
      +
      Parameters:
      +
      dstSeg - MemorySegment for the compact sketch (can be null).
      +
      Returns:
      +
      Result of the intersections so far as a compact sketch.
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets the internal set to the initial state, which represents the Universal Set
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSetOperationBuilder.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSetOperationBuilder.html new file mode 100644 index 000000000..63b5cae86 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSetOperationBuilder.html @@ -0,0 +1,408 @@ + + + + +ArrayOfDoublesSetOperationBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfDoublesSetOperationBuilder

+
+
java.lang.Object +
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder
+
+
+
+
+
public class ArrayOfDoublesSetOperationBuilder +extends Object
+
Builds set operations object for tuple sketches of type ArrayOfDoubles.
+
+
+
+ +
+
+
    + +
  • +
    +

    Field Details

    +
      +
    • +
      +

      DEFAULT_NOMINAL_ENTRIES

      +
      +
      public static final int DEFAULT_NOMINAL_ENTRIES
      +
      Default Nominal Entries (a.k.a. K)
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    • +
      +

      DEFAULT_NUMBER_OF_VALUES

      +
      +
      public static final int DEFAULT_NUMBER_OF_VALUES
      +
      Default number of values
      +
      +
      See Also:
      +
      + +
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfDoublesSetOperationBuilder

      +
      +
      public ArrayOfDoublesSetOperationBuilder()
      +
      Creates an instance of the builder with default parameters
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      setNominalEntries

      +
      +
      public ArrayOfDoublesSetOperationBuilder setNominalEntries(int nomEntries)
      +
      This is to set the nominal number of entries.
      +
      +
      Parameters:
      +
      nomEntries - Nominal number of entries. Forced to the nearest power of 2 greater than +given value.
      +
      Returns:
      +
      this builder
      +
      +
      +
      +
    • +
    • +
      +

      setNumberOfValues

      +
      +
      public ArrayOfDoublesSetOperationBuilder setNumberOfValues(int numValues)
      +
      This is to set the number of double values associated with each key
      +
      +
      Parameters:
      +
      numValues - number of double values
      +
      Returns:
      +
      this builder
      +
      +
      +
      +
    • +
    • +
      +

      setSeed

      +
      +
      public ArrayOfDoublesSetOperationBuilder setSeed(long seed)
      +
      Sets the long seed value that is required by the hashing function.
      +
      +
      Parameters:
      +
      seed - See seed
      +
      Returns:
      +
      this builder
      +
      +
      +
      +
    • +
    • +
      +

      buildUnion

      +
      +
      public ArrayOfDoublesUnion buildUnion()
      +
      Creates an instance of ArrayOfDoublesUnion based on the current configuration of the builder. +The new instance is allocated on the heap.
      +
      +
      Returns:
      +
      an instance of ArrayOfDoublesUnion
      +
      +
      +
      +
    • +
    • +
      +

      buildUnion

      +
      +
      public ArrayOfDoublesUnion buildUnion(MemorySegment dstSeg)
      +
      Creates an instance of ArrayOfDoublesUnion based on the current configuration of the builder +and the given destination MemorySegment.
      +
      +
      Parameters:
      +
      dstSeg - destination MemorySegment to be used by the sketch
      +
      Returns:
      +
      an instance of ArrayOfDoublesUnion
      +
      +
      +
      +
    • +
    • +
      +

      buildIntersection

      +
      +
      public ArrayOfDoublesIntersection buildIntersection()
      +
      Creates an instance of ArrayOfDoublesIntersection based on the current configuration of the +builder. +The new instance is allocated on the heap. +The number of nominal entries is not relevant to this, so it is ignored.
      +
      +
      Returns:
      +
      an instance of ArrayOfDoublesIntersection
      +
      +
      +
      +
    • +
    • +
      +

      buildIntersection

      +
      +
      public ArrayOfDoublesIntersection buildIntersection(MemorySegment dstSeg)
      +
      Creates an instance of ArrayOfDoublesIntersection in the given MemorySegment and based on the +current configuration of the builder. +The number of nominal entries is not relevant to this, so it is ignored.
      +
      +
      Parameters:
      +
      dstSeg - destination MemorySegment to be used by the sketch
      +
      Returns:
      +
      an instance of ArrayOfDoublesIntersection
      +
      +
      +
      +
    • +
    • +
      +

      buildAnotB

      +
      +
      public ArrayOfDoublesAnotB buildAnotB()
      +
      Creates an instance of ArrayOfDoublesAnotB based on the current configuration of the builder. +The number of nominal entries is not relevant to this, so it is ignored.
      +
      +
      Returns:
      +
      an instance of ArrayOfDoublesAnotB
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketch.html new file mode 100644 index 000000000..f3f2ad94a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketch.html @@ -0,0 +1,831 @@ + + + + +ArrayOfDoublesSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfDoublesSketch

+
+
java.lang.Object +
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch
+
+
+
+
Direct Known Subclasses:
+
ArrayOfDoublesCompactSketch, ArrayOfDoublesUpdatableSketch
+
+
+
+
public abstract class ArrayOfDoublesSketch +extends Object
+
The base class for the tuple sketch of type ArrayOfDoubles, where an array of double values +is associated with each key. +A primitive array of doubles is used here, as opposed to a generic Summary object, +for improved performance.
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapify

      +
      +
      public static ArrayOfDoublesSketch heapify(MemorySegment seg)
      +
      Heapify the given MemorySegment as an ArrayOfDoublesSketch
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      an ArrayOfDoublesSketch
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static ArrayOfDoublesSketch heapify(MemorySegment seg, + long seed)
      +
      Heapify the given MemorySegment and seed as a ArrayOfDoublesSketch
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      seed - the given seed
      +
      Returns:
      +
      an ArrayOfDoublesSketch
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ArrayOfDoublesSketch wrap(MemorySegment seg)
      +
      Wrap the given MemorySegment as an ArrayOfDoublesSketch. +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      an ArrayOfDoublesSketch
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ArrayOfDoublesSketch wrap(MemorySegment seg, + long seed)
      +
      Wrap the given MemorySegment and seed as a ArrayOfDoublesSketch. +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      seed - the given seed
      +
      Returns:
      +
      an ArrayOfDoublesSketch
      +
      +
      +
      +
    • +
    • +
      +

      getEstimate

      +
      +
      public double getEstimate()
      +
      Estimates the cardinality of the set (number of unique values presented to the sketch)
      +
      +
      Returns:
      +
      best estimate of the number of unique values
      +
      +
      +
      +
    • +
    • +
      +

      getUpperBound

      +
      +
      public double getUpperBound(int numStdDev)
      +
      Gets the approximate upper error bound given the specified number of Standard Deviations. +This will return getEstimate() if isEmpty() is true.
      +
      +
      Parameters:
      +
      numStdDev - See Number of Standard Deviations
      +
      Returns:
      +
      the upper bound.
      +
      +
      +
      +
    • +
    • +
      +

      getLowerBound

      +
      +
      public double getLowerBound(int numStdDev)
      +
      Gets the approximate lower error bound given the specified number of Standard Deviations. +This will return getEstimate() if isEmpty() is true.
      +
      +
      Parameters:
      +
      numStdDev - See Number of Standard Deviations
      +
      Returns:
      +
      the lower bound.
      +
      +
      +
      +
    • +
    • +
      +

      hasMemorySegment

      +
      +
      public abstract boolean hasMemorySegment()
      +
      Returns true if this sketch's data structure is backed by MemorySegment.
      +
      +
      Returns:
      +
      true if this sketch's data structure is backed by MemorySegment.
      +
      +
      +
      +
    • +
    • +
      +

      isEmpty

      +
      +
      public boolean isEmpty()
      + +
      +
      Returns:
      +
      true if empty.
      +
      +
      +
      +
    • +
    • +
      +

      getNumValues

      +
      +
      public int getNumValues()
      +
      Returns number of double values associated with each key
      +
      +
      Returns:
      +
      number of double values associated with each key
      +
      +
      +
      +
    • +
    • +
      +

      isEstimationMode

      +
      +
      public boolean isEstimationMode()
      +
      Returns true if the sketch is Estimation Mode (as opposed to Exact Mode). +This is true if theta < 1.0 AND isEmpty() is false.
      +
      +
      Returns:
      +
      true if the sketch is in estimation mode.
      +
      +
      +
      +
    • +
    • +
      +

      getTheta

      +
      +
      public double getTheta()
      +
      Gets the value of theta as a double between zero and one
      +
      +
      Returns:
      +
      the value of theta as a double
      +
      +
      +
      +
    • +
    • +
      +

      getRetainedEntries

      +
      +
      public abstract int getRetainedEntries()
      +
      Returns number of retained entries
      +
      +
      Returns:
      +
      number of retained entries
      +
      +
      +
      +
    • +
    • +
      +

      getMaxBytes

      +
      +
      public abstract int getMaxBytes()
      +
      Returns the maximum number of bytes for this sketch when serialized.
      +
      +
      Returns:
      +
      the maximum number of bytes for this sketch when serialized.
      +
      +
      +
      +
    • +
    • +
      +

      getCurrentBytes

      +
      +
      public abstract int getCurrentBytes()
      +
      For compact sketches this is the same as getMaxBytes().
      +
      +
      Returns:
      +
      the current number of bytes for this sketch when serialized.
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public abstract byte[] toByteArray()
      +
      Returns serialized representation of the sketch
      +
      +
      Returns:
      +
      serialized representation of the sketch
      +
      +
      +
      +
    • +
    • +
      +

      getValues

      +
      +
      public abstract double[][] getValues()
      +
      Returns array of arrays of double values in the sketch
      +
      +
      Returns:
      +
      array of arrays of double values in the sketch
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      +
      public abstract ArrayOfDoublesSketchIterator iterator()
      +
      Returns an iterator over the sketch
      +
      +
      Returns:
      +
      an iterator over the sketch
      +
      +
      +
      +
    • +
    • +
      +

      compact

      +
      +
      public ArrayOfDoublesCompactSketch compact()
      +
      Returns this sketch in compact form, which is immutable.
      +
      +
      Returns:
      +
      this sketch in compact form, which is immutable.
      +
      +
      +
      +
    • +
    • +
      +

      compact

      +
      +
      public abstract ArrayOfDoublesCompactSketch compact(MemorySegment dstSeg)
      +
      Returns this sketch in compact form, which is immutable.
      +
      +
      Parameters:
      +
      dstSeg - the destination MemorySegment
      +
      Returns:
      +
      this sketch in compact form, which is immutable.
      +
      +
      +
      +
    • +
    • +
      +

      toString

      +
      +
      public String toString()
      +
      +
      Overrides:
      +
      toString in class Object
      +
      +
      +
      +
    • +
    • +
      +

      wrapUnion

      +
      +
      public static ArrayOfDoublesUnion wrapUnion(MemorySegment srcSeg, + long seed)
      +
      Wrap the given MemorySegment and seed as an ArrayOfDoublesUnion +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      seed - the given seed
      +
      Returns:
      +
      an ArrayOfDoublesUnion
      +
      +
      +
      +
    • +
    • +
      +

      wrapUnion

      +
      +
      public static ArrayOfDoublesUnion wrapUnion(MemorySegment srcSeg)
      +
      Wrap the given MemorySegment as an ArrayOfDoublesUnion +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      Returns:
      +
      an ArrayOfDoublesUnion
      +
      +
      +
      +
    • +
    • +
      +

      heapifyUnion

      +
      +
      public static ArrayOfDoublesUnion heapifyUnion(MemorySegment srcSeg, + long seed)
      +
      Heapify the given MemorySegment and seed as an ArrayOfDoublesUnion
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      seed - the given seed
      +
      Returns:
      +
      an ArrayOfDoublesUnion
      +
      +
      +
      +
    • +
    • +
      +

      heapifyUnion

      +
      +
      public static ArrayOfDoublesUnion heapifyUnion(MemorySegment srcSeg)
      +
      Heapify the given MemorySegment as an ArrayOfDoublesUnion
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      Returns:
      +
      an ArrayOfDoublesUnion
      +
      +
      +
      +
    • +
    • +
      +

      wrapUpdatableSketch

      +
      +
      public static ArrayOfDoublesUpdatableSketch wrapUpdatableSketch(MemorySegment srcSeg, + long seed)
      +
      Wrap the given MemorySegment and seed as a ArrayOfDoublesUpdatableSketch. +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      seed - the given seed
      +
      Returns:
      +
      an ArrayOfDoublesUpdatableSketch
      +
      +
      +
      +
    • +
    • +
      +

      wrapUpdatableSketch

      +
      +
      public static ArrayOfDoublesUpdatableSketch wrapUpdatableSketch(MemorySegment srcSeg)
      +
      Wrap the given MemorySegment as an ArrayOfDoublesUpdatableSketch. +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      Returns:
      +
      an ArrayOfDoublesUpdatableSketch
      +
      +
      +
      +
    • +
    • +
      +

      wrapSketch

      +
      +
      public static ArrayOfDoublesSketch wrapSketch(MemorySegment srcSeg, + long seed)
      +
      Wrap the given MemorySegment and seed as a ArrayOfDoublesSketch. +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      seed - the given seed
      +
      Returns:
      +
      an ArrayOfDoublesSketch
      +
      +
      +
      +
    • +
    • +
      +

      wrapSketch

      +
      +
      public static ArrayOfDoublesSketch wrapSketch(MemorySegment srcSeg)
      +
      Wrap the given MemorySegment as an ArrayOfDoublesSketch. +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      Returns:
      +
      an ArrayOfDoublesSketch
      +
      +
      +
      +
    • +
    • +
      +

      heapifyUpdatableSketch

      +
      +
      public static ArrayOfDoublesUpdatableSketch heapifyUpdatableSketch(MemorySegment srcSeg, + long seed)
      +
      Heapify the given MemorySegment and seed as a ArrayOfDoublesUpdatableSketch
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      seed - the given seed
      +
      Returns:
      +
      an ArrayOfDoublesUpdatableSketch
      +
      +
      +
      +
    • +
    • +
      +

      heapifyUpdatableSketch

      +
      +
      public static ArrayOfDoublesUpdatableSketch heapifyUpdatableSketch(MemorySegment srcSeg)
      +
      Heapify the given MemorySegment as an ArrayOfDoublesUpdatableSketch
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      Returns:
      +
      an ArrayOfDoublesUpdatableSketch
      +
      +
      +
      +
    • +
    • +
      +

      heapifySketch

      +
      +
      public static ArrayOfDoublesSketch heapifySketch(MemorySegment srcSeg, + long seed)
      +
      Heapify the given MemorySegment and seed as a ArrayOfDoublesSketch
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      seed - the given seed
      +
      Returns:
      +
      an ArrayOfDoublesSketch
      +
      +
      +
      +
    • +
    • +
      +

      heapifySketch

      +
      +
      public static ArrayOfDoublesSketch heapifySketch(MemorySegment srcSeg)
      +
      Heapify the given MemorySegment as an ArrayOfDoublesSketch
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      Returns:
      +
      an ArrayOfDoublesSketch
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketchIterator.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketchIterator.html new file mode 100644 index 000000000..48ce0b967 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesSketchIterator.html @@ -0,0 +1,184 @@ + + + + +ArrayOfDoublesSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Interface ArrayOfDoublesSketchIterator

+
+
+
+
+
public interface ArrayOfDoublesSketchIterator
+
Interface for iterating over tuple sketches of type ArrayOfDoubles
+
+
+
+
    + +
  • +
    +

    Method Summary

    +
    +
    +
    +
    +
    Modifier and Type
    +
    Method
    +
    Description
    +
    long
    + +
    +
    Gets a key from the current entry in the sketch, which is a hash +of the original key passed to update().
    +
    +
    double[]
    + +
    +
    Gets an array of values from the current entry in the sketch.
    +
    +
    boolean
    + +
    +
    Advancing the iterator and checking existence of the next entry +is combined here for efficiency.
    +
    +
    +
    +
    +
    +
  • +
+
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      next

      +
      +
      boolean next()
      +
      Advancing the iterator and checking existence of the next entry +is combined here for efficiency. This results in an undefined +state of the iterator before the first call of this method.
      +
      +
      Returns:
      +
      true if the next element exists
      +
      +
      +
      +
    • +
    • +
      +

      getKey

      +
      +
      long getKey()
      +
      Gets a key from the current entry in the sketch, which is a hash +of the original key passed to update(). The original keys are not +retained. Don't call this before calling next() for the first time +or after getting false from next().
      +
      +
      Returns:
      +
      hash key from the current entry
      +
      +
      +
      +
    • +
    • +
      +

      getValues

      +
      +
      double[] getValues()
      +
      Gets an array of values from the current entry in the sketch. +Don't call this before calling next() for the first time +or after getting false from next().
      +
      +
      Returns:
      +
      array of double values for the current entry (may or may not be a copy)
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUnion.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUnion.html new file mode 100644 index 000000000..b1a6567a7 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUnion.html @@ -0,0 +1,338 @@ + + + + +ArrayOfDoublesUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfDoublesUnion

+
+
java.lang.Object +
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion
+
+
+
+
+
public abstract class ArrayOfDoublesUnion +extends Object
+
The base class for unions of tuple sketches of type ArrayOfDoubles.
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapify

      +
      +
      public static ArrayOfDoublesUnion heapify(MemorySegment srcSeg)
      +
      Heapify the given MemorySegment as an ArrayOfDoublesUnion.
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      Returns:
      +
      an ArrayOfDoublesUnion
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static ArrayOfDoublesUnion heapify(MemorySegment srcSeg, + long seed)
      +
      Heapify the given MemorySegment and seed as an ArrayOfDoublesUnion.
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      seed - the given seed
      +
      Returns:
      +
      an ArrayOfDoublesUnion
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ArrayOfDoublesUnion wrap(MemorySegment srcSeg)
      +
      Wrap the given MemorySegment as an ArrayOfDoublesUnion. +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      Returns:
      +
      an ArrayOfDoublesUnion
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ArrayOfDoublesUnion wrap(MemorySegment srcSeg, + long seed)
      +
      Wrap the given MemorySegment and seed as an ArrayOfDoublesUnion. +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
      +
      +
      Parameters:
      +
      srcSeg - the given source MemorySegment
      +
      seed - the given seed
      +
      Returns:
      +
      an ArrayOfDoublesUnion
      +
      +
      +
      +
    • +
    • +
      +

      union

      +
      +
      public void union(ArrayOfDoublesSketch tupleSketch)
      +
      Updates the union by adding a set of entries from a given sketch, which can be on-heap or off-heap. +Both the given tupleSketch and the internal state of the TupleUnion must have the same numValues. + +

      Nulls and empty sketches are ignored.

      +
      +
      Parameters:
      +
      tupleSketch - sketch to add to the union.
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public ArrayOfDoublesCompactSketch getResult(MemorySegment dstSeg)
      +
      Returns the resulting union in the form of a compact sketch
      +
      +
      Parameters:
      +
      dstSeg - MemorySegment for the result (can be null)
      +
      Returns:
      +
      compact sketch representing the union (off-heap if MemorySegment is provided)
      +
      +
      +
      +
    • +
    • +
      +

      getResult

      +
      +
      public ArrayOfDoublesCompactSketch getResult()
      +
      Returns the resulting union in the form of a compact sketch
      +
      +
      Returns:
      +
      on-heap compact sketch representing the union
      +
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets the union to an empty state
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Returns a byte array representation of this object
      +
      +
      Returns:
      +
      a byte array representation of this object
      +
      +
      +
      +
    • +
    • +
      +

      getMaxBytes

      +
      +
      public static int getMaxBytes(int nomEntries, + int numValues)
      +
      Returns maximum required storage bytes given nomEntries and numValues
      +
      +
      Parameters:
      +
      nomEntries - Nominal number of entries. Forced to the nearest power of 2 greater than or equal to +given value.
      +
      numValues - Number of double values to keep for each key
      +
      Returns:
      +
      maximum required storage bytes given nomEntries and numValues
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketch.html new file mode 100644 index 000000000..abe8f4bc2 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketch.html @@ -0,0 +1,514 @@ + + + + +ArrayOfDoublesUpdatableSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfDoublesUpdatableSketch

+
+
java.lang.Object +
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch +
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch
+
+
+
+
+
+
public abstract class ArrayOfDoublesUpdatableSketch +extends ArrayOfDoublesSketch
+
The top level for updatable tuple sketches of type ArrayOfDoubles.
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapify

      +
      +
      public static ArrayOfDoublesUpdatableSketch heapify(MemorySegment seg)
      +
      Heapify the given MemorySegment as an ArrayOfDoublesUpdatableSketch
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      an ArrayOfDoublesUpdatableSketch
      +
      +
      +
      +
    • +
    • +
      +

      heapify

      +
      +
      public static ArrayOfDoublesUpdatableSketch heapify(MemorySegment seg, + long seed)
      +
      Heapify the given MemorySegment and seed as a ArrayOfDoublesUpdatableSketch
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      seed - the given seed
      +
      Returns:
      +
      an ArrayOfDoublesUpdatableSketch
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ArrayOfDoublesUpdatableSketch wrap(MemorySegment seg)
      +
      Wrap the given MemorySegment as an ArrayOfDoublesUpdatableSketch. +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      Returns:
      +
      an ArrayOfDoublesUpdatableSketch
      +
      +
      +
      +
    • +
    • +
      +

      wrap

      +
      +
      public static ArrayOfDoublesUpdatableSketch wrap(MemorySegment seg, + long seed)
      +
      Wrap the given MemorySegment and seed as a ArrayOfDoublesUpdatableSketch. +If the given source MemorySegment is read-only, the returned TupleUnion object will also be read-only.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      seed - the given seed
      +
      Returns:
      +
      an ArrayOfDoublesUpdatableSketch
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long key, + double[] values)
      +
      Updates this sketch with a long key and double values. +The values will be stored or added to the ones associated with the key
      +
      +
      Parameters:
      +
      key - The given long key
      +
      values - The given values
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(double key, + double[] values)
      +
      Updates this sketch with a double key and double values. +The values will be stored or added to the ones associated with the key
      +
      +
      Parameters:
      +
      key - The given double key
      +
      values - The given values
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(String key, + double[] values)
      +
      Updates this sketch with a String key and double values. +The values will be stored or added to the ones associated with the key
      +
      +
      Parameters:
      +
      key - The given String key
      +
      values - The given values
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(byte[] key, + double[] values)
      +
      Updates this sketch with a byte[] key and double values. +The values will be stored or added to the ones associated with the key
      +
      +
      Parameters:
      +
      key - The given byte[] key
      +
      values - The given values
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(ByteBuffer key, + double[] values)
      +
      Updates this sketch with a ByteBuffer key and double values. +The values will be stored or added to the ones associated with the key
      +
      +
      Parameters:
      +
      key - The given ByteBuffer key
      +
      values - The given values
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(int[] key, + double[] values)
      +
      Updates this sketch with a int[] key and double values. +The values will be stored or added to the ones associated with the key
      +
      +
      Parameters:
      +
      key - The given int[] key
      +
      values - The given values
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(long[] key, + double[] values)
      +
      Updates this sketch with a long[] key and double values. +The values will be stored or added to the ones associated with the key
      +
      +
      Parameters:
      +
      key - The given long[] key
      +
      values - The given values
      +
      +
      +
      +
    • +
    • +
      +

      getNominalEntries

      +
      +
      public abstract int getNominalEntries()
      +
      Gets the configured nominal number of entries
      +
      +
      Returns:
      +
      nominal number of entries
      +
      +
      +
      +
    • +
    • +
      +

      getResizeFactor

      +
      +
      public abstract ResizeFactor getResizeFactor()
      +
      Gets the configured resize factor
      +
      +
      Returns:
      +
      resize factor
      +
      +
      +
      +
    • +
    • +
      +

      getSamplingProbability

      +
      +
      public abstract float getSamplingProbability()
      +
      Gets the configured sampling probability
      +
      +
      Returns:
      +
      sampling probability
      +
      +
      +
      +
    • +
    • +
      +

      trim

      +
      +
      public abstract void trim()
      +
      Rebuilds reducing the actual number of entries to the nominal number of entries if needed
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public abstract void reset()
      +
      Resets this sketch an empty state.
      +
      +
      +
    • +
    • +
      +

      compact

      +
      +
      public ArrayOfDoublesCompactSketch compact()
      +
      Gets an on-heap compact representation of the sketch
      +
      +
      Overrides:
      +
      compact in class ArrayOfDoublesSketch
      +
      Returns:
      +
      compact sketch
      +
      +
      +
      +
    • +
    • +
      +

      compact

      +
      +
      public ArrayOfDoublesCompactSketch compact(MemorySegment dstSeg)
      +
      Gets an off-heap compact representation of the sketch using the given MemorySegment
      +
      +
      Specified by:
      +
      compact in class ArrayOfDoublesSketch
      +
      Parameters:
      +
      dstSeg - MemorySegment for the compact sketch (can be null)
      +
      Returns:
      +
      compact sketch (off-heap if MemorySegment is provided)
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketchBuilder.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketchBuilder.html new file mode 100644 index 000000000..d6257a46d --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/ArrayOfDoublesUpdatableSketchBuilder.html @@ -0,0 +1,312 @@ + + + + +ArrayOfDoublesUpdatableSketchBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfDoublesUpdatableSketchBuilder

+
+
java.lang.Object +
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder
+
+
+
+
+
public class ArrayOfDoublesUpdatableSketchBuilder +extends Object
+
For building a new ArrayOfDoublesUpdatableSketch
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfDoublesUpdatableSketchBuilder

      +
      +
      public ArrayOfDoublesUpdatableSketchBuilder()
      +
      Creates an instance of builder with default parameters
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      setNominalEntries

      +
      +
      public ArrayOfDoublesUpdatableSketchBuilder setNominalEntries(int nomEntries)
      +
      This is to set the nominal number of entries.
      +
      +
      Parameters:
      +
      nomEntries - Nominal number of entries. Forced to the nearest power of 2 greater than +or equal to given value.
      +
      Returns:
      +
      this builder
      +
      +
      +
      +
    • +
    • +
      +

      setResizeFactor

      +
      +
      public ArrayOfDoublesUpdatableSketchBuilder setResizeFactor(ResizeFactor resizeFactor)
      +
      This is to set the resize factor. +Value of X1 means that the maximum capacity is allocated from the start. +Default resize factor is X8.
      +
      +
      Parameters:
      +
      resizeFactor - value of X1, X2, X4 or X8
      +
      Returns:
      +
      this UpdatableTupleSketchBuilder
      +
      +
      +
      +
    • +
    • +
      +

      setSamplingProbability

      +
      +
      public ArrayOfDoublesUpdatableSketchBuilder setSamplingProbability(float samplingProbability)
      +
      This is to set sampling probability. +Default probability is 1.
      +
      +
      Parameters:
      +
      samplingProbability - sampling probability from 0 to 1
      +
      Returns:
      +
      this builder
      +
      +
      +
      +
    • +
    • +
      +

      setNumberOfValues

      +
      +
      public ArrayOfDoublesUpdatableSketchBuilder setNumberOfValues(int numValues)
      +
      This is to set the number of double values associated with each key
      +
      +
      Parameters:
      +
      numValues - number of double values
      +
      Returns:
      +
      this builder
      +
      +
      +
      +
    • +
    • +
      +

      setSeed

      +
      +
      public ArrayOfDoublesUpdatableSketchBuilder setSeed(long seed)
      +
      Sets the long seed value that is required by the hashing function.
      +
      +
      Parameters:
      +
      seed - See seed
      +
      Returns:
      +
      this builder
      +
      +
      +
      +
    • +
    • +
      +

      build

      +
      + +
      Returns an ArrayOfDoublesUpdatableSketch with the current configuration of this Builder.
      +
      +
      Returns:
      +
      an ArrayOfDoublesUpdatableSketch
      +
      +
      +
      +
    • +
    • +
      +

      build

      +
      + +
      Returns an ArrayOfDoublesUpdatableSketch with the current configuration of this Builder.
      +
      +
      Parameters:
      +
      dstSeg - instance of MemorySegment to be used by the sketch
      +
      Returns:
      +
      an ArrayOfDoublesUpdatableSketch
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesAnotB.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesAnotB.html new file mode 100644 index 000000000..c0c8c6d6c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesAnotB.html @@ -0,0 +1,106 @@ + + + + +Uses of Class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotB (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotB

+
+
Packages that use ArrayOfDoublesAnotB
+
+
Package
+
Description
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesAnotBImpl.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesAnotBImpl.html new file mode 100644 index 000000000..5b9bae2ea --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesAnotBImpl.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotBImpl (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotBImpl

+
+No usage of org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesAnotBImpl +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesCombiner.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesCombiner.html new file mode 100644 index 000000000..d600aaf92 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesCombiner.html @@ -0,0 +1,96 @@ + + + + +Uses of Interface org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCombiner (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCombiner

+
+
Packages that use ArrayOfDoublesCombiner
+
+
Package
+
Description
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesCompactSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesCompactSketch.html new file mode 100644 index 000000000..886041037 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesCompactSketch.html @@ -0,0 +1,146 @@ + + + + +Uses of Class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCompactSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesCompactSketch

+
+
Packages that use ArrayOfDoublesCompactSketch
+
+
Package
+
Description
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesIntersection.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesIntersection.html new file mode 100644 index 000000000..b6d6f26eb --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesIntersection.html @@ -0,0 +1,102 @@ + + + + +Uses of Class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesIntersection (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesIntersection

+
+
Packages that use ArrayOfDoublesIntersection
+
+
Package
+
Description
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesSetOperationBuilder.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesSetOperationBuilder.html new file mode 100644 index 000000000..ff13716fe --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesSetOperationBuilder.html @@ -0,0 +1,105 @@ + + + + +Uses of Class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSetOperationBuilder

+
+ +
+
Package
+
Description
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesSketch.html new file mode 100644 index 000000000..676daadbe --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesSketch.html @@ -0,0 +1,177 @@ + + + + +Uses of Class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketch

+
+
Packages that use ArrayOfDoublesSketch
+
+
Package
+
Description
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesSketchIterator.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesSketchIterator.html new file mode 100644 index 000000000..a3f57901b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesSketchIterator.html @@ -0,0 +1,95 @@ + + + + +Uses of Interface org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesSketchIterator

+
+ +
+
Package
+
Description
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesUnion.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesUnion.html new file mode 100644 index 000000000..d828ae701 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesUnion.html @@ -0,0 +1,147 @@ + + + + +Uses of Class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUnion

+
+
Packages that use ArrayOfDoublesUnion
+
+
Package
+
Description
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesUpdatableSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesUpdatableSketch.html new file mode 100644 index 000000000..f78d2301e --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesUpdatableSketch.html @@ -0,0 +1,144 @@ + + + + +Uses of Class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketch

+
+ +
+
Package
+
Description
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesUpdatableSketchBuilder.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesUpdatableSketchBuilder.html new file mode 100644 index 000000000..4cd7ed130 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/class-use/ArrayOfDoublesUpdatableSketchBuilder.html @@ -0,0 +1,115 @@ + + + + +Uses of Class org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.arrayofdoubles.ArrayOfDoublesUpdatableSketchBuilder

+
+ +
+
Package
+
Description
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/package-summary.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/package-summary.html new file mode 100644 index 000000000..22d4662aa --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/package-summary.html @@ -0,0 +1,167 @@ + + + + +org.apache.datasketches.tuple.arrayofdoubles (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.tuple.arrayofdoubles

+
+
+
+
package org.apache.datasketches.tuple.arrayofdoubles
+
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/package-tree.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/package-tree.html new file mode 100644 index 000000000..95c5de45b --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/package-tree.html @@ -0,0 +1,100 @@ + + + + +org.apache.datasketches.tuple.arrayofdoubles Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.tuple.arrayofdoubles

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Interface Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/package-use.html b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/package-use.html new file mode 100644 index 000000000..9925da315 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/arrayofdoubles/package-use.html @@ -0,0 +1,128 @@ + + + + +Uses of Package org.apache.datasketches.tuple.arrayofdoubles (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.tuple.arrayofdoubles

+
+ +
+
Package
+
Description
+ +
+
This package is for a concrete implementation of the Tuple sketch for an array of double values.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/CompactTupleSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/CompactTupleSketch.html new file mode 100644 index 000000000..98b9fa142 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/CompactTupleSketch.html @@ -0,0 +1,167 @@ + + + + +Uses of Class org.apache.datasketches.tuple.CompactTupleSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.CompactTupleSketch

+
+
Packages that use CompactTupleSketch
+
+
Package
+
Description
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/DeserializeResult.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/DeserializeResult.html new file mode 100644 index 000000000..39c78ee19 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/DeserializeResult.html @@ -0,0 +1,161 @@ + + + + +Uses of Class org.apache.datasketches.tuple.DeserializeResult (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.DeserializeResult

+
+
Packages that use DeserializeResult
+
+
Package
+
Description
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/Filter.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/Filter.html new file mode 100644 index 000000000..71aef87ec --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/Filter.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.Filter (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.Filter

+
+No usage of org.apache.datasketches.tuple.Filter +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/JaccardSimilarity.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/JaccardSimilarity.html new file mode 100644 index 000000000..8bcbcc22c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/JaccardSimilarity.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.JaccardSimilarity (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.JaccardSimilarity

+
+No usage of org.apache.datasketches.tuple.JaccardSimilarity +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/SerializerDeserializer.SketchType.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/SerializerDeserializer.SketchType.html new file mode 100644 index 000000000..1d9a165f9 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/SerializerDeserializer.SketchType.html @@ -0,0 +1,132 @@ + + + + +Uses of Enum Class org.apache.datasketches.tuple.SerializerDeserializer.SketchType (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Enum Class
org.apache.datasketches.tuple.SerializerDeserializer.SketchType

+
+ +
+
Package
+
Description
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/SerializerDeserializer.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/SerializerDeserializer.html new file mode 100644 index 000000000..d1fa71881 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/SerializerDeserializer.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.SerializerDeserializer (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.SerializerDeserializer

+
+No usage of org.apache.datasketches.tuple.SerializerDeserializer +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/Summary.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/Summary.html new file mode 100644 index 000000000..db703cc0f --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/Summary.html @@ -0,0 +1,412 @@ + + + + +Uses of Interface org.apache.datasketches.tuple.Summary (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.tuple.Summary

+
+
Packages that use Summary
+
+
Package
+
Description
+ +
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/SummaryDeserializer.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/SummaryDeserializer.html new file mode 100644 index 000000000..27868716a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/SummaryDeserializer.html @@ -0,0 +1,180 @@ + + + + +Uses of Interface org.apache.datasketches.tuple.SummaryDeserializer (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.tuple.SummaryDeserializer

+
+
Packages that use SummaryDeserializer
+
+
Package
+
Description
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/SummaryFactory.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/SummaryFactory.html new file mode 100644 index 000000000..9e6f98892 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/SummaryFactory.html @@ -0,0 +1,198 @@ + + + + +Uses of Interface org.apache.datasketches.tuple.SummaryFactory (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.tuple.SummaryFactory

+
+
Packages that use SummaryFactory
+
+
Package
+
Description
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/SummarySetOperations.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/SummarySetOperations.html new file mode 100644 index 000000000..110b0835a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/SummarySetOperations.html @@ -0,0 +1,243 @@ + + + + +Uses of Interface org.apache.datasketches.tuple.SummarySetOperations (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.tuple.SummarySetOperations

+
+
Packages that use SummarySetOperations
+
+
Package
+
Description
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleAnotB.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleAnotB.html new file mode 100644 index 000000000..c44ad5fdf --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleAnotB.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.TupleAnotB (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.TupleAnotB

+
+No usage of org.apache.datasketches.tuple.TupleAnotB +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleIntersection.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleIntersection.html new file mode 100644 index 000000000..1fa087232 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleIntersection.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.TupleIntersection (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.TupleIntersection

+
+No usage of org.apache.datasketches.tuple.TupleIntersection +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleSketch.html new file mode 100644 index 000000000..47c6cf922 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleSketch.html @@ -0,0 +1,390 @@ + + + + +Uses of Class org.apache.datasketches.tuple.TupleSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.TupleSketch

+
+
Packages that use TupleSketch
+
+
Package
+
Description
+ +
+
Frequent Distinct Tuples Sketch
+
+ +
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleSketchIterator.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleSketchIterator.html new file mode 100644 index 000000000..d6c942188 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleSketchIterator.html @@ -0,0 +1,100 @@ + + + + +Uses of Class org.apache.datasketches.tuple.TupleSketchIterator (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.TupleSketchIterator

+
+
Packages that use TupleSketchIterator
+
+
Package
+
Description
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleUnion.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleUnion.html new file mode 100644 index 000000000..45a94fc50 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/TupleUnion.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.TupleUnion (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.TupleUnion

+
+No usage of org.apache.datasketches.tuple.TupleUnion +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/UpdatableSummary.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/UpdatableSummary.html new file mode 100644 index 000000000..71d165c20 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/UpdatableSummary.html @@ -0,0 +1,186 @@ + + + + +Uses of Interface org.apache.datasketches.tuple.UpdatableSummary (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Interface
org.apache.datasketches.tuple.UpdatableSummary

+
+
Packages that use UpdatableSummary
+
+
Package
+
Description
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/UpdatableTupleSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/UpdatableTupleSketch.html new file mode 100644 index 000000000..4c5ac48e1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/UpdatableTupleSketch.html @@ -0,0 +1,198 @@ + + + + +Uses of Class org.apache.datasketches.tuple.UpdatableTupleSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.UpdatableTupleSketch

+
+
Packages that use UpdatableTupleSketch
+
+
Package
+
Description
+ +
+
Frequent Distinct Tuples Sketch
+
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/UpdatableTupleSketchBuilder.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/UpdatableTupleSketchBuilder.html new file mode 100644 index 000000000..29ceb6b7c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/UpdatableTupleSketchBuilder.html @@ -0,0 +1,107 @@ + + + + +Uses of Class org.apache.datasketches.tuple.UpdatableTupleSketchBuilder (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.UpdatableTupleSketchBuilder

+
+
Packages that use UpdatableTupleSketchBuilder
+
+
Package
+
Description
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/class-use/Util.html b/target/site/apidocs/org/apache/datasketches/tuple/class-use/Util.html new file mode 100644 index 000000000..c40a3d951 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/class-use/Util.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.Util (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.Util

+
+No usage of org.apache.datasketches.tuple.Util +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/package-summary.html b/target/site/apidocs/org/apache/datasketches/tuple/package-summary.html new file mode 100644 index 000000000..6fa37e623 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/package-summary.html @@ -0,0 +1,204 @@ + + + + +org.apache.datasketches.tuple (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.tuple

+
+
+
+
package org.apache.datasketches.tuple
+
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/package-tree.html b/target/site/apidocs/org/apache/datasketches/tuple/package-tree.html new file mode 100644 index 000000000..68d103366 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/package-tree.html @@ -0,0 +1,121 @@ + + + + +org.apache.datasketches.tuple Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.tuple

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Interface Hierarchy

+ +
+
+

Enum Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/package-use.html b/target/site/apidocs/org/apache/datasketches/tuple/package-use.html new file mode 100644 index 000000000..68433fdc1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/package-use.html @@ -0,0 +1,315 @@ + + + + +Uses of Package org.apache.datasketches.tuple (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.tuple

+
+ +
+
Package
+
Description
+ +
+
Frequent Distinct Tuples Sketch
+
+ +
+
This package contains common tools and methods for the theta, +tuple, tuple/* and fdt packages.
+
+ +
+
The tuple package contains a number of sketches based on the same +fundamental algorithms of the Theta Sketch Framework and extend these +concepts for whole new families of sketches.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Double value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single Integer value.
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsSummary.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsSummary.html new file mode 100644 index 000000000..515a4aa3a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsSummary.html @@ -0,0 +1,259 @@ + + + + +ArrayOfStringsSummary (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfStringsSummary

+
+
java.lang.Object +
org.apache.datasketches.tuple.strings.ArrayOfStringsSummary
+
+
+
+
All Implemented Interfaces:
+
Summary, UpdatableSummary<String[]>
+
+
+
+
public final class ArrayOfStringsSummary +extends Object +implements UpdatableSummary<String[]>
+
Implements UpdatableSummary<String[]>
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      update

      +
      +
      public final ArrayOfStringsSummary update(String[] value)
      +
      Description copied from interface: UpdatableSummary
      +
      This is to provide a method of updating summaries. +This is primarily used internally.
      +
      +
      Specified by:
      +
      update in interface UpdatableSummary<String[]>
      +
      Parameters:
      +
      value - update value
      +
      Returns:
      +
      this
      +
      +
      +
      +
    • +
    • +
      +

      copy

      +
      +
      public ArrayOfStringsSummary copy()
      +
      Description copied from interface: Summary
      +
      Deep copy. + +

      Caution: This must implement a deep copy.

      +
      +
      Specified by:
      +
      copy in interface Summary
      +
      Returns:
      +
      deep copy of the Summary
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      public byte[] toByteArray()
      +
      Description copied from interface: Summary
      +
      This is to serialize a Summary instance to a byte array. + +

      The user should encode in the byte array its total size, which is used during +deserialization, especially if the Summary has variable sized elements.

      +
      +
      Specified by:
      +
      toByteArray in interface Summary
      +
      Returns:
      +
      serialized representation of the Summary
      +
      +
      +
      +
    • +
    • +
      +

      hashCode

      +
      +
      public int hashCode()
      +
      +
      Overrides:
      +
      hashCode in class Object
      +
      +
      +
      +
    • +
    • +
      +

      equals

      +
      +
      public boolean equals(Object summary)
      +
      +
      Overrides:
      +
      equals in class Object
      +
      +
      +
      +
    • +
    • +
      +

      getValue

      +
      +
      public String[] getValue()
      +
      Returns the nodes array for this summary.
      +
      +
      Returns:
      +
      the nodes array for this summary.
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryDeserializer.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryDeserializer.html new file mode 100644 index 000000000..3666146fb --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryDeserializer.html @@ -0,0 +1,201 @@ + + + + +ArrayOfStringsSummaryDeserializer (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfStringsSummaryDeserializer

+
+
java.lang.Object +
org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryDeserializer
+
+
+
+
All Implemented Interfaces:
+
SummaryDeserializer<ArrayOfStringsSummary>
+
+
+
+
public class ArrayOfStringsSummaryDeserializer +extends Object +implements SummaryDeserializer<ArrayOfStringsSummary>
+
Implements SummaryDeserializer<ArrayOfStringsSummary>
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfStringsSummaryDeserializer

      +
      +
      public ArrayOfStringsSummaryDeserializer()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      heapifySummary

      +
      + +
      Description copied from interface: SummaryDeserializer
      +
      This is to create an instance of a Summary given a serialized representation. +The user may assume that the start of the given MemorySegment is the correct place to start +deserializing. However, the user must be able to determine the number of bytes required to +deserialize the summary as the capacity of the given MemorySegment may +include multiple such summaries and may be much larger than required for a single summary.
      +
      +
      Specified by:
      +
      heapifySummary in interface SummaryDeserializer<ArrayOfStringsSummary>
      +
      Parameters:
      +
      seg - MemorySegment object with serialized representation of a Summary
      +
      Returns:
      +
      DeserializedResult object, which contains a Summary object and number of bytes read +from the MemorySegment
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryFactory.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryFactory.html new file mode 100644 index 000000000..93f2e846c --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsSummaryFactory.html @@ -0,0 +1,194 @@ + + + + +ArrayOfStringsSummaryFactory (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfStringsSummaryFactory

+
+
java.lang.Object +
org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryFactory
+
+
+
+
All Implemented Interfaces:
+
SummaryFactory<ArrayOfStringsSummary>
+
+
+
+
public class ArrayOfStringsSummaryFactory +extends Object +implements SummaryFactory<ArrayOfStringsSummary>
+
Implements SummaryFactory<ArrayOfStringsSummary>
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfStringsSummaryFactory

      +
      +
      public ArrayOfStringsSummaryFactory()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    + +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsSummarySetOperations.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsSummarySetOperations.html new file mode 100644 index 000000000..a5a27fd62 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsSummarySetOperations.html @@ -0,0 +1,236 @@ + + + + +ArrayOfStringsSummarySetOperations (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfStringsSummarySetOperations

+
+
java.lang.Object +
org.apache.datasketches.tuple.strings.ArrayOfStringsSummarySetOperations
+
+
+
+
All Implemented Interfaces:
+
SummarySetOperations<ArrayOfStringsSummary>
+
+
+
+
public class ArrayOfStringsSummarySetOperations +extends Object +implements SummarySetOperations<ArrayOfStringsSummary>
+
Implements SummarySetOperations<ArrayOfStringsSummary>
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfStringsSummarySetOperations

      +
      +
      public ArrayOfStringsSummarySetOperations()
      +
      No argument constructor.
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      union

      +
      + +
      Description copied from interface: SummarySetOperations
      +
      This is called by the union operator when both sketches have the same hash value. + +

      Caution: Do not modify the input Summary objects. Also do not return them directly, +unless they are immutable (most Summary objects are not). For mutable Summary objects, it is +important to create a new Summary object with the correct contents to be returned. Do not +return null summaries.

      +
      +
      Specified by:
      +
      union in interface SummarySetOperations<ArrayOfStringsSummary>
      +
      Parameters:
      +
      a - Summary from sketch A
      +
      b - Summary from sketch B
      +
      Returns:
      +
      union of Summary A and Summary B
      +
      +
      +
      +
    • +
    • +
      +

      intersection

      +
      + +
      Description copied from interface: SummarySetOperations
      +
      This is called by the intersection operator when both sketches have the same hash value. + +

      Caution: Do not modify the input Summary objects. Also do not return them directly, +unless they are immutable (most Summary objects are not). For mutable Summary objects, it is +important to create a new Summary object with the correct contents to be returned. Do not +return null summaries.

      +
      +
      Specified by:
      +
      intersection in interface SummarySetOperations<ArrayOfStringsSummary>
      +
      Parameters:
      +
      a - Summary from sketch A
      +
      b - Summary from sketch B
      +
      Returns:
      +
      intersection of Summary A and Summary B
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsTupleSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsTupleSketch.html new file mode 100644 index 000000000..1f3c5dca3 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/ArrayOfStringsTupleSketch.html @@ -0,0 +1,557 @@ + + + + +ArrayOfStringsTupleSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+ +
+

Class ArrayOfStringsTupleSketch

+
+ +
+
+
Direct Known Subclasses:
+
FdtSketch
+
+
+
+
public class ArrayOfStringsTupleSketch +extends UpdatableTupleSketch<String[], ArrayOfStringsSummary>
+
Extends UpdatableTupleSketch<String[], ArrayOfStringsSummary>
+
+
Author:
+
Lee Rhodes
+
+
+
+
+ +
+
+
    + +
  • +
    +

    Constructor Details

    +
      +
    • +
      +

      ArrayOfStringsTupleSketch

      +
      +
      public ArrayOfStringsTupleSketch()
      +
      Constructs new sketch with default K = 4096 (lgK = 12), default ResizeFactor=X8, +and default p = 1.0.
      +
      +
      +
    • +
    • +
      +

      ArrayOfStringsTupleSketch

      +
      +
      public ArrayOfStringsTupleSketch(int lgK)
      +
      Constructs new sketch with default ResizeFactor=X8, default p = 1.0 and given lgK.
      +
      +
      Parameters:
      +
      lgK - Log_base2 of Nominal Entries. +See Nominal Entries
      +
      +
      +
      +
    • +
    • +
      +

      ArrayOfStringsTupleSketch

      +
      +
      public ArrayOfStringsTupleSketch(int lgK, + ResizeFactor rf, + float p)
      +
      Constructs new sketch with given ResizeFactor, p and lgK.
      +
      +
      Parameters:
      +
      lgK - Log_base2 of Nominal Entries. +See Nominal Entries
      +
      rf - ResizeFactor +See Resize Factor
      +
      p - sampling probability +See Sampling Probability
      +
      +
      +
      +
    • +
    • +
      +

      ArrayOfStringsTupleSketch

      +
      +
      @Deprecated +public ArrayOfStringsTupleSketch(MemorySegment seg)
      +
      Deprecated. +
      As of 3.0.0, heapifying an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Heapifying a CompactTupleSketch is not deprecated.
      +
      +
      Constructs this sketch from a MemorySegment image, which must be from an ArrayOfStringsTupleSketch, and +usually with data.
      +
      +
      Parameters:
      +
      seg - the given MemorySegment
      +
      +
      +
      +
    • +
    • +
      +

      ArrayOfStringsTupleSketch

      +
      +
      public ArrayOfStringsTupleSketch(ArrayOfStringsTupleSketch sketch)
      +
      Copy Constructor
      +
      +
      Parameters:
      +
      sketch - the sketch to copy
      +
      +
      +
      +
    • +
    +
    +
  • + +
  • +
    +

    Method Details

    +
      +
    • +
      +

      copy

      +
      + +
      +
      Overrides:
      +
      copy in class UpdatableTupleSketch<String[], ArrayOfStringsSummary>
      +
      Returns:
      +
      a deep copy of this sketch
      +
      +
      +
      +
    • +
    • +
      +

      update

      +
      +
      public void update(String[] strArrKey, + String[] strArr)
      +
      Updates the sketch with String arrays for both key and value.
      +
      +
      Parameters:
      +
      strArrKey - the given String array key
      +
      strArr - the given String array value
      +
      +
      +
      +
    • +
    • +
      +

      getRetainedEntries

      +
      +
      public int getRetainedEntries()
      +
      Description copied from class: TupleSketch
      +
      Returns number of retained entries
      +
      +
      Specified by:
      +
      getRetainedEntries in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      number of retained entries
      +
      +
      +
      +
    • +
    • +
      +

      getCountLessThanThetaLong

      +
      +
      public int getCountLessThanThetaLong(long thetaLong)
      +
      Description copied from class: TupleSketch
      +
      Gets the number of hash values less than the given theta expressed as a long.
      +
      +
      Specified by:
      +
      getCountLessThanThetaLong in class TupleSketch<S extends Summary>
      +
      Parameters:
      +
      thetaLong - the given theta as a long in the range (zero, Long.MAX_VALUE].
      +
      Returns:
      +
      the number of hash values less than the given thetaLong.
      +
      +
      +
      +
    • +
    • +
      +

      getNominalEntries

      +
      +
      public int getNominalEntries()
      +
      Get configured nominal number of entries
      +
      +
      Returns:
      +
      nominal number of entries
      +
      +
      +
      +
    • +
    • +
      +

      getLgK

      +
      +
      public int getLgK()
      +
      Get log_base2 of Nominal Entries
      +
      +
      Returns:
      +
      log_base2 of Nominal Entries
      +
      +
      +
      +
    • +
    • +
      +

      getSamplingProbability

      +
      +
      public float getSamplingProbability()
      +
      Get configured sampling probability
      +
      +
      Returns:
      +
      sampling probability
      +
      +
      +
      +
    • +
    • +
      +

      getCurrentCapacity

      +
      +
      public int getCurrentCapacity()
      +
      Get current capacity
      +
      +
      Returns:
      +
      current capacity
      +
      +
      +
      +
    • +
    • +
      +

      getResizeFactor

      +
      +
      public ResizeFactor getResizeFactor()
      +
      Get configured resize factor
      +
      +
      Returns:
      +
      resize factor
      +
      +
      +
      +
    • +
    • +
      +

      trim

      +
      +
      public void trim()
      +
      Rebuilds reducing the actual number of entries to the nominal number of entries if needed
      +
      +
      +
    • +
    • +
      +

      reset

      +
      +
      public void reset()
      +
      Resets this sketch an empty state.
      +
      +
      +
    • +
    • +
      +

      compact

      +
      + +
      Converts the current state of the sketch into a compact sketch
      +
      +
      Specified by:
      +
      compact in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      compact sketch
      +
      +
      +
      +
    • +
    • +
      +

      toByteArray

      +
      +
      @Deprecated +public byte[] toByteArray()
      +
      Deprecated. +
      As of 3.0.0, serializing an UpdatableTupleSketch is deprecated. +This capability will be removed in a future release. +Serializing a CompactTupleSketch is not deprecated.
      +
      +
      This serializes an UpdatableTupleSketch (QuickSelectSketch).
      +
      +
      Specified by:
      +
      toByteArray in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      serialized representation of an UpdatableTupleSketch (QuickSelectSketch).
      +
      +
      +
      +
    • +
    • +
      +

      iterator

      +
      + +
      Description copied from class: TupleSketch
      +
      Returns a SketchIterator
      +
      +
      Specified by:
      +
      iterator in class TupleSketch<S extends Summary>
      +
      Returns:
      +
      a SketchIterator
      +
      +
      +
      +
    • +
    +
    +
  • +
+
+ +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsSummary.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsSummary.html new file mode 100644 index 000000000..13bf6f9c1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsSummary.html @@ -0,0 +1,162 @@ + + + + +Uses of Class org.apache.datasketches.tuple.strings.ArrayOfStringsSummary (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.strings.ArrayOfStringsSummary

+
+
Packages that use ArrayOfStringsSummary
+
+
Package
+
Description
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsSummaryDeserializer.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsSummaryDeserializer.html new file mode 100644 index 000000000..93cbf7590 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsSummaryDeserializer.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryDeserializer (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryDeserializer

+
+No usage of org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryDeserializer +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsSummaryFactory.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsSummaryFactory.html new file mode 100644 index 000000000..956b12cd1 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsSummaryFactory.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryFactory (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryFactory

+
+No usage of org.apache.datasketches.tuple.strings.ArrayOfStringsSummaryFactory +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsSummarySetOperations.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsSummarySetOperations.html new file mode 100644 index 000000000..0fd9b3a09 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsSummarySetOperations.html @@ -0,0 +1,67 @@ + + + + +Uses of Class org.apache.datasketches.tuple.strings.ArrayOfStringsSummarySetOperations (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.strings.ArrayOfStringsSummarySetOperations

+
+No usage of org.apache.datasketches.tuple.strings.ArrayOfStringsSummarySetOperations +
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsTupleSketch.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsTupleSketch.html new file mode 100644 index 000000000..bf3c97050 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/class-use/ArrayOfStringsTupleSketch.html @@ -0,0 +1,124 @@ + + + + +Uses of Class org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Class
org.apache.datasketches.tuple.strings.ArrayOfStringsTupleSketch

+
+
Packages that use ArrayOfStringsTupleSketch
+
+
Package
+
Description
+ +
+
Frequent Distinct Tuples Sketch
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/package-summary.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/package-summary.html new file mode 100644 index 000000000..f8ddbc1b3 --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/package-summary.html @@ -0,0 +1,140 @@ + + + + +org.apache.datasketches.tuple.strings (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+ +
+
+

Package org.apache.datasketches.tuple.strings

+
+
+
+
package org.apache.datasketches.tuple.strings
+
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/package-tree.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/package-tree.html new file mode 100644 index 000000000..a5712730a --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/package-tree.html @@ -0,0 +1,91 @@ + + + + +org.apache.datasketches.tuple.strings Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For Package org.apache.datasketches.tuple.strings

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/org/apache/datasketches/tuple/strings/package-use.html b/target/site/apidocs/org/apache/datasketches/tuple/strings/package-use.html new file mode 100644 index 000000000..e47846efa --- /dev/null +++ b/target/site/apidocs/org/apache/datasketches/tuple/strings/package-use.html @@ -0,0 +1,112 @@ + + + + +Uses of Package org.apache.datasketches.tuple.strings (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Uses of Package
org.apache.datasketches.tuple.strings

+
+ +
+
Package
+
Description
+ +
+
Frequent Distinct Tuples Sketch
+
+ +
+
This package is for a generic implementation of the Tuple sketch for single String value.
+
+
+
+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/overview-summary.html b/target/site/apidocs/overview-summary.html new file mode 100644 index 000000000..d39a1c106 --- /dev/null +++ b/target/site/apidocs/overview-summary.html @@ -0,0 +1,26 @@ + + + + +datasketches-java 9.0.1-SNAPSHOT API + + + + + + + + + + + +
+ +

index.html

+
+ + diff --git a/target/site/apidocs/overview-tree.html b/target/site/apidocs/overview-tree.html new file mode 100644 index 000000000..a30a7a40e --- /dev/null +++ b/target/site/apidocs/overview-tree.html @@ -0,0 +1,408 @@ + + + + +Class Hierarchy (datasketches-java 9.0.1-SNAPSHOT API) + + + + + + + + + + + + + + +
+ +
+
+
+
+

Hierarchy For All Packages

+
+Package Hierarchies: + +
+

Class Hierarchy

+ +
+
+

Interface Hierarchy

+ +
+
+

Annotation Interface Hierarchy

+ +
+
+

Enum Class Hierarchy

+ +
+
+
+ +
+
+
+ + diff --git a/target/site/apidocs/package-search-index.js b/target/site/apidocs/package-search-index.js new file mode 100644 index 000000000..bfb0d185f --- /dev/null +++ b/target/site/apidocs/package-search-index.js @@ -0,0 +1 @@ +packageSearchIndex = [{"l":"All Packages","u":"allpackages-index.html","k":"18"},{"l":"org.apache.datasketches"},{"l":"org.apache.datasketches.common"},{"l":"org.apache.datasketches.common.positional"},{"l":"org.apache.datasketches.count"},{"l":"org.apache.datasketches.cpc"},{"l":"org.apache.datasketches.fdt"},{"l":"org.apache.datasketches.filters"},{"l":"org.apache.datasketches.filters.bloomfilter"},{"l":"org.apache.datasketches.frequencies"},{"l":"org.apache.datasketches.hash"},{"l":"org.apache.datasketches.hll"},{"l":"org.apache.datasketches.hllmap"},{"l":"org.apache.datasketches.kll"},{"l":"org.apache.datasketches.partitions"},{"l":"org.apache.datasketches.quantiles"},{"l":"org.apache.datasketches.quantilescommon"},{"l":"org.apache.datasketches.req"},{"l":"org.apache.datasketches.sampling"},{"l":"org.apache.datasketches.tdigest"},{"l":"org.apache.datasketches.theta"},{"l":"org.apache.datasketches.thetacommon"},{"l":"org.apache.datasketches.tuple"},{"l":"org.apache.datasketches.tuple.adouble"},{"l":"org.apache.datasketches.tuple.aninteger"},{"l":"org.apache.datasketches.tuple.arrayofdoubles"},{"l":"org.apache.datasketches.tuple.strings"}];updateSearchResults(); \ No newline at end of file diff --git a/target/site/apidocs/resource-files/copy.svg b/target/site/apidocs/resource-files/copy.svg new file mode 100644 index 000000000..b07ac7e8c --- /dev/null +++ b/target/site/apidocs/resource-files/copy.svg @@ -0,0 +1,15 @@ + + + + + + + + diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-Bold.woff b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-Bold.woff new file mode 100644 index 000000000..63a79c041 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-Bold.woff differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-Bold.woff2 b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-Bold.woff2 new file mode 100644 index 000000000..06655540c Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-Bold.woff2 differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-BoldOblique.woff b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-BoldOblique.woff new file mode 100644 index 000000000..dead29087 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-BoldOblique.woff differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-BoldOblique.woff2 b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-BoldOblique.woff2 new file mode 100644 index 000000000..89328f3c4 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-BoldOblique.woff2 differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-Oblique.woff b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-Oblique.woff new file mode 100644 index 000000000..6c62443d0 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-Oblique.woff differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-Oblique.woff2 b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-Oblique.woff2 new file mode 100644 index 000000000..8a50fa152 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans-Oblique.woff2 differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSans.woff b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans.woff new file mode 100644 index 000000000..a0f1efa91 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans.woff differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSans.woff2 b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans.woff2 new file mode 100644 index 000000000..fecdbd87e Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSans.woff2 differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-Bold.woff b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-Bold.woff new file mode 100644 index 000000000..9f646ba06 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-Bold.woff differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-Bold.woff2 b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-Bold.woff2 new file mode 100644 index 000000000..346de2da4 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-Bold.woff2 differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-BoldOblique.woff b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-BoldOblique.woff new file mode 100644 index 000000000..7a6b3ac04 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-BoldOblique.woff differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-BoldOblique.woff2 b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-BoldOblique.woff2 new file mode 100644 index 000000000..ede24ef6a Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-BoldOblique.woff2 differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-Oblique.woff b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-Oblique.woff new file mode 100644 index 000000000..892833b94 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-Oblique.woff differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-Oblique.woff2 b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-Oblique.woff2 new file mode 100644 index 000000000..9e9051434 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono-Oblique.woff2 differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono.woff b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono.woff new file mode 100644 index 000000000..e94e844d1 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono.woff differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono.woff2 b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono.woff2 new file mode 100644 index 000000000..9460c050f Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSansMono.woff2 differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-Bold.woff b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-Bold.woff new file mode 100644 index 000000000..0f38846c5 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-Bold.woff differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-Bold.woff2 b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-Bold.woff2 new file mode 100644 index 000000000..d65a5e956 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-Bold.woff2 differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-BoldItalic.woff b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-BoldItalic.woff new file mode 100644 index 000000000..63fd5e38d Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-BoldItalic.woff differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-BoldItalic.woff2 b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-BoldItalic.woff2 new file mode 100644 index 000000000..e29307ea2 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-BoldItalic.woff2 differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-Italic.woff b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-Italic.woff new file mode 100644 index 000000000..5df6d0015 Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-Italic.woff differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-Italic.woff2 b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-Italic.woff2 new file mode 100644 index 000000000..61ff1463c Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif-Italic.woff2 differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif.woff b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif.woff new file mode 100644 index 000000000..280e3783c Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif.woff differ diff --git a/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif.woff2 b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif.woff2 new file mode 100644 index 000000000..bbd32cdec Binary files /dev/null and b/target/site/apidocs/resource-files/fonts/DejaVuLGCSerif.woff2 differ diff --git a/target/site/apidocs/resource-files/fonts/dejavu.css b/target/site/apidocs/resource-files/fonts/dejavu.css new file mode 100644 index 000000000..b450caa32 --- /dev/null +++ b/target/site/apidocs/resource-files/fonts/dejavu.css @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ + */ + +/* DejaVu fonts v2.37 */ + +@font-face { + font-family: 'DejaVu Sans Mono'; + src: url('DejaVuLGCSansMono.woff2') format('woff2'), + url('DejaVuLGCSansMono.woff') format('woff'); + font-weight: normal; + font-style: normal; +} + +@font-face { + font-family: 'DejaVu Sans Mono'; + src: url('DejaVuLGCSansMono-Oblique.woff2') format('woff2'), + url('DejaVuLGCSansMono-Oblique.woff') format('woff'); + font-weight: normal; + font-style: italic; +} + +@font-face { + font-family: 'DejaVu Sans Mono'; + src: url('DejaVuLGCSansMono-Bold.woff2') format('woff2'), + url('DejaVuLGCSansMono-Bold.woff') format('woff'); + font-weight: bold; + font-style: normal; +} + +@font-face { + font-family: 'DejaVu Sans Mono'; + src: url('DejaVuLGCSansMono-BoldOblique.woff2') format('woff2'), + url('DejaVuLGCSansMono-BoldOblique.woff') format('woff'); + font-weight: bold; + font-style: italic; +} + +@font-face { + font-family: 'DejaVu Sans'; + src: url('DejaVuLGCSans.woff2') format('woff2'), + url('DejaVuLGCSans.woff') format('woff'); + font-weight: normal; + font-style: normal; +} + +@font-face { + font-family: 'DejaVu Sans'; + src: url('DejaVuLGCSans-Oblique.woff2') format('woff2'), + url('DejaVuLGCSans-Oblique.woff') format('woff'); + font-weight: normal; + font-style: italic; +} + +@font-face { + font-family: 'DejaVu Sans'; + src: url('DejaVuLGCSans-Bold.woff2') format('woff2'), + url('DejaVuLGCSans-Bold.woff') format('woff'); + font-weight: bold; + font-style: normal; +} + +@font-face { + font-family: 'DejaVu Sans'; + src: url('DejaVuLGCSans-BoldOblique.woff2') format('woff2'), + url('DejaVuLGCSans-BoldOblique.woff') format('woff'); + font-weight: bold; + font-style: italic; +} + +@font-face { + font-family: 'DejaVu Serif'; + src: url('DejaVuLGCSerif.woff2') format('woff2'), + url('DejaVuLGCSerif.woff') format('woff'); + font-weight: normal; + font-style: normal; +} + +@font-face { + font-family: 'DejaVu Serif'; + src: url('DejaVuLGCSerif-Italic.woff2') format('woff2'), + url('DejaVuLGCSerif-Italic.woff') format('woff'); + font-weight: normal; + font-style: italic; +} + +@font-face { + font-family: 'DejaVu Serif'; + src: url('DejaVuLGCSerif-Bold.woff2') format('woff2'), + url('DejaVuLGCSerif-Bold.woff') format('woff'); + font-weight: bold; + font-style: normal; +} + +@font-face { + font-family: 'DejaVu Serif'; + src: url('DejaVuLGCSerif-BoldItalic.woff2') format('woff2'), + url('DejaVuLGCSerif-BoldItalic.woff') format('woff'); + font-weight: bold; + font-style: italic; +} diff --git a/target/site/apidocs/resource-files/glass.svg b/target/site/apidocs/resource-files/glass.svg new file mode 100644 index 000000000..ff7df85e8 --- /dev/null +++ b/target/site/apidocs/resource-files/glass.svg @@ -0,0 +1,13 @@ + + + + + + + + \ No newline at end of file diff --git a/target/site/apidocs/resource-files/jquery-ui.min.css b/target/site/apidocs/resource-files/jquery-ui.min.css new file mode 100644 index 000000000..7e0692dc9 --- /dev/null +++ b/target/site/apidocs/resource-files/jquery-ui.min.css @@ -0,0 +1,6 @@ +/*! jQuery UI - v1.14.1 - 2025-01-13 +* https://jqueryui.com +* Includes: core.css, autocomplete.css, menu.css +* Copyright OpenJS Foundation and other contributors; Licensed MIT */ + +.ui-helper-hidden{display:none}.ui-helper-hidden-accessible{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.ui-helper-reset{margin:0;padding:0;border:0;outline:0;line-height:1.3;text-decoration:none;font-size:100%;list-style:none}.ui-helper-clearfix:before,.ui-helper-clearfix:after{content:"";display:table;border-collapse:collapse}.ui-helper-clearfix:after{clear:both}.ui-helper-zfix{width:100%;height:100%;top:0;left:0;position:absolute;opacity:0}.ui-front{z-index:100}.ui-state-disabled{cursor:default!important;pointer-events:none}.ui-icon{display:inline-block;vertical-align:middle;margin-top:-.25em;position:relative;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat}.ui-widget-icon-block{left:50%;margin-left:-8px;display:block}.ui-widget-overlay{position:fixed;top:0;left:0;width:100%;height:100%}.ui-autocomplete{position:absolute;top:0;left:0;cursor:default}.ui-menu{list-style:none;padding:0;margin:0;display:block;outline:0}.ui-menu .ui-menu{position:absolute}.ui-menu .ui-menu-item{margin:0;cursor:pointer}.ui-menu .ui-menu-item-wrapper{position:relative;padding:3px 1em 3px .4em}.ui-menu .ui-menu-divider{margin:5px 0;height:0;font-size:0;line-height:0;border-width:1px 0 0 0}.ui-menu .ui-state-focus,.ui-menu .ui-state-active{margin:-1px}.ui-menu-icons{position:relative}.ui-menu-icons .ui-menu-item-wrapper{padding-left:2em}.ui-menu .ui-icon{position:absolute;top:0;bottom:0;left:.2em;margin:auto 0}.ui-menu .ui-menu-icon{left:auto;right:0} \ No newline at end of file diff --git a/target/site/apidocs/resource-files/left.svg b/target/site/apidocs/resource-files/left.svg new file mode 100644 index 000000000..11a93ff04 --- /dev/null +++ b/target/site/apidocs/resource-files/left.svg @@ -0,0 +1,12 @@ + + + + + + + diff --git a/target/site/apidocs/resource-files/link.svg b/target/site/apidocs/resource-files/link.svg new file mode 100644 index 000000000..58d38ac98 --- /dev/null +++ b/target/site/apidocs/resource-files/link.svg @@ -0,0 +1,13 @@ + + + + + + + + diff --git a/target/site/apidocs/resource-files/right.svg b/target/site/apidocs/resource-files/right.svg new file mode 100644 index 000000000..4b54939c3 --- /dev/null +++ b/target/site/apidocs/resource-files/right.svg @@ -0,0 +1,12 @@ + + + + + + + diff --git a/target/site/apidocs/resource-files/stylesheet.css b/target/site/apidocs/resource-files/stylesheet.css new file mode 100644 index 000000000..f7994c7f7 --- /dev/null +++ b/target/site/apidocs/resource-files/stylesheet.css @@ -0,0 +1,1667 @@ +/* + * Copyright (c) 2010, 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ + */ + +/* + * Javadoc style sheet + */ + +@import url('fonts/dejavu.css'); + +/* + * These CSS custom properties (variables) define the core color and font + * properties used in this stylesheet. + */ +:root { + /* body, block and code fonts */ + --body-font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; + --block-font-family: 'DejaVu Serif', Georgia, "Times New Roman", Times, serif; + --code-font-family: 'DejaVu Sans Mono', monospace; + /* Base font sizes for body and code elements */ + --body-font-size: 14.2px; + --block-font-size: 14.4px; + --code-font-size: 14px; + --nav-font-size: 13.4px; + /* Line height for continuous text blocks */ + --block-line-height: 1.5; + --code-line-height: 1.6; + /* Text colors for body and block elements */ + --body-text-color: #181818; + --block-text-color: #181818; + /* Background colors for various elements */ + --body-background-color: #ffffff; + --section-background-color: var(--body-background-color); + --detail-background-color: #ffffff; + --code-background-color: #f5f5f5; + --mark-background-color: #f7f7f7; + --detail-block-color: #f4f4f4; + /* Colors for navigation bar and table captions */ + --navbar-background-color: #4D7A97; + --navbar-text-color: #ffffff; + /* Background color for subnavigation and various headers */ + --subnav-background-color: #dee3e9; + --subnav-link-color: #47688a; + --member-heading-background-color: var(--subnav-background-color); + /* Background and text colors for selected tabs and navigation items */ + --selected-background-color: #f8981d; + --selected-text-color: #253441; + --selected-link-color: #4a698a; + /* Background colors for generated tables */ + --table-header-color: #ebeff4; + --even-row-color: #ffffff; + --odd-row-color: #f0f0f2; + /* Text color for page title */ + --title-color: #2c4557; + /* Text colors for links */ + --link-color: #437291; + --link-color-active: #bb7a2a; + /* Table of contents */ + --toc-background-color: #f8f8f8; + --toc-highlight-color: var(--subnav-background-color); + --toc-hover-color: #e9ecf0; + /* Snippet and pre colors */ + --snippet-background-color: #f2f2f4; + --snippet-text-color: var(--block-text-color); + --snippet-highlight-color: #f7c590; + --pre-background-color: var(--snippet-background-color); + --pre-text-color: var(--snippet-text-color); + /* Border colors for structural elements and user defined tables */ + --border-color: #e6e6e6; + --table-border-color: #000000; + /* Styles for table tabs */ + --tab-border-radius: 2px 2px 0 0; + /* Search input colors */ + --search-input-background-color: #ffffff; + --search-input-text-color: #000000; + --search-input-placeholder-color: #909090; + /* Highlight color for active search tag target */ + --search-tag-highlight-color: #ffff66; + /* Copy button colors and filters */ + --button-border-color: #b0b8c8; + --button-active-filter: brightness(96%); + --button-focus-filter: brightness(104%); + /* Colors for invalid tag notifications */ + --invalid-tag-background-color: #ffe6e6; + --invalid-tag-text-color: #000000; + /* Navigation bar dimensions */ + --top-nav-height: 44px; + --sub-nav-height: 36px; + --nav-height: calc(var(--top-nav-height) + var(--sub-nav-height)); + --max-content-width: 1500px; + --content-margin: 0 auto; +} +/* + * Styles for individual HTML elements. + * + * These are styles that are specific to individual HTML elements. Changing them affects the style of a particular + * HTML element throughout the page. + */ +body { + background-color:var(--body-background-color); + color:var(--body-text-color); + font-family:var(--body-font-family); + font-size:var(--body-font-size); + margin:0; + padding:0; + height:100%; + width:100%; +} +main [id] { + scroll-margin-top: calc(var(--nav-height) + 6px); +} +div.main-grid { + max-width: var(--max-content-width); + margin: var(--content-margin); +} +a:link, a:visited { + text-decoration:none; + color:var(--link-color); +} +nav a:link, nav a:visited { + color: var(--subnav-link-color); +} +a[href]:hover, a[href]:active { + text-decoration:none; + color:var(--link-color-active); +} +pre { + font-family:var(--code-font-family); + font-size:var(--code-font-size); + line-height: var(--code-line-height); + background-color: var(--pre-background-color); + color: var(--pre-text-color); + padding: 10px; + overflow-x:auto; +} +h1 { + font-size:1.425em; +} +h2 { + font-size:1.28em; +} +h3 { + font-size:1.14em; +} +h4 { + font-size:1.072em; +} +h5 { + font-size:1.001em; +} +h6 { + font-size:0.93em; +} +/* Disable font boosting for selected elements */ +h1, h2, h3, h4, h5, h6, div.member-signature, div.member-signature > span { + max-height: 1000em; +} +ul { + list-style-type:disc; +} +tt { + font-family:var(--code-font-family); +} +code { + font-family:var(--code-font-family); + font-size:var(--code-font-size); +} +button { + font-family: var(--body-font-family); + font-size: 1em; +} +hr { + border-color: #aaa; +} +/* + * Styles for HTML generated by javadoc. + * + * These are style classes that are used by the standard doclet to generate HTML documentation. + */ + +/* + * Styles for document title and copyright. + */ +.about-language { + flex: 0 0 auto; + padding:0 20px; + margin:0; + font-size:0.915em; + max-width: 50%; + white-space: nowrap; +} +.legal-copy { + font-family: var(--body-font-family); + line-height: normal; +} +/* + * Styles for navigation bar. + */ +@media screen { + header { + position:sticky; + top:0; + z-index:2; + background: var(--body-background-color); + } +} +.nav-content { + display:flex; + flex-direction: row; + align-items: center; + width: 100%; + height: 100%; + max-width: var(--max-content-width); + margin: var(--content-margin); +} +.top-nav { + background-color:var(--navbar-background-color); + color:var(--navbar-text-color); + width:100%; + height:var(--top-nav-height); + overflow:visible; + font-size:0.857em; + position:relative; +} +.top-nav nav.toc { + display: none; + flex-direction: column; +} +.top-nav nav.toc button.show-sidebar, +.top-nav nav.toc button.hide-sidebar { + display: none; +} +button#navbar-toggle-button { + display:none; +} +ul.nav-list { + display:inline-flex; + margin:0; + padding-left:4px; + flex: 1 1 auto; + white-space: nowrap; +} +ul.nav-list li { + list-style:none; + padding: 5px 6px; + text-transform:uppercase; + height: 1.2em; +} +div.sub-nav { + background-color:var(--subnav-background-color); + width:100%; + overflow:hidden; + font-size:var(--nav-font-size); + height: var(--sub-nav-height); +} +ol.sub-nav-list { + flex: 1 1 90%; + line-height: 1.8; + display: inline-flex; + overflow: auto; + scroll-snap-type: x mandatory; + scroll-padding-left: 13px; + scrollbar-width: none; + padding-left:6px; + white-space: nowrap; + margin:0; +} +ol.sub-nav-list::-webkit-scrollbar { + display: none; +} +ol.sub-nav-list li { + list-style:none; + scroll-snap-align: start; +} +ol.sub-nav-list li:not(:first-child) { + background: url("right.svg") no-repeat 3px; + background-size: 10px; + padding-left: 17px; + list-style: none; +} +ol.sub-nav-list a { + padding: 3px; +} +ol.sub-nav-list a.current-selection { + background-color: var(--toc-background-color); + border-radius: 3px; +} +.sub-nav .nav-list-search { + flex: 1 1 10%; + margin: 0 15px; + position:relative; + white-space: nowrap; +} +.top-nav .nav-list a:link, .top-nav .nav-list a:active, .top-nav .nav-list a:visited { + color:var(--navbar-text-color); + text-decoration:none; + text-transform:uppercase; +} +.top-nav .nav-list a:hover { + color:var(--link-color-active); +} +.nav-bar-cell1-rev { + background-color:var(--selected-background-color); + color:var(--selected-text-color); + margin: 0 5px; + border-radius: 1px; +} +.skip-nav { + position:absolute; + top:auto; + left:-9999px; + overflow:hidden; +} +/* + * Styles for page header. + */ +.title { + color:var(--title-color); + margin:10px 0 12px 0; +} +.sub-title { + margin:5px 0 0 0; +} +ul.contents-list { + margin: 0 0 15px 0; + padding: 0; + list-style: none; +} +ul.contents-list li { + font-size:0.93em; +} +/* + * Styles for headings. + */ +body.class-declaration-page .summary h2, +body.class-declaration-page .details h2, +body.class-use-page h2, +body.module-declaration-page .block-list h2 { + font-style: italic; + padding:0; + margin:15px 0; + overflow-x:auto; +} +body.class-use-page h2 { + margin-top: 20px; +} +body.class-declaration-page .details h3 { + background-color:var(--member-heading-background-color); + border:1px solid var(--border-color); + margin:6px 0; + padding:7px; + overflow-x:auto; + font-size: 1.08em; +} +body.class-declaration-page section.detail:target > h3, +body.class-declaration-page section.detail > h3:target { + background-color: var(--navbar-background-color); + color: var(--navbar-text-color); +} +body.class-declaration-page section.detail:target > h3 > a.anchor-link > img, +body.class-declaration-page section.detail > h3:target > a.anchor-link > img { + filter: invert(100%) sepia(4%) saturate(98%) hue-rotate(212deg) brightness(160%) contrast(160%); +} +h1 > sup { + font-size: small; +} +/* + * Styles for page layout containers. + */ +.main-grid { + display: flex; + flex-direction: row; +} +.main-grid main { + flex: 3.2 1 0; + min-width: 240px +} +.main-grid nav.toc { + flex: 1 1 0; + min-width: 240px; +} +main { + padding:10px 25px; + position:relative; +} +/* Compensate for non-collapsing margins between element description and summary tables */ +div.horizontal-scroll > section[id$=-description] > :is(dl, ol, ul, p, div, blockquote, pre):last-child, +div.horizontal-scroll > section[id$=-description] > :last-child > :is(li, dd):last-child, +section.class-description > div.horizontal-scroll > :is(dl, ol, ul, p, div, blockquote, pre):last-child, +section.class-description > div.horizontal-scroll > :last-child > :is(li, dd):last-child { + margin-bottom:4px; +} +dl.notes > dt { + font-family: var(--body-font-family); + font-size:0.856em; + font-weight:bold; + margin:10px 0 0 0; + color:var(--body-text-color); +} +dl.notes > dd { + margin:6px 10px 10px 15px; + font-size:var(--block-font-size); + font-family:var(--block-font-family); + line-height:var(--block-line-height); +} +dl.notes > dd > ul, dl.notes > dd > ol { + margin-bottom: 1em; + margin-top: 1em; +} +dl.name-value > dt { + margin-left:1px; + font-size:1.1em; + display:inline; + font-weight:bold; +} +dl.name-value > dd { + margin:0 0 0 1px; + font-size:1.1em; + display:inline; +} +/* + * Styles for table of contents. + */ +.main-grid nav.toc { + background-color: var(--toc-background-color); + position: sticky; + top: calc(var(--nav-height)); + max-height: calc(100vh - var(--nav-height)); + display: flex; + flex-direction: column; + font-family: var(--body-font-family); + z-index: 1; +} +.main-grid nav.toc div.toc-header { + top: var(--nav-height); + z-index: 1; + padding: 15px 20px; +} +.main-grid nav.toc > ol.toc-list { + max-height: calc(100vh - var(--nav-height) - 100px); + padding-left: 12px; +} +.main-grid nav.toc button { + position: absolute; + bottom: 16px; + z-index: 3; + background-color: var(--toc-background-color); + color: #666666; + font-size: 0.76rem; + border: none; + cursor: pointer; + padding: 6px 10px; + white-space: nowrap; +} +.main-grid nav.toc button > img { + vertical-align: middle; + width: 16px; + height: 16px; +} +.main-grid nav.toc button.hide-sidebar { + right: 0; +} +.main-grid nav.toc button.show-sidebar { + left: 0; + display: none; +} +.main-grid nav.toc button span { + display: none; +} +.main-grid nav.toc button:hover, +.main-grid nav.toc button:focus { + color: var(--body-text-color); + border: 1px solid var(--subnav-background-color); +} +.main-grid nav.toc button:active { + background-color: var(--subnav-background-color); + color: var(--link-color-active); +} +.main-grid nav.toc button:hover span, +.main-grid nav.toc button:focus span { + display: inline; +} +.main-grid nav.toc button:hover, +.main-grid nav.toc button:focus { + box-shadow: 1px 1px 5px rgba(0,0,0,0.2); +} +.main-grid nav.toc.hide-sidebar { + min-width: revert; + background-color: var(--body-background-color); + max-width: 20px; +} +.main-grid nav.toc.hide-sidebar div.toc-header, +.main-grid nav.toc.hide-sidebar ol.toc-list, +.main-grid nav.toc.hide-sidebar button.hide-sidebar { + display: none; +} +.main-grid nav.toc.hide-sidebar button.show-sidebar { + display: inline; +} +nav.toc div.toc-header { + padding: 15px; + display: inline-flex; + align-items: center; + color: var(--body-text-color); + font-size: 0.856em; + font-weight: bold; + white-space: nowrap; + overflow-x: hidden; + position: sticky; + min-height: 20px; +} +nav.toc > ol.toc-list { + overflow: hidden auto; + overscroll-behavior: contain; +} +nav.toc ol.toc-list { + list-style: none; + font-size: var(--nav-font-size); + padding-left: 0; + margin: 0; +} +a.current-selection { + font-weight: bold; +} +nav.toc a { + display: block; + padding: 8px; + overflow: hidden; + text-overflow: ellipsis; +} +nav.toc ol.toc-list ol.toc-list a { + padding-left: 24px; +} +nav.toc ol.toc-list ol.toc-list ol.toc-list a { + padding-left: 40px; +} +nav.toc a:hover { + background-color: var(--toc-hover-color); +} +nav.toc a.current-selection { + background-color: var(--toc-highlight-color); +} +nav.toc a:focus-visible { + background-color: var(--selected-background-color); + color: var(--selected-text-color); + outline: none; +} +/* + * Styles for lists. + */ +ul.details-list .block > ul, +ul.details-list .notes dd > ul { + margin: 12px 0; +} +li.circle { + list-style:circle; +} +ul.horizontal li { + display:inline; + font-size:0.9em; +} +div.inheritance div.inheritance { + margin-left:2em; +} +main > div.inheritance { + overflow-x:auto; +} +ul.block-list, +ul.details-list, +ul.member-list, +ul.summary-list { + margin:4px 0 10px 0; + padding:0; +} +ul.block-list > li, +ul.details-list > li, +ul.member-list > li, +ul.summary-list > li { + list-style:none; + margin-bottom:15px; + line-height:1.4; +} +ul.ref-list { + padding:0; + margin:0; +} +ul.ref-list > li { + list-style:none; +} +.summary-table dl, .summary-table dl dt, .summary-table dl dd { + margin-top:0; + margin-bottom:1px; +} +dl.notes > dd > ul.tag-list, dl.notes > dd > ul.tag-list-long { + padding-left: 0; + margin: 0; + list-style: none; +} +ul.tag-list li { + display: inline; +} +ul.tag-list li:not(:last-child):after, +ul.tag-list-long li:not(:last-child):after +{ + content: ", "; + white-space: pre-wrap; +} +ul.preview-feature-list { + list-style: none; + margin:0; + padding:0.1em; + line-height: 1.6; +} +ul.preview-feature-list input { + margin-right: 8px; +} +/* + * Styles for tables. + */ +.summary-table, .details-table { + border:1px solid var(--border-color); + border-top:0; + padding:0; + margin-bottom: 14px; +} +.caption { + overflow: auto hidden; + padding: 8px 0 0 1px; +} +.caption span, +.inherited-list h3 { + font-size: 0.98em; + font-weight:bold; + white-space:nowrap; + border-radius: var(--tab-border-radius); + margin: 0; +} +.caption span { + background-color: var(--navbar-background-color); + padding:5px 12px 7px 12px; + height:16px; + color:var(--navbar-text-color); + display:inline-block; +} +.inherited-list h3 { + background-color: var(--subnav-background-color); + padding:6px 12px 7px 12px; + height:17px; + width: fit-content; + max-width: 93%; +} +/* Background required for captions with links */ +.class-use-page .caption span, +.package-use-page .caption span, +.constants-summary-page .caption span, +.inherited-list h3 { + background-color: var(--subnav-background-color); + color: var(--block-text-color); +} +.caption a:link, +.caption a:visited, +.inherited-list h3 a:link, +.inherited-list h3 a:visited { + color:var(--subnav-link-color); +} +div.table-tabs { + padding: 8px 0 0 1px; + white-space: nowrap; + overflow-x: auto; +} +div.table-tabs > button { + font-size: 0.98em; + border: none; + cursor: pointer; + padding: 6px 12px; + font-weight: bold; + margin-right: 8px; + border-radius: var(--tab-border-radius); +} +div.table-tabs > .active-table-tab { + background: var(--selected-background-color); + color: var(--selected-text-color); +} +div.table-tabs > button.table-tab { + background: var(--navbar-background-color); + color: var(--navbar-text-color); +} +.two-column-search-results { + display: grid; + grid-template-columns: minmax(400px, max-content) minmax(400px, auto); +} +div.checkboxes { + line-height: 2; +} +div.checkboxes > span { + margin-left: 10px; +} +div.checkboxes > label { + margin-left: 8px; + white-space: nowrap; +} +div.checkboxes > label > input { + margin: 0 6px 0 2px; +} +.two-column-summary { + display: grid; + grid-template-columns: minmax(25%, max-content) minmax(25%, auto); +} +.three-column-summary { + display: grid; + grid-template-columns: minmax(15%, max-content) minmax(20%, max-content) minmax(20%, auto); +} +.three-column-release-summary { + display: grid; + grid-template-columns: minmax(40%, max-content) minmax(10%, max-content) minmax(40%, auto); +} +.four-column-summary { + display: grid; + grid-template-columns: minmax(10%, max-content) minmax(15%, max-content) minmax(15%, max-content) minmax(15%, auto); +} +@media screen and (max-width: 1000px) { + .four-column-summary { + display: grid; + grid-template-columns: minmax(15%, max-content) minmax(15%, auto); + } +} +@media screen and (max-width: 800px) { + .two-column-search-results { + display: grid; + grid-template-columns: minmax(40%, max-content) minmax(40%, auto); + } + .three-column-summary { + display: grid; + grid-template-columns: minmax(10%, max-content) minmax(25%, auto); + } + .three-column-release-summary { + display: grid; + grid-template-columns: minmax(70%, max-content) minmax(30%, max-content) + } + .three-column-summary .col-last, + .three-column-release-summary .col-last{ + grid-column-end: span 2; + } +} +@media screen and (max-width: 600px) { + .two-column-summary { + display: grid; + grid-template-columns: 1fr; + } +} +.summary-table > div, .details-table > div { + font-size: var(--nav-font-size); + line-height: 1.6; + padding: 8px 3px 3px 7px; + overflow: auto hidden; +} +.summary-table > div.table-header, .details-table > div.table-header { + font-size: 0.92em; + line-height: 1.2; + height: 18px; +} +.table-header { + background: var(--table-header-color); + font-weight: bold; + border-bottom: 1px solid var(--border-color); +} +/* Sortable table columns */ +.table-header[onclick] { + cursor: pointer; +} +.table-header[onclick]::after { + content:""; + display:inline-block; + background-image:url('data:image/svg+xml; utf8, \ + \ + '); + background-size:100% 100%; + width:9px; + height:14px; + margin-left:4px; + margin-bottom:-3px; +} +.table-header[onclick].sort-asc::after { + background-image:url('data:image/svg+xml; utf8, \ + \ + \ + '); + +} +.table-header[onclick].sort-desc::after { + background-image:url('data:image/svg+xml; utf8, \ + \ + \ + '); +} +.col-first, .col-second, .col-constructor-name { + overflow: auto; +} +body:not(.class-declaration-page) .col-first a:link, +.col-summary-item-name a:link { + font-weight:bold; +} +.even-row-color { + background-color:var(--even-row-color); +} +.odd-row-color { + background-color:var(--odd-row-color); +} +/* + * Styles for contents. + */ +div.block { + font-size:var(--block-font-size); + font-family:var(--block-font-family); + line-height:var(--block-line-height); +} +.module-signature, +.package-signature, +.type-signature, +.member-signature { + font-family:var(--code-font-family); + font-size:var(--code-font-size); + margin:8px 0 14px 0; + white-space: pre-wrap; +} +.module-signature, +.package-signature, +.type-signature { + margin-top: 0; +} +.member-signature .parameters, +.member-signature .exceptions { + display: inline-block; + vertical-align: top; + white-space: pre-wrap; +} +.member-signature .type-parameters { + white-space: pre-wrap; +} +:is(h1, h2, h3, h4, h5, h6, sup, sub, small, big) code, +[style*=font-size] code { + font-size: inherit; +} +.doc-file-page main { + font-family: var(--block-font-family); + font-size: var(--block-font-size); + line-height: var(--block-line-height); +} +.doc-file-page main footer { + font-family: var(--body-font-family); + font-size: var(--body-font-size); +} +.tree-page .hierarchy, +.package-tree-page .hierarchy { + line-height: 1.4; +} +/* + * Styles for formatting effect. + */ +.source-line-no { + /* Color of line numbers in source pages can be set via custom property below */ + color:var(--source-linenumber-color, green); + padding:0 30px 0 0; +} +.block { + display:block; + margin:0 10px 5px 0; + color:var(--block-text-color); +} +.deprecated-label, .description-from-type-label, .implementation-label, .member-name-link, +.package-hierarchy-label, .type-name-label, .type-name-link, .search-tag-link, .preview-label, +.restricted-label { + font-weight:bold; +} +sup.preview-mark, +sup.restricted-mark { + font-family: var(--code-font-family); + font-weight: normal; + font-size: 8px; + background-color: var(--mark-background-color); + padding: 1px; + border-radius: 2px; +} +sup.preview-mark > a:link, +sup.restricted-mark > a:link { + font-weight: normal; +} +.deprecation-comment, .help-footnote, .preview-comment, .restricted-comment { + font-style:italic; +} +.deprecation-block, .preview-block, .restricted-block { + font-size:1em; + font-family:var(--block-font-family); + border-style:solid; + border-width:thin; + border-radius:6px; + padding:10px; + margin-bottom:10px; + margin-right:10px; + display:inline-block; +} +.deprecation-block code, .preview-block code, .restricted-block code { + font-size: 0.97em; +} +div.block div.deprecation-comment { + font-style:normal; +} +details.invalid-tag, span.invalid-tag { + font-size:1em; + font-family:var(--block-font-family); + color: var(--invalid-tag-text-color); + background: var(--invalid-tag-background-color); + border: thin solid var(--table-border-color); + border-radius:2px; + padding: 2px 4px; + display:inline-block; +} +details summary { + cursor: pointer; +} +/* + * Styles specific to HTML5 elements. + */ +main, nav, header, footer, section { + display:block; +} +/* + * Styles for javadoc search. + */ +.ui-menu .ui-state-active { + /* Overrides the color of selection used in jQuery UI */ + background: var(--selected-background-color); + color: var(--selected-text-color); + /* Workaround for browser bug, see JDK-8275889 */ + margin: -1px 0; + border-top: 1px solid var(--selected-background-color); + border-bottom: 1px solid var(--selected-background-color); +} +.ui-autocomplete-category { + font-weight:bold; + font-size:15px; + padding:7px 8px; + background-color:var(--navbar-background-color); + color:var(--navbar-text-color); + box-sizing: border-box; +} +.ui-autocomplete { + max-height:calc(98vh - var(--nav-height)); + max-width:min(75vw, calc(var(--max-content-width) * 0.748)); + overflow-y:auto; + white-space:nowrap; + box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23); + overscroll-behavior: contain; +} +ul.ui-autocomplete { + position:fixed; + z-index:10; + background-color: var(--body-background-color); +} +ul.ui-autocomplete li { + float:left; + clear:both; + min-width:100%; + box-sizing: border-box; +} +ul.ui-autocomplete li.ui-static-link { + position:sticky; + bottom:0; + left:0; + background: var(--subnav-background-color); + padding: 5px 0; + font-family: var(--body-font-family); + font-size: 0.93em; + font-weight: bold; + z-index: 10; +} +li.ui-static-link a, li.ui-static-link a:visited { + text-decoration:none; + color:var(--link-color); + float:right; + margin-right:20px; +} +.ui-autocomplete > li.result-item:nth-child(even) { + background-color: var(--even-row-color) +} +.ui-autocomplete > li.result-item:nth-child(odd) { + background-color: var(--odd-row-color) +} +.ui-autocomplete { + display: grid; + grid-template-columns: auto auto; +} +.ui-autocomplete > li, +.ui-autocomplete > li > div { + grid-column: 1 / 3; +} +.ui-autocomplete > li.result-item, +.ui-autocomplete > li.result-item > div { + display: grid; + grid-template-columns: subgrid; +} +.ui-autocomplete > li.result-item { + font-family: var(--body-font-family); + font-size: var(--body-font-size); + line-height: 1.7; +} +.ui-autocomplete .search-result-label { + padding: 1px 4px; + overflow: hidden; + text-overflow: ellipsis; +} +.ui-autocomplete .search-result-desc { + font-size: var(--nav-font-size); + padding: 2px 4px; + color: #404040; + overflow: hidden; + text-overflow: ellipsis; +} +.ui-autocomplete .result-highlight { + font-weight:bold; +} +.ui-menu .ui-state-active .search-result-desc { + color: #383838; +} +.ui-menu .ui-menu-item-wrapper { + padding: 3px 4px; +} +input[type="text"] { + background-image:url('glass.svg'); + background-size:13px; + background-repeat:no-repeat; + background-position:3px 4px; + background-color: var(--search-input-background-color); + color: var(--search-input-text-color); + border-color: var(--border-color); + border-radius: 4px; + padding-left:20px; + padding-right: 18px; + font-size: var(--nav-font-size); + height: 19px; +} +input#page-search-input { + width: calc(180px + 10vw); + margin: 10px 0; +} +input#search-input { + width: 270px; + margin: 0; +} +input.filter-input { + min-width: 40px; + width: 180px; + margin: 0 -8px 0 5px; +} +input#reset-search, input.reset-filter, input#page-search-reset { + background-color: transparent; + background-image:url('x.svg'); + background-repeat:no-repeat; + background-size:contain; + border:0; + border-radius:0; + width:12px; + height:12px; + min-width:12px; + min-height:12px; + font-size:0; + visibility:hidden; +} +input#reset-search { + position:absolute; + right:5px; + top:7px; +} +input.reset-filter { + position: relative; + right: 10px; + top: 0; +} +input#page-search-reset { + position: relative; + right: 18px; + top: -5px; +} +input::placeholder { + color:var(--search-input-placeholder-color); + opacity: 1; +} +input:focus::placeholder { + color: transparent; +} +select#search-modules { + margin: 0 10px 10px 2px; + font-size: var(--nav-font-size); + padding: 3px 5px; + border-radius: 4px; + background: #f0f0f0; + border: 1px solid #909090; +} +kbd { + background-color: #eeeeee; + border: 1px solid #b0b0b0; + border-radius: 3px; + padding: 0 4px; + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), 0 2px 0 0 rgba(255, 255, 255, 0.6) inset; + font-size: 0.9em; + font-weight: bold; +} +.search-tag-result:target { + background-color:var(--search-tag-highlight-color); +} +dd > span:target, +h1 > span:target { + background-color: var(--search-tag-highlight-color); +} +section.class-description dd > span:target, +section.class-description h1 > span:target { + scroll-margin-top: 20em; +} +details.page-search-details { + display: inline-block; +} +div#result-container { + font-size: 1em; +} +#result-container .result-highlight { + font-weight:bold; +} +#result-container div.result-table { + display: grid; + grid-template-columns: minmax(40%, max-content) minmax(40%, auto); +} +#result-container div.result-table > div.table-header, +#result-container div.result-table > a.search-result-link { + display: grid; + grid-template-columns: subgrid; + grid-column: 1 / 3; + margin: 0; +} +#result-container div.result-table > div.table-header > span { + padding: 5px 12px; + font-size: 0.93em; + background-color: var(--subnav-background-color); +} +#result-container div.result-table > a.search-result-link > span { + padding: 8px 12px; +} +#result-container div.result-table > a.search-result-link:nth-child(odd) { + background-color: var(--odd-row-color) +} +#result-container div.result-table > a.search-result-link:nth-child(even) { + background-color: var(--even-row-color) +} +#result-container div.result-table > a.search-result-link { + color: var(--block-text-color); + white-space: nowrap; +} +#result-container div.result-table > a.search-result-link:focus-visible, +#result-container div.result-table > a.search-result-link.selected { + background-color: var(--selected-background-color); + outline: none; +} +#result-container div.result-table > a.search-result-link .search-result-label { + overflow: hidden; + text-overflow: ellipsis; +} +#result-container div.result-table > a.search-result-link .search-result-desc { + font-size: var(--nav-font-size); + color: #404040; + overflow: hidden; + text-overflow: ellipsis; +} +.page-search-info { + background-color: var(--subnav-background-color); + border-radius: 3px; + border: 0 solid var(--border-color); + padding: 0 8px; + margin: 8px 0; + overflow: hidden; + display: none; + transition: all 0.2s ease; +} +div.table-tabs > button.table-tab { + background: var(--navbar-background-color); + color: var(--navbar-text-color); +} +.page-search-header { + padding: 5px 12px 7px 12px; + font-weight: bold; + margin-right: 3px; + background-color:var(--navbar-background-color); + color:var(--navbar-text-color); + display: inline-block; +} +button.page-search-header { + border: none; + cursor: pointer; +} +span#page-search-link { + text-decoration: underline; +} +.module-graph span, .sealed-graph span { + display:none; + position:absolute; +} +.module-graph:hover span, .sealed-graph:hover span { + display:block; + margin: -100px 0 0 100px; + z-index: 5; +} +.horizontal-scroll { + overflow: auto hidden; +} +section.class-description { + line-height: 1.4; +} +.summary section[class$="-summary"], .details section[class$="-details"] { + margin-bottom: 24px; + background-color: var(--section-background-color); +} +body.class-uses section.detail { + padding: 0 25px 5px 10px; + margin: 25px 0; +} +section.serialized-class-details { + padding: 0 20px 5px 10px; + border: 1px solid var(--border-color); + background-color: var(--detail-block-color); +} +section.serialized-class-details .detail { + overflow: auto; + padding-left: 12px; +} +section[class$="-details"] .detail { + background-color:var(--detail-background-color); +} +section[class$="-details"] .detail > div { + padding-left: 8px; +} +.inherited-list { + margin: 20px 0; + background-color:var(--detail-background-color); +} +.inherited-list > code { + padding: 8px; + display: block; + background-color: var(--code-background-color); + border-radius: 0; + line-height: var(--code-line-height); +} +.vertical-separator { + padding: 0 5px; +} +.help-section { + font-size: var(--block-font-size); + line-height: var(--block-line-height); +} +ul.help-section-list { + margin: 0; +} +ul.help-subtoc > li { + display: inline-block; + padding-right: 5px; + font-size: smaller; +} +ul.help-subtoc > li::before { + content: "\2022" ; + padding-right:2px; +} +.help-note { + font-style: italic; +} +/* + * Indicator icon for external links. + */ +main a[href*="://"]::after { + content:""; + display:inline-block; + background-image:url('data:image/svg+xml; utf8, \ + \ + \ + '); + background-size:100% 100%; + width:7px; + height:7px; + margin-left:2px; + margin-bottom:4px; +} +main a[href*="://"]:hover::after, +main a[href*="://"]:focus::after { + background-image:url('data:image/svg+xml; utf8, \ + \ + \ + '); +} +/* + * Styles for header/section anchor links + */ +a.anchor-link { + opacity: 0; + transition: opacity 0.1s 0.1s; +} +:hover > a.anchor-link { + opacity: 90%; +} +a.anchor-link:hover, +a.anchor-link:focus-visible, +a.anchor-link.visible { + opacity: 100%; +} +a.anchor-link > img { + width: 0.9em; + height: 0.9em; +} +/* + * Styles for copy-to-clipboard buttons + */ +button.copy { + font-size: var(--nav-font-size); + line-height: 1.2; + padding:0.3em; + background-color: transparent; + border: 1px solid transparent; + border-radius: 3px; + position: relative; + opacity: 80%; + transition: all 0.1s ease; + cursor: pointer; +} +button.copy:hover, +button.copy:active, +button.copy:focus, +button.copy.visible { + opacity: 100%; + background-color: inherit; + border-color: var(--button-border-color); + filter: var(--button-focus-filter); +} +button.copy:active { + filter: var(--button-active-filter); +} +button.copy img { + position: relative; +} +button.copy span { + color: var(--body-text-color); + position: relative; + padding: 0.2em; + top: -0.1em; + transition: opacity 0.1s ease; + opacity: 0; +} +button.copy:hover span, +button.copy:focus span, +button.copy.visible span { + opacity: 100%; +} +/* search page copy button */ +button#page-search-copy { + margin-left: 0.4em; + top:0.13em; +} +button#page-search-copy img { + width: 1.2em; + height: 1.2em; + padding: 0.01em 0; + top: 0.15em; +} +button#page-search-copy span { + top: -0.18em; +} +/* snippet copy button */ +button.snippet-copy { + position: absolute; + top: 4px; + right: 1px; + height: 32px; +} +button.snippet-copy img { + width: 18px; + height: 18px; + padding: 2px 0; +} +button.snippet-copy span { + top: -7px; +} +/* + * Styles for user-provided tables. + * + * borderless: + * No borders, vertical margins, styled caption. + * This style is provided for use with existing doc comments. + * In general, borderless tables should not be used for layout purposes. + * + * plain: + * Plain borders around table and cells, vertical margins, styled caption. + * Best for small tables or for complex tables for tables with cells that span + * rows and columns, when the "striped" style does not work well. + * + * striped: + * Borders around the table and vertical borders between cells, striped rows, + * vertical margins, styled caption. + * Best for tables that have a header row, and a body containing a series of simple rows. + */ + +table.borderless, +table.plain, +table.striped { + margin-top: 10px; + margin-bottom: 10px; +} +table.borderless > caption, +table.plain > caption, +table.striped > caption { + font-weight: bold; + font-size: smaller; +} +table.borderless th, table.borderless td, +table.plain th, table.plain td, +table.striped th, table.striped td { + padding: 2px 5px; +} +table.borderless, +table.borderless > thead > tr > th, table.borderless > tbody > tr > th, table.borderless > tr > th, +table.borderless > thead > tr > td, table.borderless > tbody > tr > td, table.borderless > tr > td { + border: none; +} +table.borderless > thead > tr, table.borderless > tbody > tr, table.borderless > tr { + background-color: transparent; +} +table.plain { + border-collapse: collapse; + border: 1px solid var(--table-border-color); +} +table.plain > thead > tr, table.plain > tbody tr, table.plain > tr { + background-color: transparent; +} +table.plain > thead > tr > th, table.plain > tbody > tr > th, table.plain > tr > th, +table.plain > thead > tr > td, table.plain > tbody > tr > td, table.plain > tr > td { + border: 1px solid var(--table-border-color); +} +table.striped { + border-collapse: collapse; + border: 1px solid var(--table-border-color); +} +table.striped > thead { + background-color: var(--subnav-background-color); +} +table.striped > thead > tr > th, table.striped > thead > tr > td { + border: 1px solid var(--table-border-color); +} +table.striped > tbody > tr:nth-child(even) { + background-color: var(--odd-row-color) +} +table.striped > tbody > tr:nth-child(odd) { + background-color: var(--even-row-color) +} +table.striped > tbody > tr > th, table.striped > tbody > tr > td { + border-left: 1px solid var(--table-border-color); + border-right: 1px solid var(--table-border-color); +} +table.striped > tbody > tr > th { + font-weight: normal; +} +/** + * Media queries for responsive design + */ +@media (prefers-reduced-motion: reduce) { + :root { + scroll-behavior: auto; + } +} +@media screen and (max-width: 1200px) { + input#search-input { + width: 22.5vw; + } +} +@media screen and (max-width: 1000px) { + .main-grid nav.toc { + display: none; + } + .top-nav nav.toc { + display: none; + position: absolute; + top: var(--top-nav-height); + left: 40vw; + width: 60vw; + z-index: 7; + background-color: var(--toc-background-color); + box-sizing: border-box; + } + .top-nav nav.toc div.toc-header { + padding: 6px 15px; + font-size: 0.94em; + background-color: var(--toc-background-color); + top: calc(var(--top-nav-height) + 10px); + } + .top-nav nav.toc ol.toc-list li { + font-size: 1.04em; + } + nav.toc a:link, nav.toc a:visited { + text-decoration:none; + color:var(--link-color); + } + nav.toc a[href]:hover, nav.toc a[href]:focus { + text-decoration:none; + color:var(--link-color-active); + } + :root { + scroll-behavior: auto; + } + header { + max-height: 100vh; + overflow-y: visible; + overscroll-behavior: contain; + } + nav { + overflow: visible; + } + ul.nav-list { + display: none; + position: absolute; + top: var(--top-nav-height); + overflow: auto; + z-index: 7; + background-color: var(--navbar-background-color); + width: 40%; + padding: 0; + box-sizing: border-box; + } + ul.nav-list li { + float: none; + padding: 6px; + margin-left: 10px; + margin-top: 2px; + } + .top-nav a:link, .top-nav a:active, .top-nav a:visited { + display: block; + } + .top-nav div.nav-menu-button { + flex: 1 1 auto; + } + .sub-nav ol.sub-nav-list { + margin-left: 4px; + padding-left: 4px; + } + button#navbar-toggle-button { + width: 3.4em; + height: 2.8em; + background-color: transparent; + display: block; + border: 0; + margin: 0 10px; + cursor: pointer; + font-size: 10px; + } + button#navbar-toggle-button .nav-bar-toggle-icon { + display: block; + width: 24px; + height: 3px; + margin: 4px 0; + border-radius: 2px; + background-color: var(--navbar-text-color); + } + button#navbar-toggle-button.expanded span.nav-bar-toggle-icon:nth-child(1) { + transform: rotate(45deg); + transform-origin: 10% 10%; + width: 26px; + } + button#navbar-toggle-button.expanded span.nav-bar-toggle-icon:nth-child(2) { + opacity: 0; + } + button#navbar-toggle-button.expanded span.nav-bar-toggle-icon:nth-child(3) { + transform: rotate(-45deg); + transform-origin: 10% 90%; + width: 26px; + } + .ui-autocomplete { + display: block; + grid-template-columns: none; + } + .ui-autocomplete > li, + .ui-autocomplete > li > div, + .ui-autocomplete > li.result-item, + .ui-autocomplete > li.result-item > div { + grid-column: unset; + display: block; + grid-template-columns: none; + } + .ui-autocomplete > li.result-item { + line-height: 1.45; + } + .ui-autocomplete .search-result-label { + display: block; + } + .ui-autocomplete .search-result-desc { + display: block; + } +} +@media screen and (max-width: 800px) { + .about-language { + padding: 0 16px; + max-width: 90%; + } + ul.nav-list li { + margin-left: 5px; + } + main { + padding: 10px 12px; + } + body { + -webkit-text-size-adjust: none; + } +} +@media screen and (max-width: 600px) { + .nav-list-search > a { + display: none; + } + .member-signature { + white-space: pre-line; + } + .member-signature .annotations { + white-space: pre-wrap; + } + input#search-input { + width: 18vw; + } + .inherited-list h3 { + overflow: auto clip; + } + .summary section[class$="-summary"], .details section[class$="-details"], + .class-uses .detail, .serialized-class-details { + padding: 0; + } +} +pre.snippet { + background-color: var(--snippet-background-color); + color: var(--snippet-text-color); + padding: 12px; +} +div.snippet-container { + position: relative; + padding-right: 30px; + background-color: var(--snippet-background-color); +} +pre.snippet .italic { + font-style: italic; +} +pre.snippet .bold { + font-weight: bold; +} +pre.snippet .highlighted { + background-color: var(--snippet-highlight-color); + border-radius: 10%; +} +/* + * Hide navigation links and search box in print layout + */ +@media print { + ul.nav-list, div.sub-nav, .main-grid nav.toc, button.copy { + display:none; + } +} diff --git a/target/site/apidocs/resource-files/x.svg b/target/site/apidocs/resource-files/x.svg new file mode 100644 index 000000000..1efb41092 --- /dev/null +++ b/target/site/apidocs/resource-files/x.svg @@ -0,0 +1,13 @@ + + + + + + + + \ No newline at end of file diff --git a/src/main/javadoc/resources/dictionary.html b/target/site/apidocs/resources/dictionary.html similarity index 100% rename from src/main/javadoc/resources/dictionary.html rename to target/site/apidocs/resources/dictionary.html diff --git a/target/site/apidocs/script-files/jquery-3.7.1.min.js b/target/site/apidocs/script-files/jquery-3.7.1.min.js new file mode 100644 index 000000000..7f37b5d99 --- /dev/null +++ b/target/site/apidocs/script-files/jquery-3.7.1.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.7.1 | (c) OpenJS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(ie,e){"use strict";var oe=[],r=Object.getPrototypeOf,ae=oe.slice,g=oe.flat?function(e){return oe.flat.call(e)}:function(e){return oe.concat.apply([],e)},s=oe.push,se=oe.indexOf,n={},i=n.toString,ue=n.hasOwnProperty,o=ue.toString,a=o.call(Object),le={},v=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},y=function(e){return null!=e&&e===e.window},C=ie.document,u={type:!0,src:!0,nonce:!0,noModule:!0};function m(e,t,n){var r,i,o=(n=n||C).createElement("script");if(o.text=e,t)for(r in u)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[i.call(e)]||"object":typeof e}var t="3.7.1",l=/HTML$/i,ce=function(e,t){return new ce.fn.init(e,t)};function c(e){var t=!!e&&"length"in e&&e.length,n=x(e);return!v(e)&&!y(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+ge+")"+ge+"*"),x=new RegExp(ge+"|>"),j=new RegExp(g),A=new RegExp("^"+t+"$"),D={ID:new RegExp("^#("+t+")"),CLASS:new RegExp("^\\.("+t+")"),TAG:new RegExp("^("+t+"|[*])"),ATTR:new RegExp("^"+p),PSEUDO:new RegExp("^"+g),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ge+"*(even|odd|(([+-]|)(\\d*)n|)"+ge+"*(?:([+-]|)"+ge+"*(\\d+)|))"+ge+"*\\)|)","i"),bool:new RegExp("^(?:"+f+")$","i"),needsContext:new RegExp("^"+ge+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ge+"*((?:-\\d)?\\d*)"+ge+"*\\)|)(?=[^-]|$)","i")},N=/^(?:input|select|textarea|button)$/i,q=/^h\d$/i,L=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,H=/[+~]/,O=new RegExp("\\\\[\\da-fA-F]{1,6}"+ge+"?|\\\\([^\\r\\n\\f])","g"),P=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},M=function(){V()},R=J(function(e){return!0===e.disabled&&fe(e,"fieldset")},{dir:"parentNode",next:"legend"});try{k.apply(oe=ae.call(ye.childNodes),ye.childNodes),oe[ye.childNodes.length].nodeType}catch(e){k={apply:function(e,t){me.apply(e,ae.call(t))},call:function(e){me.apply(e,ae.call(arguments,1))}}}function I(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(V(e),e=e||T,C)){if(11!==p&&(u=L.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return k.call(n,a),n}else if(f&&(a=f.getElementById(i))&&I.contains(e,a)&&a.id===i)return k.call(n,a),n}else{if(u[2])return k.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&e.getElementsByClassName)return k.apply(n,e.getElementsByClassName(i)),n}if(!(h[t+" "]||d&&d.test(t))){if(c=t,f=e,1===p&&(x.test(t)||m.test(t))){(f=H.test(t)&&U(e.parentNode)||e)==e&&le.scope||((s=e.getAttribute("id"))?s=ce.escapeSelector(s):e.setAttribute("id",s=S)),o=(l=Y(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+Q(l[o]);c=l.join(",")}try{return k.apply(n,f.querySelectorAll(c)),n}catch(e){h(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return re(t.replace(ve,"$1"),e,n,r)}function W(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function F(e){return e[S]=!0,e}function $(e){var t=T.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function B(t){return function(e){return fe(e,"input")&&e.type===t}}function _(t){return function(e){return(fe(e,"input")||fe(e,"button"))&&e.type===t}}function z(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&R(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function X(a){return F(function(o){return o=+o,F(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function U(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function V(e){var t,n=e?e.ownerDocument||e:ye;return n!=T&&9===n.nodeType&&n.documentElement&&(r=(T=n).documentElement,C=!ce.isXMLDoc(T),i=r.matches||r.webkitMatchesSelector||r.msMatchesSelector,r.msMatchesSelector&&ye!=T&&(t=T.defaultView)&&t.top!==t&&t.addEventListener("unload",M),le.getById=$(function(e){return r.appendChild(e).id=ce.expando,!T.getElementsByName||!T.getElementsByName(ce.expando).length}),le.disconnectedMatch=$(function(e){return i.call(e,"*")}),le.scope=$(function(){return T.querySelectorAll(":scope")}),le.cssHas=$(function(){try{return T.querySelector(":has(*,:jqfake)"),!1}catch(e){return!0}}),le.getById?(b.filter.ID=function(e){var t=e.replace(O,P);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(O,P);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):t.querySelectorAll(e)},b.find.CLASS=function(e,t){if("undefined"!=typeof t.getElementsByClassName&&C)return t.getElementsByClassName(e)},d=[],$(function(e){var t;r.appendChild(e).innerHTML="",e.querySelectorAll("[selected]").length||d.push("\\["+ge+"*(?:value|"+f+")"),e.querySelectorAll("[id~="+S+"-]").length||d.push("~="),e.querySelectorAll("a#"+S+"+*").length||d.push(".#.+[+~]"),e.querySelectorAll(":checked").length||d.push(":checked"),(t=T.createElement("input")).setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),r.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&d.push(":enabled",":disabled"),(t=T.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||d.push("\\["+ge+"*name"+ge+"*="+ge+"*(?:''|\"\")")}),le.cssHas||d.push(":has"),d=d.length&&new RegExp(d.join("|")),l=function(e,t){if(e===t)return a=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!le.sortDetached&&t.compareDocumentPosition(e)===n?e===T||e.ownerDocument==ye&&I.contains(ye,e)?-1:t===T||t.ownerDocument==ye&&I.contains(ye,t)?1:o?se.call(o,e)-se.call(o,t):0:4&n?-1:1)}),T}for(e in I.matches=function(e,t){return I(e,null,null,t)},I.matchesSelector=function(e,t){if(V(e),C&&!h[t+" "]&&(!d||!d.test(t)))try{var n=i.call(e,t);if(n||le.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){h(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(O,P),e[3]=(e[3]||e[4]||e[5]||"").replace(O,P),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||I.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&I.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return D.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&j.test(n)&&(t=Y(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(O,P).toLowerCase();return"*"===e?function(){return!0}:function(e){return fe(e,t)}},CLASS:function(e){var t=s[e+" "];return t||(t=new RegExp("(^|"+ge+")"+e+"("+ge+"|$)"))&&s(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=I.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function T(e,n,r){return v(n)?ce.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?ce.grep(e,function(e){return e===n!==r}):"string"!=typeof n?ce.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(ce.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||k,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:S.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof ce?t[0]:t,ce.merge(this,ce.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:C,!0)),w.test(r[1])&&ce.isPlainObject(t))for(r in t)v(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=C.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):v(e)?void 0!==n.ready?n.ready(e):e(ce):ce.makeArray(e,this)}).prototype=ce.fn,k=ce(C);var E=/^(?:parents|prev(?:Until|All))/,j={children:!0,contents:!0,next:!0,prev:!0};function A(e,t){while((e=e[t])&&1!==e.nodeType);return e}ce.fn.extend({has:function(e){var t=ce(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,Ce=/^$|^module$|\/(?:java|ecma)script/i;xe=C.createDocumentFragment().appendChild(C.createElement("div")),(be=C.createElement("input")).setAttribute("type","radio"),be.setAttribute("checked","checked"),be.setAttribute("name","t"),xe.appendChild(be),le.checkClone=xe.cloneNode(!0).cloneNode(!0).lastChild.checked,xe.innerHTML="",le.noCloneChecked=!!xe.cloneNode(!0).lastChild.defaultValue,xe.innerHTML="",le.option=!!xe.lastChild;var ke={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function Se(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&fe(e,t)?ce.merge([e],n):n}function Ee(e,t){for(var n=0,r=e.length;n",""]);var je=/<|&#?\w+;/;function Ae(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function Re(e,t){return fe(e,"table")&&fe(11!==t.nodeType?t:t.firstChild,"tr")&&ce(e).children("tbody")[0]||e}function Ie(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function We(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Fe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(_.hasData(e)&&(s=_.get(e).events))for(i in _.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),C.head.appendChild(r[0])},abort:function(){i&&i()}}});var Jt,Kt=[],Zt=/(=)\?(?=&|$)|\?\?/;ce.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Kt.pop()||ce.expando+"_"+jt.guid++;return this[e]=!0,e}}),ce.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Zt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Zt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=v(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Zt,"$1"+r):!1!==e.jsonp&&(e.url+=(At.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||ce.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=ie[r],ie[r]=function(){o=arguments},n.always(function(){void 0===i?ce(ie).removeProp(r):ie[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Kt.push(r)),o&&v(i)&&i(o[0]),o=i=void 0}),"script"}),le.createHTMLDocument=((Jt=C.implementation.createHTMLDocument("").body).innerHTML="
",2===Jt.childNodes.length),ce.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(le.createHTMLDocument?((r=(t=C.implementation.createHTMLDocument("")).createElement("base")).href=C.location.href,t.head.appendChild(r)):t=C),o=!n&&[],(i=w.exec(e))?[t.createElement(i[1])]:(i=Ae([e],t,o),o&&o.length&&ce(o).remove(),ce.merge([],i.childNodes)));var r,i,o},ce.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(ce.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},ce.expr.pseudos.animated=function(t){return ce.grep(ce.timers,function(e){return t===e.elem}).length},ce.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=ce.css(e,"position"),c=ce(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=ce.css(e,"top"),u=ce.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),v(t)&&(t=t.call(e,n,ce.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},ce.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){ce.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===ce.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===ce.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=ce(e).offset()).top+=ce.css(e,"borderTopWidth",!0),i.left+=ce.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-ce.css(r,"marginTop",!0),left:t.left-i.left-ce.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===ce.css(e,"position"))e=e.offsetParent;return e||J})}}),ce.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;ce.fn[t]=function(e){return M(this,function(e,t,n){var r;if(y(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),ce.each(["top","left"],function(e,n){ce.cssHooks[n]=Ye(le.pixelPosition,function(e,t){if(t)return t=Ge(e,n),_e.test(t)?ce(e).position()[n]+"px":t})}),ce.each({Height:"height",Width:"width"},function(a,s){ce.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){ce.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return M(this,function(e,t,n){var r;return y(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?ce.css(e,t,i):ce.style(e,t,n,i)},s,n?e:void 0,n)}})}),ce.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ce.fn[t]=function(e){return this.on(t,e)}}),ce.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.on("mouseenter",e).on("mouseleave",t||e)}}),ce.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){ce.fn[n]=function(e,t){return 0{"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)})(function(x){x.ui=x.ui||{};x.ui.version="1.14.1";var n,s,C,k,o,l,a,r,u,i,h=0,c=Array.prototype.hasOwnProperty,d=Array.prototype.slice;x.cleanData=(n=x.cleanData,function(t){for(var e,i,s=0;null!=(i=t[s]);s++)(e=x._data(i,"events"))&&e.remove&&x(i).triggerHandler("remove");n(t)}),x.widget=function(t,i,e){var s,n,o,l,a={},r=t.split(".")[0];return"__proto__"===(t=t.split(".")[1])||"constructor"===t?x.error("Invalid widget name: "+t):(l=r+"-"+t,e||(e=i,i=x.Widget),Array.isArray(e)&&(e=x.extend.apply(null,[{}].concat(e))),x.expr.pseudos[l.toLowerCase()]=function(t){return!!x.data(t,l)},x[r]=x[r]||{},s=x[r][t],n=x[r][t]=function(t,e){if(!this||!this._createWidget)return new n(t,e);arguments.length&&this._createWidget(t,e)},x.extend(n,s,{version:e.version,_proto:x.extend({},e),_childConstructors:[]}),(o=new i).options=x.widget.extend({},o.options),x.each(e,function(e,s){function n(){return i.prototype[e].apply(this,arguments)}function o(t){return i.prototype[e].apply(this,t)}a[e]="function"!=typeof s?s:function(){var t,e=this._super,i=this._superApply;return this._super=n,this._superApply=o,t=s.apply(this,arguments),this._super=e,this._superApply=i,t}}),n.prototype=x.widget.extend(o,{widgetEventPrefix:s&&o.widgetEventPrefix||t},a,{constructor:n,namespace:r,widgetName:t,widgetFullName:l}),s?(x.each(s._childConstructors,function(t,e){var i=e.prototype;x.widget(i.namespace+"."+i.widgetName,n,e._proto)}),delete s._childConstructors):i._childConstructors.push(n),x.widget.bridge(t,n),n)},x.widget.extend=function(t){for(var e,i,s=d.call(arguments,1),n=0,o=s.length;n",options:{classes:{},disabled:!1,create:null},_createWidget:function(t,e){e=x(e||this.defaultElement||this)[0],this.element=x(e),this.uuid=h++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=x(),this.hoverable=x(),this.focusable=x(),this.classesElementLookup={},e!==this&&(x.data(e,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===e&&this.destroy()}}),this.document=x(e.style?e.ownerDocument:e.document||e),this.window=x(this.document[0].defaultView||this.document[0].parentWindow)),this.options=x.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:x.noop,_create:x.noop,_init:x.noop,destroy:function(){var i=this;this._destroy(),x.each(this.classesElementLookup,function(t,e){i._removeClass(e,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:x.noop,widget:function(){return this.element},option:function(t,e){var i,s,n,o=t;if(0===arguments.length)return x.widget.extend({},this.options);if("string"==typeof t)if(o={},t=(i=t.split(".")).shift(),i.length){for(s=o[t]=x.widget.extend({},this.options[t]),n=0;n{var i=[];n.element.each(function(t,e){x.map(l.classesElementLookup,function(t){return t}).some(function(t){return t.is(e)})||i.push(e)}),l._on(x(i),{remove:"_untrackClassesElement"})})(),x(x.uniqueSort(i.get().concat(n.element.get())))):x(i.not(n.element).get()),l.classesElementLookup[t[s]]=i,o.push(t[s]),e&&n.classes[t[s]]&&o.push(n.classes[t[s]])}return(n=x.extend({element:this.element,classes:this.options.classes||{}},n)).keys&&t(n.keys.match(/\S+/g)||[],!0),n.extra&&t(n.extra.match(/\S+/g)||[]),o.join(" ")},_untrackClassesElement:function(i){var s=this;x.each(s.classesElementLookup,function(t,e){-1!==x.inArray(i.target,e)&&(s.classesElementLookup[t]=x(e.not(i.target).get()))}),this._off(x(i.target))},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,s){var n="string"==typeof t||null===t,e={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s="boolean"==typeof s?s:i};return e.element.toggleClass(this._classes(e),s),this},_on:function(n,o,t){var l,a=this;"boolean"!=typeof n&&(t=o,o=n,n=!1),t?(o=l=x(o),this.bindings=this.bindings.add(o)):(t=o,o=this.element,l=this.widget()),x.each(t,function(t,e){function i(){if(n||!0!==a.options.disabled&&!x(this).hasClass("ui-state-disabled"))return("string"==typeof e?a[e]:e).apply(a,arguments)}"string"!=typeof e&&(i.guid=e.guid=e.guid||i.guid||x.guid++);var t=t.match(/^([\w:-]*)\s*(.*)$/),s=t[1]+a.eventNamespace,t=t[2];t?l.on(s,t,i):o.on(s,i)})},_off:function(t,e){e=(e||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.off(e),this.bindings=x(this.bindings.not(t).get()),this.focusable=x(this.focusable.not(t).get()),this.hoverable=x(this.hoverable.not(t).get())},_delay:function(t,e){var i=this;return setTimeout(function(){return("string"==typeof t?i[t]:t).apply(i,arguments)},e||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){this._addClass(x(t.currentTarget),null,"ui-state-hover")},mouseleave:function(t){this._removeClass(x(t.currentTarget),null,"ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){this._addClass(x(t.currentTarget),null,"ui-state-focus")},focusout:function(t){this._removeClass(x(t.currentTarget),null,"ui-state-focus")}})},_trigger:function(t,e,i){var s,n,o=this.options[t];if(i=i||{},(e=x.Event(e)).type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),e.target=this.element[0],n=e.originalEvent)for(s in n)s in e||(e[s]=n[s]);return this.element.trigger(e,i),!("function"==typeof o&&!1===o.apply(this.element[0],[e].concat(i))||e.isDefaultPrevented())}},x.each({show:"fadeIn",hide:"fadeOut"},function(o,l){x.Widget.prototype["_"+o]=function(e,t,i){var s,n=(t="string"==typeof t?{effect:t}:t)?!0!==t&&"number"!=typeof t&&t.effect||l:o;"number"==typeof(t=t||{})?t={duration:t}:!0===t&&(t={}),s=!x.isEmptyObject(t),t.complete=i,t.delay&&e.delay(t.delay),s&&x.effects&&x.effects.effect[n]?e[o](t):n!==o&&e[n]?e[n](t.duration,t.easing,i):e.queue(function(t){x(this)[o](),i&&i.call(e[0]),t()})}}),x.widget;function E(t,e,i){return[parseFloat(t[0])*(u.test(t[0])?e/100:1),parseFloat(t[1])*(u.test(t[1])?i/100:1)]}function T(t,e){return parseInt(x.css(t,e),10)||0}function W(t){return null!=t&&t===t.window}C=Math.max,k=Math.abs,o=/left|center|right/,l=/top|center|bottom/,a=/[\+\-]\d+(\.[\d]+)?%?/,r=/^\w+/,u=/%$/,i=x.fn.position,x.position={scrollbarWidth:function(){var t,e,i;return void 0!==s?s:(i=(e=x("
")).children()[0],x("body").append(e),t=i.offsetWidth,e.css("overflow","scroll"),t===(i=i.offsetWidth)&&(i=e[0].clientWidth),e.remove(),s=t-i)},getScrollInfo:function(t){var e=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),i=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),e="scroll"===e||"auto"===e&&t.widthC(k(s),k(n))?o.important="horizontal":o.important="vertical",c.using.call(this,t,o)}),l.offset(x.extend(u,{using:t}))})):i.apply(this,arguments)},x.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,s=s.width,o=t.left-e.collisionPosition.marginLeft,l=n-o,a=o+e.collisionWidth-s-n;s",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.lastMousePosition={x:null,y:null},this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault(),this._activateItem(t)},"click .ui-menu-item":function(t){var e=x(t.target),i=x(this.document[0].activeElement);!this.mouseHandled&&e.not(".ui-state-disabled").length&&(this.select(t),t.isPropagationStopped()||(this.mouseHandled=!0),e.has(".ui-menu").length?this.expand(t):!this.element.is(":focus")&&i.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active)&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer))},"mouseenter .ui-menu-item":"_activateItem","mousemove .ui-menu-item":"_activateItem",mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this._menuItems().first();e||this.focus(t,i)},blur:function(t){this._delay(function(){x.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t,!0),this.mouseHandled=!1}})},_activateItem:function(t){var e,i;this.previousFilter||t.clientX===this.lastMousePosition.x&&t.clientY===this.lastMousePosition.y||(this.lastMousePosition={x:t.clientX,y:t.clientY},e=x(t.target).closest(".ui-menu-item"),i=x(t.currentTarget),e[0]!==i[0])||i.is(".ui-state-active")||(this._removeClass(i.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(t,i))},_destroy:function(){var t=this.element.find(".ui-menu-item").removeAttr("role aria-disabled").children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),t.children().each(function(){var t=x(this);t.data("ui-menu-submenu-caret")&&t.remove()})},_keydown:function(t){var e,i,s,n=!0;switch(t.keyCode){case x.ui.keyCode.PAGE_UP:this.previousPage(t);break;case x.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case x.ui.keyCode.HOME:this._move("first","first",t);break;case x.ui.keyCode.END:this._move("last","last",t);break;case x.ui.keyCode.UP:this.previous(t);break;case x.ui.keyCode.DOWN:this.next(t);break;case x.ui.keyCode.LEFT:this.collapse(t);break;case x.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case x.ui.keyCode.ENTER:case x.ui.keyCode.SPACE:this._activate(t);break;case x.ui.keyCode.ESCAPE:this.collapse(t);break;default:e=this.previousFilter||"",s=n=!1,i=96<=t.keyCode&&t.keyCode<=105?(t.keyCode-96).toString():String.fromCharCode(t.keyCode),clearTimeout(this.filterTimer),i===e?s=!0:i=e+i,e=this._filterMenuItems(i),(e=s&&-1!==e.index(this.active.next())?this.active.nextAll(".ui-menu-item"):e).length||(i=String.fromCharCode(t.keyCode),e=this._filterMenuItems(i)),e.length?(this.focus(t,e),this.previousFilter=i,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}n&&t.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var t,e,s=this,n=this.options.icons.submenu,i=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),t=i.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=x(this),e=t.prev(),i=x("").data("ui-menu-submenu-caret",!0);s._addClass(i,"ui-menu-icon","ui-icon "+n),e.attr("aria-haspopup","true").prepend(i),t.attr("aria-labelledby",e.attr("id"))}),this._addClass(t,"ui-menu","ui-widget ui-widget-content ui-front"),(t=i.add(this.element).find(this.options.items)).not(".ui-menu-item").each(function(){var t=x(this);s._isDivider(t)&&s._addClass(t,"ui-menu-divider","ui-widget-content")}),e=(i=t.not(".ui-menu-item, .ui-menu-divider")).children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(i,"ui-menu-item")._addClass(e,"ui-menu-item-wrapper"),t.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!x.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){var i;"icons"===t&&(i=this.element.find(".ui-menu-icon"),this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",String(t)),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),i=this.active.children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",i.attr("id")),i=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),(i=e.children(".ui-menu")).length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(t){var e,i,s;this._hasScroll()&&(e=parseFloat(x.css(this.activeMenu[0],"borderTopWidth"))||0,i=parseFloat(x.css(this.activeMenu[0],"paddingTop"))||0,e=t.offset().top-this.activeMenu.offset().top-e-i,i=this.activeMenu.scrollTop(),s=this.activeMenu.height(),t=t.outerHeight(),e<0?this.activeMenu.scrollTop(i+e):s",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,liveRegionTimer:null,_create:function(){var i,s,n,t=this.element[0].nodeName.toLowerCase(),e="textarea"===t,t="input"===t;this.isMultiLine=e||!t&&"true"===this.element.prop("contentEditable"),this.valueMethod=this.element[e||t?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(t){if(this.element.prop("readOnly"))s=n=i=!0;else{s=n=i=!1;var e=x.ui.keyCode;switch(t.keyCode){case e.PAGE_UP:i=!0,this._move("previousPage",t);break;case e.PAGE_DOWN:i=!0,this._move("nextPage",t);break;case e.UP:i=!0,this._keyEvent("previous",t);break;case e.DOWN:i=!0,this._keyEvent("next",t);break;case e.ENTER:this.menu.active&&(i=!0,t.preventDefault(),this.menu.select(t));break;case e.TAB:this.menu.active&&this.menu.select(t);break;case e.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(t),t.preventDefault());break;default:s=!0,this._searchTimeout(t)}}},keypress:function(t){if(i)i=!1,this.isMultiLine&&!this.menu.element.is(":visible")||t.preventDefault();else if(!s){var e=x.ui.keyCode;switch(t.keyCode){case e.PAGE_UP:this._move("previousPage",t);break;case e.PAGE_DOWN:this._move("nextPage",t);break;case e.UP:this._keyEvent("previous",t);break;case e.DOWN:this._keyEvent("next",t)}}},input:function(t){n?(n=!1,t.preventDefault()):this._searchTimeout(t)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){clearTimeout(this.searching),this.close(t),this._change(t)}}),this._initSource(),this.menu=x("